agentpen-cli 0.1.1 → 0.1.4

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
@@ -63,6 +63,7 @@ agentpen install
63
63
 
64
64
  - **Claude Code:** a small hook in your shell file makes plain `claude` start a shared session. It prints one quiet line with the link and otherwise behaves as before. One-off commands (`claude -p`, `claude mcp …`, `claude update`), scripts and pipes are never shared.
65
65
  - **Codex app (macOS):** a background helper watches the app and shares a conversation while it is active, then stops once it has been quiet for 20 minutes. Only conversations inside a git repository are shared, so general chat stays out. On other systems, keep `agentpen watch` running.
66
+ - **Mac menu bar app (macOS):** installs `Agentpen.app` into `/Applications` (or `~/Applications`) from the latest release and verifies its SHA-256 checksum. Pass `--no-app` to skip it, or download it anytime from Settings in the web app.
66
67
 
67
68
  It is built to stay out of the way. If the server is unreachable, you are signed out, or Agentpen is removed from the machine, `claude` simply runs as normal, after at most a couple of seconds' wait.
68
69
 
@@ -76,14 +77,22 @@ Everyone in the workspace can see shared sessions, so `install` is something eac
76
77
 
77
78
  ## Share a session that is already running
78
79
 
79
- Sometimes the agent is an hour into something before you think to share it. You do not have to restart it:
80
+ 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
 
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`.
82
+ ```
83
+ /agentpen
84
+ ```
85
+
86
+ The session appears on the team page, and teammates can prompt it. (`/agentpen stop` stops sharing, `/agentpen --private` starts it visible only to you.)
87
+
88
+ Agentpen did not start that session, so it has no terminal to stream or type into. Two things stand in for it:
89
+
90
+ - **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.
91
+ - **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
92
 
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.
93
+ 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
94
 
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`.
95
+ `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
96
 
88
97
  `/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
98
 
@@ -170,11 +179,20 @@ cd mac && ./build-app.sh # needs the Xcode command line tools; full Xcode
170
179
  open dist/Agentpen.app
171
180
  ```
172
181
 
173
- CI builds the app on every push and attaches `Agentpen.zip` to the workflow run. It is ad-hoc signed, not notarized: first launch needs right-click, Open.
182
+ The app talks to `https://agentpen.app` unless you change the server in its settings.
183
+
184
+ To sign it for other people's Macs, build with a Developer ID, then notarize the zip:
185
+
186
+ ```sh
187
+ AGENTPEN_SIGN="Developer ID Application: Your Company (TEAMID)" ./build-app.sh
188
+ xcrun notarytool submit dist/Agentpen.zip --keychain-profile PROFILE --wait && xcrun stapler staple dist/Agentpen.app
189
+ ```
190
+
191
+ CI builds the app on every push and attaches `Agentpen.zip` to the workflow run. That build is ad-hoc signed, not notarized: first launch needs right-click, Open.
174
192
 
175
193
  ## Run it locally
176
194
 
177
- Needs Node 22.13+.
195
+ The server needs Node 22.13+. The CLI on its own (`npm i -g agentpen-cli`) runs on Node 20 and later.
178
196
 
179
197
  ```sh
180
198
  npm install
@@ -195,7 +213,7 @@ First run prints a code and opens the browser to approve the machine. The sessio
195
213
  ```
196
214
  agentpen [agent] [args...] share a terminal agent (default: claude)
197
215
  agentpen codex-app share a Codex desktop app conversation
198
- agentpen share [stop] share a Claude Code session that is already running (watch only)
216
+ agentpen share [stop] share a Claude Code session that is already running (/agentpen from inside it)
199
217
  agentpen install | uninstall share automatically: plain `claude`, and the Codex app
200
218
  agentpen pause | resume stop or restart automatic sharing on this machine
201
219
  agentpen default private|watch|type|workspace how your sessions start on this machine
@@ -231,9 +249,13 @@ docker run -p 8080:8080 -v agentpen-data:/data \
231
249
  | `RESEND_API_KEY`, `AGENTPEN_MAIL_FROM` | Sends sign-in and invite emails through Resend. Without a key, links are only written to the server log. |
232
250
  | `AGENTPEN_DATA` | Directory for the database and recordings (default `./data`). |
233
251
  | `AGENTPEN_TRUST_PROXY=1` | Believe `X-Forwarded-For` (set when behind a load balancer). |
234
- | `AGENTPEN_SECRET` | Encrypts stored provider keys. If unset, a key file is created beside the database. |
252
+ | `AGENTPEN_SECRET` | Encrypts stored provider keys and checkpoints at rest. If unset, a key file is created beside the database. |
253
+ | `AGENTPEN_CLAUDE_MODEL` | Override the Anthropic model used for `@claude`, summaries, and steering (default `claude-opus-5-5`). |
254
+ | `AGENTPEN_RECORDING_DAYS` | Days to retain ended session recordings on disk (default `90`). |
255
+ | `AGENTPEN_BACKUP_DIR` | Optional directory for daily WAL-safe SQLite backups (`VACUUM INTO`, keeps last 7). |
235
256
  | `ANTHROPIC_API_KEY` | Optional, for self-hosting: one Claude credential for every workspace, instead of a key per workspace. |
236
257
  | `AGENTPEN_UPGRADE_URL` | Where the "Upgrade" button sends admins (for example a Stripe payment link). |
258
+ | `AGENTPEN_MAC_APP_URL` | Download URL for `Agentpen.zip` used by `/download/mac`, Settings, and `agentpen install` on macOS (set empty to disable). |
237
259
  | `PORT` | Listen port (default 4400; 8080 in the image). |
238
260
 
239
261
  The published CLI talks to the hosted service at `https://agentpen.app`. Point it at your own deployment with `agentpen login --server https://agentpen.yourco.com`.
@@ -259,13 +281,13 @@ Not built:
259
281
  - **SSO / SAML / SCIM.** Email links only.
260
282
  - **Horizontal scaling.** Live sessions are held in one process. Past one node this needs a pub/sub layer and Postgres.
261
283
  - **Codex desktop app, verified only against the Codex app-server daemon.** Listing, reading and queueing prompts were exercised against a real `codex app-server` (0.171) on Linux, without a signed-in account, so no real agent reply was seen. It has not been run against the desktop app's window on a Mac. The bridge relies on Codex's experimental app-server API, polls for changes, and depends on the app picking up queued prompts.
262
- - **The Mac app has been compiled by CI but never run.** Nothing here can launch a Mac app, so sign-in, the menu bar panel and real notification banners have not been seen working. It has no app icon, is not notarized, and "time sensitive" delivery needs an Apple Developer entitlement it does not have.
284
+ - **The Mac app has been launched but not used.** A Developer ID signed universal build starts and stays running on macOS, but sign-in, the menu bar panel and real notification banners have not been seen working. It has no app icon, has not been notarized, and "time sensitive" delivery needs an entitlement it does not have.
263
285
  - **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
286
  - **Search covers ended sessions only**, and terminal sessions are indexed from the same plain-text capture, so full-screen programs produce noisy matches.
265
287
  - **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).
288
+ - **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
289
  - **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
- - **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.
290
+ - **Checkpoints put source code on the Agentpen server**, encrypted at rest with `AGENTPEN_SECRET` (not end-to-end encrypted). Workspaces that cannot store source snapshots on the server should turn the setting off.
269
291
  - **No phone push.** Notifications reach open browser tabs and the Mac app only.
270
292
  - **No Claude desktop app support.** Claude Code is shared from the terminal only.
271
293
  - **"Needs a human" is a heuristic for terminal sessions**: the terminal went quiet and the last lines look like a question. Agent-native hooks would be exact.
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`.
@@ -119,13 +119,47 @@ function claudeSession(command) {
119
119
  const accessFor = (cfg, opts) => (opts.private ? 'private' : opts.watchOnly ? 'view' : cfg.defaultAccess || undefined);
120
120
  const ACCESS_WORDS = { private: 'private, only you can see it', view: 'teammates can watch', control: 'teammates can watch and type' };
121
121
 
122
+ // Split a shell-style argument string (e.g. from an existing `claude` alias or /agentpen --args).
123
+ function splitShellArgs(str) {
124
+ const out = [];
125
+ let cur = '';
126
+ let q = null;
127
+ for (let i = 0; i < str.length; i++) {
128
+ const c = str[i];
129
+ if (q) {
130
+ if (c === q) q = null;
131
+ else if (c === '\\' && q === '"' && i + 1 < str.length) cur += str[++i];
132
+ else cur += c;
133
+ } else if (c === '"' || c === "'") {
134
+ q = c;
135
+ } else if (/\s/.test(c)) {
136
+ if (cur) { out.push(cur); cur = ''; }
137
+ } else if (c === '\\' && i + 1 < str.length) {
138
+ cur += str[++i];
139
+ } else {
140
+ cur += c;
141
+ }
142
+ }
143
+ if (cur) out.push(cur);
144
+ return out;
145
+ }
146
+
122
147
  // Where the agent's real program is. The shell hook passes it along when
123
- // `claude` was an alias rather than something on PATH.
124
- const realBin = (command) => (path.basename(command[0]) === 'claude' && process.env.AGENTPEN_CLAUDE) || command[0];
148
+ // `claude` was an alias rather than something on PATH (even if the alias had flags).
149
+ function realExec(command) {
150
+ if (path.basename(command[0]) === 'claude' && process.env.AGENTPEN_CLAUDE) {
151
+ const raw = process.env.AGENTPEN_CLAUDE.trim();
152
+ if (fs.existsSync(raw)) return [raw, command.slice(1)];
153
+ const parts = splitShellArgs(raw);
154
+ if (parts.length) return [parts[0], [...parts.slice(1), ...command.slice(1)]];
155
+ }
156
+ return [command[0], command.slice(1)];
157
+ }
125
158
 
126
159
  // Run the agent exactly as if Agentpen were not there, and leave with its exit code.
127
160
  function runPlain(command) {
128
- const child = spawnProc(realBin(command), command.slice(1), { stdio: 'inherit' });
161
+ const [bin, args] = realExec(command);
162
+ const child = spawnProc(bin, args, { stdio: 'inherit' });
129
163
  child.on('error', (e) => die(`could not start "${command[0]}": ${e.message}`));
130
164
  child.on('exit', (code, signal) => process.exit(signal ? 1 : code ?? 0));
131
165
  for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => {});
@@ -179,12 +213,16 @@ async function share(cfg, opts, command) {
179
213
  let pendingBytes = 0;
180
214
  let people = [];
181
215
 
182
- const outbound = makeRedactor(opts.shareSecrets ? [] : collectSecrets(process.cwd()), (buf) => {
216
+ const outbound = makeRedactor(opts.shareSecrets ? [] : collectSecrets(process.cwd(), top), (buf) => {
183
217
  if (ws?.readyState === 1 && session) return ws.send(buf, { binary: true });
184
218
  pending.push(buf); // offline: keep the last 1MB for when the link is back
185
219
  pendingBytes += buf.length;
186
220
  while (pendingBytes > 1_000_000 && pending.length > 1) pendingBytes -= pending.shift().length;
187
221
  });
222
+ const secretRefresh = opts.shareSecrets ? null : setInterval(() => {
223
+ outbound.update(collectSecrets(process.cwd(), top));
224
+ }, 15_000);
225
+ secretRefresh?.unref();
188
226
 
189
227
  const title = () => {
190
228
  if (!process.stdout.isTTY || !session) return;
@@ -229,7 +267,7 @@ async function share(cfg, opts, command) {
229
267
  people = m.people;
230
268
  title();
231
269
  } else if (m.t === 'end') {
232
- session.dead = true;
270
+ if (session) session.dead = true;
233
271
  if (term) term.kill();
234
272
  }
235
273
  });
@@ -267,7 +305,8 @@ async function share(cfg, opts, command) {
267
305
  if (!opts.auto) say();
268
306
 
269
307
  try {
270
- term = pty.spawn(realBin(command), command.slice(1), { name: process.env.TERM || 'xterm-256color', ...size(), cwd: process.cwd(), env: { ...process.env, AGENTPEN_SESSION: session.id } });
308
+ const [bin, args] = realExec(command);
309
+ term = pty.spawn(bin, args, { name: process.env.TERM || 'xterm-256color', ...size(), cwd: process.cwd(), env: { ...process.env, AGENTPEN_SESSION: session.id } });
271
310
  } catch (e) {
272
311
  exited = true;
273
312
  ws.send(JSON.stringify({ t: 'exit' }));
@@ -277,7 +316,7 @@ async function share(cfg, opts, command) {
277
316
 
278
317
  const cwd = fs.realpathSync(process.cwd());
279
318
  const checkpoints = checkpointing ? startCheckpoints({
280
- cfg, getSession: () => session, cwd, agentSession: agent.id, secrets: opts.shareSecrets ? [] : collectSecrets(cwd),
319
+ cfg, getSession: () => session, cwd, agentSession: agent.id, secrets: opts.shareSecrets ? [] : collectSecrets(cwd, top), shareSecrets: !!opts.shareSecrets,
281
320
  onError: (m) => { if (process.env.AGENTPEN_DEBUG) say(`checkpoint: ${m}`); if (process.stdout.isTTY) process.stdout.write(`\x1b]0;agentpen: checkpoint failed (${m})\x07`); },
282
321
  }) : null;
283
322
  // an agent mid-task should not be put to sleep by an idle laptop (a closed lid still sleeps)
@@ -327,10 +366,11 @@ const HELP = `
327
366
  ${bold('Usage')}
328
367
  agentpen [agent] [agent args...] share a terminal agent (default: claude)
329
368
  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)
369
+ agentpen share share a Claude Code session that is already running
370
+ (type /agentpen inside it instead to let teammates prompt it)
331
371
  agentpen share stop stop sharing it
332
372
  agentpen pickup LINK [--worktree] carry on a teammate's Claude Code session here
333
- agentpen install share automatically: plain \`claude\`, and the Codex app
373
+ agentpen install [--no-app] share automatically: plain \`claude\`, Codex app, and Mac menu bar app
334
374
  agentpen pause | resume stop or restart automatic sharing on this machine
335
375
  agentpen default private|watch|type|workspace
336
376
  how your sessions start on this machine
@@ -392,6 +432,11 @@ async function main() {
392
432
  return login(cfg);
393
433
  }
394
434
  if (cmd === 'logout' && rest.length === 1) {
435
+ if (cfg.token) {
436
+ await fetch(`${cfg.server}/api/auth/revoke`, {
437
+ method: 'POST', headers: { authorization: `Bearer ${cfg.token}` }, signal: AbortSignal.timeout(5000),
438
+ }).catch(() => {});
439
+ }
395
440
  cfg.token = null; cfg.user = null;
396
441
  saveConfig(cfg);
397
442
  return say('Signed out on this machine.');
@@ -406,10 +451,14 @@ async function main() {
406
451
  } catch (e) { die(e.status === 401 ? 'session expired. Run: agentpen login' : e.message); }
407
452
  return;
408
453
  }
409
- if (cmd === 'install' && rest.length <= 2) {
454
+ if (cmd === 'install') {
455
+ const flags = rest.slice(1);
456
+ const unknown = flags.find((f) => f !== '--shell-only' && f !== '--no-app');
457
+ if (unknown) die(`unknown option ${unknown} for install.`);
410
458
  await ensureAccount(cfg);
411
459
  const me = await api(cfg, 'GET', '/api/me');
412
- return install({ workspace: me.workspaces[0].name, shellOnly: rest[1] === '--shell-only' }, { say, die, bold, dim, accent });
460
+ const macAppUrl = process.env.AGENTPEN_MAC_APP_URL ?? me.macAppUrl;
461
+ return install({ workspace: me.workspaces[0].name, shellOnly: flags.includes('--shell-only'), noApp: flags.includes('--no-app'), macAppUrl, server: cfg.server }, { say, die, bold, dim, accent });
413
462
  }
414
463
  if (cmd === 'default' && rest.length === 2) {
415
464
  const map = { private: 'private', watch: 'view', type: 'control', workspace: '' };
@@ -439,16 +488,23 @@ async function main() {
439
488
  }
440
489
  if (cmd === 'share') {
441
490
  if (rest[1] === '--run' && rest.length === 3) return cfg.token ? runShareChild(cfg, rest[2]) : process.exit(1);
491
+ if (rest[1] === '--await-prompt' && rest.length === 2) return awaitPrompt().catch(() => {}); // the hook /agentpen registers
442
492
  // its options may also come after the word, which is how the /agentpen command passes them
443
493
  let stop = false;
444
494
  let inClaude = false;
495
+ const expanded = [];
445
496
  for (let j = 1; j < rest.length; j++) {
446
- const a = rest[j];
497
+ if (rest[j] === '--args') expanded.push(...splitShellArgs(rest[++j] || ''));
498
+ else expanded.push(rest[j]);
499
+ }
500
+ for (let j = 0; j < expanded.length; j++) {
501
+ const a = expanded[j];
447
502
  if (a === 'stop') stop = true;
448
503
  else if (a === '--in-claude') inClaude = true;
449
504
  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];
505
+ else if (a === '--watch-only') opts.watchOnly = true;
506
+ else if (a === '--session') opts.session = expanded[++j];
507
+ else if (a === '-t' || a === '--title') opts.title = expanded[++j];
452
508
  else die(`unexpected argument "${a}" for share. Try agentpen --help.`);
453
509
  }
454
510
  // run by /agentpen: Claude Code reads standard output, and a failure should be passed on rather than abort the command
@@ -456,7 +512,7 @@ async function main() {
456
512
  const ui = { say: out, die: inClaude ? (s) => { out(`Agentpen: ${s}`); process.exit(0); } : die, bold, dim, accent };
457
513
  if (stop) return stopSharing(ui);
458
514
  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);
515
+ return shareRunningClaude(cfg, { ...opts, inClaude, access: accessFor(cfg, opts) }, ui);
460
516
  }
461
517
  if (opts.codexApp) {
462
518
  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';
@@ -112,8 +131,9 @@ export function follow(file, mask) {
112
131
 
113
132
  return {
114
133
  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
134
+ const st = fs.statSync(file);
135
+ const size = st.size;
136
+ if (size < offset) { offset = 0; rest = ''; turns.length = 0; tools.clear(); turn = null; } // rewritten: rebuild cleanly
117
137
  if (size > offset) {
118
138
  const fd = fs.openSync(file, 'r');
119
139
  try {
@@ -125,7 +145,7 @@ export function follow(file, mask) {
125
145
  for (const l of lines) { if (!l.trim()) continue; try { take(JSON.parse(l)); } catch {} }
126
146
  } finally { fs.closeSync(fd); }
127
147
  }
128
- const quiet = Date.now() - fs.statSync(file).mtimeMs;
148
+ const quiet = Date.now() - st.mtimeMs;
129
149
  const shown = turns.slice(-MAX_TURNS).map((t) => ({ id: t.id, status: t.status, items: t.items.map(({ shell, ...it }) => it) }));
130
150
  return { title: title || 'Claude Code session', cwd, branch, turns: shown, quiet, status: turn?.status === 'inProgress' && quiet < STALE_MS ? 'working' : 'idle' };
131
151
  },
@@ -136,16 +156,56 @@ export function follow(file, mask) {
136
156
 
137
157
  /** Runs until the session is over. Calls onReady once the team can see it. */
138
158
  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);
159
+ let secrets = [];
142
160
  const mask = (s) => { for (const v of secrets) s = s.split(v).join('••••••'); return s; };
161
+ const gitRoot = (dir) => { try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd: dir, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim(); } catch { return ''; } };
162
+ // Peek cwd cheaply from the first 32 KB (or fallback to process.cwd()) before full read so we only parse the file once.
163
+ const peekCwd = () => {
164
+ try {
165
+ const fd = fs.openSync(file, 'r');
166
+ try {
167
+ const buf = Buffer.alloc(32768);
168
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
169
+ for (const l of buf.subarray(0, n).toString('utf8').split('\n')) {
170
+ try { const e = JSON.parse(l); if (e.cwd) return e.cwd; } catch {}
171
+ }
172
+ } finally { fs.closeSync(fd); }
173
+ } catch {}
174
+ return process.cwd();
175
+ };
176
+ const cwd = peekCwd();
177
+ const top = gitRoot(cwd);
178
+ const refreshSecrets = () => { secrets = opts.shareSecrets ? [] : collectSecrets(cwd, top).sort((a, b) => b.length - a.length); };
179
+ refreshSecrets();
143
180
  const conv = follow(file, mask);
144
- let snap = conv.read();
181
+ const convId = path.basename(file, '.jsonl');
182
+ // prompts still waiting for Claude are shown at the end, marked as queued
183
+ const read = () => {
184
+ const s = conv.read();
185
+ const waiting = queued(convId).map((p) => ({ id: p.rid, role: 'user', text: mask(p.text), by: p.by, status: 'queued' }));
186
+ if (waiting.length) s.turns.push({ id: 'queued', status: 'completed', items: waiting });
187
+ return s;
188
+ };
189
+ let snap = read();
145
190
  const hello = {
146
191
  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',
192
+ project: path.basename(snap.cwd || cwd), branch: snap.branch || '', access: opts.access,
193
+ };
194
+ // true once /agentpen has run inside the session: its hook is what delivers prompts.
195
+ // Clear a stale waiter file if the 12-hour hook timed out and its process is long gone.
196
+ const HOOK_MAX_MS = 12 * 3_600_000;
197
+ const canPrompt = () => {
198
+ const wf = waiterFile(convId);
199
+ let st;
200
+ try { st = fs.statSync(wf); } catch { return false; }
201
+ if (Date.now() - st.mtimeMs > HOOK_MAX_MS) {
202
+ let pid = 0;
203
+ try { pid = Number(fs.readFileSync(wf, 'utf8').trim()); } catch {}
204
+ if (!pid || !alive(pid)) { fs.rmSync(wf, { force: true }); return false; }
205
+ }
206
+ return true;
148
207
  };
208
+ let sentCaps = null;
149
209
 
150
210
  let ws = null;
151
211
  let session = null;
@@ -164,6 +224,26 @@ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, l
164
224
  for (const t of changed) sent.set(t.id, JSON.stringify(t));
165
225
  sentMeta = meta;
166
226
  };
227
+ const caps = () => {
228
+ if (ws?.readyState !== 1 || !session || sentCaps === canPrompt()) return;
229
+ sentCaps = canPrompt();
230
+ ws.send(JSON.stringify({ t: 'caps', prompts: sentCaps }));
231
+ };
232
+ const onPrompt = (m) => {
233
+ let ok = canPrompt();
234
+ if (ok) {
235
+ try {
236
+ fs.mkdirSync(queueDir(convId), { recursive: true, mode: 0o700 });
237
+ const name = `${Date.now()}-${String(m.rid).replace(/[^\w-]/g, '')}.json`;
238
+ 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 });
239
+ fs.renameSync(path.join(queueDir(convId), `.${name}`), path.join(queueDir(convId), name)); // appears whole or not at all
240
+ log(`${m.by} queued a prompt`);
241
+ snap = read();
242
+ push();
243
+ } catch { ok = false; }
244
+ }
245
+ if (ws?.readyState === 1) ws.send(JSON.stringify({ t: 'prompt-result', rid: m.rid, ok }));
246
+ };
167
247
  const stop = (reason) => new Promise((resolve) => {
168
248
  if (stopping) return resolve();
169
249
  stopping = true;
@@ -184,14 +264,15 @@ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, l
184
264
  const fresh = !session;
185
265
  session = { ...session, ...m };
186
266
  retry = 0;
187
- if (!m.resumed) { sent = new Map(); sentMeta = ''; }
267
+ if (!m.resumed) { sent = new Map(); sentMeta = ''; sentCaps = null; }
268
+ caps();
188
269
  push();
189
- if (fresh) onReady?.(session);
270
+ if (fresh) onReady?.(session, opts.title || snap.title);
190
271
  resolve();
191
272
  } else if (m.t === 'error') {
192
273
  if (session && m.code === 'gone') session = null; // server restarted: start a fresh session
193
274
  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
275
+ } else if (m.t === 'prompt') onPrompt(m);
195
276
  else if (m.t === 'end') { stopping = true; onEnd?.(m.reason); }
196
277
  });
197
278
  ws.on('close', () => {
@@ -208,8 +289,9 @@ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, l
208
289
  await new Promise((r) => setTimeout(r, POLL_MS));
209
290
  if (stopping) break;
210
291
  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; }
292
+ try { snap = read(); } catch { log('conversation file is gone'); await stop('conversation ended'); break; }
212
293
  if (snap.quiet > IDLE_MS) { log('quiet for too long'); await stop('no activity'); break; }
294
+ caps();
213
295
  push();
214
296
  }
215
297
  }
@@ -237,12 +319,15 @@ export async function shareRunningClaude(cfg, opts, ui) {
237
319
  if (running && alive(running.pid)) return ui.say(`Already sharing “${running.title}”: ${ui.accent(running.url)}`);
238
320
 
239
321
  fs.mkdirSync(path.dirname(stateFile(convId)), { recursive: true, mode: 0o700 });
240
- const logFd = fs.openSync(path.join(HOME(), 'share.log'), 'a');
322
+ const logFile = path.join(HOME(), 'share.log');
323
+ try { if (fs.statSync(logFile).size > 5 * 1024 * 1024) fs.truncateSync(logFile, 0); } catch {}
324
+ const logFd = fs.openSync(logFile, 'a');
241
325
  const claudePid = Number(process.env.CLAUDE_PID) || 0;
242
326
  const child = spawn(process.execPath, [fileURLToPath(new URL('./agentpen.js', import.meta.url)), 'share', '--run', file], {
243
327
  detached: true, stdio: ['ignore', logFd, logFd, 'ipc'],
244
328
  env: { ...process.env, AGENTPEN_SHARE_OPTS: JSON.stringify({ ...opts, claudePid }) },
245
329
  });
330
+ fs.closeSync(logFd);
246
331
  const result = await new Promise((resolve) => {
247
332
  const t = setTimeout(() => resolve({ error: `cannot reach ${cfg.server}` }), 20_000);
248
333
  child.once('message', (m) => { clearTimeout(t); resolve(m); });
@@ -254,7 +339,9 @@ export async function shareRunningClaude(cfg, opts, ui) {
254
339
  ui.say();
255
340
  ui.say(` ${ui.accent('●')} ${ui.bold(`Sharing “${result.title}”`)} ${ui.dim(`live in ${result.workspace}`)}`);
256
341
  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.'}`));
342
+ ui.say(ui.dim(` ${result.access === 'private' ? 'Only you can see it until you share it from that page.' : opts.inClaude
343
+ ? `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.'}`
344
+ : 'Teammates can watch the conversation and chat. To let them prompt it too, type /agentpen inside that Claude Code session.'}`));
258
345
  ui.say(ui.dim(' It stops when Claude Code exits, or with: agentpen share stop\n'));
259
346
  }
260
347
 
@@ -263,7 +350,14 @@ export async function runShareChild(cfg, file) {
263
350
  const opts = JSON.parse(process.env.AGENTPEN_SHARE_OPTS || '{}');
264
351
  const convId = path.basename(file, '.jsonl');
265
352
  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 {} };
353
+ const cleanup = () => {
354
+ try {
355
+ if (readState(convId)?.pid !== process.pid) return;
356
+ fs.rmSync(stateFile(convId), { force: true });
357
+ fs.rmSync(queueDir(convId), { recursive: true, force: true });
358
+ fs.rmSync(waiterFile(convId), { force: true });
359
+ } catch {}
360
+ };
267
361
  let stop = null;
268
362
  const quit = () => (stop ? stop('stopped by host') : process.exit(0));
269
363
  process.on('SIGTERM', quit);
@@ -272,8 +366,8 @@ export async function runShareChild(cfg, file) {
272
366
  await runShare(cfg, file, opts, {
273
367
  log,
274
368
  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 };
369
+ onReady: (s, title) => {
370
+ const info = { pid: process.pid, title: title || opts.title || 'Claude Code session', url: s.url, workspace: s.workspace.name, access: s.access };
277
371
  fs.writeFileSync(stateFile(convId), JSON.stringify(info), { mode: 0o600 });
278
372
  log(`sharing at ${s.url}`);
279
373
  if (process.connected) process.send(info);
@@ -287,3 +381,36 @@ export async function runShareChild(cfg, file) {
287
381
  process.exit(1);
288
382
  }
289
383
  }
384
+
385
+ /**
386
+ * The hook /agentpen registers in a Claude Code session. Claude Code starts it in the
387
+ * background each time Claude finishes a turn. It waits for a teammate's prompt and
388
+ * ends with exit code 2 and the prompt on standard error, which is how a background
389
+ * hook wakes Claude with a message. It ends quietly if the session is not being
390
+ * shared, or once a newer copy of itself has taken over.
391
+ */
392
+ export async function awaitPrompt() {
393
+ let input = '';
394
+ if (!process.stdin.isTTY) for await (const c of process.stdin) input += c;
395
+ let id = process.env.CLAUDE_CODE_SESSION_ID || '';
396
+ try { id = JSON.parse(input).session_id || id; } catch {}
397
+ if (!/^[\w-]{6,80}$/.test(id)) return;
398
+ const sharing = () => { const s = readState(id); return !!s && alive(s.pid); };
399
+ if (!sharing()) return;
400
+ const me = String(process.pid);
401
+ fs.writeFileSync(waiterFile(id), me, { mode: 0o600 });
402
+ for (;;) {
403
+ let holder = '';
404
+ try { holder = fs.readFileSync(waiterFile(id), 'utf8'); } catch {}
405
+ if (holder !== me || !sharing()) return;
406
+ for (const p of queued(id)) {
407
+ const mine = path.join(queueDir(id), `${p.f}.${me}`);
408
+ try { fs.renameSync(path.join(queueDir(id), p.f), mine); } catch { continue; } // another copy got there first
409
+ fs.rmSync(mine, { force: true });
410
+ process.stderr.write(forClaude(p.by, p.text));
411
+ process.exitCode = 2;
412
+ return;
413
+ }
414
+ await new Promise((r) => setTimeout(r, 300));
415
+ }
416
+ }
package/cli/codex-app.js CHANGED
@@ -7,6 +7,7 @@ import net from 'node:net';
7
7
  import os from 'node:os';
8
8
  import path from 'node:path';
9
9
  import readline from 'node:readline';
10
+ import { execFileSync } from 'node:child_process';
10
11
  import { randomUUID } from 'node:crypto';
11
12
  import WebSocket from 'ws';
12
13
  import { collectSecrets } from './redact.js';
@@ -139,7 +140,14 @@ async function pickThread(codex, opts, ui) {
139
140
  // A connection to the Codex app that is reopened whenever it has dropped.
140
141
  function codexLink(sock) {
141
142
  let codex = null;
142
- return { async get() { if (!codex?.open) { codex = new Codex(sock); await codex.connect(); } return codex; } };
143
+ return {
144
+ async get() { if (!codex?.open) { codex = new Codex(sock); await codex.connect(); } return codex; },
145
+ close() { try { codex?.ws?.close(); } catch {} codex = null; },
146
+ };
147
+ }
148
+
149
+ function gitRoot(dir) {
150
+ try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd: dir, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim(); } catch { return ''; }
143
151
  }
144
152
 
145
153
  /**
@@ -152,7 +160,8 @@ async function shareThread(cfg, link, threadId, opts, ui, onEnd) {
152
160
  // fail now, not on a teammate's first prompt, if this Codex cannot queue messages
153
161
  try { await (await link.get()).request('thread/queue/list', { threadId, limit: 1 }); } catch { throw new Error('this version of Codex cannot accept queued prompts. Update the Codex app and try again.'); }
154
162
 
155
- const secrets = opts.shareSecrets ? [] : collectSecrets(thread.cwd || process.cwd()).sort((a, b) => b.length - a.length);
163
+ const cwd = thread.cwd || process.cwd();
164
+ const secrets = opts.shareSecrets ? [] : collectSecrets(cwd, gitRoot(cwd)).sort((a, b) => b.length - a.length);
156
165
  const mask = (s) => { for (const v of secrets) s = s.split(v).join('••••••'); return s; };
157
166
  const read = async () => { const c = await link.get(); return transcript(await c.readThread(threadId), mask, await c.queued(threadId)); };
158
167
  let snap = await read();
@@ -276,7 +285,7 @@ export async function shareCodexApp(cfg, opts, ui) {
276
285
  ui.say(ui.dim(` Keep working in the Codex app. ${session.access === 'private' ? 'Only you can see this until you share it from that page.' : session.access === 'view' ? 'Teammates can watch.' : 'Teammates can watch, and their prompts are queued into this conversation under their names.'}`));
277
286
  ui.say(ui.dim(' Approvals stay with you in the app. Ctrl-C stops sharing.\n'));
278
287
 
279
- const stop = async () => { await share.stop(); ui.say(`\n ${ui.dim('Sharing stopped. Transcript:')} ${share.session?.url || ''}`); process.exit(0); };
288
+ const stop = async () => { await share.stop(); link.close(); ui.say(`\n ${ui.dim('Sharing stopped. Transcript:')} ${share.session?.url || ''}`); process.exit(0); };
280
289
  process.on('SIGINT', stop);
281
290
  process.on('SIGTERM', stop);
282
291
  await new Promise(() => {}); // runs until stopped
@@ -294,10 +303,14 @@ export async function watchCodexApp(cfg, opts, ui, isPaused = () => false) {
294
303
  const FRESH = 90; // seconds since the last change that still count as "in use"
295
304
  const shares = new Map(); // thread id -> { share, last }
296
305
  const starting = new Set();
306
+ const failedUntil = new Map(); // thread id -> retry timestamp after error
297
307
  let link = null;
298
308
  let stopped = false;
299
309
 
300
- const stopAll = async () => { stopped = true; await Promise.all([...shares.values()].map((s) => s.share.stop())); process.exit(0); };
310
+ const logFile = path.join(process.env.AGENTPEN_HOME || path.join(os.homedir(), '.agentpen'), 'watch.log');
311
+ try { if (fs.statSync(logFile).size > 5 * 1024 * 1024) fs.truncateSync(logFile, 0); } catch {}
312
+
313
+ const stopAll = async () => { stopped = true; await Promise.all([...shares.values()].map((s) => s.share.stop())); link?.close(); process.exit(0); };
301
314
  process.on('SIGINT', stopAll);
302
315
  process.on('SIGTERM', stopAll);
303
316
  ui.say(` ${ui.accent('●')} Watching the Codex app. Coding conversations are shared while they are active.`);
@@ -319,10 +332,11 @@ export async function watchCodexApp(cfg, opts, ui, isPaused = () => false) {
319
332
  if (s) { if (active) s.last = Date.now(); continue; }
320
333
  const inRepo = !!(t.gitInfo && (t.gitInfo.branch || t.gitInfo.sha || t.gitInfo.originUrl));
321
334
  if (!active || !inRepo || starting.has(t.id) || shares.size + starting.size >= 5) continue;
335
+ if ((failedUntil.get(t.id) || 0) > Date.now()) continue;
322
336
  starting.add(t.id);
323
337
  shareThread(cfg, link, t.id, opts, ui, () => shares.delete(t.id))
324
- .then((share) => { shares.set(t.id, { share, last: Date.now() }); ui.say(` ${ui.dim('›')} sharing “${share.title}” ${ui.dim(share.session.url)}`); })
325
- .catch(() => {})
338
+ .then((share) => { failedUntil.delete(t.id); shares.set(t.id, { share, last: Date.now() }); ui.say(` ${ui.dim('›')} sharing “${share.title}” ${ui.dim(share.session.url)}`); })
339
+ .catch((e) => { failedUntil.set(t.id, Date.now() + 30_000); ui.say(` ${ui.dim('›')} could not share conversation ${t.id}: ${e.message}`); })
326
340
  .finally(() => starting.delete(t.id));
327
341
  }
328
342
  for (const [id, s] of shares) {