agentpen-cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,442 @@
1
+ #!/usr/bin/env node
2
+ // agentpen - run your coding agent as usual; your team sees it live.
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { execFileSync, spawn as spawnProc } from 'node:child_process';
7
+ import WebSocket from 'ws';
8
+ import { collectSecrets, makeRedactor } from './redact.js';
9
+ import { shareCodexApp, watchCodexApp } from './codex-app.js';
10
+ import { install, uninstall } from './install.js';
11
+ import { startCheckpoints, pickup } from './handoff.js';
12
+ import { randomUUID } from 'node:crypto';
13
+
14
+ // The hosted service address. Self-hosters: `agentpen login --server https://agentpen.acme.internal`.
15
+ const DEFAULT_SERVER = 'https://agentpen.app';
16
+ const CONFIG_DIR = process.env.AGENTPEN_HOME || path.join(os.homedir(), '.agentpen');
17
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
18
+
19
+ const dim = (s) => `\x1b[2m${s}\x1b[0m`;
20
+ const bold = (s) => `\x1b[1m${s}\x1b[0m`;
21
+ const accent = (s) => `\x1b[38;5;215m${s}\x1b[0m`;
22
+ const say = (s = '') => process.stderr.write(s + '\n');
23
+ const die = (s) => { say(`\x1b[31magentpen:\x1b[0m ${s}`); process.exit(1); };
24
+
25
+ function loadConfig() {
26
+ let c = {};
27
+ try { c = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); } catch {}
28
+ if (process.env.AGENTPEN_URL) c.server = process.env.AGENTPEN_URL;
29
+ if (process.env.AGENTPEN_TOKEN) c.token = process.env.AGENTPEN_TOKEN;
30
+ c.server = (c.server || DEFAULT_SERVER).replace(/\/$/, '');
31
+ return c;
32
+ }
33
+ function saveConfig(c) {
34
+ fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
35
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify({ server: c.server, token: c.token, user: c.user, paused: c.paused || undefined, defaultAccess: c.defaultAccess || undefined }, null, 2), { mode: 0o600 });
36
+ }
37
+
38
+ async function api(cfg, method, route, data) {
39
+ let r;
40
+ try {
41
+ r = await fetch(cfg.server + route, {
42
+ method,
43
+ headers: { 'content-type': 'application/json', ...(cfg.token ? { authorization: `Bearer ${cfg.token}` } : {}) },
44
+ body: data ? JSON.stringify(data) : undefined,
45
+ });
46
+ } catch {
47
+ die(`cannot reach ${cfg.server}. Check your connection, or set the address with --server.`);
48
+ }
49
+ const out = await r.json().catch(() => ({}));
50
+ if (!r.ok) { const e = new Error(out.error || `HTTP ${r.status}`); e.status = r.status; throw e; }
51
+ return out;
52
+ }
53
+
54
+ function openBrowser(url) {
55
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
56
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
57
+ try { spawnProc(cmd, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref(); } catch {}
58
+ }
59
+
60
+ async function login(cfg) {
61
+ const d = await api(cfg, 'POST', '/api/device/start', { label: os.hostname() });
62
+ say();
63
+ say(` ${bold('Sign in to Agentpen')}`);
64
+ say(` Open ${accent(d.verify_url)}`);
65
+ say(` Code ${bold(d.user_code)}`);
66
+ say(dim(' Waiting for you to approve in the browser...'));
67
+ if (process.stdout.isTTY && !process.env.AGENTPEN_NO_OPEN) openBrowser(d.verify_url);
68
+ for (;;) {
69
+ await new Promise((r) => setTimeout(r, d.interval * 1000));
70
+ let p;
71
+ try { p = await api(cfg, 'POST', '/api/device/poll', { device_code: d.device_code }); } catch (e) { die(e.message); }
72
+ if (p.pending) continue;
73
+ cfg.token = p.token;
74
+ cfg.user = p.user;
75
+ saveConfig(cfg);
76
+ say(` Signed in as ${bold(p.user.name)} ${dim(`<${p.user.email}>`)}\n`);
77
+ return;
78
+ }
79
+ }
80
+
81
+ function git(args) {
82
+ try { return execFileSync('git', args, { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim(); } catch { return ''; }
83
+ }
84
+
85
+ // Signed in and in at least one workspace, or we stop with a useful message.
86
+ async function ensureAccount(cfg) {
87
+ if (!cfg.token) await login(cfg);
88
+ let me;
89
+ try { me = await api(cfg, 'GET', '/api/me'); } catch (e) { die(e.message); }
90
+ if (!me.user) { // token expired or revoked
91
+ cfg.token = null;
92
+ await login(cfg);
93
+ me = await api(cfg, 'GET', '/api/me');
94
+ }
95
+ if (!me.workspaces.length) die(`you are not in a workspace yet. Create or join one at ${cfg.server} and run this again.`);
96
+ }
97
+
98
+ // Claude Code keeps each conversation in a file named after its session id.
99
+ // Knowing the id up front is what lets us checkpoint exactly this conversation.
100
+ function claudeSession(command) {
101
+ if (path.basename(command[0]) !== 'claude') return { tracked: false };
102
+ const args = command.slice(1);
103
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
104
+ for (const flag of ['--session-id', '--resume', '-r']) {
105
+ const i = args.indexOf(flag);
106
+ if (i >= 0 && uuid.test(args[i + 1] || '')) return { tracked: true, id: args[i + 1] };
107
+ }
108
+ // resuming "the latest" or printing once: find the conversation by looking for the newest file instead
109
+ if (args.some((a) => ['--resume', '-r', '--continue', '-c', '--print', '-p', '--fork-session'].includes(a))) return { tracked: true, id: null };
110
+ const id = randomUUID();
111
+ command.splice(1, 0, '--session-id', id);
112
+ return { tracked: true, id };
113
+ }
114
+
115
+ // How this session starts: a flag wins, then this machine's own default, then the workspace's.
116
+ const accessFor = (cfg, opts) => (opts.private ? 'private' : opts.watchOnly ? 'view' : cfg.defaultAccess || undefined);
117
+ const ACCESS_WORDS = { private: 'private, only you can see it', view: 'teammates can watch', control: 'teammates can watch and type' };
118
+
119
+ // Where the agent's real program is. The shell hook passes it along when
120
+ // `claude` was an alias rather than something on PATH.
121
+ const realBin = (command) => (path.basename(command[0]) === 'claude' && process.env.AGENTPEN_CLAUDE) || command[0];
122
+
123
+ // Run the agent exactly as if Agentpen were not there, and leave with its exit code.
124
+ function runPlain(command) {
125
+ const child = spawnProc(realBin(command), command.slice(1), { stdio: 'inherit' });
126
+ child.on('error', (e) => die(`could not start "${command[0]}": ${e.message}`));
127
+ child.on('exit', (code, signal) => process.exit(signal ? 1 : code ?? 0));
128
+ for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => {});
129
+ return new Promise(() => {});
130
+ }
131
+
132
+ // Claude Code commands that manage the tool rather than start a conversation.
133
+ const CLAUDE_ADMIN = new Set(['agents', 'attach', 'auth', 'auto-mode', 'doctor', 'gateway', 'import', 'install', 'logs', 'mcp', 'plugin', 'plugins', 'purge', 'respawn', 'rm', 'sessions', 'setup-token', 'stop', 'kill', 'ultrareview', 'update', 'upgrade', 'config', 'migrate-installer']);
134
+
135
+ /**
136
+ * --auto is how the shell hook calls us: the developer typed plain `claude`.
137
+ * It must never get in their way, so anything that is not an interactive
138
+ * conversation, and any trouble reaching Agentpen, means "just run claude".
139
+ */
140
+ async function shouldShareAuto(cfg, command) {
141
+ const args = command.slice(1);
142
+ const tty = (process.stdin.isTTY && process.stdout.isTTY) || process.env.AGENTPEN_AUTO_ANYWHERE === '1';
143
+ if (!tty || process.env.AGENTPEN_OFF || process.env.AGENTPEN_SESSION || cfg.paused || !cfg.token) return false;
144
+ if (args.some((a) => ['-p', '--print', '-v', '--version', '-h', '--help'].includes(a))) return false;
145
+ if (args[0] && CLAUDE_ADMIN.has(args[0])) return false;
146
+ try {
147
+ const r = await fetch(cfg.server + '/api/me', { headers: { authorization: `Bearer ${cfg.token}` }, signal: AbortSignal.timeout(2000) });
148
+ const me = await r.json();
149
+ return !!(r.ok && me.user && me.workspaces.length);
150
+ } catch { return false; }
151
+ }
152
+
153
+ async function share(cfg, opts, command) {
154
+ if (opts.auto) { if (!(await shouldShareAuto(cfg, command))) return runPlain(command); }
155
+ else await ensureAccount(cfg);
156
+ const agent = claudeSession(command);
157
+
158
+ let pty;
159
+ try { pty = (await import('node-pty')).default; } catch {
160
+ die('the terminal component (node-pty) is not installed. Reinstall with build tools available: npm install -g agentpen-cli');
161
+ }
162
+ const size = () => ({ cols: process.stdout.columns || 100, rows: process.stdout.rows || 30 });
163
+ const top = git(['rev-parse', '--show-toplevel']);
164
+ const project = path.basename(top || process.cwd());
165
+ const hello = {
166
+ t: 'hello', workspace: opts.workspace, title: opts.title, agent: path.basename(command[0]), project,
167
+ branch: git(['rev-parse', '--abbrev-ref', 'HEAD']), access: accessFor(cfg, opts), ...size(),
168
+ };
169
+
170
+ let ws = null;
171
+ let session = null;
172
+ let term = null;
173
+ let exited = false;
174
+ let retry = 0;
175
+ let pending = [];
176
+ let pendingBytes = 0;
177
+ let people = [];
178
+
179
+ const outbound = makeRedactor(opts.shareSecrets ? [] : collectSecrets(process.cwd()), (buf) => {
180
+ if (ws?.readyState === 1 && session) return ws.send(buf, { binary: true });
181
+ pending.push(buf); // offline: keep the last 1MB for when the link is back
182
+ pendingBytes += buf.length;
183
+ while (pendingBytes > 1_000_000 && pending.length > 1) pendingBytes -= pending.shift().length;
184
+ });
185
+
186
+ const title = () => {
187
+ if (!process.stdout.isTTY || !session) return;
188
+ const n = people.length;
189
+ process.stdout.write(`\x1b]0;● agentpen · ${n ? `${n} watching` : 'live'} · ${session.url.replace(/^https?:\/\//, '')}\x07`);
190
+ };
191
+
192
+ let repaintTimer = null;
193
+ const repaint = () => {
194
+ if (!term || repaintTimer) return;
195
+ const { cols, rows } = size();
196
+ // a one-row wiggle makes full-screen UIs redraw for whoever just joined
197
+ try { term.resize(cols, Math.max(2, rows - 1)); } catch {}
198
+ repaintTimer = setTimeout(() => { repaintTimer = null; try { term.resize(cols, rows); } catch {} }, 60);
199
+ };
200
+
201
+ const ready = new Promise((resolve, reject) => {
202
+ const connect = () => {
203
+ ws = new WebSocket(cfg.server.replace(/^http/, 'ws') + '/ws/host', { headers: { authorization: `Bearer ${cfg.token}` } });
204
+ ws.on('open', () => ws.send(JSON.stringify(session ? { t: 'hello', resume: { id: session.id, key: session.key } } : { ...hello, ...size() })));
205
+ ws.on('message', (data, isBinary) => {
206
+ if (isBinary) { if (term) term.write(data.toString()); return; }
207
+ let m;
208
+ try { m = JSON.parse(data); } catch { return; }
209
+ if (m.t === 'ready') {
210
+ session = { ...session, ...m };
211
+ retry = 0;
212
+ ws.send(JSON.stringify({ t: 'resize', ...size() }));
213
+ for (const b of pending) ws.send(b, { binary: true });
214
+ pending = []; pendingBytes = 0;
215
+ title();
216
+ resolve();
217
+ } else if (m.t === 'error') {
218
+ // The server forgot the session (restart or deploy). Never take the agent
219
+ // down with it: quietly start a fresh session for the same terminal.
220
+ if (term && m.code === 'gone') session = null;
221
+ else if (!term) { exited = true; reject(new Error(m.message)); }
222
+ } else if (m.t === 'repaint') {
223
+ repaint();
224
+ } else if (m.t === 'people') {
225
+ if (m.people.length > people.length && process.stdout.isTTY) process.stdout.write('\x07');
226
+ people = m.people;
227
+ title();
228
+ } else if (m.t === 'end') {
229
+ session.dead = true;
230
+ if (term) term.kill();
231
+ }
232
+ });
233
+ ws.on('close', () => {
234
+ if (exited || session?.dead) return;
235
+ if (!session && !term && retry >= 3) return reject(new Error(`cannot reach ${cfg.server}`));
236
+ setTimeout(connect, Math.min(8000, 500 * 2 ** retry++));
237
+ });
238
+ ws.on('error', () => {});
239
+ };
240
+ connect();
241
+ });
242
+
243
+ try {
244
+ await (opts.auto ? Promise.race([ready, new Promise((_, no) => setTimeout(() => no(new Error('timeout')), 4000))]) : ready);
245
+ } catch (e) {
246
+ if (!opts.auto) die(e.message);
247
+ exited = true; // could not go live in time: stop trying and get out of the way
248
+ try { ws?.terminate(); } catch {}
249
+ return runPlain(command);
250
+ }
251
+
252
+ if (opts.auto) {
253
+ // they typed `claude`, so keep it to one quiet line
254
+ say(dim(session.access === 'private'
255
+ ? ` ${accent('●')} agentpen: private session · ${session.url} · share it from that page`
256
+ : ` ${accent('●')} agentpen: live in ${session.workspace.name} · ${session.url} · "agentpen pause" to stop sharing`));
257
+ } else {
258
+ say();
259
+ say(` ${accent('●')} ${bold('Live in ' + session.workspace.name)} ${dim(ACCESS_WORDS[session.access] || '')}`);
260
+ say(` ${accent(session.url)}`);
261
+ }
262
+ const checkpointing = agent.tracked && session.handoff && !opts.noHandoff;
263
+ if (checkpointing && !opts.auto) say(dim(' Checkpoints on: if this machine goes offline, a teammate can pick the session up.'));
264
+ if (!opts.auto) say();
265
+
266
+ try {
267
+ term = pty.spawn(realBin(command), command.slice(1), { name: process.env.TERM || 'xterm-256color', ...size(), cwd: process.cwd(), env: { ...process.env, AGENTPEN_SESSION: session.id } });
268
+ } catch (e) {
269
+ exited = true;
270
+ ws.send(JSON.stringify({ t: 'exit' }));
271
+ ws.close();
272
+ die(`could not start "${command[0]}": ${e.message}`);
273
+ }
274
+
275
+ const cwd = fs.realpathSync(process.cwd());
276
+ const checkpoints = checkpointing ? startCheckpoints({
277
+ cfg, getSession: () => session, cwd, agentSession: agent.id, secrets: opts.shareSecrets ? [] : collectSecrets(cwd),
278
+ onError: (m) => { if (process.env.AGENTPEN_DEBUG) say(`checkpoint: ${m}`); if (process.stdout.isTTY) process.stdout.write(`\x1b]0;agentpen: checkpoint failed (${m})\x07`); },
279
+ }) : null;
280
+ // an agent mid-task should not be put to sleep by an idle laptop (a closed lid still sleeps)
281
+ if (process.platform === 'darwin') { try { spawnProc('caffeinate', ['-i', '-w', String(term.pid)], { stdio: 'ignore' }).on('error', () => {}).unref(); } catch {} }
282
+
283
+ term.onData((d) => {
284
+ process.stdout.write(d);
285
+ outbound.write(Buffer.from(d));
286
+ });
287
+ const onInput = (d) => term.write(d.toString());
288
+ if (process.stdin.isTTY) process.stdin.setRawMode(true);
289
+ process.stdin.on('data', onInput);
290
+ process.stdin.resume();
291
+ const onResize = () => {
292
+ const s = size();
293
+ try { term.resize(s.cols, s.rows); } catch {}
294
+ if (ws?.readyState === 1) ws.send(JSON.stringify({ t: 'resize', ...s }));
295
+ };
296
+ process.stdout.on('resize', onResize);
297
+ for (const sig of ['SIGTERM', 'SIGHUP']) process.on(sig, () => term.kill());
298
+
299
+ term.onExit(async ({ exitCode }) => {
300
+ outbound.flush();
301
+ // one last checkpoint while the session is still live, so the final state is what a teammate gets
302
+ if (checkpoints && session && !session.dead) { checkpoints.stop(); await Promise.race([checkpoints.now(), new Promise((r) => setTimeout(r, 6000))]); }
303
+ exited = true;
304
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
305
+ process.stdin.off('data', onInput);
306
+ process.stdin.pause();
307
+ if (process.stdout.isTTY) process.stdout.write('\x1b]0;\x07');
308
+ const done = () => {
309
+ say();
310
+ if (session) say(` ${dim('Session ended. Replay:')} ${session.url}`);
311
+ process.exit(session?.dead ? 0 : exitCode);
312
+ };
313
+ if (ws?.readyState === 1 && session && !session.dead) {
314
+ ws.send(JSON.stringify({ t: 'exit' }), () => { ws.close(); });
315
+ ws.on('close', done);
316
+ setTimeout(done, 1500);
317
+ } else done();
318
+ });
319
+ }
320
+
321
+ const HELP = `
322
+ ${bold('agentpen')} - your coding agent, live for your team
323
+
324
+ ${bold('Usage')}
325
+ agentpen [agent] [agent args...] share a terminal agent (default: claude)
326
+ agentpen codex-app share a conversation from the Codex desktop app
327
+ agentpen pickup LINK [--worktree] carry on a teammate's Claude Code session here
328
+ agentpen install share automatically: plain \`claude\`, and the Codex app
329
+ agentpen pause | resume stop or restart automatic sharing on this machine
330
+ agentpen default private|watch|type|workspace
331
+ how your sessions start on this machine
332
+ agentpen uninstall remove the automatic sharing set up by install
333
+ agentpen login [--server URL] sign in from this machine
334
+ agentpen logout forget this machine's credentials
335
+ agentpen whoami show the signed-in account
336
+
337
+ ${bold('Options')} (before the agent name)
338
+ -t, --title TEXT name the session, e.g. "Checkout refactor"
339
+ -w, --workspace SLUG share to a specific workspace
340
+ --watch-only teammates can watch but not type
341
+ --private only you can see the session until you share it
342
+ --share-secrets do not mask .env values in the shared stream
343
+ --no-handoff do not checkpoint the conversation and code for teammates
344
+ --server URL Agentpen server address
345
+ --thread ID (codex-app) share this conversation instead of choosing
346
+ --latest (codex-app) share the most recently active conversation
347
+
348
+ ${bold('Examples')}
349
+ agentpen share Claude Code in this terminal
350
+ agentpen codex share the Codex CLI in this terminal
351
+ agentpen codex-app share what you are doing in the Codex app
352
+ agentpen -t "Fix flaky CI" claude --resume
353
+ agentpen -- npm run dev share any terminal program
354
+ `;
355
+
356
+ async function main() {
357
+ const argv = process.argv.slice(2);
358
+ const cfg = loadConfig();
359
+ const opts = {};
360
+ let i = 0;
361
+ for (; i < argv.length; i++) {
362
+ const a = argv[i];
363
+ if (a === '--') { i++; break; }
364
+ if (a === '-h' || a === '--help') return say(HELP);
365
+ if (a === '-v' || a === '--version') return console.log(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url))).version);
366
+ if (a === '-t' || a === '--title') opts.title = argv[++i];
367
+ else if (a === '-w' || a === '--workspace') opts.workspace = argv[++i];
368
+ else if (a === '--watch-only') opts.watchOnly = true;
369
+ else if (a === '--share-secrets') opts.shareSecrets = true;
370
+ else if (a === '--no-handoff') opts.noHandoff = true;
371
+ else if (a === '--private') opts.private = true;
372
+ else if (a === '--auto') opts.auto = true;
373
+ else if (a === '--thread') opts.thread = argv[++i];
374
+ else if (a === '--latest') opts.latest = true;
375
+ else if (a === '--socket') opts.socket = argv[++i];
376
+ else if (a === '--server') cfg.server = String(argv[++i] || '').replace(/\/$/, '');
377
+ else if (a.startsWith('-')) die(`unknown option ${a}. Try agentpen --help.`);
378
+ else if ((a === 'codex-app' || a === 'app') && !opts.codexApp) opts.codexApp = true; // its options may come before or after
379
+ else break;
380
+ }
381
+ const rest = argv.slice(i);
382
+ const cmd = rest[0];
383
+ if (cmd === 'login' && rest.length <= 3) {
384
+ const s = rest.indexOf('--server');
385
+ if (s > 0) cfg.server = String(rest[s + 1] || '').replace(/\/$/, '');
386
+ return login(cfg);
387
+ }
388
+ if (cmd === 'logout' && rest.length === 1) {
389
+ cfg.token = null; cfg.user = null;
390
+ saveConfig(cfg);
391
+ return say('Signed out on this machine.');
392
+ }
393
+ if (cmd === 'whoami' && rest.length === 1) {
394
+ if (!cfg.token) return say('Not signed in. Run: agentpen login');
395
+ try {
396
+ const me = await api(cfg, 'GET', '/api/me');
397
+ if (!me.user) die('session expired. Run: agentpen login');
398
+ say(`${me.user.name} <${me.user.email}> on ${cfg.server}`);
399
+ for (const w of me.workspaces) say(` ${w.name} ${dim(`(${w.slug}, ${w.role})`)}`);
400
+ } catch (e) { die(e.status === 401 ? 'session expired. Run: agentpen login' : e.message); }
401
+ return;
402
+ }
403
+ if (cmd === 'install' && rest.length <= 2) {
404
+ await ensureAccount(cfg);
405
+ const me = await api(cfg, 'GET', '/api/me');
406
+ return install({ workspace: me.workspaces[0].name, shellOnly: rest[1] === '--shell-only' }, { say, die, bold, dim, accent });
407
+ }
408
+ if (cmd === 'default' && rest.length === 2) {
409
+ const map = { private: 'private', watch: 'view', type: 'control', workspace: '' };
410
+ if (!(rest[1] in map)) die('choose one of: private, watch, type, workspace');
411
+ const disk = (() => { try { return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); } catch { return {}; } })();
412
+ saveConfig({ ...disk, defaultAccess: map[rest[1]] });
413
+ return say(rest[1] === 'workspace' ? 'Your sessions now start the way the workspace is set up.' : `Your sessions on this machine now start as: ${ACCESS_WORDS[map[rest[1]]]}.`);
414
+ }
415
+ if (cmd === 'uninstall' && rest.length === 1) return uninstall({ say, die, bold, dim, accent });
416
+ if ((cmd === 'pause' || cmd === 'resume') && rest.length === 1) {
417
+ const disk = (() => { try { return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')); } catch { return {}; } })();
418
+ saveConfig({ ...disk, paused: cmd === 'pause' });
419
+ return say(cmd === 'pause' ? 'Automatic sharing is paused on this machine. New sessions stay private until you run: agentpen resume' : 'Automatic sharing is back on.');
420
+ }
421
+ if (cmd === 'watch' && rest.length === 1) {
422
+ if (!cfg.token) die('not signed in. Run: agentpen login'); // runs in the background: never open a browser from here
423
+ return watchCodexApp(cfg, { ...opts, access: accessFor(cfg, opts) }, { say, die, bold, dim, accent }, () => { try { return !!JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8')).paused; } catch { return false; } });
424
+ }
425
+ if (cmd === 'pickup') {
426
+ const flags = rest.slice(2);
427
+ const bad = flags.find((f) => f !== '--worktree' && f !== '--force');
428
+ if (!rest[1] || bad) die(bad ? `unknown option ${bad} for pickup.` : 'which session? Usage: agentpen pickup LINK [--worktree]');
429
+ await ensureAccount(cfg);
430
+ const p = await pickup(cfg, rest[1], { worktree: flags.includes('--worktree'), force: flags.includes('--force') }, { say, die, bold, dim, accent });
431
+ process.chdir(p.cwd);
432
+ return share(cfg, { ...opts, title: opts.title || `${p.title} (picked up)` }, [process.env.AGENTPEN_CLAUDE || 'claude', '--resume', p.agentSession]);
433
+ }
434
+ if (opts.codexApp) {
435
+ if (rest.length) die(`unexpected argument "${rest[0]}" for codex-app. Try agentpen --help.`);
436
+ await ensureAccount(cfg);
437
+ return shareCodexApp(cfg, { ...opts, access: accessFor(cfg, opts) }, { say, die, bold, dim, accent });
438
+ }
439
+ return share(cfg, opts, rest.length ? rest : ['claude']);
440
+ }
441
+
442
+ main().catch((e) => die(e.message));