agentpen-cli 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,289 @@
1
+ // Share a Claude Code session that is already running. Agentpen did not start
2
+ // it, so there is no terminal to stream: instead the conversation Claude Code
3
+ // writes to disk is followed and shown to the team as a conversation.
4
+ // Teammates watch and chat; nothing can be typed into the host's terminal.
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { execFileSync, spawn } from 'node:child_process';
9
+ import { fileURLToPath } from 'node:url';
10
+ import WebSocket from 'ws';
11
+ import { collectSecrets } from './redact.js';
12
+ import { claudeProjectDir } from './handoff.js';
13
+
14
+ const POLL_MS = Number(process.env.AGENTPEN_SHARE_POLL_MS) || 700;
15
+ const IDLE_MS = Number(process.env.AGENTPEN_SHARE_IDLE_MS) || 30 * 60_000;
16
+ // a turn with no new output for this long is treated as waiting, not working
17
+ const STALE_MS = Number(process.env.AGENTPEN_SHARE_STALE_MS) || 3 * 60_000;
18
+ const MAX_TURNS = 200;
19
+ const HOME = () => process.env.AGENTPEN_HOME || path.join(os.homedir(), '.agentpen');
20
+ const stateFile = (id) => path.join(HOME(), 'shares', `${id}.json`);
21
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
22
+ const tail = (s, n) => (s.length > n ? '…' + s.slice(-n) : s);
23
+
24
+ // ---- finding the conversation ----------------------------------------------
25
+
26
+ const newest = (dir) => {
27
+ try {
28
+ return fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')).map((f) => ({ f: path.join(dir, f), m: fs.statSync(path.join(dir, f)).mtimeMs })).sort((a, b) => b.m - a.m)[0]?.f || null;
29
+ } catch { return null; }
30
+ };
31
+
32
+ export function findConversation({ cwd, id }) {
33
+ const dirs = [claudeProjectDir(cwd)];
34
+ try { dirs.push(claudeProjectDir(execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim())); } catch {}
35
+ if (id) {
36
+ if (!/^[\w-]{6,80}$/.test(id)) return null;
37
+ const root = path.dirname(dirs[0]);
38
+ let all = [];
39
+ try { all = fs.readdirSync(root).map((d) => path.join(root, d)); } catch {}
40
+ return [...dirs, ...all].map((d) => path.join(d, `${id}.jsonl`)).find((f) => fs.existsSync(f)) || null;
41
+ }
42
+ for (const d of dirs) { const f = newest(d); if (f) return f; }
43
+ return null;
44
+ }
45
+
46
+ // ---- reading it -------------------------------------------------------------
47
+
48
+ const rel = (p, cwd) => { const r = path.relative(cwd || '/', String(p || '')); return r && !r.startsWith('..') ? r : String(p || ''); };
49
+
50
+ function toolLabel(name, input = {}, cwd) {
51
+ if (name === 'Bash') return String(input.command || 'command');
52
+ if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit'].includes(name)) return `Edited ${rel(input.file_path || input.notebook_path, cwd)}`;
53
+ if (name === 'Read') return `Read ${rel(input.file_path, cwd)}`;
54
+ if (name === 'Grep' || name === 'Glob') return `Search: ${input.pattern || ''}`;
55
+ if (name === 'Task' || name === 'Agent') return `Subagent: ${input.description || ''}`;
56
+ if (name === 'WebFetch') return `Fetch ${input.url || ''}`;
57
+ if (name === 'WebSearch') return `Web search: ${input.query || ''}`;
58
+ const mcp = /^mcp__(.+?)__(.+)$/.exec(name);
59
+ return mcp ? `${mcp[1]}.${mcp[2]}` : name;
60
+ }
61
+
62
+ const blockText = (content) => (typeof content === 'string' ? content : Array.isArray(content) ? content.filter((b) => b?.type === 'text').map((b) => b.text).join('\n') : '');
63
+ // what Claude Code adds around a prompt (command echoes, reminders) is not something the person typed
64
+ const NOT_TYPED = /^\s*<(local-command|command-|system-reminder|task-notification|bash-|user-prompt-submit-hook)/;
65
+
66
+ /** Follows one conversation file. read() takes in whatever was appended and returns the conversation so far. */
67
+ export function follow(file, mask) {
68
+ let offset = 0;
69
+ let rest = '';
70
+ let title = '';
71
+ let cwd = '';
72
+ let branch = '';
73
+ const turns = [];
74
+ const tools = new Map(); // tool call id -> its item
75
+ let turn = null;
76
+ const open = (id) => { turn = { id, status: 'inProgress', items: [] }; turns.push(turn); };
77
+
78
+ const take = (e) => {
79
+ if (e.type === 'ai-title' && e.aiTitle) { title = String(e.aiTitle); return; }
80
+ if (e.isSidechain || e.isMeta || !e.message) return;
81
+ if (e.cwd) cwd = e.cwd;
82
+ if (e.gitBranch) branch = e.gitBranch;
83
+ const content = e.message.content;
84
+ if (e.type === 'user') {
85
+ for (const b of Array.isArray(content) ? content : []) {
86
+ if (b?.type !== 'tool_result') continue;
87
+ const it = tools.get(b.tool_use_id);
88
+ if (!it) continue;
89
+ it.status = b.is_error ? 'failed' : 'completed';
90
+ if (it.shell) it.detail = mask(tail(blockText(b.content), 3000)) || undefined;
91
+ }
92
+ const text = blockText(content).trim();
93
+ if (!text || NOT_TYPED.test(text)) return;
94
+ if (text.startsWith('[Request interrupted')) { if (turn) turn.status = 'interrupted'; return; }
95
+ if (turn?.status === 'inProgress') turn.status = 'completed';
96
+ open(e.uuid || `u${turns.length}`);
97
+ turn.items.push({ id: turn.id, role: 'user', text: mask(text) });
98
+ if (!title) title = text.split('\n')[0].slice(0, 80);
99
+ } else if (e.type === 'assistant') {
100
+ if (!turn) open('start');
101
+ (Array.isArray(content) ? content : []).forEach((b, i) => {
102
+ if (b?.type === 'text' && b.text?.trim()) turn.items.push({ id: `${e.uuid}:${i}`, role: 'assistant', text: mask(b.text) });
103
+ else if (b?.type === 'tool_use') {
104
+ const it = { id: String(b.id), role: 'tool', text: mask(toolLabel(b.name, b.input, cwd)), status: 'inProgress', shell: b.name === 'Bash' };
105
+ tools.set(it.id, it);
106
+ turn.items.push(it);
107
+ }
108
+ });
109
+ if (turn.status !== 'interrupted') turn.status = e.message.stop_reason === 'end_turn' ? 'completed' : 'inProgress';
110
+ }
111
+ };
112
+
113
+ return {
114
+ read() {
115
+ const size = fs.statSync(file).size;
116
+ if (size < offset) { offset = 0; rest = ''; } // rewritten: start over rather than read from the middle of a line
117
+ if (size > offset) {
118
+ const fd = fs.openSync(file, 'r');
119
+ try {
120
+ const buf = Buffer.alloc(size - offset);
121
+ fs.readSync(fd, buf, 0, buf.length, offset);
122
+ offset = size;
123
+ const lines = (rest + buf.toString('utf8')).split('\n');
124
+ rest = lines.pop();
125
+ for (const l of lines) { if (!l.trim()) continue; try { take(JSON.parse(l)); } catch {} }
126
+ } finally { fs.closeSync(fd); }
127
+ }
128
+ const quiet = Date.now() - fs.statSync(file).mtimeMs;
129
+ const shown = turns.slice(-MAX_TURNS).map((t) => ({ id: t.id, status: t.status, items: t.items.map(({ shell, ...it }) => it) }));
130
+ return { title: title || 'Claude Code session', cwd, branch, turns: shown, quiet, status: turn?.status === 'inProgress' && quiet < STALE_MS ? 'working' : 'idle' };
131
+ },
132
+ };
133
+ }
134
+
135
+ // ---- sharing it -------------------------------------------------------------
136
+
137
+ /** Runs until the session is over. Calls onReady once the team can see it. */
138
+ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, log = () => {} }) {
139
+ const first = follow(file, (s) => s).read();
140
+ const cwd = first.cwd || process.cwd();
141
+ const secrets = opts.shareSecrets ? [] : collectSecrets(cwd).sort((a, b) => b.length - a.length);
142
+ const mask = (s) => { for (const v of secrets) s = s.split(v).join('••••••'); return s; };
143
+ const conv = follow(file, mask);
144
+ let snap = conv.read();
145
+ const hello = {
146
+ t: 'hello', kind: 'thread', workspace: opts.workspace, title: opts.title || snap.title, agent: 'claude',
147
+ project: path.basename(cwd), branch: snap.branch || '', access: opts.access === 'private' ? 'private' : 'view',
148
+ };
149
+
150
+ let ws = null;
151
+ let session = null;
152
+ let stopping = false;
153
+ let retry = 0;
154
+ let sent = new Map();
155
+ let sentMeta = '';
156
+ const push = () => {
157
+ if (ws?.readyState !== 1 || !session) return;
158
+ const changed = snap.turns.filter((t) => sent.get(t.id) !== JSON.stringify(t));
159
+ const meta = JSON.stringify([snap.title, snap.status, snap.turns.map((t) => t.id)]);
160
+ if (!changed.length && meta === sentMeta) return;
161
+ for (let i = 0; i < Math.max(1, changed.length); i += 40) {
162
+ ws.send(JSON.stringify({ t: 'thread', title: opts.title || snap.title, status: snap.status, turns: changed.slice(i, i + 40), order: i + 40 >= changed.length ? snap.turns.map((t) => t.id) : undefined }));
163
+ }
164
+ for (const t of changed) sent.set(t.id, JSON.stringify(t));
165
+ sentMeta = meta;
166
+ };
167
+ const stop = (reason) => new Promise((resolve) => {
168
+ if (stopping) return resolve();
169
+ stopping = true;
170
+ const done = () => { onEnd?.(reason); resolve(); };
171
+ if (ws?.readyState === 1) { ws.send(JSON.stringify({ t: 'exit' }), () => ws.close()); setTimeout(done, 400); } else done();
172
+ });
173
+ onStoppable?.(stop);
174
+
175
+ await new Promise((resolve, reject) => {
176
+ const connect = () => {
177
+ ws = new WebSocket(cfg.server.replace(/^http/, 'ws') + '/ws/host', { headers: { authorization: `Bearer ${cfg.token}` } });
178
+ ws.on('open', () => ws.send(JSON.stringify(session ? { t: 'hello', resume: { id: session.id, key: session.key } } : hello)));
179
+ ws.on('message', (data, isBinary) => {
180
+ if (isBinary) return;
181
+ let m;
182
+ try { m = JSON.parse(data); } catch { return; }
183
+ if (m.t === 'ready') {
184
+ const fresh = !session;
185
+ session = { ...session, ...m };
186
+ retry = 0;
187
+ if (!m.resumed) { sent = new Map(); sentMeta = ''; }
188
+ push();
189
+ if (fresh) onReady?.(session);
190
+ resolve();
191
+ } else if (m.t === 'error') {
192
+ if (session && m.code === 'gone') session = null; // server restarted: start a fresh session
193
+ else if (!session) { stopping = true; reject(new Error(m.message)); }
194
+ } else if (m.t === 'prompt') ws.send(JSON.stringify({ t: 'prompt-result', rid: m.rid, ok: false })); // nothing can be typed into a terminal Agentpen did not start
195
+ else if (m.t === 'end') { stopping = true; onEnd?.(m.reason); }
196
+ });
197
+ ws.on('close', () => {
198
+ if (stopping) return;
199
+ if (!session && retry >= 3) { stopping = true; return reject(new Error(`cannot reach ${cfg.server}`)); }
200
+ setTimeout(connect, Math.min(8000, 500 * 2 ** retry++));
201
+ });
202
+ ws.on('error', () => {});
203
+ };
204
+ connect();
205
+ });
206
+
207
+ while (!stopping) {
208
+ await new Promise((r) => setTimeout(r, POLL_MS));
209
+ if (stopping) break;
210
+ if (opts.claudePid && !alive(opts.claudePid)) { log('Claude Code exited'); await stop('Claude Code exited'); break; }
211
+ try { snap = conv.read(); } catch { log('conversation file is gone'); await stop('conversation ended'); break; }
212
+ if (snap.quiet > IDLE_MS) { log('quiet for too long'); await stop('no activity'); break; }
213
+ push();
214
+ }
215
+ }
216
+
217
+ // ---- the command ------------------------------------------------------------
218
+
219
+ const readState = (id) => { try { return JSON.parse(fs.readFileSync(stateFile(id), 'utf8')); } catch { return null; } };
220
+ const allStates = () => {
221
+ try { return fs.readdirSync(path.dirname(stateFile('x'))).filter((f) => f.endsWith('.json')).map((f) => readState(f.slice(0, -5))).filter((s) => s && alive(s.pid)); } catch { return []; }
222
+ };
223
+
224
+ export function stopSharing(ui) {
225
+ const live = allStates();
226
+ if (!live.length) return ui.say('Nothing is being shared from this machine with `agentpen share`.');
227
+ for (const s of live) { try { process.kill(s.pid, 'SIGTERM'); } catch {} ui.say(`Stopped sharing “${s.title}”. ${ui.dim(s.url)}`); }
228
+ }
229
+
230
+ /** `agentpen share`: starts a background sharer for the running conversation, prints the link, and returns. */
231
+ export async function shareRunningClaude(cfg, opts, ui) {
232
+ const id = opts.session || process.env.CLAUDE_CODE_SESSION_ID;
233
+ const file = findConversation({ cwd: process.cwd(), id });
234
+ if (!file) ui.die(id ? `cannot find Claude Code conversation ${id} on this machine.` : 'no Claude Code conversation found for this folder. Run this from the folder where Claude Code is running, or from inside it with: ! agentpen share');
235
+ const convId = path.basename(file, '.jsonl');
236
+ const running = readState(convId);
237
+ if (running && alive(running.pid)) return ui.say(`Already sharing “${running.title}”: ${ui.accent(running.url)}`);
238
+
239
+ fs.mkdirSync(path.dirname(stateFile(convId)), { recursive: true, mode: 0o700 });
240
+ const logFd = fs.openSync(path.join(HOME(), 'share.log'), 'a');
241
+ const claudePid = Number(process.env.CLAUDE_PID) || 0;
242
+ const child = spawn(process.execPath, [fileURLToPath(new URL('./agentpen.js', import.meta.url)), 'share', '--run', file], {
243
+ detached: true, stdio: ['ignore', logFd, logFd, 'ipc'],
244
+ env: { ...process.env, AGENTPEN_SHARE_OPTS: JSON.stringify({ ...opts, claudePid }) },
245
+ });
246
+ const result = await new Promise((resolve) => {
247
+ const t = setTimeout(() => resolve({ error: `cannot reach ${cfg.server}` }), 20_000);
248
+ child.once('message', (m) => { clearTimeout(t); resolve(m); });
249
+ child.once('exit', () => { clearTimeout(t); resolve({ error: 'sharing stopped before it started. See ~/.agentpen/share.log' }); });
250
+ });
251
+ if (result.error) { try { child.kill(); } catch {} ui.die(result.error); }
252
+ child.disconnect();
253
+ child.unref();
254
+ ui.say();
255
+ ui.say(` ${ui.accent('●')} ${ui.bold(`Sharing “${result.title}”`)} ${ui.dim(`live in ${result.workspace}`)}`);
256
+ ui.say(` ${ui.accent(result.url)}`);
257
+ ui.say(ui.dim(` ${result.access === 'private' ? 'Only you can see it until you share it from that page.' : 'Teammates can watch the conversation and chat. They cannot type into this session.'}`));
258
+ ui.say(ui.dim(' It stops when Claude Code exits, or with: agentpen share stop\n'));
259
+ }
260
+
261
+ /** The background half, started by shareRunningClaude. */
262
+ export async function runShareChild(cfg, file) {
263
+ const opts = JSON.parse(process.env.AGENTPEN_SHARE_OPTS || '{}');
264
+ const convId = path.basename(file, '.jsonl');
265
+ const log = (m) => console.log(`${new Date().toISOString()} ${convId} ${m}`);
266
+ const cleanup = () => { try { if (readState(convId)?.pid === process.pid) fs.rmSync(stateFile(convId), { force: true }); } catch {} };
267
+ let stop = null;
268
+ const quit = () => (stop ? stop('stopped by host') : process.exit(0));
269
+ process.on('SIGTERM', quit);
270
+ process.on('SIGINT', quit);
271
+ try {
272
+ await runShare(cfg, file, opts, {
273
+ log,
274
+ onStoppable: (fn) => { stop = fn; },
275
+ onReady: (s) => {
276
+ const info = { pid: process.pid, title: opts.title || follow(file, (x) => x).read().title, url: s.url, workspace: s.workspace.name, access: s.access };
277
+ fs.writeFileSync(stateFile(convId), JSON.stringify(info), { mode: 0o600 });
278
+ log(`sharing at ${s.url}`);
279
+ if (process.connected) process.send(info);
280
+ },
281
+ onEnd: (reason) => { log(`ended: ${reason}`); cleanup(); setTimeout(() => process.exit(0), 500); },
282
+ });
283
+ } catch (e) {
284
+ log(`failed: ${e.message}`);
285
+ if (process.connected) process.send({ error: e.message });
286
+ cleanup();
287
+ process.exit(1);
288
+ }
289
+ }
@@ -0,0 +1,338 @@
1
+ // Share a conversation from the Codex desktop app. There is no terminal to
2
+ // mirror, so this bridges the app's own local control socket instead: it reads
3
+ // the chosen thread, streams it to the team, and queues teammates' prompts
4
+ // into it. Tool approvals are never answered from here; they stay in the app.
5
+ import fs from 'node:fs';
6
+ import net from 'node:net';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import readline from 'node:readline';
10
+ import { randomUUID } from 'node:crypto';
11
+ import WebSocket from 'ws';
12
+ import { collectSecrets } from './redact.js';
13
+
14
+ const TAG = /^\[(.{1,60}) via Agentpen\]\n/;
15
+
16
+ function socketPath(opts) {
17
+ const p = opts.socket || path.join(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), 'app-server-control', 'app-server-control.sock');
18
+ // Codex publishes a symlink to a short path; unix socket paths cannot be long.
19
+ try { return fs.realpathSync(p); } catch { return null; }
20
+ }
21
+
22
+ class Codex {
23
+ constructor(sock) {
24
+ this.sock = sock;
25
+ this.pending = new Map();
26
+ this.nextId = 1;
27
+ }
28
+
29
+ async connect() {
30
+ this.ws = new WebSocket('ws://localhost', { createConnection: () => net.connect(this.sock), handshakeTimeout: 8000, maxPayload: 64 * 1024 * 1024 });
31
+ await new Promise((resolve, reject) => { this.ws.once('open', resolve); this.ws.once('error', reject); });
32
+ this.ws.on('error', () => {});
33
+ this.ws.on('close', () => this.fail(new Error('Codex connection closed')));
34
+ this.ws.on('message', (data) => {
35
+ let m;
36
+ try { m = JSON.parse(data); } catch { return; }
37
+ if (m.method) {
38
+ // a request from Codex (for example a tool approval): decline to handle it
39
+ if (m.id !== undefined) this.ws.send(JSON.stringify({ id: m.id, error: { code: -32601, message: 'Handled in the Codex app' } }));
40
+ return;
41
+ }
42
+ const p = this.pending.get(m.id);
43
+ if (!p) return;
44
+ this.pending.delete(m.id);
45
+ clearTimeout(p.timer);
46
+ if (m.error) p.reject(new Error(m.error.message)); else p.resolve(m.result);
47
+ });
48
+ await this.request('initialize', { clientInfo: { name: 'agentpen', version: '0.1.0' }, capabilities: { experimentalApi: true } });
49
+ this.ws.send(JSON.stringify({ method: 'initialized', params: {} }));
50
+ }
51
+
52
+ get open() { return this.ws?.readyState === 1; }
53
+
54
+ request(method, params = {}) {
55
+ if (!this.open) return Promise.reject(new Error('Codex connection closed'));
56
+ const id = this.nextId++;
57
+ return new Promise((resolve, reject) => {
58
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Codex did not answer ${method}`)); }, 20_000);
59
+ this.pending.set(id, { resolve, reject, timer });
60
+ this.ws.send(JSON.stringify({ id, method, params }));
61
+ });
62
+ }
63
+
64
+ fail(err) {
65
+ for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(err); }
66
+ this.pending.clear();
67
+ }
68
+
69
+ async readThread(threadId) {
70
+ try { return (await this.request('thread/read', { threadId, includeTurns: true })).thread; } catch (e) {
71
+ if (!this.open) throw e;
72
+ // a brand-new conversation has no turns to load yet
73
+ return { ...(await this.request('thread/read', { threadId })).thread, turns: [] };
74
+ }
75
+ }
76
+
77
+ // Prompts waiting for the app to pick them up; shown to the team as "queued".
78
+ async queued(threadId) {
79
+ try { return (await this.request('thread/queue/list', { threadId, limit: 20 })).data || []; } catch { return []; }
80
+ }
81
+ }
82
+
83
+ const tail = (s, n) => (s && s.length > n ? '…' + s.slice(-n) : s || '');
84
+
85
+ // Codex's thread -> the small transcript shape Agentpen shows. Reasoning and
86
+ // system instructions are left out on purpose.
87
+ export function transcript(thread, mask = (s) => s, queue = []) {
88
+ const turns = (thread.turns || []).slice(-300).map((turn) => ({
89
+ id: turn.id,
90
+ status: turn.status,
91
+ error: turn.error?.message ? mask(turn.error.message) : undefined,
92
+ items: (turn.items || []).flatMap((it) => {
93
+ if (it.type === 'userMessage') {
94
+ let text = (it.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n');
95
+ const by = TAG.exec(text)?.[1];
96
+ if (by) text = text.replace(TAG, '');
97
+ return [{ id: it.id, role: 'user', text: mask(text), by }];
98
+ }
99
+ if (it.type === 'agentMessage') return [{ id: it.id, role: 'assistant', text: mask(it.text || '') }];
100
+ if (it.type === 'plan') return [{ id: it.id, role: 'plan', text: mask(it.text || '') }];
101
+ if (it.type === 'commandExecution') return [{ id: it.id, role: 'tool', text: mask(it.command || ''), detail: mask(tail(it.aggregatedOutput, 3000)), status: it.status }];
102
+ if (it.type === 'fileChange') return [{ id: it.id, role: 'tool', text: `Edited ${(it.changes || []).map((c) => c.path).join(', ') || 'files'}`, status: it.status }];
103
+ if (it.type === 'mcpToolCall') return [{ id: it.id, role: 'tool', text: `${it.server}.${it.tool}`, status: it.status }];
104
+ if (it.type === 'webSearch') return [{ id: it.id, role: 'tool', text: `Web search${it.query ? `: ${mask(it.query)}` : ''}` }];
105
+ return [];
106
+ }),
107
+ }));
108
+ const waiting = queue.map((sub) => {
109
+ let text = (sub.input || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n');
110
+ const by = TAG.exec(text)?.[1];
111
+ if (by) text = text.replace(TAG, '');
112
+ return { id: sub.id, role: 'user', text: mask(text), by, status: 'queued' };
113
+ });
114
+ if (waiting.length) turns.push({ id: 'queued', status: 'completed', items: waiting });
115
+ const flags = thread.status?.activeFlags || [];
116
+ const busy = thread.status?.type === 'active' || turns.at(-1)?.status === 'inProgress';
117
+ return { title: thread.name || thread.preview?.split('\n')[0].slice(0, 80) || 'Codex conversation', turns, status: flags.length ? 'blocked' : busy ? 'working' : 'idle' };
118
+ }
119
+
120
+ async function pickThread(codex, opts, ui) {
121
+ if (opts.thread) return opts.thread;
122
+ const list = await codex.request('thread/list', { limit: 30, sortKey: 'updated_at', sortDirection: 'desc' });
123
+ const threads = list.data.filter((t) => !t.parentThreadId && !t.ephemeral).slice(0, 9);
124
+ if (!threads.length) ui.die('no Codex conversations found. Start one in the Codex app, then run this again.');
125
+ if (threads.length === 1 || opts.latest || !process.stdin.isTTY) return threads[0].id;
126
+ ui.say(`\n ${ui.bold('Which Codex conversation?')}`);
127
+ threads.forEach((t, i) => {
128
+ const name = (t.name || t.preview || 'Untitled').split('\n')[0].slice(0, 60);
129
+ ui.say(` ${ui.accent(String(i + 1))} ${name} ${ui.dim(path.basename(t.cwd || ''))}`);
130
+ });
131
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
132
+ const answer = await new Promise((r) => rl.question(` Number ${ui.dim('(Enter for 1)')}: `, r));
133
+ rl.close();
134
+ const n = answer.trim() === '' ? 1 : Number(answer);
135
+ if (!Number.isInteger(n) || n < 1 || n > threads.length) ui.die('that is not one of the listed conversations.');
136
+ return threads[n - 1].id;
137
+ }
138
+
139
+ // A connection to the Codex app that is reopened whenever it has dropped.
140
+ function codexLink(sock) {
141
+ let codex = null;
142
+ return { async get() { if (!codex?.open) { codex = new Codex(sock); await codex.connect(); } return codex; } };
143
+ }
144
+
145
+ /**
146
+ * Share one conversation. Throws if it cannot start. After that it keeps the
147
+ * team's copy up to date until stop() is called or the server ends the session.
148
+ */
149
+ async function shareThread(cfg, link, threadId, opts, ui, onEnd) {
150
+ let thread;
151
+ try { thread = await (await link.get()).readThread(threadId); } catch (e) { throw new Error(`could not read that conversation: ${e.message}`); }
152
+ // fail now, not on a teammate's first prompt, if this Codex cannot queue messages
153
+ try { await (await link.get()).request('thread/queue/list', { threadId, limit: 1 }); } catch { throw new Error('this version of Codex cannot accept queued prompts. Update the Codex app and try again.'); }
154
+
155
+ const secrets = opts.shareSecrets ? [] : collectSecrets(thread.cwd || process.cwd()).sort((a, b) => b.length - a.length);
156
+ const mask = (s) => { for (const v of secrets) s = s.split(v).join('••••••'); return s; };
157
+ const read = async () => { const c = await link.get(); return transcript(await c.readThread(threadId), mask, await c.queued(threadId)); };
158
+ let snap = await read();
159
+
160
+ const hello = {
161
+ t: 'hello', kind: 'thread', workspace: opts.workspace, title: opts.title || snap.title, agent: 'codex app',
162
+ project: path.basename(thread.cwd || ''), branch: thread.gitInfo?.branch || '', access: opts.access,
163
+ };
164
+
165
+ let ws = null;
166
+ let session = null;
167
+ let stopping = false;
168
+ let retry = 0;
169
+ let sent = new Map(); // turn id -> JSON last sent
170
+ let sentMeta = '';
171
+ let people = [];
172
+
173
+ const push = () => {
174
+ if (ws?.readyState !== 1 || !session) return;
175
+ const changed = snap.turns.filter((t) => sent.get(t.id) !== JSON.stringify(t));
176
+ const meta = JSON.stringify([snap.title, snap.status, snap.turns.map((t) => t.id)]);
177
+ if (!changed.length && meta === sentMeta) return;
178
+ // big histories go up in slices so no single frame is huge
179
+ for (let i = 0; i < Math.max(1, changed.length); i += 40) {
180
+ ws.send(JSON.stringify({ t: 'thread', title: opts.title || snap.title, status: snap.status, turns: changed.slice(i, i + 40), order: i + 40 >= changed.length ? snap.turns.map((t) => t.id) : undefined }));
181
+ }
182
+ for (const t of changed) sent.set(t.id, JSON.stringify(t));
183
+ sentMeta = meta;
184
+ };
185
+
186
+ const onPrompt = async (m) => {
187
+ let ok = true;
188
+ try {
189
+ await (await link.get()).request('thread/queue/add', {
190
+ threadId, clientUserMessageId: randomUUID(),
191
+ input: [{ type: 'text', text: `[${m.by} via Agentpen]\n${m.text}`, text_elements: [] }],
192
+ });
193
+ ui.say(` ${ui.dim('›')} ${m.by} queued a prompt`);
194
+ snap = await read();
195
+ push();
196
+ } catch { ok = false; ui.say(` ${ui.dim('›')} could not queue ${m.by}'s prompt (Codex did not confirm it)`); }
197
+ if (ws?.readyState === 1) ws.send(JSON.stringify({ t: 'prompt-result', rid: m.rid, ok }));
198
+ };
199
+
200
+ await new Promise((resolve, reject) => {
201
+ const connect = () => {
202
+ ws = new WebSocket(cfg.server.replace(/^http/, 'ws') + '/ws/host', { headers: { authorization: `Bearer ${cfg.token}` } });
203
+ ws.on('open', () => ws.send(JSON.stringify(session ? { t: 'hello', resume: { id: session.id, key: session.key } } : hello)));
204
+ ws.on('message', (data, isBinary) => {
205
+ if (isBinary) return;
206
+ let m;
207
+ try { m = JSON.parse(data); } catch { return; }
208
+ if (m.t === 'ready') {
209
+ session = { ...session, ...m };
210
+ retry = 0;
211
+ if (!m.resumed) { sent = new Map(); sentMeta = ''; }
212
+ push();
213
+ resolve();
214
+ } else if (m.t === 'error') {
215
+ if (session && m.code === 'gone') session = null; // server restarted: start a fresh session
216
+ else if (!session) { stopping = true; reject(new Error(m.message)); }
217
+ } else if (m.t === 'prompt') onPrompt(m);
218
+ else if (m.t === 'people') {
219
+ for (const p of m.people) if (!people.some((o) => o.name === p.name)) ui.say(` ${ui.dim('›')} ${p.name} joined “${snap.title}”`);
220
+ people = m.people;
221
+ } else if (m.t === 'end') { stopping = true; onEnd?.(m.reason); }
222
+ });
223
+ ws.on('close', () => {
224
+ if (stopping) return;
225
+ if (!session && retry >= 3 && !sentMeta) { stopping = true; return reject(new Error(`cannot reach ${cfg.server}`)); }
226
+ setTimeout(connect, Math.min(8000, 500 * 2 ** retry++));
227
+ });
228
+ ws.on('error', () => {});
229
+ };
230
+ connect();
231
+ });
232
+
233
+ (async () => {
234
+ let codexDown = false;
235
+ while (!stopping) {
236
+ await new Promise((r) => setTimeout(r, snap.status === 'idle' ? 1200 : 500));
237
+ if (stopping) return;
238
+ try {
239
+ snap = await read();
240
+ if (codexDown) { codexDown = false; ui.say(` ${ui.dim('›')} Codex is back`); }
241
+ push();
242
+ } catch {
243
+ if (!codexDown) { codexDown = true; ui.say(` ${ui.dim('›')} lost the Codex app, waiting for it to come back…`); }
244
+ await new Promise((r) => setTimeout(r, 2000));
245
+ }
246
+ }
247
+ })();
248
+
249
+ return {
250
+ get session() { return session; },
251
+ get title() { return snap.title; },
252
+ stop: () => new Promise((resolve) => {
253
+ if (stopping) return resolve();
254
+ stopping = true;
255
+ if (ws?.readyState === 1) { ws.send(JSON.stringify({ t: 'exit' }), () => ws.close()); setTimeout(resolve, 600); } else resolve();
256
+ }),
257
+ };
258
+ }
259
+
260
+ export async function shareCodexApp(cfg, opts, ui) {
261
+ const sock = socketPath(opts);
262
+ if (!sock) ui.die('cannot find the Codex app on this machine. Open the Codex app (or run `codex app-server daemon start`) and try again.');
263
+ const link = codexLink(sock);
264
+ let codex;
265
+ try { codex = await link.get(); } catch { ui.die('the Codex app is not answering. Make sure it is open and up to date, then try again.'); }
266
+ const threadId = await pickThread(codex, opts, ui);
267
+ let share;
268
+ try {
269
+ share = await shareThread(cfg, link, threadId, opts, ui, (reason) => { ui.say(`\n Sharing stopped (${reason}).`); process.exit(0); });
270
+ } catch (e) { ui.die(e.message); }
271
+
272
+ const session = share.session;
273
+ ui.say();
274
+ ui.say(` ${ui.accent('●')} ${ui.bold(`Sharing “${share.title}”`)} ${ui.dim(`live in ${session.workspace.name}`)}`);
275
+ ui.say(` ${ui.accent(session.url)}`);
276
+ ui.say(ui.dim(` Keep working in the Codex app. ${session.access === 'private' ? 'Only you can see this until you share it from that page.' : session.access === 'view' ? 'Teammates can watch.' : 'Teammates can watch, and their prompts are queued into this conversation under their names.'}`));
277
+ ui.say(ui.dim(' Approvals stay with you in the app. Ctrl-C stops sharing.\n'));
278
+
279
+ const stop = async () => { await share.stop(); ui.say(`\n ${ui.dim('Sharing stopped. Transcript:')} ${share.session?.url || ''}`); process.exit(0); };
280
+ process.on('SIGINT', stop);
281
+ process.on('SIGTERM', stop);
282
+ await new Promise(() => {}); // runs until stopped
283
+ }
284
+
285
+ /**
286
+ * Background mode: nobody types a command. Any Codex app conversation that is
287
+ * doing work inside a git repository is shared while it is active, and the
288
+ * share ends once it has been quiet for a while. Conversations outside a
289
+ * repository (general chat) are never shared.
290
+ */
291
+ export async function watchCodexApp(cfg, opts, ui, isPaused = () => false) {
292
+ const POLL = Number(process.env.AGENTPEN_WATCH_POLL_MS) || 4000;
293
+ const IDLE = Number(process.env.AGENTPEN_WATCH_IDLE_MS) || 20 * 60_000;
294
+ const FRESH = 90; // seconds since the last change that still count as "in use"
295
+ const shares = new Map(); // thread id -> { share, last }
296
+ const starting = new Set();
297
+ let link = null;
298
+ let stopped = false;
299
+
300
+ const stopAll = async () => { stopped = true; await Promise.all([...shares.values()].map((s) => s.share.stop())); process.exit(0); };
301
+ process.on('SIGINT', stopAll);
302
+ process.on('SIGTERM', stopAll);
303
+ ui.say(` ${ui.accent('●')} Watching the Codex app. Coding conversations are shared while they are active.`);
304
+
305
+ while (!stopped) {
306
+ try {
307
+ if (isPaused()) {
308
+ for (const [id, s] of shares) { await s.share.stop(); shares.delete(id); }
309
+ } else {
310
+ const sock = socketPath(opts);
311
+ if (!sock) throw new Error('Codex is not running');
312
+ link ||= codexLink(sock);
313
+ const list = await (await link.get()).request('thread/list', { limit: 20, sortKey: 'updated_at', sortDirection: 'desc' });
314
+ const nowS = Date.now() / 1000;
315
+ for (const t of list.data) {
316
+ if (t.parentThreadId || t.ephemeral) continue;
317
+ const active = t.status?.type === 'active' || nowS - (t.updatedAt || 0) < FRESH;
318
+ const s = shares.get(t.id);
319
+ if (s) { if (active) s.last = Date.now(); continue; }
320
+ const inRepo = !!(t.gitInfo && (t.gitInfo.branch || t.gitInfo.sha || t.gitInfo.originUrl));
321
+ if (!active || !inRepo || starting.has(t.id) || shares.size + starting.size >= 5) continue;
322
+ starting.add(t.id);
323
+ shareThread(cfg, link, t.id, opts, ui, () => shares.delete(t.id))
324
+ .then((share) => { shares.set(t.id, { share, last: Date.now() }); ui.say(` ${ui.dim('›')} sharing “${share.title}” ${ui.dim(share.session.url)}`); })
325
+ .catch(() => {})
326
+ .finally(() => starting.delete(t.id));
327
+ }
328
+ for (const [id, s] of shares) {
329
+ if (Date.now() - s.last < IDLE) continue;
330
+ ui.say(` ${ui.dim('›')} “${s.share.title}” has gone quiet; sharing stopped`);
331
+ await s.share.stop();
332
+ shares.delete(id);
333
+ }
334
+ }
335
+ } catch { link = null; } // Codex closed or not started yet: keep waiting
336
+ await new Promise((r) => setTimeout(r, POLL));
337
+ }
338
+ }