agentpen-cli 0.1.0 → 0.1.2

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,27 @@ 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. Inside Claude Code, type:
80
+
81
+ ```
82
+ /agentpen
83
+ ```
84
+
85
+ The session appears on the team page, and teammates can prompt it. (`/agentpen stop` stops sharing, `/agentpen --private` starts it visible only to you.)
86
+
87
+ Agentpen did not start that session, so it has no terminal to stream or type into. Two things stand in for it:
88
+
89
+ - **What the team sees** is the conversation, read from the file Claude Code keeps on disk: 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.
90
+ - **How a teammate's prompt gets in** is a Claude Code hook that `/agentpen` registers for the rest of that session. Each time Claude finishes a turn, the hook waits in the background; when a teammate sends a prompt, it hands it to Claude under their name, waking Claude if it was idle. A prompt sent while Claude is busy shows as queued and goes in when the turn ends.
91
+
92
+ Who may prompt follows the same setting as every other session ("Teammates can prompt" or "Teammates watch only"), and a teammate's prompt runs with whatever permissions that Claude Code session has, so read "can prompt" as "people I would hand my laptop to". An invited agent cannot be handed the wheel in these sessions.
93
+
94
+ `agentpen share`, run from another terminal in the same folder, shares the conversation too, but watch-only: without `/agentpen` there is no hook inside the session to deliver prompts. Typing `/agentpen` later opens prompting up on the same share. Sharing stops when Claude Code exits, after 30 quiet minutes, or with `agentpen share stop`.
95
+
96
+ `/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.
97
+
77
98
  ## Bring another agent into the session
78
99
 
79
100
  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 +203,7 @@ First run prints a code and opens the browser to approve the machine. The sessio
182
203
  ```
183
204
  agentpen [agent] [args...] share a terminal agent (default: claude)
184
205
  agentpen codex-app share a Codex desktop app conversation
206
+ agentpen share [stop] share a Claude Code session that is already running (/agentpen from inside it)
185
207
  agentpen install | uninstall share automatically: plain `claude`, and the Codex app
186
208
  agentpen pause | resume stop or restart automatic sharing on this machine
187
209
  agentpen default private|watch|type|workspace how your sessions start on this machine
@@ -249,6 +271,7 @@ Not built:
249
271
  - **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
272
  - **Search covers ended sessions only**, and terminal sessions are indexed from the same plain-text capture, so full-screen programs produce noisy matches.
251
273
  - **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.
274
+ - **Sharing a running session 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. Teammates' prompts ride on Claude Code's background hooks (`asyncRewake`), which are thinly documented: this was run once for real against Claude Code 2.1.331 (share with the skill, prompt from the page, idle session woke and answered) and is otherwise covered against a stand-in. Claude sees a teammate's prompt labelled as hook feedback rather than as something typed. If the session sits idle for more than 12 hours the waiting hook times out, and prompts then queue until the host's next turn. `/clear` or `/resume` drops the hook until `/agentpen` is typed again.
252
275
  - **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
276
  - **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
277
  - **No phone push.** Notifications reach open browser tabs and the Mac app only.
@@ -266,6 +289,7 @@ cli/agentpen.js the `agentpen` command
266
289
  cli/codex-app.js bridge to the Codex desktop app's control socket
267
290
  cli/install.js `agentpen install`: the shell hook and the macOS background helper
268
291
  cli/handoff.js checkpoints and `agentpen pickup`
292
+ cli/claude-share.js `agentpen share`: follow a running Claude Code conversation
269
293
  cli/redact.js .env masking
270
294
  server/notify.js who is notified about what; per-user stream and preferences
271
295
  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, awaitPrompt } 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,9 @@ 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
331
+ (type /agentpen inside it instead to let teammates prompt it)
332
+ agentpen share stop stop sharing it
327
333
  agentpen pickup LINK [--worktree] carry on a teammate's Claude Code session here
328
334
  agentpen install share automatically: plain \`claude\`, and the Codex app
329
335
  agentpen pause | resume stop or restart automatic sharing on this machine
@@ -371,6 +377,7 @@ async function main() {
371
377
  else if (a === '--private') opts.private = true;
372
378
  else if (a === '--auto') opts.auto = true;
373
379
  else if (a === '--thread') opts.thread = argv[++i];
380
+ else if (a === '--session') opts.session = argv[++i];
374
381
  else if (a === '--latest') opts.latest = true;
375
382
  else if (a === '--socket') opts.socket = argv[++i];
376
383
  else if (a === '--server') cfg.server = String(argv[++i] || '').replace(/\/$/, '');
@@ -431,6 +438,28 @@ async function main() {
431
438
  process.chdir(p.cwd);
432
439
  return share(cfg, { ...opts, title: opts.title || `${p.title} (picked up)` }, [process.env.AGENTPEN_CLAUDE || 'claude', '--resume', p.agentSession]);
433
440
  }
441
+ if (cmd === 'share') {
442
+ if (rest[1] === '--run' && rest.length === 3) return cfg.token ? runShareChild(cfg, rest[2]) : process.exit(1);
443
+ if (rest[1] === '--await-prompt' && rest.length === 2) return awaitPrompt().catch(() => {}); // the hook /agentpen registers
444
+ // its options may also come after the word, which is how the /agentpen command passes them
445
+ let stop = false;
446
+ let inClaude = false;
447
+ for (let j = 1; j < rest.length; j++) {
448
+ const a = rest[j];
449
+ if (a === 'stop') stop = true;
450
+ else if (a === '--in-claude') inClaude = true;
451
+ else if (a === '--private') opts.private = true;
452
+ else if (a === '--session') opts.session = rest[++j];
453
+ else if (a === '-t' || a === '--title') opts.title = rest[++j];
454
+ else die(`unexpected argument "${a}" for share. Try agentpen --help.`);
455
+ }
456
+ // run by /agentpen: Claude Code reads standard output, and a failure should be passed on rather than abort the command
457
+ const out = inClaude ? (s = '') => process.stdout.write(s.replace(/\x1b\[[0-9;]*m/g, '') + '\n') : say;
458
+ const ui = { say: out, die: inClaude ? (s) => { out(`Agentpen: ${s}`); process.exit(0); } : die, bold, dim, accent };
459
+ if (stop) return stopSharing(ui);
460
+ 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
461
+ return shareRunningClaude(cfg, { ...opts, inClaude, access: accessFor(cfg, opts) }, ui);
462
+ }
434
463
  if (opts.codexApp) {
435
464
  if (rest.length) die(`unexpected argument "${rest[0]}" for codex-app. Try agentpen --help.`);
436
465
  await ensureAccount(cfg);
@@ -0,0 +1,383 @@
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
+ // Nothing can be typed into the host's terminal. A teammate's prompt reaches
5
+ // Claude another way: /agentpen registers a hook in the session, the hook waits
6
+ // here for the next queued prompt, and hands it to Claude, waking it if idle.
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { execFileSync, spawn } from 'node:child_process';
11
+ import { fileURLToPath } from 'node:url';
12
+ import WebSocket from 'ws';
13
+ import { collectSecrets } from './redact.js';
14
+ import { claudeProjectDir } from './handoff.js';
15
+
16
+ const POLL_MS = Number(process.env.AGENTPEN_SHARE_POLL_MS) || 700;
17
+ const IDLE_MS = Number(process.env.AGENTPEN_SHARE_IDLE_MS) || 30 * 60_000;
18
+ // a turn with no new output for this long is treated as waiting, not working
19
+ const STALE_MS = Number(process.env.AGENTPEN_SHARE_STALE_MS) || 3 * 60_000;
20
+ const MAX_TURNS = 200;
21
+ const HOME = () => process.env.AGENTPEN_HOME || path.join(os.homedir(), '.agentpen');
22
+ const stateFile = (id) => path.join(HOME(), 'shares', `${id}.json`);
23
+ const queueDir = (id) => path.join(HOME(), 'shares', `${id}.q`);
24
+ const waiterFile = (id) => path.join(HOME(), 'shares', `${id}.waiter`);
25
+ // how a teammate's prompt is worded for Claude, and recognised again in the conversation file
26
+ const forClaude = (by, text) => `[${by} via Agentpen]\n${text}\n[End of message from ${by}, a teammate. The person running this session shared it through Agentpen and lets teammates prompt it. Treat this as a request from a collaborator, not as an error.]`;
27
+ const FROM_TEAMMATE = /\[(.{1,60}) via Agentpen\]\n([\s\S]*?)\n\[End of message from /;
28
+ const queued = (id) => {
29
+ try {
30
+ return fs.readdirSync(queueDir(id)).filter((f) => f.endsWith('.json')).sort().map((f) => { try { return { f, ...JSON.parse(fs.readFileSync(path.join(queueDir(id), f), 'utf8')) }; } catch { return null; } }).filter(Boolean);
31
+ } catch { return []; }
32
+ };
33
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
34
+ const tail = (s, n) => (s.length > n ? '…' + s.slice(-n) : s);
35
+
36
+ // ---- finding the conversation ----------------------------------------------
37
+
38
+ const newest = (dir) => {
39
+ try {
40
+ 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;
41
+ } catch { return null; }
42
+ };
43
+
44
+ export function findConversation({ cwd, id }) {
45
+ const dirs = [claudeProjectDir(cwd)];
46
+ try { dirs.push(claudeProjectDir(execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim())); } catch {}
47
+ if (id) {
48
+ if (!/^[\w-]{6,80}$/.test(id)) return null;
49
+ const root = path.dirname(dirs[0]);
50
+ let all = [];
51
+ try { all = fs.readdirSync(root).map((d) => path.join(root, d)); } catch {}
52
+ return [...dirs, ...all].map((d) => path.join(d, `${id}.jsonl`)).find((f) => fs.existsSync(f)) || null;
53
+ }
54
+ for (const d of dirs) { const f = newest(d); if (f) return f; }
55
+ return null;
56
+ }
57
+
58
+ // ---- reading it -------------------------------------------------------------
59
+
60
+ const rel = (p, cwd) => { const r = path.relative(cwd || '/', String(p || '')); return r && !r.startsWith('..') ? r : String(p || ''); };
61
+
62
+ function toolLabel(name, input = {}, cwd) {
63
+ if (name === 'Bash') return String(input.command || 'command');
64
+ if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit'].includes(name)) return `Edited ${rel(input.file_path || input.notebook_path, cwd)}`;
65
+ if (name === 'Read') return `Read ${rel(input.file_path, cwd)}`;
66
+ if (name === 'Grep' || name === 'Glob') return `Search: ${input.pattern || ''}`;
67
+ if (name === 'Task' || name === 'Agent') return `Subagent: ${input.description || ''}`;
68
+ if (name === 'WebFetch') return `Fetch ${input.url || ''}`;
69
+ if (name === 'WebSearch') return `Web search: ${input.query || ''}`;
70
+ const mcp = /^mcp__(.+?)__(.+)$/.exec(name);
71
+ return mcp ? `${mcp[1]}.${mcp[2]}` : name;
72
+ }
73
+
74
+ const blockText = (content) => (typeof content === 'string' ? content : Array.isArray(content) ? content.filter((b) => b?.type === 'text').map((b) => b.text).join('\n') : '');
75
+ // what Claude Code adds around a prompt (command echoes, reminders) is not something the person typed
76
+ const NOT_TYPED = /^\s*<(local-command|command-|system-reminder|task-notification|bash-|user-prompt-submit-hook)/;
77
+
78
+ /** Follows one conversation file. read() takes in whatever was appended and returns the conversation so far. */
79
+ export function follow(file, mask) {
80
+ let offset = 0;
81
+ let rest = '';
82
+ let title = '';
83
+ let cwd = '';
84
+ let branch = '';
85
+ const turns = [];
86
+ const tools = new Map(); // tool call id -> its item
87
+ let turn = null;
88
+ const open = (id) => { turn = { id, status: 'inProgress', items: [] }; turns.push(turn); };
89
+
90
+ const take = (e) => {
91
+ if (e.type === 'ai-title' && e.aiTitle) { title = String(e.aiTitle); return; }
92
+ if (e.isSidechain || e.isMeta || !e.message) return;
93
+ if (e.cwd) cwd = e.cwd;
94
+ if (e.gitBranch) branch = e.gitBranch;
95
+ const content = e.message.content;
96
+ if (e.type === 'user') {
97
+ for (const b of Array.isArray(content) ? content : []) {
98
+ if (b?.type !== 'tool_result') continue;
99
+ const it = tools.get(b.tool_use_id);
100
+ if (!it) continue;
101
+ it.status = b.is_error ? 'failed' : 'completed';
102
+ if (it.shell) it.detail = mask(tail(blockText(b.content), 3000)) || undefined;
103
+ }
104
+ const text = blockText(content).trim();
105
+ const mate = FROM_TEAMMATE.exec(text); // a teammate's prompt, delivered by the hook
106
+ if (mate) {
107
+ if (turn?.status === 'inProgress') turn.status = 'completed';
108
+ open(e.uuid || `u${turns.length}`);
109
+ turn.items.push({ id: turn.id, role: 'user', text: mask(mate[2]), by: mate[1] });
110
+ return;
111
+ }
112
+ if (!text || NOT_TYPED.test(text)) return;
113
+ if (text.startsWith('[Request interrupted')) { if (turn) turn.status = 'interrupted'; return; }
114
+ if (turn?.status === 'inProgress') turn.status = 'completed';
115
+ open(e.uuid || `u${turns.length}`);
116
+ turn.items.push({ id: turn.id, role: 'user', text: mask(text) });
117
+ if (!title) title = text.split('\n')[0].slice(0, 80);
118
+ } else if (e.type === 'assistant') {
119
+ if (!turn) open('start');
120
+ (Array.isArray(content) ? content : []).forEach((b, i) => {
121
+ if (b?.type === 'text' && b.text?.trim()) turn.items.push({ id: `${e.uuid}:${i}`, role: 'assistant', text: mask(b.text) });
122
+ else if (b?.type === 'tool_use') {
123
+ const it = { id: String(b.id), role: 'tool', text: mask(toolLabel(b.name, b.input, cwd)), status: 'inProgress', shell: b.name === 'Bash' };
124
+ tools.set(it.id, it);
125
+ turn.items.push(it);
126
+ }
127
+ });
128
+ if (turn.status !== 'interrupted') turn.status = e.message.stop_reason === 'end_turn' ? 'completed' : 'inProgress';
129
+ }
130
+ };
131
+
132
+ return {
133
+ read() {
134
+ const size = fs.statSync(file).size;
135
+ if (size < offset) { offset = 0; rest = ''; } // rewritten: start over rather than read from the middle of a line
136
+ if (size > offset) {
137
+ const fd = fs.openSync(file, 'r');
138
+ try {
139
+ const buf = Buffer.alloc(size - offset);
140
+ fs.readSync(fd, buf, 0, buf.length, offset);
141
+ offset = size;
142
+ const lines = (rest + buf.toString('utf8')).split('\n');
143
+ rest = lines.pop();
144
+ for (const l of lines) { if (!l.trim()) continue; try { take(JSON.parse(l)); } catch {} }
145
+ } finally { fs.closeSync(fd); }
146
+ }
147
+ const quiet = Date.now() - fs.statSync(file).mtimeMs;
148
+ const shown = turns.slice(-MAX_TURNS).map((t) => ({ id: t.id, status: t.status, items: t.items.map(({ shell, ...it }) => it) }));
149
+ return { title: title || 'Claude Code session', cwd, branch, turns: shown, quiet, status: turn?.status === 'inProgress' && quiet < STALE_MS ? 'working' : 'idle' };
150
+ },
151
+ };
152
+ }
153
+
154
+ // ---- sharing it -------------------------------------------------------------
155
+
156
+ /** Runs until the session is over. Calls onReady once the team can see it. */
157
+ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, log = () => {} }) {
158
+ const first = follow(file, (s) => s).read();
159
+ const cwd = first.cwd || process.cwd();
160
+ const secrets = opts.shareSecrets ? [] : collectSecrets(cwd).sort((a, b) => b.length - a.length);
161
+ const mask = (s) => { for (const v of secrets) s = s.split(v).join('••••••'); return s; };
162
+ const conv = follow(file, mask);
163
+ const convId = path.basename(file, '.jsonl');
164
+ // prompts still waiting for Claude are shown at the end, marked as queued
165
+ const read = () => {
166
+ const s = conv.read();
167
+ const waiting = queued(convId).map((p) => ({ id: p.rid, role: 'user', text: mask(p.text), by: p.by, status: 'queued' }));
168
+ if (waiting.length) s.turns.push({ id: 'queued', status: 'completed', items: waiting });
169
+ return s;
170
+ };
171
+ let snap = read();
172
+ const hello = {
173
+ t: 'hello', kind: 'thread', workspace: opts.workspace, title: opts.title || snap.title, agent: 'claude',
174
+ project: path.basename(cwd), branch: snap.branch || '', access: opts.access,
175
+ };
176
+ // true once /agentpen has run inside the session: its hook is what delivers prompts
177
+ const canPrompt = () => fs.existsSync(waiterFile(convId));
178
+ let sentCaps = null;
179
+
180
+ let ws = null;
181
+ let session = null;
182
+ let stopping = false;
183
+ let retry = 0;
184
+ let sent = new Map();
185
+ let sentMeta = '';
186
+ const push = () => {
187
+ if (ws?.readyState !== 1 || !session) return;
188
+ const changed = snap.turns.filter((t) => sent.get(t.id) !== JSON.stringify(t));
189
+ const meta = JSON.stringify([snap.title, snap.status, snap.turns.map((t) => t.id)]);
190
+ if (!changed.length && meta === sentMeta) return;
191
+ for (let i = 0; i < Math.max(1, changed.length); i += 40) {
192
+ 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 }));
193
+ }
194
+ for (const t of changed) sent.set(t.id, JSON.stringify(t));
195
+ sentMeta = meta;
196
+ };
197
+ const caps = () => {
198
+ if (ws?.readyState !== 1 || !session || sentCaps === canPrompt()) return;
199
+ sentCaps = canPrompt();
200
+ ws.send(JSON.stringify({ t: 'caps', prompts: sentCaps }));
201
+ };
202
+ const onPrompt = (m) => {
203
+ let ok = canPrompt();
204
+ if (ok) {
205
+ try {
206
+ fs.mkdirSync(queueDir(convId), { recursive: true, mode: 0o700 });
207
+ const name = `${Date.now()}-${String(m.rid).replace(/[^\w-]/g, '')}.json`;
208
+ fs.writeFileSync(path.join(queueDir(convId), `.${name}`), JSON.stringify({ rid: String(m.rid), by: String(m.by).slice(0, 60), text: String(m.text) }), { mode: 0o600 });
209
+ fs.renameSync(path.join(queueDir(convId), `.${name}`), path.join(queueDir(convId), name)); // appears whole or not at all
210
+ log(`${m.by} queued a prompt`);
211
+ snap = read();
212
+ push();
213
+ } catch { ok = false; }
214
+ }
215
+ if (ws?.readyState === 1) ws.send(JSON.stringify({ t: 'prompt-result', rid: m.rid, ok }));
216
+ };
217
+ const stop = (reason) => new Promise((resolve) => {
218
+ if (stopping) return resolve();
219
+ stopping = true;
220
+ const done = () => { onEnd?.(reason); resolve(); };
221
+ if (ws?.readyState === 1) { ws.send(JSON.stringify({ t: 'exit' }), () => ws.close()); setTimeout(done, 400); } else done();
222
+ });
223
+ onStoppable?.(stop);
224
+
225
+ await new Promise((resolve, reject) => {
226
+ const connect = () => {
227
+ ws = new WebSocket(cfg.server.replace(/^http/, 'ws') + '/ws/host', { headers: { authorization: `Bearer ${cfg.token}` } });
228
+ ws.on('open', () => ws.send(JSON.stringify(session ? { t: 'hello', resume: { id: session.id, key: session.key } } : hello)));
229
+ ws.on('message', (data, isBinary) => {
230
+ if (isBinary) return;
231
+ let m;
232
+ try { m = JSON.parse(data); } catch { return; }
233
+ if (m.t === 'ready') {
234
+ const fresh = !session;
235
+ session = { ...session, ...m };
236
+ retry = 0;
237
+ if (!m.resumed) { sent = new Map(); sentMeta = ''; sentCaps = null; }
238
+ caps();
239
+ push();
240
+ if (fresh) onReady?.(session);
241
+ resolve();
242
+ } else if (m.t === 'error') {
243
+ if (session && m.code === 'gone') session = null; // server restarted: start a fresh session
244
+ else if (!session) { stopping = true; reject(new Error(m.message)); }
245
+ } else if (m.t === 'prompt') onPrompt(m);
246
+ else if (m.t === 'end') { stopping = true; onEnd?.(m.reason); }
247
+ });
248
+ ws.on('close', () => {
249
+ if (stopping) return;
250
+ if (!session && retry >= 3) { stopping = true; return reject(new Error(`cannot reach ${cfg.server}`)); }
251
+ setTimeout(connect, Math.min(8000, 500 * 2 ** retry++));
252
+ });
253
+ ws.on('error', () => {});
254
+ };
255
+ connect();
256
+ });
257
+
258
+ while (!stopping) {
259
+ await new Promise((r) => setTimeout(r, POLL_MS));
260
+ if (stopping) break;
261
+ if (opts.claudePid && !alive(opts.claudePid)) { log('Claude Code exited'); await stop('Claude Code exited'); break; }
262
+ try { snap = read(); } catch { log('conversation file is gone'); await stop('conversation ended'); break; }
263
+ if (snap.quiet > IDLE_MS) { log('quiet for too long'); await stop('no activity'); break; }
264
+ caps();
265
+ push();
266
+ }
267
+ }
268
+
269
+ // ---- the command ------------------------------------------------------------
270
+
271
+ const readState = (id) => { try { return JSON.parse(fs.readFileSync(stateFile(id), 'utf8')); } catch { return null; } };
272
+ const allStates = () => {
273
+ 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 []; }
274
+ };
275
+
276
+ export function stopSharing(ui) {
277
+ const live = allStates();
278
+ if (!live.length) return ui.say('Nothing is being shared from this machine with `agentpen share`.');
279
+ for (const s of live) { try { process.kill(s.pid, 'SIGTERM'); } catch {} ui.say(`Stopped sharing “${s.title}”. ${ui.dim(s.url)}`); }
280
+ }
281
+
282
+ /** `agentpen share`: starts a background sharer for the running conversation, prints the link, and returns. */
283
+ export async function shareRunningClaude(cfg, opts, ui) {
284
+ const id = opts.session || process.env.CLAUDE_CODE_SESSION_ID;
285
+ const file = findConversation({ cwd: process.cwd(), id });
286
+ 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');
287
+ const convId = path.basename(file, '.jsonl');
288
+ const running = readState(convId);
289
+ if (running && alive(running.pid)) return ui.say(`Already sharing “${running.title}”: ${ui.accent(running.url)}`);
290
+
291
+ fs.mkdirSync(path.dirname(stateFile(convId)), { recursive: true, mode: 0o700 });
292
+ const logFd = fs.openSync(path.join(HOME(), 'share.log'), 'a');
293
+ const claudePid = Number(process.env.CLAUDE_PID) || 0;
294
+ const child = spawn(process.execPath, [fileURLToPath(new URL('./agentpen.js', import.meta.url)), 'share', '--run', file], {
295
+ detached: true, stdio: ['ignore', logFd, logFd, 'ipc'],
296
+ env: { ...process.env, AGENTPEN_SHARE_OPTS: JSON.stringify({ ...opts, claudePid }) },
297
+ });
298
+ const result = await new Promise((resolve) => {
299
+ const t = setTimeout(() => resolve({ error: `cannot reach ${cfg.server}` }), 20_000);
300
+ child.once('message', (m) => { clearTimeout(t); resolve(m); });
301
+ child.once('exit', () => { clearTimeout(t); resolve({ error: 'sharing stopped before it started. See ~/.agentpen/share.log' }); });
302
+ });
303
+ if (result.error) { try { child.kill(); } catch {} ui.die(result.error); }
304
+ child.disconnect();
305
+ child.unref();
306
+ ui.say();
307
+ ui.say(` ${ui.accent('●')} ${ui.bold(`Sharing “${result.title}”`)} ${ui.dim(`live in ${result.workspace}`)}`);
308
+ ui.say(` ${ui.accent(result.url)}`);
309
+ ui.say(ui.dim(` ${result.access === 'private' ? 'Only you can see it until you share it from that page.' : opts.inClaude
310
+ ? `Teammates can watch the conversation and chat.${result.access === 'control' ? ' Their prompts reach Claude here under their names.' : ' To let them prompt Claude too, switch to "Teammates can prompt" on that page.'}`
311
+ : 'Teammates can watch the conversation and chat. To let them prompt it too, type /agentpen inside that Claude Code session.'}`));
312
+ ui.say(ui.dim(' It stops when Claude Code exits, or with: agentpen share stop\n'));
313
+ }
314
+
315
+ /** The background half, started by shareRunningClaude. */
316
+ export async function runShareChild(cfg, file) {
317
+ const opts = JSON.parse(process.env.AGENTPEN_SHARE_OPTS || '{}');
318
+ const convId = path.basename(file, '.jsonl');
319
+ const log = (m) => console.log(`${new Date().toISOString()} ${convId} ${m}`);
320
+ const cleanup = () => {
321
+ try {
322
+ if (readState(convId)?.pid !== process.pid) return;
323
+ fs.rmSync(stateFile(convId), { force: true });
324
+ fs.rmSync(queueDir(convId), { recursive: true, force: true });
325
+ fs.rmSync(waiterFile(convId), { force: true });
326
+ } catch {}
327
+ };
328
+ let stop = null;
329
+ const quit = () => (stop ? stop('stopped by host') : process.exit(0));
330
+ process.on('SIGTERM', quit);
331
+ process.on('SIGINT', quit);
332
+ try {
333
+ await runShare(cfg, file, opts, {
334
+ log,
335
+ onStoppable: (fn) => { stop = fn; },
336
+ onReady: (s) => {
337
+ const info = { pid: process.pid, title: opts.title || follow(file, (x) => x).read().title, url: s.url, workspace: s.workspace.name, access: s.access };
338
+ fs.writeFileSync(stateFile(convId), JSON.stringify(info), { mode: 0o600 });
339
+ log(`sharing at ${s.url}`);
340
+ if (process.connected) process.send(info);
341
+ },
342
+ onEnd: (reason) => { log(`ended: ${reason}`); cleanup(); setTimeout(() => process.exit(0), 500); },
343
+ });
344
+ } catch (e) {
345
+ log(`failed: ${e.message}`);
346
+ if (process.connected) process.send({ error: e.message });
347
+ cleanup();
348
+ process.exit(1);
349
+ }
350
+ }
351
+
352
+ /**
353
+ * The hook /agentpen registers in a Claude Code session. Claude Code starts it in the
354
+ * background each time Claude finishes a turn. It waits for a teammate's prompt and
355
+ * ends with exit code 2 and the prompt on standard error, which is how a background
356
+ * hook wakes Claude with a message. It ends quietly if the session is not being
357
+ * shared, or once a newer copy of itself has taken over.
358
+ */
359
+ export async function awaitPrompt() {
360
+ let input = '';
361
+ if (!process.stdin.isTTY) for await (const c of process.stdin) input += c;
362
+ let id = process.env.CLAUDE_CODE_SESSION_ID || '';
363
+ try { id = JSON.parse(input).session_id || id; } catch {}
364
+ if (!/^[\w-]{6,80}$/.test(id)) return;
365
+ const sharing = () => { const s = readState(id); return !!s && alive(s.pid); };
366
+ if (!sharing()) return;
367
+ const me = String(process.pid);
368
+ fs.writeFileSync(waiterFile(id), me, { mode: 0o600 });
369
+ for (;;) {
370
+ let holder = '';
371
+ try { holder = fs.readFileSync(waiterFile(id), 'utf8'); } catch {}
372
+ if (holder !== me || !sharing()) return;
373
+ for (const p of queued(id)) {
374
+ const mine = path.join(queueDir(id), `${p.f}.${me}`);
375
+ try { fs.renameSync(path.join(queueDir(id), p.f), mine); } catch { continue; } // another copy got there first
376
+ fs.rmSync(mine, { force: true });
377
+ process.stderr.write(forClaude(p.by, p.text));
378
+ process.exitCode = 2;
379
+ return;
380
+ }
381
+ await new Promise((r) => setTimeout(r, 300));
382
+ }
383
+ }
package/cli/install.js CHANGED
@@ -73,10 +73,59 @@ ${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 registers a
79
+ // hook for the rest of that session: each time Claude finishes a turn, the hook
80
+ // waits in the background for a teammate's prompt and wakes Claude with it.
81
+ const SKILL = `---
82
+ name: agentpen
83
+ description: Share this Claude Code session with your Agentpen workspace so teammates can watch it live. "/agentpen stop" stops sharing.
84
+ argument-hint: "[stop | --private]"
85
+ disable-model-invocation: true
86
+ allowed-tools: Bash(agentpen share *)
87
+ hooks:
88
+ Stop:
89
+ - hooks:
90
+ - type: command
91
+ command: agentpen share --await-prompt
92
+ asyncRewake: true
93
+ timeout: 43200
94
+ ---
95
+ <!-- installed by agentpen. Remove with: agentpen uninstall -->
96
+ The user asked to share this session with their team through Agentpen. This command has already run:
97
+
98
+ !\`agentpen share --in-claude --session \${CLAUDE_SESSION_ID} $ARGUMENTS\`
99
+
100
+ 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.
101
+ `;
102
+ const skillFile = () => path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'skills', 'agentpen', 'SKILL.md');
103
+
104
+ /** Adds /agentpen to Claude Code. Returns true if it is in place. Does nothing where Claude Code has never run. */
105
+ export function installSkill() {
106
+ try {
107
+ const f = skillFile();
108
+ if (!fs.existsSync(path.dirname(path.dirname(path.dirname(f))))) return false;
109
+ if (fs.existsSync(f) && !fs.readFileSync(f, 'utf8').includes('installed by agentpen')) return false; // someone else's skill of the same name: leave it
110
+ fs.mkdirSync(path.dirname(f), { recursive: true });
111
+ fs.writeFileSync(f, SKILL);
112
+ return true;
113
+ } catch { return false; }
114
+ }
115
+ export function removeSkill() {
116
+ try {
117
+ const f = skillFile();
118
+ if (!fs.readFileSync(f, 'utf8').includes('installed by agentpen')) return false;
119
+ fs.rmSync(path.dirname(f), { recursive: true, force: true });
120
+ return true;
121
+ } catch { return false; }
122
+ }
123
+
76
124
  export function install({ workspace, shellOnly }, ui) {
77
125
  const files = rcFiles();
78
126
  for (const f of files) writeHook(f);
79
127
 
128
+ const skill = installSkill();
80
129
  let codex = 'skipped';
81
130
  if (!shellOnly && process.platform === 'darwin') {
82
131
  const p = plistPath();
@@ -93,6 +142,11 @@ export function install({ workspace, shellOnly }, ui) {
93
142
  ui.say(` ${ui.accent('claude')} Typing plain ${ui.bold('claude')} in a new terminal now starts a shared session.`);
94
143
  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
144
  ui.say(ui.dim(' One-off commands (claude -p, claude mcp, claude update) are never shared.'));
145
+ if (skill) {
146
+ ui.say();
147
+ ui.say(` ${ui.accent('/agentpen')} In a Claude Code session that is already running, type ${ui.bold('/agentpen')} to share it.`);
148
+ ui.say(ui.dim(' Teammates can watch that one and chat. They cannot type into it.'));
149
+ }
96
150
  ui.say();
97
151
  if (codex === 'on') {
98
152
  ui.say(` ${ui.accent('Codex app')} A background helper shares coding conversations while they are active.`);
@@ -122,6 +176,7 @@ export function uninstall(ui) {
122
176
  launchctl('bootout', `gui/${process.getuid()}/${LABEL}`);
123
177
  fs.rmSync(plistPath(), { force: true });
124
178
  }
179
+ if (removeSkill()) ui.say('Removed /agentpen from Claude Code.');
125
180
  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
181
  if (process.platform === 'darwin') ui.say('Stopped the Codex app helper.');
127
182
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentpen-cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
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,9 @@ 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 has no terminal to type into. Prompts can
62
+ // reach it only once its host has run /agentpen inside it, which the CLI then reports.
63
+ this.promptable = false;
61
64
  this.turns = new Map(); // thread sessions: turn id -> turn
62
65
  this.order = [];
63
66
  this.rec = null;
@@ -70,6 +73,19 @@ class LiveSession {
70
73
  }) + '\n');
71
74
  }
72
75
 
76
+ get attached() { return this.kind === 'thread' && this.row.agent === 'claude'; }
77
+ get readOnly() { return this.attached && !this.promptable; }
78
+
79
+ setPromptable(on) {
80
+ if (!this.attached || this.promptable === on) return;
81
+ this.promptable = on;
82
+ for (const v of this.viewers.values()) {
83
+ v.canType = this.canType(v.user);
84
+ send(v.ws, { t: 'caps', prompts: on, canType: v.canType });
85
+ }
86
+ this.peopleChanged();
87
+ }
88
+
73
89
  // A Codex app conversation arrives as changed turns plus the full turn order.
74
90
  threadUpdate(m) {
75
91
  const changed = [];
@@ -110,7 +126,7 @@ class LiveSession {
110
126
  const r = this.row;
111
127
  return {
112
128
  id: r.id, title: r.title, agent: r.agent, project: r.project, branch: r.branch,
113
- access: r.access, state: this.state, started_at: r.started_at, kind: this.kind,
129
+ access: r.access, state: this.state, started_at: r.started_at, kind: this.kind, prompts: this.attached ? this.promptable : undefined,
114
130
  host: this.host, people,
115
131
  };
116
132
  }
@@ -121,7 +137,7 @@ class LiveSession {
121
137
  }
122
138
 
123
139
  canType(user) {
124
- if (user.guest) return false;
140
+ if (user.guest || this.readOnly) return false;
125
141
  return user.id === this.row.host_id || this.row.access === 'control';
126
142
  }
127
143
 
@@ -179,7 +195,7 @@ class LiveSession {
179
195
 
180
196
  // What the agent is actually asking, so the notification can be answered at a glance.
181
197
  question() {
182
- if (this.kind === 'thread') return 'Waiting for you to approve or answer in the Codex app.';
198
+ if (this.kind === 'thread') return this.attached ? 'Waiting for you in your terminal.' : 'Waiting for you to approve or answer in the Codex app.';
183
199
  const lines = this.recentLines(6);
184
200
  // the question itself reads better than the menu under it ("❯ 1. Yes")
185
201
  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 +345,7 @@ class LiveSession {
329
345
 
330
346
  // An attributed prompt for the agent. Returns false if it could not be delivered.
331
347
  prompt(user, raw, asInvitedAgent = false) {
332
- if ((!asInvitedAgent && !this.canType(user)) || this.ws?.readyState !== 1) return false;
348
+ if (this.readOnly || (!asInvitedAgent && !this.canType(user)) || this.ws?.readyState !== 1) return false;
333
349
  let text;
334
350
  if (this.kind === 'thread') {
335
351
  // a conversation takes the prompt as a message, queued under the sender's name
@@ -469,8 +485,10 @@ export function attachHost(ws, user) {
469
485
  s.end(s.kind === 'thread' ? 'sharing stopped' : 'agent exited');
470
486
  } else if (m.t === 'thread' && s.kind === 'thread') {
471
487
  s.threadUpdate(m);
488
+ } else if (m.t === 'caps') {
489
+ s.setPromptable(m.prompts === true);
472
490
  } 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.' });
491
+ s.broadcast({ t: 'notice', text: `${s.agentName()} did not confirm that prompt. Check with the host before sending it again.` });
474
492
  }
475
493
  });
476
494
  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.attached) bad(400, 'This session was shared after it started. 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 };
@@ -641,12 +642,13 @@ function serveStatic(req, res, pathname) {
641
642
  if (path.extname(pathname)) { res.writeHead(404, SECURITY_HEADERS); return res.end('Not found'); }
642
643
  file = path.join(WEB, 'index.html');
643
644
  }
644
- const isHtml = file.endsWith('.html');
645
- res.writeHead(200, {
646
- ...SECURITY_HEADERS,
647
- 'content-type': MIME[path.extname(file)] || 'application/octet-stream',
648
- 'cache-control': isHtml || IS_LOCAL ? 'no-cache' : 'public, max-age=3600',
649
- });
645
+ // Browsers keep a copy but ask before using it, so a deploy shows up on the next page load
646
+ // instead of an hour later; an unchanged file costs one small "not modified" reply.
647
+ const st = fs.statSync(file);
648
+ const etag = `"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`;
649
+ const headers = { ...SECURITY_HEADERS, 'content-type': MIME[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-cache', etag };
650
+ if (req.headers['if-none-match'] === etag) { res.writeHead(304, headers); return res.end(); }
651
+ res.writeHead(200, headers);
650
652
  fs.createReadStream(file).pipe(res);
651
653
  }
652
654
 
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,12 @@ 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. It takes prompts only once its host has
177
+ // typed /agentpen inside it; until then it is a conversation to watch.
178
+ const attached = isThread && meta.agent === 'claude';
179
+ let readOnly = attached;
180
+ const agentLabel = attached ? 'Claude' : 'Codex';
181
+ const view = isThread ? threadView(agentLabel, attached ? 'in their terminal' : 'in the Codex app') : null;
177
182
  const banner = h('div');
178
183
  const stateSlot = h('span');
179
184
  const peopleSlot = h('span.hide-sm');
@@ -185,10 +190,11 @@ function liveRoom(meta, guest, mount, me) {
185
190
 
186
191
  const setBanner = (state) => {
187
192
  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.' : ''));
193
+ if (state === 'blocked') fill(banner, h('.banner.blocked', { role: 'status' }, isThread ? `${agentLabel} is waiting on ${meta.host.name} to approve or answer ${attached ? 'in their terminal' : 'in the app'}.` : 'The agent is waiting on a human.', !isThread && you.canType ? ' Click the terminal to answer.' : ''));
189
194
  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
195
  else if (you.guest) fill(banner, h('.banner.info', {}, `You are watching ${meta.host.name}'s session as a guest.`));
191
196
  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.'));
197
+ else if (readOnly) fill(banner, h('.banner.info', {}, meta.isHost ? 'Teammates can watch and chat. To let them prompt it too, type /agentpen inside that Claude Code session.' : `Watch only for now. It takes prompts once ${meta.host.name} types /agentpen inside the session. Use chat to reach them.`));
192
198
  else if (!you.canType) fill(banner, h('.banner.info', {}, `Watch only. The host has ${isThread ? 'prompting' : 'typing'} turned off for teammates.`));
193
199
  else fill(banner);
194
200
  };
@@ -221,7 +227,7 @@ function liveRoom(meta, guest, mount, me) {
221
227
  // composer: two clearly different destinations
222
228
  const input = h('textarea.input', { rows: 2, 'aria-label': 'Message' });
223
229
  const sendBtn = h('button.btn.primary.small', { type: 'submit' });
224
- const toAgent = h('button.btn.ghost.small', { type: 'button', onclick: () => setMode('prompt') }, isThread ? 'Ask Codex' : 'Prompt the agent');
230
+ const toAgent = h('button.btn.ghost.small', { type: 'button', onclick: () => setMode('prompt') }, isThread ? `Ask ${agentLabel}` : 'Prompt the agent');
225
231
  const toTeam = h('button.btn.ghost.small', { type: 'button', onclick: () => setMode('chat') }, 'Chat with team');
226
232
  // invite another model in: anyone can ask it, only the host can give it the wheel
227
233
  const needAgent = () => { if (pick.any()) return true; toast(NO_AGENT); return false; };
@@ -234,7 +240,7 @@ function liveRoom(meta, guest, mount, me) {
234
240
  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
241
  const nameAgent = () => { askClaude.textContent = `Ask ${pick.get()?.name || 'an agent'}`; if (mode === 'drive') setMode('drive'); };
236
242
  pick.onChange(nameAgent);
237
- giveWheel.hidden = !meta.isHost;
243
+ giveWheel.hidden = !meta.isHost || attached;
238
244
  askClaude.hidden = !!meta.guest;
239
245
  const setMode = (m) => {
240
246
  mode = (m === 'prompt' && !you.canType) || (m === 'drive' && !meta.isHost) ? 'chat' : m;
@@ -243,8 +249,8 @@ function liveRoom(meta, guest, mount, me) {
243
249
  toTeam.classList.toggle('on', mode === 'chat');
244
250
  giveWheel.classList.toggle('on', mode === 'drive');
245
251
  if (mode === 'drive') { input.placeholder = `What should ${pick.get()?.name || 'the agent'} get done? It steers your agent for up to 8 steps and never approves anything for you.`; sendBtn.textContent = 'Hand over the wheel'; return; }
246
- input.placeholder = mode === 'prompt' ? (isThread ? 'Ask Codex. Queued into the conversation under your name.' : 'Tell the agent what to do. Sent under your name.') : 'Message the people in this session';
247
- sendBtn.textContent = mode === 'prompt' ? (isThread ? 'Send to Codex' : 'Send to agent') : 'Send';
252
+ input.placeholder = mode === 'prompt' ? (isThread ? `Ask ${agentLabel}. Queued into the conversation under your name.` : 'Tell the agent what to do. Sent under your name.') : 'Message the people in this session';
253
+ sendBtn.textContent = mode === 'prompt' ? (isThread ? `Send to ${agentLabel}` : 'Send to agent') : 'Send';
248
254
  };
249
255
  const submit = () => {
250
256
  const text = input.value.trim();
@@ -264,8 +270,9 @@ function liveRoom(meta, guest, mount, me) {
264
270
  // host / admin controls
265
271
  const access = h('select.input.hide-sm', { style: 'width:auto;height:30px;font-size:13px', 'aria-label': 'What teammates can do',
266
272
  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'),
273
+ h('option', { value: 'control', disabled: readOnly }, isThread ? 'Teammates can prompt' : 'Teammates can type'), h('option', { value: 'view' }, 'Teammates watch only'),
268
274
  meta.isHost && h('option', { value: 'private' }, 'Private (only you)'));
275
+ const setPrompts = (on) => { readOnly = attached && !on; const o = access.querySelector('option[value=control]'); if (o) o.disabled = readOnly; };
269
276
  const controls = [];
270
277
  if (summary) controls.push(summary.btn);
271
278
  if (!meta.guest) controls.push(h('button.btn.small', { onclick: () => copy(`${location.origin}/s/${meta.id}`, 'Link copied. Teammates in the workspace can open it.') }, 'Copy link'));
@@ -276,7 +283,7 @@ function liveRoom(meta, guest, mount, me) {
276
283
  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
284
  } }, 'Guest link'),
278
285
  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;
286
+ if (!confirm(isThread ? `Stop sharing this conversation? It carries on ${attached ? '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
287
  try { await api('POST', `/api/sessions/${meta.id}/end`); } catch (x) { toast(x.message); }
281
288
  } }, 'End'));
282
289
  }
@@ -305,6 +312,7 @@ function liveRoom(meta, guest, mount, me) {
305
312
  } else view.set(m.thread || []);
306
313
  chat.length = 0;
307
314
  chat.push(...m.chat);
315
+ if (attached) setPrompts(m.session.prompts === true);
308
316
  access.value = m.session.access;
309
317
  privateNow = m.session.access === 'private';
310
318
  state = m.session.state;
@@ -333,6 +341,11 @@ function liveRoom(meta, guest, mount, me) {
333
341
  if (t) t.term.options.disableStdin = !you.canType;
334
342
  setMode(mode);
335
343
  setBanner(state);
344
+ } else if (m.t === 'caps') {
345
+ you.canType = m.canType;
346
+ setPrompts(m.prompts === true);
347
+ setMode(you.canType ? 'prompt' : mode);
348
+ setBanner(state);
336
349
  } else if (m.t === 'end') onEnd(m.reason);
337
350
  };
338
351
  ws.onclose = () => {
@@ -379,7 +392,7 @@ async function replayRoom(meta, mount) {
379
392
  const side = h('aside.side', {}, summary.box, h('.tabs', {}, h('button.btn.ghost.small.on', {}, 'Activity')),
380
393
  h('.feed', {}, meta.events.length ? meta.events.map(eventRow) : h('p.small.muted', {}, 'No recorded activity.')));
381
394
  if (meta.kind === 'thread' && meta.hasRecording) {
382
- const view = threadView();
395
+ const view = meta.agent === 'claude' ? threadView('Claude', 'in their terminal') : threadView();
383
396
  view.set((await (await fetch(`/api/sessions/${meta.id}/recording`)).json()).turns || []);
384
397
  return mount(h('.room', {}, bar, h('.roombody', {}, h('.stage.light', {}, panel, view.el), side)));
385
398
  }
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; }