@bramblex/codex-workbench 0.1.2 → 0.1.4

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/src/cli.js CHANGED
@@ -1,302 +1,25 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- const fs = require('fs');
5
- const path = require('path');
6
- const os = require('os');
7
- const blessed = require('blessed');
8
- const { spawnSync, spawn } = require('child_process');
9
- const { inspectCodexBin, resolveCodexBin } = require('./codex-bin');
10
-
11
- const HOME = os.homedir();
12
- const CODEX_HOME = process.env.CODEX_HOME || path.join(HOME, '.codex');
13
- const SESSIONS_DIR = process.env.CODEX_SESSIONS_DIR || path.join(CODEX_HOME, 'sessions');
14
- const META_PATH = process.env.CODEX_WORKBENCH_META || process.env.CSM_META || path.join(CODEX_HOME, 'codex-workbench.json');
15
-
16
- function usage() {
17
- console.log(`codex-workbench
18
-
19
- Usage:
20
- codex-workbench [ui]
21
- codex-workbench doctor
22
- codex-workbench list [--json] [--cwd <dir>] [--all]
23
- codex-workbench show <session>
24
- codex-workbench rename <session> <name>
25
- codex-workbench note <session> <note>
26
- codex-workbench resume <session> [prompt...]
27
- codex-workbench fork <session>
28
- codex-workbench archive <session>
29
- codex-workbench unarchive <session>
30
- codex-workbench hide <session>
31
- codex-workbench unhide <session>
32
- codex-workbench delete <session> [--force]
33
-
34
- Environment:
35
- CODEX_HOME default: ~/.codex
36
- CODEX_SESSIONS_DIR default: $CODEX_HOME/sessions
37
- CODEX_WORKBENCH_META default: $CODEX_HOME/codex-workbench.json
38
- CODEX_BIN default: codex from shell PATH
39
- `);
40
- }
41
-
42
- function readJson(file, fallback) {
43
- try {
44
- return JSON.parse(fs.readFileSync(file, 'utf8'));
45
- } catch {
46
- return fallback;
47
- }
48
- }
49
-
50
- function writeJson(file, value) {
51
- fs.mkdirSync(path.dirname(file), { recursive: true });
52
- fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n');
53
- }
54
-
55
- function walk(dir, out = []) {
56
- let entries = [];
57
- try {
58
- entries = fs.readdirSync(dir, { withFileTypes: true });
59
- } catch {
60
- return out;
61
- }
62
- for (const entry of entries) {
63
- const full = path.join(dir, entry.name);
64
- if (entry.isDirectory()) walk(full, out);
65
- else if (entry.isFile() && entry.name.endsWith('.jsonl')) out.push(full);
66
- }
67
- return out;
68
- }
69
-
70
- function textFromContent(content) {
71
- if (!Array.isArray(content)) return '';
72
- return content
73
- .filter((item) => item && (item.type === 'input_text' || item.type === 'output_text'))
74
- .map((item) => item.text || '')
75
- .join(' ')
76
- .replace(/\s+/g, ' ')
77
- .trim();
78
- }
79
-
80
- function isNoiseUserText(text) {
81
- return text.includes('<environment_context>') || text.includes('<permissions instructions>');
82
- }
83
-
84
- function parseSession(file) {
85
- const stat = fs.statSync(file);
86
- const raw = fs.readFileSync(file, 'utf8').trim();
87
- const lines = raw ? raw.split(/\n/) : [];
88
- let meta = {};
89
- const messages = [];
90
- let turns = 0;
91
-
92
- for (const line of lines) {
93
- let row;
94
- try {
95
- row = JSON.parse(line);
96
- } catch {
97
- continue;
98
- }
99
- if (row.type === 'session_meta') meta = row.payload || {};
100
- if (row.type === 'response_item' && row.payload && row.payload.type === 'message') {
101
- const msg = row.payload;
102
- if (msg.role === 'developer') continue;
103
- const text = textFromContent(msg.content);
104
- if (!text) continue;
105
- if (msg.role === 'user' && isNoiseUserText(text)) continue;
106
- messages.push({
107
- role: msg.role,
108
- phase: msg.phase || '',
109
- text,
110
- });
111
- if (msg.role === 'user') turns += 1;
112
- }
113
- }
114
-
115
- const id = meta.id || path.basename(file, '.jsonl').split('-').slice(-5).join('-');
116
- const firstUser = messages.find((msg) => msg.role === 'user');
117
- const lastUser = [...messages].reverse().find((msg) => msg.role === 'user');
118
- const lastAssistant = [...messages].reverse().find((msg) => msg.role === 'assistant');
119
-
120
- return {
121
- id,
122
- file,
123
- cwd: meta.cwd || '(unknown)',
124
- startedAt: meta.timestamp || null,
125
- updatedAt: stat.mtime.toISOString(),
126
- cliVersion: meta.cli_version || '',
127
- source: meta.source || '',
128
- provider: meta.model_provider || '',
129
- turns,
130
- first: firstUser ? firstUser.text : '',
131
- last: lastUser ? lastUser.text : '',
132
- lastAssistant: lastAssistant ? lastAssistant.text : '',
133
- messages,
134
- };
135
- }
136
-
137
- function loadMeta() {
138
- const data = readJson(META_PATH, { sessions: {} });
139
- if (!data.sessions) data.sessions = {};
140
- return data;
141
- }
142
-
143
- function listSessions() {
144
- const meta = loadMeta();
145
- return walk(SESSIONS_DIR)
146
- .map(parseSession)
147
- .map((session) => ({ ...session, ...(meta.sessions[session.id] || {}) }))
148
- .sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt));
149
- }
150
-
151
- function resolveSession(query, sessions = listSessions()) {
152
- if (!query) throw new Error('Missing session. Run `codex-workbench list` to find a session id.');
153
- const matches = sessions.filter((session) => {
154
- return session.id === query ||
155
- session.id.startsWith(query) ||
156
- session.name === query ||
157
- path.basename(session.file) === query;
158
- });
159
- if (matches.length === 1) return matches[0];
160
- if (matches.length === 0) throw new Error(`No session matched: ${query}`);
161
- throw new Error(`Ambiguous session: ${query}\n${matches.map((s) => ` ${s.id} ${s.name || ''}`).join('\n')}`);
162
- }
163
-
164
- function shortId(id) {
165
- return id.slice(0, 13);
166
- }
167
-
168
- function localTime(iso) {
169
- if (!iso) return '';
170
- return new Date(iso).toLocaleString();
171
- }
172
-
173
- function truncate(text, width) {
174
- if (!text) return '';
175
- return text.length > width ? text.slice(0, Math.max(0, width - 1)) + '...' : text;
176
- }
177
-
178
- function printList(sessions, opts = {}) {
179
- const filtered = sessions.filter((session) => {
180
- if (!opts.all && (session.archived || session.hidden)) return false;
181
- if (opts.cwd) return path.resolve(session.cwd) === path.resolve(opts.cwd);
182
- return true;
183
- });
184
- if (opts.json) {
185
- console.log(JSON.stringify(filtered, null, 2));
186
- return;
187
- }
188
- const groups = new Map();
189
- for (const session of filtered) {
190
- if (!groups.has(session.cwd)) groups.set(session.cwd, []);
191
- groups.get(session.cwd).push(session);
192
- }
193
- for (const [cwd, group] of groups) {
194
- console.log(`\n${cwd}`);
195
- for (const session of group) {
196
- const label = session.name || truncate(session.first || session.last || '(no prompt)', 56);
197
- const flags = [session.archived ? 'archived' : '', session.hidden ? 'hidden' : '', session.note ? 'note' : ''].filter(Boolean).join(',');
198
- console.log(` ${shortId(session.id)} ${localTime(session.updatedAt)} ${String(session.turns).padStart(2)} turns ${flags ? `[${flags}] ` : ''}${label}`);
199
- }
200
- }
201
- if (!filtered.length) console.log('No sessions found.');
202
- }
203
-
204
- function printShow(session) {
205
- console.log(`${session.name || '(unnamed)'} ${session.archived ? '[archived]' : ''}${session.hidden ? '[hidden]' : ''}`);
206
- console.log(`id: ${session.id}`);
207
- console.log(`cwd: ${session.cwd}`);
208
- console.log(`started: ${localTime(session.startedAt)}`);
209
- console.log(`updated: ${localTime(session.updatedAt)}`);
210
- console.log(`file: ${session.file}`);
211
- console.log(`turns: ${session.turns}`);
212
- if (session.note) console.log(`note: ${session.note}`);
213
- console.log('\nMessages:');
214
- for (const msg of session.messages) {
215
- if (msg.role === 'developer') continue;
216
- const prefix = msg.role === 'assistant' ? 'A' : msg.role === 'user' ? 'U' : msg.role.slice(0, 1).toUpperCase();
217
- console.log(` ${prefix}: ${truncate(msg.text, 180)}`);
218
- }
219
- }
220
-
221
- function printDoctor() {
222
- const result = inspectCodexBin();
223
- console.log('codex-workbench doctor');
224
- console.log(`status: ${result.ok ? 'ok' : 'error'}`);
225
- if (result.path) console.log(`codex: ${result.path}`);
226
- if (result.source) console.log(`source: ${result.source}`);
227
- if (result.error) console.log(`error: ${result.error}`);
228
- console.log('\nChecks:');
229
- for (const check of result.checks) {
230
- const parts = [
231
- check.source,
232
- check.mode ? `mode=${check.mode}` : '',
233
- check.shell ? `shell=${check.shell}` : '',
234
- check.path ? `path=${check.path}` : '',
235
- `executable=${check.executable ? 'yes' : 'no'}`,
236
- ].filter(Boolean);
237
- console.log(` - ${parts.join(' ')}`);
238
- }
239
- if (!result.ok) process.exitCode = 1;
240
- }
241
-
242
- function updateMetadata(session, patch) {
243
- const meta = loadMeta();
244
- meta.sessions[session.id] = { ...(meta.sessions[session.id] || {}), ...patch };
245
- meta.updatedAt = new Date().toISOString();
246
- writeJson(META_PATH, meta);
247
- }
248
-
249
- function usableCwd(dir) {
250
- const candidates = [dir, process.cwd(), HOME];
251
- for (const candidate of candidates) {
252
- if (!candidate || candidate === '(unknown)') continue;
253
- try {
254
- if (fs.statSync(candidate).isDirectory()) return candidate;
255
- } catch {
256
- // Try the next fallback.
257
- }
258
- }
259
- return HOME;
260
- }
261
-
262
- function shellQuote(value) {
263
- return `'${String(value).replace(/'/g, "'\\''")}'`;
264
- }
265
-
266
- function commandShell() {
267
- const shell = process.env.SHELL || '/bin/sh';
268
- try {
269
- fs.accessSync(shell, fs.constants.X_OK);
270
- return shell;
271
- } catch {
272
- return '/bin/sh';
273
- }
274
- }
275
-
276
- function codexCommand(command, session, args = [], inherit = false) {
277
- const executable = resolveCodexBin();
278
- const argv = [executable, command, session.id, ...args];
279
- const shellCommand = `exec ${argv.map(shellQuote).join(' ')}`;
280
- const cwd = usableCwd(session.cwd);
281
- const shell = commandShell();
282
- if (inherit) {
283
- const child = spawn(shell, ['-lc', shellCommand], { stdio: 'inherit', cwd, env: process.env });
284
- child.on('error', (err) => {
285
- console.error(`error: failed to start codex: ${err.message}`);
286
- process.exit(1);
287
- });
288
- child.on('exit', (code, signal) => {
289
- if (signal) process.kill(process.pid, signal);
290
- process.exit(code || 0);
291
- });
292
- return;
293
- }
294
- const result = spawnSync(shell, ['-lc', shellCommand], { stdio: 'inherit', cwd, env: process.env });
295
- if (result.error) throw new Error(`failed to start codex: ${result.error.message}`);
296
- const status = result.status || 0;
297
- process.exitCode = status;
298
- return status;
299
- }
4
+ const {
5
+ deleteSessionFile,
6
+ listSessions,
7
+ resolveSession,
8
+ updateMetadata,
9
+ } = require('./model/session-store');
10
+ const {
11
+ printDoctor,
12
+ printList,
13
+ printShow,
14
+ usage,
15
+ } = require('./cli-output');
16
+ const {
17
+ runCodexCommand,
18
+ runNewCodexSession,
19
+ usableCwd,
20
+ } = require('./services/codex-runner');
21
+ const { runWorkbench } = require('./ui/workbench');
22
+ const { createChildDirectory, listDirectories } = require('./model/directories');
300
23
 
301
24
  function parseFlags(args) {
302
25
  const out = { _: [] };
@@ -305,6 +28,7 @@ function parseFlags(args) {
305
28
  if (arg === '--json') out.json = true;
306
29
  else if (arg === '--all') out.all = true;
307
30
  else if (arg === '--force') out.force = true;
31
+ else if (arg === '--file') out.file = true;
308
32
  else if (arg === '--cwd') {
309
33
  if (i + 1 >= args.length) throw new Error('--cwd requires a directory.');
310
34
  out.cwd = args[++i];
@@ -314,450 +38,63 @@ function parseFlags(args) {
314
38
  return out;
315
39
  }
316
40
 
317
- async function ui() {
318
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
319
- return printList(listSessions());
320
- }
321
-
322
- let sessions = [];
323
- let groups = [];
324
- let groupIndex = 0;
325
- let selected = 0;
326
- let message = '';
327
- let syncingList = false;
328
-
329
- const screen = blessed.screen({
330
- smartCSR: true,
331
- fullUnicode: true,
332
- title: 'Codex Workbench',
333
- });
334
-
335
- const header = blessed.box({
336
- parent: screen,
337
- top: 0,
338
- left: 0,
339
- right: 0,
340
- height: 3,
341
- padding: { left: 1, right: 1 },
342
- style: { fg: 'white', bg: 'blue' },
343
- content: 'Codex Workbench',
344
- });
345
-
346
- const groupsBar = blessed.box({
347
- parent: screen,
348
- label: ' Projects ',
349
- top: 3,
350
- left: 0,
351
- right: 0,
352
- height: 3,
353
- border: 'line',
354
- padding: { left: 1, right: 1 },
355
- tags: true,
356
- parseTags: true,
357
- style: {
358
- border: { fg: 'green' },
359
- fg: 'white',
360
- },
361
- });
362
-
363
- const sessionsList = blessed.list({
364
- parent: screen,
365
- label: ' Sessions ',
366
- top: 6,
367
- left: 0,
368
- right: 0,
369
- height: '40%',
370
- border: 'line',
371
- mouse: true,
372
- keys: true,
373
- vi: false,
374
- scrollbar: { ch: ' ', track: { bg: 'black' }, style: { bg: 'cyan' } },
375
- style: {
376
- border: { fg: 'cyan' },
377
- selected: { fg: 'black', bg: 'cyan', bold: true },
378
- item: { fg: 'white' },
379
- },
380
- });
381
-
382
- const detailBox = blessed.log({
383
- parent: screen,
384
- label: ' Details ',
385
- top: '50%',
386
- left: 0,
387
- right: 0,
388
- bottom: 3,
389
- border: 'line',
390
- padding: { left: 1, right: 1 },
391
- scrollable: true,
392
- mouse: true,
393
- keys: true,
394
- vi: true,
395
- alwaysScroll: true,
396
- tags: false,
397
- parseTags: false,
398
- scrollbar: { ch: ' ', track: { bg: 'black' }, style: { bg: 'cyan' } },
399
- style: { border: { fg: 'cyan' }, fg: 'white' },
400
- });
401
-
402
- const status = blessed.box({
403
- parent: screen,
404
- left: 0,
405
- right: 0,
406
- bottom: 0,
407
- height: 3,
408
- padding: { left: 1, right: 1 },
409
- style: { fg: 'white', bg: 'black' },
410
- });
411
-
412
- const prompt = blessed.prompt({
413
- parent: screen,
414
- border: 'line',
415
- height: 8,
416
- width: '70%',
417
- top: 'center',
418
- left: 'center',
419
- padding: { left: 1, right: 1 },
420
- style: { border: { fg: 'yellow' }, fg: 'white', bg: 'black' },
421
- });
422
-
423
- const question = blessed.question({
424
- parent: screen,
425
- border: 'line',
426
- height: 6,
427
- width: '70%',
428
- top: 'center',
429
- left: 'center',
430
- padding: { left: 1, right: 1 },
431
- style: { border: { fg: 'red' }, fg: 'white', bg: 'black' },
432
- });
433
-
434
- const currentSessions = () => {
435
- const group = groups[groupIndex];
436
- return group === 'All' ? sessions : sessions.filter((s) => s.cwd === group);
437
- };
438
-
439
- const selectedSession = () => currentSessions()[selected] || null;
440
-
441
- const groupLabel = (group) => {
442
- if (group === 'All') return `All (${sessions.length})`;
443
- const count = sessions.filter((s) => s.cwd === group).length;
444
- return `${path.basename(group) || group} (${count})`;
445
- };
446
-
447
- const tagText = (text) => String(text).replace(/[{}]/g, '');
448
-
449
- const groupsContent = () => {
450
- if (!groups.length) return '';
451
- const width = Math.max(20, (screen.width || 80) - 4);
452
- const labels = groups.map((group, index) => {
453
- const max = index === groupIndex ? 34 : 24;
454
- return tagText(truncate(groupLabel(group), max));
455
- });
456
- const chipWidth = (index) => labels[index].length + 2;
457
- let start = groupIndex;
458
- let end = groupIndex;
459
- let used = chipWidth(groupIndex);
460
-
461
- while (start > 0 || end < groups.length - 1) {
462
- const reserve = (start > 0 ? 4 : 0) + (end < groups.length - 1 ? 4 : 0);
463
- const leftCost = start > 0 ? chipWidth(start - 1) + 2 : Infinity;
464
- const rightCost = end < groups.length - 1 ? chipWidth(end + 1) + 2 : Infinity;
465
- const preferLeft = groupIndex - start <= end - groupIndex;
466
- const firstCost = preferLeft ? leftCost : rightCost;
467
- const secondCost = preferLeft ? rightCost : leftCost;
468
-
469
- if (used + firstCost + reserve <= width) {
470
- if (preferLeft) start -= 1;
471
- else end += 1;
472
- used += firstCost;
473
- } else if (used + secondCost + reserve <= width) {
474
- if (preferLeft) end += 1;
475
- else start -= 1;
476
- used += secondCost;
477
- } else {
478
- break;
479
- }
480
- }
481
-
482
- const parts = [];
483
- if (start > 0) parts.push('...');
484
- for (let index = start; index <= end; index += 1) {
485
- const label = ` ${labels[index]} `;
486
- parts.push(index === groupIndex ? `{black-fg}{cyan-bg}{bold}${label}{/bold}{/cyan-bg}{/black-fg}` : label);
487
- }
488
- if (end < groups.length - 1) parts.push('...');
489
- return parts.join(' ');
490
- };
491
-
492
- const sessionLabel = (session) => {
493
- const flags = [
494
- session.name ? 'renamed' : '',
495
- session.note ? 'note' : '',
496
- ].filter(Boolean).join(',');
497
- const title = session.name || session.first || session.last || '(no prompt)';
498
- const flagText = flags ? `[${flags}]` : '';
499
- return `${shortId(session.id)} ${String(session.turns).padStart(2)}t ${truncate(localTime(session.updatedAt), 18)} ${flagText} ${truncate(title, 90)}`;
500
- };
501
-
502
- const detailContent = (session) => {
503
- if (!session) return 'No sessions in this project.';
504
- const title = session.name || session.first || session.last || '(no prompt)';
505
- return [
506
- title,
507
- '',
508
- `id: ${session.id}`,
509
- `cwd: ${session.cwd}`,
510
- `started: ${localTime(session.startedAt)}`,
511
- `updated: ${localTime(session.updatedAt)}`,
512
- `turns: ${session.turns}`,
513
- session.note ? `note: ${session.note}` : '',
514
- '',
515
- `last user: ${session.last || session.first || ''}`,
516
- '',
517
- `last assistant: ${session.lastAssistant || ''}`,
518
- ].filter((line) => line !== '').join('\n');
519
- };
520
-
521
- const setMessage = (text, isError = false) => {
522
- message = text || 'Ready';
523
- status.style.fg = isError ? 'red' : 'white';
524
- };
525
-
526
- const promptOpen = () => prompt.visible || question.visible;
527
-
528
- const reload = () => {
529
- sessions = listSessions().filter((s) => !s.archived && !s.hidden);
530
- groups = ['All', ...new Set(sessions.map((s) => s.cwd))];
531
- if (groupIndex >= groups.length) groupIndex = Math.max(0, groups.length - 1);
532
- const visible = currentSessions();
533
- if (selected >= visible.length) selected = Math.max(0, visible.length - 1);
534
- };
535
-
536
- const syncList = () => {
537
- const visible = currentSessions();
538
- const listRows = Math.max(1, (screen.height || 24) - 11);
539
- const items = visible.length ? visible.map(sessionLabel) : ['No sessions in this project.'];
540
- while (items.length < listRows) items.push('');
541
- syncingList = true;
542
- sessionsList.clearItems();
543
- sessionsList.setItems(items);
544
- selected = Math.min(selected, Math.max(0, visible.length - 1));
545
- sessionsList.childBase = 0;
546
- sessionsList.childOffset = 0;
547
- sessionsList.select(selected);
548
- sessionsList.scrollTo(0);
549
- syncingList = false;
550
- };
551
-
552
- const render = () => {
553
- const visible = currentSessions();
554
- header.setContent(` Codex Workbench\n ${visible.length}/${sessions.length} visible ${groups[groupIndex] === 'All' ? 'All projects' : groups[groupIndex]}`);
555
- groupsBar.setContent(groupsContent());
556
- detailBox.setLabel(' Details ');
557
- detailBox.setContent(detailContent(selectedSession()));
558
- status.setContent(`${message || 'Ready'}\nEnter/r resume tab focus f fork v view n rename o note a archive d delete q quit`);
559
- screen.render();
560
- };
561
-
562
- const askInput = (label, initial = '') => new Promise((resolve) => {
563
- prompt.input(label, initial, (err, value) => resolve(err ? null : value));
564
- });
565
-
566
- const askConfirm = (label) => new Promise((resolve) => {
567
- question.ask(label, (err, answer) => resolve(!err && Boolean(answer)));
568
- });
569
-
570
- const leaveScreen = () => {
571
- screen.destroy();
572
- };
573
-
574
- const refreshAfterAction = (text, isError = false) => {
575
- setMessage(text, isError);
576
- reload();
577
- syncList();
578
- render();
579
- };
580
-
581
- const switchGroup = (offset) => {
582
- if (!groups.length) return;
583
- groupIndex = Math.max(0, Math.min(groups.length - 1, groupIndex + offset));
584
- selected = 0;
585
- syncList();
586
- render();
587
- };
588
-
589
- const runCodexAndReturn = (command, session, args = [], doneText = `${command} finished.`) => {
590
- screen.leave();
591
- let status = 0;
592
- try {
593
- status = codexCommand(command, session, args);
594
- } finally {
595
- screen.enter();
596
- }
597
- if (status === 0) refreshAfterAction(doneText);
598
- else refreshAfterAction(`${command} exited with code ${status}.`, true);
599
- return status;
600
- };
601
-
602
- const runAction = async (action) => {
603
- if (promptOpen()) return;
604
- const session = selectedSession();
605
- if (!session) return;
606
- try {
607
- await action(session);
608
- } catch (err) {
609
- setMessage(`error: ${err.message}`, true);
610
- render();
611
- }
612
- };
613
-
614
- reload();
615
- setMessage('Ready');
616
- syncList();
617
-
618
- sessionsList.on('select item', (_item, index) => {
619
- if (syncingList) return;
620
- const visible = currentSessions();
621
- if (index >= visible.length) {
622
- selected = Math.max(0, visible.length - 1);
623
- sessionsList.select(selected);
624
- return;
625
- }
626
- selected = Math.min(index, Math.max(0, visible.length - 1));
627
- detailBox.setContent(detailContent(selectedSession()));
628
- screen.render();
629
- });
630
-
631
- sessionsList.on('select', () => runAction((session) => {
632
- runCodexAndReturn('resume', session);
633
- }));
634
-
635
- sessionsList.key(['j'], () => {
636
- if (promptOpen()) return;
637
- sessionsList.down();
638
- screen.render();
639
- });
640
-
641
- sessionsList.key(['k'], () => {
642
- if (promptOpen()) return;
643
- sessionsList.up();
644
- screen.render();
645
- });
646
-
647
- sessionsList.key(['left', 'h'], () => {
648
- if (promptOpen()) return;
649
- switchGroup(-1);
650
- });
651
-
652
- sessionsList.key(['right', 'l'], () => {
653
- if (promptOpen()) return;
654
- switchGroup(1);
655
- });
656
-
657
- detailBox.key(['left', 'h'], () => {
658
- if (promptOpen()) return;
659
- switchGroup(-1);
660
- });
661
-
662
- detailBox.key(['right', 'l'], () => {
663
- if (promptOpen()) return;
664
- switchGroup(1);
665
- });
666
-
667
- screen.key(['tab'], () => {
668
- if (promptOpen()) return;
669
- if (screen.focused === detailBox) sessionsList.focus();
670
- else detailBox.focus();
671
- screen.render();
672
- });
673
-
674
- screen.key(['q', 'escape', 'C-c'], () => {
675
- if (promptOpen()) return;
676
- leaveScreen();
677
- process.exit(0);
678
- });
679
-
680
- screen.key(['r'], () => runAction((session) => {
681
- runCodexAndReturn('resume', session);
682
- }));
683
-
684
- screen.key(['f'], () => runAction((session) => {
685
- runCodexAndReturn('fork', session);
686
- }));
687
-
688
- screen.key(['v'], () => runAction((session) => {
689
- leaveScreen();
690
- printShow(session);
691
- process.exit(0);
692
- }));
693
-
694
- screen.key(['n'], () => runAction(async (session) => {
695
- const name = await askInput('Name', session.name || '');
696
- if (name === null) return render();
697
- updateMetadata(session, { name });
698
- refreshAfterAction('Renamed.');
699
- }));
700
-
701
- screen.key(['o'], () => runAction(async (session) => {
702
- const note = await askInput('Note', session.note || '');
703
- if (note === null) return render();
704
- updateMetadata(session, { note });
705
- refreshAfterAction('Note saved.');
706
- }));
707
-
708
- screen.key(['a'], () => runAction((session) => {
709
- runCodexAndReturn('archive', session, [], `Archived ${shortId(session.id)}.`);
710
- }));
711
-
712
- screen.key(['d'], () => runAction(async (session) => {
713
- const confirmed = await askConfirm(`Delete ${shortId(session.id)}? Enter/y to confirm, n/Esc to cancel`);
714
- if (!confirmed) {
715
- setMessage('Delete cancelled.');
716
- return render();
717
- }
718
- const status = runCodexAndReturn('delete', session, ['--force'], `Deleted ${shortId(session.id)}.`);
719
- if (status !== 0) {
720
- const hide = await askConfirm(`Codex could not delete ${shortId(session.id)}. Hide it from workbench?`);
721
- if (hide) {
722
- updateMetadata(session, { hidden: true });
723
- refreshAfterAction(`Hidden ${shortId(session.id)}.`);
724
- }
725
- }
726
- }));
727
-
728
- sessionsList.focus();
729
- render();
730
-
731
- return new Promise(() => {});
732
- }
733
-
734
41
  async function main() {
735
42
  const [cmd = 'ui', ...rest] = process.argv.slice(2);
736
43
  if (cmd === '-h' || cmd === '--help' || cmd === 'help') return usage();
737
44
 
738
45
  const flags = parseFlags(rest);
739
46
  if (cmd === 'doctor') return printDoctor();
47
+ if (cmd === 'dirs') {
48
+ const payload = listDirectories(flags.cwd || process.cwd(), usableCwd);
49
+ if (flags.json) console.log(JSON.stringify(payload, null, 2));
50
+ else {
51
+ console.log(payload.cwd);
52
+ for (const entry of payload.entries) console.log(entry.path);
53
+ }
54
+ return undefined;
55
+ }
56
+ if (cmd === 'mkdir') {
57
+ const target = createChildDirectory(usableCwd(flags.cwd || process.cwd()), flags._[0] || '');
58
+ if (flags.json) console.log(JSON.stringify({ path: target }, null, 2));
59
+ else console.log(target);
60
+ return undefined;
61
+ }
740
62
 
741
63
  const sessions = listSessions();
742
64
 
743
- if (cmd === 'ui') return ui();
65
+ if (cmd === 'ui') return runWorkbench();
744
66
  if (cmd === 'list' || cmd === 'ls') return printList(sessions, flags);
745
67
  if (cmd === 'show') return printShow(resolveSession(flags._[0], sessions));
746
68
  if (cmd === 'rename') return updateMetadata(resolveSession(flags._[0], sessions), { name: flags._.slice(1).join(' ') });
747
69
  if (cmd === 'note') return updateMetadata(resolveSession(flags._[0], sessions), { note: flags._.slice(1).join(' ') });
748
- if (cmd === 'resume') return codexCommand('resume', resolveSession(flags._[0], sessions), flags._.slice(1), true);
749
- if (cmd === 'fork') return codexCommand('fork', resolveSession(flags._[0], sessions), [], true);
750
- if (cmd === 'archive') return codexCommand('archive', resolveSession(flags._[0], sessions));
751
- if (cmd === 'unarchive') return codexCommand('unarchive', resolveSession(flags._[0], sessions));
70
+ if (cmd === 'new' || cmd === 'start') return runNewCodexSession(flags.cwd || process.cwd(), flags._, true);
71
+ if (cmd === 'resume') return runCodexCommand('resume', resolveSession(flags._[0], sessions), flags._.slice(1), true);
72
+ if (cmd === 'fork') return runCodexCommand('fork', resolveSession(flags._[0], sessions), [], true);
73
+ if (cmd === 'archive') return runCodexCommand('archive', resolveSession(flags._[0], sessions));
74
+ if (cmd === 'unarchive') return runCodexCommand('unarchive', resolveSession(flags._[0], sessions));
752
75
  if (cmd === 'hide') return updateMetadata(resolveSession(flags._[0], sessions), { hidden: true });
753
76
  if (cmd === 'unhide') return updateMetadata(resolveSession(flags._[0], sessions), { hidden: false });
754
- if (cmd === 'delete') return codexCommand('delete', resolveSession(flags._[0], sessions), flags.force ? ['--force'] : []);
77
+ if (cmd === 'delete') {
78
+ const session = resolveSession(flags._[0], sessions);
79
+ if (flags.file) return deleteSessionFile(session);
80
+ return runCodexCommand('delete', session, flags.force ? ['--force'] : []);
81
+ }
755
82
 
756
83
  usage();
757
84
  process.exitCode = 2;
758
85
  }
759
86
 
760
- main().catch((err) => {
761
- console.error(`error: ${err.message}`);
762
- process.exit(1);
763
- });
87
+ function run() {
88
+ return main().catch((err) => {
89
+ console.error(`error: ${err.message}`);
90
+ process.exit(1);
91
+ });
92
+ }
93
+
94
+ if (require.main === module) run();
95
+
96
+ module.exports = {
97
+ main,
98
+ parseFlags,
99
+ run,
100
+ };