agentpen-cli 0.1.1 → 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
@@ -76,14 +76,22 @@ Everyone in the workspace can see shared sessions, so `install` is something eac
76
76
 
77
77
  ## Share a session that is already running
78
78
 
79
- Sometimes the agent is an hour into something before you think to share it. You do not have to restart it:
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
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`.
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.
83
91
 
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.
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.
85
93
 
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`.
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`.
87
95
 
88
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.
89
97
 
@@ -195,7 +203,7 @@ First run prints a code and opens the browser to approve the machine. The sessio
195
203
  ```
196
204
  agentpen [agent] [args...] share a terminal agent (default: claude)
197
205
  agentpen codex-app share a Codex desktop app conversation
198
- agentpen share [stop] share a Claude Code session that is already running (watch only)
206
+ agentpen share [stop] share a Claude Code session that is already running (/agentpen from inside it)
199
207
  agentpen install | uninstall share automatically: plain `claude`, and the Codex app
200
208
  agentpen pause | resume stop or restart automatic sharing on this machine
201
209
  agentpen default private|watch|type|workspace how your sessions start on this machine
@@ -263,7 +271,7 @@ Not built:
263
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.
264
272
  - **Search covers ended sessions only**, and terminal sessions are indexed from the same plain-text capture, so full-screen programs produce noisy matches.
265
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.
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).
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.
267
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.
268
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.
269
277
  - **No phone push.** Notifications reach open browser tabs and the Mac app only.
package/cli/agentpen.js CHANGED
@@ -9,7 +9,7 @@ import { collectSecrets, makeRedactor } from './redact.js';
9
9
  import { shareCodexApp, watchCodexApp } from './codex-app.js';
10
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
+ import { shareRunningClaude, runShareChild, stopSharing, awaitPrompt } from './claude-share.js';
13
13
  import { randomUUID } from 'node:crypto';
14
14
 
15
15
  // The hosted service address. Self-hosters: `agentpen login --server https://agentpen.acme.internal`.
@@ -327,7 +327,8 @@ const HELP = `
327
327
  ${bold('Usage')}
328
328
  agentpen [agent] [agent args...] share a terminal agent (default: claude)
329
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)
330
+ agentpen share share a Claude Code session that is already running
331
+ (type /agentpen inside it instead to let teammates prompt it)
331
332
  agentpen share stop stop sharing it
332
333
  agentpen pickup LINK [--worktree] carry on a teammate's Claude Code session here
333
334
  agentpen install share automatically: plain \`claude\`, and the Codex app
@@ -439,6 +440,7 @@ async function main() {
439
440
  }
440
441
  if (cmd === 'share') {
441
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
442
444
  // its options may also come after the word, which is how the /agentpen command passes them
443
445
  let stop = false;
444
446
  let inClaude = false;
@@ -456,7 +458,7 @@ async function main() {
456
458
  const ui = { say: out, die: inClaude ? (s) => { out(`Agentpen: ${s}`); process.exit(0); } : die, bold, dim, accent };
457
459
  if (stop) return stopSharing(ui);
458
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
459
- return shareRunningClaude(cfg, { ...opts, access: accessFor(cfg, opts) }, ui);
461
+ return shareRunningClaude(cfg, { ...opts, inClaude, access: accessFor(cfg, opts) }, ui);
460
462
  }
461
463
  if (opts.codexApp) {
462
464
  if (rest.length) die(`unexpected argument "${rest[0]}" for codex-app. Try agentpen --help.`);
@@ -1,7 +1,9 @@
1
1
  // Share a Claude Code session that is already running. Agentpen did not start
2
2
  // it, so there is no terminal to stream: instead the conversation Claude Code
3
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.
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.
5
7
  import fs from 'node:fs';
6
8
  import os from 'node:os';
7
9
  import path from 'node:path';
@@ -18,6 +20,16 @@ const STALE_MS = Number(process.env.AGENTPEN_SHARE_STALE_MS) || 3 * 60_000;
18
20
  const MAX_TURNS = 200;
19
21
  const HOME = () => process.env.AGENTPEN_HOME || path.join(os.homedir(), '.agentpen');
20
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
+ };
21
33
  const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
22
34
  const tail = (s, n) => (s.length > n ? '…' + s.slice(-n) : s);
23
35
 
@@ -90,6 +102,13 @@ export function follow(file, mask) {
90
102
  if (it.shell) it.detail = mask(tail(blockText(b.content), 3000)) || undefined;
91
103
  }
92
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
+ }
93
112
  if (!text || NOT_TYPED.test(text)) return;
94
113
  if (text.startsWith('[Request interrupted')) { if (turn) turn.status = 'interrupted'; return; }
95
114
  if (turn?.status === 'inProgress') turn.status = 'completed';
@@ -141,11 +160,22 @@ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, l
141
160
  const secrets = opts.shareSecrets ? [] : collectSecrets(cwd).sort((a, b) => b.length - a.length);
142
161
  const mask = (s) => { for (const v of secrets) s = s.split(v).join('••••••'); return s; };
143
162
  const conv = follow(file, mask);
144
- let snap = conv.read();
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();
145
172
  const hello = {
146
173
  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',
174
+ project: path.basename(cwd), branch: snap.branch || '', access: opts.access,
148
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;
149
179
 
150
180
  let ws = null;
151
181
  let session = null;
@@ -164,6 +194,26 @@ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, l
164
194
  for (const t of changed) sent.set(t.id, JSON.stringify(t));
165
195
  sentMeta = meta;
166
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
+ };
167
217
  const stop = (reason) => new Promise((resolve) => {
168
218
  if (stopping) return resolve();
169
219
  stopping = true;
@@ -184,14 +234,15 @@ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, l
184
234
  const fresh = !session;
185
235
  session = { ...session, ...m };
186
236
  retry = 0;
187
- if (!m.resumed) { sent = new Map(); sentMeta = ''; }
237
+ if (!m.resumed) { sent = new Map(); sentMeta = ''; sentCaps = null; }
238
+ caps();
188
239
  push();
189
240
  if (fresh) onReady?.(session);
190
241
  resolve();
191
242
  } else if (m.t === 'error') {
192
243
  if (session && m.code === 'gone') session = null; // server restarted: start a fresh session
193
244
  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
245
+ } else if (m.t === 'prompt') onPrompt(m);
195
246
  else if (m.t === 'end') { stopping = true; onEnd?.(m.reason); }
196
247
  });
197
248
  ws.on('close', () => {
@@ -208,8 +259,9 @@ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, l
208
259
  await new Promise((r) => setTimeout(r, POLL_MS));
209
260
  if (stopping) break;
210
261
  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; }
262
+ try { snap = read(); } catch { log('conversation file is gone'); await stop('conversation ended'); break; }
212
263
  if (snap.quiet > IDLE_MS) { log('quiet for too long'); await stop('no activity'); break; }
264
+ caps();
213
265
  push();
214
266
  }
215
267
  }
@@ -254,7 +306,9 @@ export async function shareRunningClaude(cfg, opts, ui) {
254
306
  ui.say();
255
307
  ui.say(` ${ui.accent('●')} ${ui.bold(`Sharing “${result.title}”`)} ${ui.dim(`live in ${result.workspace}`)}`);
256
308
  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.'}`));
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.'}`));
258
312
  ui.say(ui.dim(' It stops when Claude Code exits, or with: agentpen share stop\n'));
259
313
  }
260
314
 
@@ -263,7 +317,14 @@ export async function runShareChild(cfg, file) {
263
317
  const opts = JSON.parse(process.env.AGENTPEN_SHARE_OPTS || '{}');
264
318
  const convId = path.basename(file, '.jsonl');
265
319
  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 {} };
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
+ };
267
328
  let stop = null;
268
329
  const quit = () => (stop ? stop('stopped by host') : process.exit(0));
269
330
  process.on('SIGTERM', quit);
@@ -287,3 +348,36 @@ export async function runShareChild(cfg, file) {
287
348
  process.exit(1);
288
349
  }
289
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
@@ -75,13 +75,22 @@ const launchctl = (...args) => { try { execFileSync('launchctl', args, { stdio:
75
75
 
76
76
  // ---- /agentpen inside Claude Code -------------------------------------------
77
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.
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.
79
81
  const SKILL = `---
80
82
  name: agentpen
81
83
  description: Share this Claude Code session with your Agentpen workspace so teammates can watch it live. "/agentpen stop" stops sharing.
82
84
  argument-hint: "[stop | --private]"
83
85
  disable-model-invocation: true
84
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
85
94
  ---
86
95
  <!-- installed by agentpen. Remove with: agentpen uninstall -->
87
96
  The user asked to share this session with their team through Agentpen. This command has already run:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentpen-cli",
3
- "version": "0.1.1",
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,8 +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: there is no terminal to type into
62
- this.readOnly = row.kind === 'thread' && row.agent === 'claude';
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;
63
64
  this.turns = new Map(); // thread sessions: turn id -> turn
64
65
  this.order = [];
65
66
  this.rec = null;
@@ -72,6 +73,19 @@ class LiveSession {
72
73
  }) + '\n');
73
74
  }
74
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
+
75
89
  // A Codex app conversation arrives as changed turns plus the full turn order.
76
90
  threadUpdate(m) {
77
91
  const changed = [];
@@ -112,7 +126,7 @@ class LiveSession {
112
126
  const r = this.row;
113
127
  return {
114
128
  id: r.id, title: r.title, agent: r.agent, project: r.project, branch: r.branch,
115
- 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,
116
130
  host: this.host, people,
117
131
  };
118
132
  }
@@ -181,7 +195,7 @@ class LiveSession {
181
195
 
182
196
  // What the agent is actually asking, so the notification can be answered at a glance.
183
197
  question() {
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.';
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.';
185
199
  const lines = this.recentLines(6);
186
200
  // the question itself reads better than the menu under it ("❯ 1. Yes")
187
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);
@@ -471,6 +485,8 @@ export function attachHost(ws, user) {
471
485
  s.end(s.kind === 'thread' ? 'sharing stopped' : 'agent exited');
472
486
  } else if (m.t === 'thread' && s.kind === 'thread') {
473
487
  s.threadUpdate(m);
488
+ } else if (m.t === 'caps') {
489
+ s.setPromptable(m.prompts === true);
474
490
  } else if (m.t === 'prompt-result' && !m.ok) {
475
491
  s.broadcast({ t: 'notice', text: `${s.agentName()} did not confirm that prompt. Check with the host before sending it again.` });
476
492
  }
package/server/index.js CHANGED
@@ -496,7 +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
+ if (live.attached) bad(400, 'This session was shared after it started. Hand over the wheel in a session started with agentpen.');
500
500
  if (live.driver) bad(409, `${live.driver.name} already has the wheel.`);
501
501
  live.drive(pickAgent(a.s.workspace_id, data.agent), { id: user.id, name: user.name }, goal); // runs in the background
502
502
  return { ok: true };
@@ -642,12 +642,13 @@ function serveStatic(req, res, pathname) {
642
642
  if (path.extname(pathname)) { res.writeHead(404, SECURITY_HEADERS); return res.end('Not found'); }
643
643
  file = path.join(WEB, 'index.html');
644
644
  }
645
- const isHtml = file.endsWith('.html');
646
- res.writeHead(200, {
647
- ...SECURITY_HEADERS,
648
- 'content-type': MIME[path.extname(file)] || 'application/octet-stream',
649
- 'cache-control': isHtml || IS_LOCAL ? 'no-cache' : 'public, max-age=3600',
650
- });
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);
651
652
  fs.createReadStream(file).pipe(res);
652
653
  }
653
654
 
package/web/session.js CHANGED
@@ -173,10 +173,12 @@ function liveRoom(meta, guest, mount, me) {
173
173
 
174
174
  const isThread = meta.kind === 'thread';
175
175
  const wrap = h('.termwrap');
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;
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;
180
182
  const banner = h('div');
181
183
  const stateSlot = h('span');
182
184
  const peopleSlot = h('span.hide-sm');
@@ -188,11 +190,11 @@ function liveRoom(meta, guest, mount, me) {
188
190
 
189
191
  const setBanner = (state) => {
190
192
  if (ended) return;
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.' : ''));
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.' : ''));
192
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?'));
193
195
  else if (you.guest) fill(banner, h('.banner.info', {}, `You are watching ${meta.host.name}'s session as a guest.`));
194
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.'));
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.`));
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.`));
196
198
  else if (!you.canType) fill(banner, h('.banner.info', {}, `Watch only. The host has ${isThread ? 'prompting' : 'typing'} turned off for teammates.`));
197
199
  else fill(banner);
198
200
  };
@@ -225,7 +227,7 @@ function liveRoom(meta, guest, mount, me) {
225
227
  // composer: two clearly different destinations
226
228
  const input = h('textarea.input', { rows: 2, 'aria-label': 'Message' });
227
229
  const sendBtn = h('button.btn.primary.small', { type: 'submit' });
228
- 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');
229
231
  const toTeam = h('button.btn.ghost.small', { type: 'button', onclick: () => setMode('chat') }, 'Chat with team');
230
232
  // invite another model in: anyone can ask it, only the host can give it the wheel
231
233
  const needAgent = () => { if (pick.any()) return true; toast(NO_AGENT); return false; };
@@ -238,7 +240,7 @@ function liveRoom(meta, guest, mount, me) {
238
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');
239
241
  const nameAgent = () => { askClaude.textContent = `Ask ${pick.get()?.name || 'an agent'}`; if (mode === 'drive') setMode('drive'); };
240
242
  pick.onChange(nameAgent);
241
- giveWheel.hidden = !meta.isHost || readOnly;
243
+ giveWheel.hidden = !meta.isHost || attached;
242
244
  askClaude.hidden = !!meta.guest;
243
245
  const setMode = (m) => {
244
246
  mode = (m === 'prompt' && !you.canType) || (m === 'drive' && !meta.isHost) ? 'chat' : m;
@@ -247,8 +249,8 @@ function liveRoom(meta, guest, mount, me) {
247
249
  toTeam.classList.toggle('on', mode === 'chat');
248
250
  giveWheel.classList.toggle('on', mode === 'drive');
249
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; }
250
- 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';
251
- 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';
252
254
  };
253
255
  const submit = () => {
254
256
  const text = input.value.trim();
@@ -268,8 +270,9 @@ function liveRoom(meta, guest, mount, me) {
268
270
  // host / admin controls
269
271
  const access = h('select.input.hide-sm', { style: 'width:auto;height:30px;font-size:13px', 'aria-label': 'What teammates can do',
270
272
  onchange: async (e) => { try { await api('PATCH', `/api/sessions/${meta.id}`, { access: e.target.value }); } catch (x) { toast(x.message); } } },
271
- !readOnly && 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'),
272
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; };
273
276
  const controls = [];
274
277
  if (summary) controls.push(summary.btn);
275
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'));
@@ -280,7 +283,7 @@ function liveRoom(meta, guest, mount, me) {
280
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); }
281
284
  } }, 'Guest link'),
282
285
  h('button.btn.small.danger', { onclick: async () => {
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;
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;
284
287
  try { await api('POST', `/api/sessions/${meta.id}/end`); } catch (x) { toast(x.message); }
285
288
  } }, 'End'));
286
289
  }
@@ -309,6 +312,7 @@ function liveRoom(meta, guest, mount, me) {
309
312
  } else view.set(m.thread || []);
310
313
  chat.length = 0;
311
314
  chat.push(...m.chat);
315
+ if (attached) setPrompts(m.session.prompts === true);
312
316
  access.value = m.session.access;
313
317
  privateNow = m.session.access === 'private';
314
318
  state = m.session.state;
@@ -337,6 +341,11 @@ function liveRoom(meta, guest, mount, me) {
337
341
  if (t) t.term.options.disableStdin = !you.canType;
338
342
  setMode(mode);
339
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);
340
349
  } else if (m.t === 'end') onEnd(m.reason);
341
350
  };
342
351
  ws.onclose = () => {