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