agentpen-cli 0.1.0 → 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.
package/README.md CHANGED
@@ -74,6 +74,19 @@ It is built to stay out of the way. If the server is unreachable, you are signed
74
74
 
75
75
  Everyone in the workspace can see shared sessions, so `install` is something each developer chooses to run, and it says so when it finishes.
76
76
 
77
+ ## Share a session that is already running
78
+
79
+ Sometimes the agent is an hour into something before you think to share it. You do not have to restart it:
80
+
81
+ - **Inside Claude Code**, type `/agentpen`. (`/agentpen stop` stops it, `/agentpen --private` starts it visible only to you.)
82
+ - **From another terminal** in the same folder, run `agentpen share`.
83
+
84
+ Agentpen did not start that session, so it has no terminal to stream. It follows the conversation file Claude Code keeps on disk and shows the team the conversation instead: your messages, the agent's replies, the commands it ran with their output, and which files it read or edited. Reasoning and file contents are not shared, and `.env` values are masked.
85
+
86
+ It is watch-only. Teammates can follow along and chat, but nobody can type into it or prompt it, and an invited agent cannot be handed the wheel. Sharing stops when Claude Code exits, after 30 quiet minutes, or with `agentpen share stop`.
87
+
88
+ `/agentpen` is a personal Claude Code skill (`~/.claude/skills/agentpen/`), added by `agentpen login` and `agentpen install` on machines where Claude Code has run, and removed by `agentpen uninstall`. Installing the npm package does not write outside its own folder.
89
+
77
90
  ## Bring another agent into the session
78
91
 
79
92
  A session does not have to depend on one model any more than on one person. An admin connects the agents the team may invite, under Settings:
@@ -182,6 +195,7 @@ First run prints a code and opens the browser to approve the machine. The sessio
182
195
  ```
183
196
  agentpen [agent] [args...] share a terminal agent (default: claude)
184
197
  agentpen codex-app share a Codex desktop app conversation
198
+ agentpen share [stop] share a Claude Code session that is already running (watch only)
185
199
  agentpen install | uninstall share automatically: plain `claude`, and the Codex app
186
200
  agentpen pause | resume stop or restart automatic sharing on this machine
187
201
  agentpen default private|watch|type|workspace how your sessions start on this machine
@@ -249,6 +263,7 @@ Not built:
249
263
  - **Invited agents have only been run against a simulated Anthropic API.** The request the server sends was checked field by field and the flows are covered end to end, but no real reply from Claude, Grok or Muse has been seen. The Grok and Muse request shape was taken from search summaries of their docs, because those docs sites could not be opened from the build environment; xAI also describes Chat Completions as its legacy endpoint. What an invited agent reads from a terminal session is a plain-text capture of a terminal UI, and only its most recent part, so answers about long sessions can miss early context.
250
264
  - **Search covers ended sessions only**, and terminal sessions are indexed from the same plain-text capture, so full-screen programs produce noisy matches.
251
265
  - **Automatic sharing is tested with bash and a simulated Codex app.** The shell hook has not been run under zsh, the Mac default, and the macOS background helper (a launchd agent) has never been loaded on a real Mac. The helper finds coding conversations by whether Codex reports a git repository for them.
266
+ - **Sharing a running session is watch-only and has no "needs a human" signal.** The conversation file does not say when Claude Code is waiting on an approval, so such a session shows as working or idle, never amber. It is covered end to end against a stand-in conversation file and was checked against one real Claude Code file, but the `/agentpen` command has not been typed into a real Claude Code session; it relies on Claude Code's skill features (running a command when the skill is invoked, and filling in the session id).
252
267
  - **Pickup is Claude Code only**, and only for sessions started through Agentpen. Codex sessions are not checkpointed. It moves the work to another person's machine; it does not keep the agent running in the cloud while every laptop is shut. Up to about 20 seconds of work before the lid closed can be missing. If the original host comes back and keeps going, the two copies diverge and are reconciled with git like any two branches.
253
268
  - **Checkpoints put source code on the Agentpen server**, unencrypted at rest. That is the trade for being able to pick up; workspaces that cannot accept it should turn the setting off.
254
269
  - **No phone push.** Notifications reach open browser tabs and the Mac app only.
@@ -266,6 +281,7 @@ cli/agentpen.js the `agentpen` command
266
281
  cli/codex-app.js bridge to the Codex desktop app's control socket
267
282
  cli/install.js `agentpen install`: the shell hook and the macOS background helper
268
283
  cli/handoff.js checkpoints and `agentpen pickup`
284
+ cli/claude-share.js `agentpen share`: follow a running Claude Code conversation
269
285
  cli/redact.js .env masking
270
286
  server/notify.js who is notified about what; per-user stream and preferences
271
287
  server/agents.js invited agents: Claude via the Anthropic SDK (second opinion, summary, steering)
package/cli/agentpen.js CHANGED
@@ -7,8 +7,9 @@ import { execFileSync, spawn as spawnProc } from 'node:child_process';
7
7
  import WebSocket from 'ws';
8
8
  import { collectSecrets, makeRedactor } from './redact.js';
9
9
  import { shareCodexApp, watchCodexApp } from './codex-app.js';
10
- import { install, uninstall } from './install.js';
10
+ import { install, uninstall, installSkill } from './install.js';
11
11
  import { startCheckpoints, pickup } from './handoff.js';
12
+ import { shareRunningClaude, runShareChild, stopSharing } from './claude-share.js';
12
13
  import { randomUUID } from 'node:crypto';
13
14
 
14
15
  // The hosted service address. Self-hosters: `agentpen login --server https://agentpen.acme.internal`.
@@ -73,7 +74,9 @@ async function login(cfg) {
73
74
  cfg.token = p.token;
74
75
  cfg.user = p.user;
75
76
  saveConfig(cfg);
76
- say(` Signed in as ${bold(p.user.name)} ${dim(`<${p.user.email}>`)}\n`);
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();
77
80
  return;
78
81
  }
79
82
  }
@@ -324,6 +327,8 @@ const HELP = `
324
327
  ${bold('Usage')}
325
328
  agentpen [agent] [agent args...] share a terminal agent (default: claude)
326
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
327
332
  agentpen pickup LINK [--worktree] carry on a teammate's Claude Code session here
328
333
  agentpen install share automatically: plain \`claude\`, and the Codex app
329
334
  agentpen pause | resume stop or restart automatic sharing on this machine
@@ -371,6 +376,7 @@ async function main() {
371
376
  else if (a === '--private') opts.private = true;
372
377
  else if (a === '--auto') opts.auto = true;
373
378
  else if (a === '--thread') opts.thread = argv[++i];
379
+ else if (a === '--session') opts.session = argv[++i];
374
380
  else if (a === '--latest') opts.latest = true;
375
381
  else if (a === '--socket') opts.socket = argv[++i];
376
382
  else if (a === '--server') cfg.server = String(argv[++i] || '').replace(/\/$/, '');
@@ -431,6 +437,27 @@ async function main() {
431
437
  process.chdir(p.cwd);
432
438
  return share(cfg, { ...opts, title: opts.title || `${p.title} (picked up)` }, [process.env.AGENTPEN_CLAUDE || 'claude', '--resume', p.agentSession]);
433
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
+ }
434
461
  if (opts.codexApp) {
435
462
  if (rest.length) die(`unexpected argument "${rest[0]}" for codex-app. Try agentpen --help.`);
436
463
  await ensureAccount(cfg);
@@ -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
+ }
package/cli/install.js CHANGED
@@ -73,10 +73,50 @@ ${args}
73
73
 
74
74
  const launchctl = (...args) => { try { execFileSync('launchctl', args, { stdio: 'ignore' }); return true; } catch { return false; } };
75
75
 
76
+ // ---- /agentpen inside Claude Code -------------------------------------------
77
+ // A personal skill, so typing /agentpen in a session that is already running
78
+ // shares it. It runs `agentpen share` for that conversation and nothing else.
79
+ const SKILL = `---
80
+ name: agentpen
81
+ description: Share this Claude Code session with your Agentpen workspace so teammates can watch it live. "/agentpen stop" stops sharing.
82
+ argument-hint: "[stop | --private]"
83
+ disable-model-invocation: true
84
+ allowed-tools: Bash(agentpen share *)
85
+ ---
86
+ <!-- installed by agentpen. Remove with: agentpen uninstall -->
87
+ The user asked to share this session with their team through Agentpen. This command has already run:
88
+
89
+ !\`agentpen share --in-claude --session \${CLAUDE_SESSION_ID} $ARGUMENTS\`
90
+
91
+ Reply with one or two short lines that pass on what it printed: the link if there is one, or the problem and the fix it suggests. Do not run anything else.
92
+ `;
93
+ const skillFile = () => path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'skills', 'agentpen', 'SKILL.md');
94
+
95
+ /** Adds /agentpen to Claude Code. Returns true if it is in place. Does nothing where Claude Code has never run. */
96
+ export function installSkill() {
97
+ try {
98
+ const f = skillFile();
99
+ if (!fs.existsSync(path.dirname(path.dirname(path.dirname(f))))) return false;
100
+ if (fs.existsSync(f) && !fs.readFileSync(f, 'utf8').includes('installed by agentpen')) return false; // someone else's skill of the same name: leave it
101
+ fs.mkdirSync(path.dirname(f), { recursive: true });
102
+ fs.writeFileSync(f, SKILL);
103
+ return true;
104
+ } catch { return false; }
105
+ }
106
+ export function removeSkill() {
107
+ try {
108
+ const f = skillFile();
109
+ if (!fs.readFileSync(f, 'utf8').includes('installed by agentpen')) return false;
110
+ fs.rmSync(path.dirname(f), { recursive: true, force: true });
111
+ return true;
112
+ } catch { return false; }
113
+ }
114
+
76
115
  export function install({ workspace, shellOnly }, ui) {
77
116
  const files = rcFiles();
78
117
  for (const f of files) writeHook(f);
79
118
 
119
+ const skill = installSkill();
80
120
  let codex = 'skipped';
81
121
  if (!shellOnly && process.platform === 'darwin') {
82
122
  const p = plistPath();
@@ -93,6 +133,11 @@ export function install({ workspace, shellOnly }, ui) {
93
133
  ui.say(` ${ui.accent('claude')} Typing plain ${ui.bold('claude')} in a new terminal now starts a shared session.`);
94
134
  ui.say(ui.dim(` Hook added to ${files.map((f) => f.replace(os.homedir(), '~')).join(' and ')}. Open a new terminal for it to take effect.`));
95
135
  ui.say(ui.dim(' One-off commands (claude -p, claude mcp, claude update) are never shared.'));
136
+ if (skill) {
137
+ ui.say();
138
+ ui.say(` ${ui.accent('/agentpen')} In a Claude Code session that is already running, type ${ui.bold('/agentpen')} to share it.`);
139
+ ui.say(ui.dim(' Teammates can watch that one and chat. They cannot type into it.'));
140
+ }
96
141
  ui.say();
97
142
  if (codex === 'on') {
98
143
  ui.say(` ${ui.accent('Codex app')} A background helper shares coding conversations while they are active.`);
@@ -122,6 +167,7 @@ export function uninstall(ui) {
122
167
  launchctl('bootout', `gui/${process.getuid()}/${LABEL}`);
123
168
  fs.rmSync(plistPath(), { force: true });
124
169
  }
170
+ if (removeSkill()) ui.say('Removed /agentpen from Claude Code.');
125
171
  ui.say(touched.length ? `Removed the claude hook from ${touched.join(' and ')}. Open a new terminal for it to take effect.` : 'No claude hook was installed.');
126
172
  if (process.platform === 'darwin') ui.say('Stopped the Codex app helper.');
127
173
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentpen-cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "The team room for your coding agents - share live Claude Code / Codex sessions with your whole company",
5
5
  "license": "MIT",
6
6
  "homepage": "https://agentpen.app",
package/server/hub.js CHANGED
@@ -58,6 +58,8 @@ class LiveSession {
58
58
  this.asking = false;
59
59
  this.recBytes = 0;
60
60
  this.kind = row.kind;
61
+ // a Claude Code session shared after it started: there is no terminal to type into
62
+ this.readOnly = row.kind === 'thread' && row.agent === 'claude';
61
63
  this.turns = new Map(); // thread sessions: turn id -> turn
62
64
  this.order = [];
63
65
  this.rec = null;
@@ -121,7 +123,7 @@ class LiveSession {
121
123
  }
122
124
 
123
125
  canType(user) {
124
- if (user.guest) return false;
126
+ if (user.guest || this.readOnly) return false;
125
127
  return user.id === this.row.host_id || this.row.access === 'control';
126
128
  }
127
129
 
@@ -179,7 +181,7 @@ class LiveSession {
179
181
 
180
182
  // What the agent is actually asking, so the notification can be answered at a glance.
181
183
  question() {
182
- if (this.kind === 'thread') return 'Waiting for you to approve or answer in the Codex app.';
184
+ if (this.kind === 'thread') return this.readOnly ? 'Waiting for you in your terminal.' : 'Waiting for you to approve or answer in the Codex app.';
183
185
  const lines = this.recentLines(6);
184
186
  // the question itself reads better than the menu under it ("❯ 1. Yes")
185
187
  return (lines.findLast((l) => /\?\s*$|\(y\/n\)/i.test(l)) || lines.findLast((l) => BLOCKED_RE.test(l)) || lines.at(-1) || 'It is waiting for input.').slice(0, 200);
@@ -329,7 +331,7 @@ class LiveSession {
329
331
 
330
332
  // An attributed prompt for the agent. Returns false if it could not be delivered.
331
333
  prompt(user, raw, asInvitedAgent = false) {
332
- if ((!asInvitedAgent && !this.canType(user)) || this.ws?.readyState !== 1) return false;
334
+ if (this.readOnly || (!asInvitedAgent && !this.canType(user)) || this.ws?.readyState !== 1) return false;
333
335
  let text;
334
336
  if (this.kind === 'thread') {
335
337
  // a conversation takes the prompt as a message, queued under the sender's name
@@ -470,7 +472,7 @@ export function attachHost(ws, user) {
470
472
  } else if (m.t === 'thread' && s.kind === 'thread') {
471
473
  s.threadUpdate(m);
472
474
  } else if (m.t === 'prompt-result' && !m.ok) {
473
- s.broadcast({ t: 'notice', text: 'Codex did not confirm that prompt. Check with the host before sending it again.' });
475
+ s.broadcast({ t: 'notice', text: `${s.agentName()} did not confirm that prompt. Check with the host before sending it again.` });
474
476
  }
475
477
  });
476
478
  ws.on('close', () => {
package/server/index.js CHANGED
@@ -496,6 +496,7 @@ route('POST', '/api/sessions/:id/driver', async ({ user, params, data }) => {
496
496
  if (a.s.host_id !== user.id) bad(403, 'Only the host can hand the wheel to an agent.');
497
497
  const goal = clip(data.goal, 600);
498
498
  if (goal.length < 8) bad(400, 'Say what you want done, in a sentence.');
499
+ if (live.readOnly) bad(400, 'This session was shared after it started, so nothing can be typed into it. Hand over the wheel in a session started with agentpen.');
499
500
  if (live.driver) bad(409, `${live.driver.name} already has the wheel.`);
500
501
  live.drive(pickAgent(a.s.workspace_id, data.agent), { id: user.id, name: user.name }, goal); // runs in the background
501
502
  return { ok: true };
package/web/app.js CHANGED
@@ -288,6 +288,9 @@ function onboarding(extra) {
288
288
  const r = await api('POST', '/api/workspaces', { name });
289
289
  go(`/w/${r.slug}`);
290
290
  }));
291
+ if (!extra) put(card, h('div', { style: 'border-top:1px solid var(--line);padding-top:14px' },
292
+ h('p.small.muted', {}, 'Then run this once in a terminal. After that, just type ', h('code', {}, 'claude'), ' and your sessions show up for your team.'),
293
+ startCommand()));
291
294
  mount(h('.center', {}, card));
292
295
  }
293
296
 
package/web/session.js CHANGED
@@ -49,7 +49,7 @@ function eventRow(e) {
49
49
  e.detail && (e.type === 'session.prompt' ? h('span.q', {}, e.detail) : h('span', {}, ` - ${e.detail}`)));
50
50
  }
51
51
 
52
- // ---- conversation view (Codex app sessions) --------------------------------
52
+ // ---- conversation view (Codex app sessions, and Claude Code sessions shared after they started) ----
53
53
 
54
54
  // Just enough Markdown for agent replies: fenced code, inline code, bold, lists.
55
55
  function inline(s) {
@@ -71,15 +71,15 @@ function prose(text) {
71
71
  return out;
72
72
  }
73
73
 
74
- function threadView() {
74
+ function threadView(agent = 'Codex', where = 'in the Codex app') {
75
75
  const list = h('.turns');
76
- const working = h('.thinking', { hidden: true }, h('span.pill.working', {}, 'Codex is working'));
76
+ const working = h('.thinking', { hidden: true }, h('span.pill.working', {}, `${agent} is working`));
77
77
  const el = h('.transcript', { tabindex: 0, 'aria-label': 'Conversation' }, list, working);
78
78
  const turns = new Map();
79
79
  let order = [];
80
80
  const item = (it) => {
81
81
  if (it.role === 'user') return h('.bubble.user', {}, it.by && h('.by', {}, avatar(it.by), h('b', {}, it.by), h('span.muted', {}, ' via Agentpen')), h('p', {}, it.text),
82
- it.status === 'queued' && h('.queued', {}, 'Queued. Codex picks it up when it is free.'));
82
+ it.status === 'queued' && h('.queued', {}, `Queued. ${agent} picks it up when it is free.`));
83
83
  if (it.role === 'assistant') return h('.bubble.agent', {}, prose(it.text));
84
84
  if (it.role === 'plan') return h('.bubble.agent.plan', {}, h('.label', {}, 'Plan'), prose(it.text));
85
85
  const row = h('summary', {}, h('code', {}, it.text.length > 140 ? it.text.slice(0, 140) + '…' : it.text), it.status && it.status !== 'completed' && h('span.tag', {}, it.status === 'inProgress' ? 'running' : it.status));
@@ -89,7 +89,7 @@ function threadView() {
89
89
  const draw = () => {
90
90
  const stick = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
91
91
  fill(list, order.length ? order.map((id) => turns.get(id)).filter(Boolean).map(turnEl)
92
- : h('p.muted', { style: 'padding:24px 0' }, 'Nothing in this conversation yet. It will appear here as soon as the host sends a message in the Codex app.'));
92
+ : h('p.muted', { style: 'padding:24px 0' }, `Nothing in this conversation yet. It will appear here as soon as the host sends a message ${where}.`));
93
93
  if (stick) el.scrollTop = el.scrollHeight;
94
94
  };
95
95
  return {
@@ -173,7 +173,10 @@ function liveRoom(meta, guest, mount, me) {
173
173
 
174
174
  const isThread = meta.kind === 'thread';
175
175
  const wrap = h('.termwrap');
176
- const view = isThread ? threadView() : null;
176
+ // a Claude Code session shared after it started: a conversation nobody else can type into
177
+ const readOnly = isThread && meta.agent === 'claude';
178
+ const agentLabel = readOnly ? 'Claude' : 'Codex';
179
+ const view = isThread ? threadView(agentLabel, readOnly ? 'in their terminal' : 'in the Codex app') : null;
177
180
  const banner = h('div');
178
181
  const stateSlot = h('span');
179
182
  const peopleSlot = h('span.hide-sm');
@@ -185,10 +188,11 @@ function liveRoom(meta, guest, mount, me) {
185
188
 
186
189
  const setBanner = (state) => {
187
190
  if (ended) return;
188
- if (state === 'blocked') fill(banner, h('.banner.blocked', { role: 'status' }, isThread ? `Codex is waiting on ${meta.host.name} to approve or answer in the app.` : 'The agent is waiting on a human.', !isThread && you.canType ? ' Click the terminal to answer.' : ''));
191
+ if (state === 'blocked') fill(banner, h('.banner.blocked', { role: 'status' }, isThread ? `${agentLabel} is waiting on ${meta.host.name} to approve or answer ${readOnly ? 'in their terminal' : 'in the app'}.` : 'The agent is waiting on a human.', !isThread && you.canType ? ' Click the terminal to answer.' : ''));
189
192
  else if (state === 'reconnecting') fill(banner, h('.banner.reconnecting', { role: 'status' }, `${meta.host.name}'s machine went offline. Waiting for it to reconnect…`), pickupPanel(meta, 'Can’t wait?'));
190
193
  else if (you.guest) fill(banner, h('.banner.info', {}, `You are watching ${meta.host.name}'s session as a guest.`));
191
194
  else if (privateNow) fill(banner, h('.banner.info', {}, 'Private. Only you can see this session. Change it at the top right whenever you want to share.'));
195
+ else if (readOnly) fill(banner, h('.banner.info', {}, meta.isHost ? 'Shared from a session that was already running. Teammates can watch and chat, not type.' : `Watch only. ${meta.host.name} shared this after it started, so it cannot take prompts. Use chat to reach them.`));
192
196
  else if (!you.canType) fill(banner, h('.banner.info', {}, `Watch only. The host has ${isThread ? 'prompting' : 'typing'} turned off for teammates.`));
193
197
  else fill(banner);
194
198
  };
@@ -234,7 +238,7 @@ function liveRoom(meta, guest, mount, me) {
234
238
  const giveWheel = h('button.btn.ghost.small', { type: 'button', title: 'An invited agent steers your agent toward a goal, for a few steps', onclick: () => { if (needAgent()) setMode('drive'); } }, 'Hand over');
235
239
  const nameAgent = () => { askClaude.textContent = `Ask ${pick.get()?.name || 'an agent'}`; if (mode === 'drive') setMode('drive'); };
236
240
  pick.onChange(nameAgent);
237
- giveWheel.hidden = !meta.isHost;
241
+ giveWheel.hidden = !meta.isHost || readOnly;
238
242
  askClaude.hidden = !!meta.guest;
239
243
  const setMode = (m) => {
240
244
  mode = (m === 'prompt' && !you.canType) || (m === 'drive' && !meta.isHost) ? 'chat' : m;
@@ -264,7 +268,7 @@ function liveRoom(meta, guest, mount, me) {
264
268
  // host / admin controls
265
269
  const access = h('select.input.hide-sm', { style: 'width:auto;height:30px;font-size:13px', 'aria-label': 'What teammates can do',
266
270
  onchange: async (e) => { try { await api('PATCH', `/api/sessions/${meta.id}`, { access: e.target.value }); } catch (x) { toast(x.message); } } },
267
- h('option', { value: 'control' }, isThread ? 'Teammates can prompt' : 'Teammates can type'), h('option', { value: 'view' }, 'Teammates watch only'),
271
+ !readOnly && h('option', { value: 'control' }, isThread ? 'Teammates can prompt' : 'Teammates can type'), h('option', { value: 'view' }, 'Teammates watch only'),
268
272
  meta.isHost && h('option', { value: 'private' }, 'Private (only you)'));
269
273
  const controls = [];
270
274
  if (summary) controls.push(summary.btn);
@@ -276,7 +280,7 @@ function liveRoom(meta, guest, mount, me) {
276
280
  try { const r = await api('POST', `/api/sessions/${meta.id}/guest-link`); await copy(r.url, 'Guest link copied. View-only, dies with the session.'); } catch (x) { toast(x.message); }
277
281
  } }, 'Guest link'),
278
282
  h('button.btn.small.danger', { onclick: async () => {
279
- if (!confirm(isThread ? 'Stop sharing this conversation? It carries on in the Codex app.' : 'End this session for everyone? The agent on the host machine will be stopped.')) return;
283
+ if (!confirm(isThread ? `Stop sharing this conversation? It carries on ${readOnly ? 'in the host’s terminal' : 'in the Codex app'}.` : 'End this session for everyone? The agent on the host machine will be stopped.')) return;
280
284
  try { await api('POST', `/api/sessions/${meta.id}/end`); } catch (x) { toast(x.message); }
281
285
  } }, 'End'));
282
286
  }
@@ -379,7 +383,7 @@ async function replayRoom(meta, mount) {
379
383
  const side = h('aside.side', {}, summary.box, h('.tabs', {}, h('button.btn.ghost.small.on', {}, 'Activity')),
380
384
  h('.feed', {}, meta.events.length ? meta.events.map(eventRow) : h('p.small.muted', {}, 'No recorded activity.')));
381
385
  if (meta.kind === 'thread' && meta.hasRecording) {
382
- const view = threadView();
386
+ const view = meta.agent === 'claude' ? threadView('Claude', 'in their terminal') : threadView();
383
387
  view.set((await (await fetch(`/api/sessions/${meta.id}/recording`)).json()).turns || []);
384
388
  return mount(h('.room', {}, bar, h('.roombody', {}, h('.stage.light', {}, panel, view.el), side)));
385
389
  }
package/web/styles.css CHANGED
@@ -131,6 +131,9 @@ a.session .meta { color: var(--muted); font-size: 13px; overflow: hidden; text-o
131
131
  .empty h3 { font-size: 18px; margin-bottom: 6px; }
132
132
  .cmd { display: inline-flex; align-items: center; gap: 12px; margin-top: 16px; padding: 10px 10px 10px 16px; background: var(--term-bg); color: #efe8df; border-radius: 9px; font: 14px var(--mono); border: 1px solid var(--line); max-width: 100%; }
133
133
  .cmd span { overflow-x: auto; white-space: nowrap; }
134
+ /* In the narrow sign-up card the command wraps instead of scrolling out of view. */
135
+ .center .cmd { display: flex; margin-top: 10px; font-size: 13px; }
136
+ .center .cmd span { flex: 1; white-space: normal; overflow-wrap: anywhere; }
134
137
  .cmd .btn { color: #efe8df; background: #2a2520; border-color: #3a332c; }
135
138
 
136
139
  table.list { width: 100%; border-collapse: collapse; }