agentpen-cli 0.1.2 → 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 +19 -5
- package/cli/agentpen.js +67 -13
- package/cli/claude-share.js +46 -13
- package/cli/codex-app.js +20 -6
- package/cli/handoff.js +44 -28
- package/cli/install.js +128 -8
- package/cli/redact.js +32 -16
- package/package.json +2 -4
- package/server/agents.js +0 -250
- package/server/db.js +0 -161
- package/server/hub.js +0 -637
- package/server/index.js +0 -746
- package/server/notify.js +0 -91
- package/server/search.js +0 -34
- package/web/app.js +0 -518
- package/web/favicon.svg +0 -1
- package/web/index.html +0 -16
- package/web/session.js +0 -460
- package/web/styles.css +0 -263
- package/web/team-page.png +0 -0
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
|
|
|
@@ -178,11 +179,20 @@ cd mac && ./build-app.sh # needs the Xcode command line tools; full Xcode
|
|
|
178
179
|
open dist/Agentpen.app
|
|
179
180
|
```
|
|
180
181
|
|
|
181
|
-
|
|
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.
|
|
182
192
|
|
|
183
193
|
## Run it locally
|
|
184
194
|
|
|
185
|
-
|
|
195
|
+
The server needs Node 22.13+. The CLI on its own (`npm i -g agentpen-cli`) runs on Node 20 and later.
|
|
186
196
|
|
|
187
197
|
```sh
|
|
188
198
|
npm install
|
|
@@ -239,9 +249,13 @@ docker run -p 8080:8080 -v agentpen-data:/data \
|
|
|
239
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. |
|
|
240
250
|
| `AGENTPEN_DATA` | Directory for the database and recordings (default `./data`). |
|
|
241
251
|
| `AGENTPEN_TRUST_PROXY=1` | Believe `X-Forwarded-For` (set when behind a load balancer). |
|
|
242
|
-
| `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). |
|
|
243
256
|
| `ANTHROPIC_API_KEY` | Optional, for self-hosting: one Claude credential for every workspace, instead of a key per workspace. |
|
|
244
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). |
|
|
245
259
|
| `PORT` | Listen port (default 4400; 8080 in the image). |
|
|
246
260
|
|
|
247
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`.
|
|
@@ -267,13 +281,13 @@ Not built:
|
|
|
267
281
|
- **SSO / SAML / SCIM.** Email links only.
|
|
268
282
|
- **Horizontal scaling.** Live sessions are held in one process. Past one node this needs a pub/sub layer and Postgres.
|
|
269
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.
|
|
270
|
-
- **The Mac app has been
|
|
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.
|
|
271
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.
|
|
272
286
|
- **Search covers ended sessions only**, and terminal sessions are indexed from the same plain-text capture, so full-screen programs produce noisy matches.
|
|
273
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.
|
|
274
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.
|
|
275
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.
|
|
276
|
-
- **Checkpoints put source code on the Agentpen server**,
|
|
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.
|
|
277
291
|
- **No phone push.** Notifications reach open browser tabs and the Mac app only.
|
|
278
292
|
- **No Claude desktop app support.** Claude Code is shared from the terminal only.
|
|
279
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
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
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)
|
|
@@ -331,7 +370,7 @@ const HELP = `
|
|
|
331
370
|
(type /agentpen inside it instead to let teammates prompt it)
|
|
332
371
|
agentpen share stop stop sharing it
|
|
333
372
|
agentpen pickup LINK [--worktree] carry on a teammate's Claude Code session here
|
|
334
|
-
agentpen install
|
|
373
|
+
agentpen install [--no-app] share automatically: plain \`claude\`, Codex app, and Mac menu bar app
|
|
335
374
|
agentpen pause | resume stop or restart automatic sharing on this machine
|
|
336
375
|
agentpen default private|watch|type|workspace
|
|
337
376
|
how your sessions start on this machine
|
|
@@ -393,6 +432,11 @@ async function main() {
|
|
|
393
432
|
return login(cfg);
|
|
394
433
|
}
|
|
395
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
|
+
}
|
|
396
440
|
cfg.token = null; cfg.user = null;
|
|
397
441
|
saveConfig(cfg);
|
|
398
442
|
return say('Signed out on this machine.');
|
|
@@ -407,10 +451,14 @@ async function main() {
|
|
|
407
451
|
} catch (e) { die(e.status === 401 ? 'session expired. Run: agentpen login' : e.message); }
|
|
408
452
|
return;
|
|
409
453
|
}
|
|
410
|
-
if (cmd === 'install'
|
|
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.`);
|
|
411
458
|
await ensureAccount(cfg);
|
|
412
459
|
const me = await api(cfg, 'GET', '/api/me');
|
|
413
|
-
|
|
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 });
|
|
414
462
|
}
|
|
415
463
|
if (cmd === 'default' && rest.length === 2) {
|
|
416
464
|
const map = { private: 'private', watch: 'view', type: 'control', workspace: '' };
|
|
@@ -444,13 +492,19 @@ async function main() {
|
|
|
444
492
|
// its options may also come after the word, which is how the /agentpen command passes them
|
|
445
493
|
let stop = false;
|
|
446
494
|
let inClaude = false;
|
|
495
|
+
const expanded = [];
|
|
447
496
|
for (let j = 1; j < rest.length; j++) {
|
|
448
|
-
|
|
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];
|
|
449
502
|
if (a === 'stop') stop = true;
|
|
450
503
|
else if (a === '--in-claude') inClaude = true;
|
|
451
504
|
else if (a === '--private') opts.private = true;
|
|
452
|
-
else if (a === '--
|
|
453
|
-
else if (a === '
|
|
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];
|
|
454
508
|
else die(`unexpected argument "${a}" for share. Try agentpen --help.`);
|
|
455
509
|
}
|
|
456
510
|
// run by /agentpen: Claude Code reads standard output, and a failure should be passed on rather than abort the command
|
package/cli/claude-share.js
CHANGED
|
@@ -131,8 +131,9 @@ export function follow(file, mask) {
|
|
|
131
131
|
|
|
132
132
|
return {
|
|
133
133
|
read() {
|
|
134
|
-
const
|
|
135
|
-
|
|
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
|
|
136
137
|
if (size > offset) {
|
|
137
138
|
const fd = fs.openSync(file, 'r');
|
|
138
139
|
try {
|
|
@@ -144,7 +145,7 @@ export function follow(file, mask) {
|
|
|
144
145
|
for (const l of lines) { if (!l.trim()) continue; try { take(JSON.parse(l)); } catch {} }
|
|
145
146
|
} finally { fs.closeSync(fd); }
|
|
146
147
|
}
|
|
147
|
-
const quiet = Date.now() -
|
|
148
|
+
const quiet = Date.now() - st.mtimeMs;
|
|
148
149
|
const shown = turns.slice(-MAX_TURNS).map((t) => ({ id: t.id, status: t.status, items: t.items.map(({ shell, ...it }) => it) }));
|
|
149
150
|
return { title: title || 'Claude Code session', cwd, branch, turns: shown, quiet, status: turn?.status === 'inProgress' && quiet < STALE_MS ? 'working' : 'idle' };
|
|
150
151
|
},
|
|
@@ -155,10 +156,27 @@ export function follow(file, mask) {
|
|
|
155
156
|
|
|
156
157
|
/** Runs until the session is over. Calls onReady once the team can see it. */
|
|
157
158
|
export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, log = () => {} }) {
|
|
158
|
-
|
|
159
|
-
const cwd = first.cwd || process.cwd();
|
|
160
|
-
const secrets = opts.shareSecrets ? [] : collectSecrets(cwd).sort((a, b) => b.length - a.length);
|
|
159
|
+
let secrets = [];
|
|
161
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();
|
|
162
180
|
const conv = follow(file, mask);
|
|
163
181
|
const convId = path.basename(file, '.jsonl');
|
|
164
182
|
// prompts still waiting for Claude are shown at the end, marked as queued
|
|
@@ -171,10 +189,22 @@ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, l
|
|
|
171
189
|
let snap = read();
|
|
172
190
|
const hello = {
|
|
173
191
|
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,
|
|
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;
|
|
175
207
|
};
|
|
176
|
-
// true once /agentpen has run inside the session: its hook is what delivers prompts
|
|
177
|
-
const canPrompt = () => fs.existsSync(waiterFile(convId));
|
|
178
208
|
let sentCaps = null;
|
|
179
209
|
|
|
180
210
|
let ws = null;
|
|
@@ -237,7 +267,7 @@ export async function runShare(cfg, file, opts, { onReady, onEnd, onStoppable, l
|
|
|
237
267
|
if (!m.resumed) { sent = new Map(); sentMeta = ''; sentCaps = null; }
|
|
238
268
|
caps();
|
|
239
269
|
push();
|
|
240
|
-
if (fresh) onReady?.(session);
|
|
270
|
+
if (fresh) onReady?.(session, opts.title || snap.title);
|
|
241
271
|
resolve();
|
|
242
272
|
} else if (m.t === 'error') {
|
|
243
273
|
if (session && m.code === 'gone') session = null; // server restarted: start a fresh session
|
|
@@ -289,12 +319,15 @@ export async function shareRunningClaude(cfg, opts, ui) {
|
|
|
289
319
|
if (running && alive(running.pid)) return ui.say(`Already sharing “${running.title}”: ${ui.accent(running.url)}`);
|
|
290
320
|
|
|
291
321
|
fs.mkdirSync(path.dirname(stateFile(convId)), { recursive: true, mode: 0o700 });
|
|
292
|
-
const
|
|
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');
|
|
293
325
|
const claudePid = Number(process.env.CLAUDE_PID) || 0;
|
|
294
326
|
const child = spawn(process.execPath, [fileURLToPath(new URL('./agentpen.js', import.meta.url)), 'share', '--run', file], {
|
|
295
327
|
detached: true, stdio: ['ignore', logFd, logFd, 'ipc'],
|
|
296
328
|
env: { ...process.env, AGENTPEN_SHARE_OPTS: JSON.stringify({ ...opts, claudePid }) },
|
|
297
329
|
});
|
|
330
|
+
fs.closeSync(logFd);
|
|
298
331
|
const result = await new Promise((resolve) => {
|
|
299
332
|
const t = setTimeout(() => resolve({ error: `cannot reach ${cfg.server}` }), 20_000);
|
|
300
333
|
child.once('message', (m) => { clearTimeout(t); resolve(m); });
|
|
@@ -333,8 +366,8 @@ export async function runShareChild(cfg, file) {
|
|
|
333
366
|
await runShare(cfg, file, opts, {
|
|
334
367
|
log,
|
|
335
368
|
onStoppable: (fn) => { stop = fn; },
|
|
336
|
-
onReady: (s) => {
|
|
337
|
-
const info = { pid: process.pid, title: opts.title ||
|
|
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 };
|
|
338
371
|
fs.writeFileSync(stateFile(convId), JSON.stringify(info), { mode: 0o600 });
|
|
339
372
|
log(`sharing at ${s.url}`);
|
|
340
373
|
if (process.connected) process.send(info);
|
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 {
|
|
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
|
|
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
|
|
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) {
|
package/cli/handoff.js
CHANGED
|
@@ -5,7 +5,12 @@ import fs from 'node:fs';
|
|
|
5
5
|
import os from 'node:os';
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import zlib from 'node:zlib';
|
|
8
|
-
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { execFile, execFileSync } from 'node:child_process';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
10
|
+
import { collectSecrets } from './redact.js';
|
|
11
|
+
|
|
12
|
+
const execFileAsync = promisify(execFile);
|
|
13
|
+
const gzipAsync = promisify(zlib.gzip);
|
|
9
14
|
|
|
10
15
|
const INTERVAL_MS = Number(process.env.AGENTPEN_CHECKPOINT_MS) || 20_000;
|
|
11
16
|
const MAX_BUNDLE = 100 * 1024 * 1024;
|
|
@@ -23,6 +28,12 @@ function git(args, { cwd, env, input } = {}) {
|
|
|
23
28
|
}
|
|
24
29
|
const tryGit = (args, opts) => { try { return git(args, opts); } catch { return ''; } };
|
|
25
30
|
|
|
31
|
+
async function gitAsync(args, { cwd, env } = {}) {
|
|
32
|
+
const { stdout } = await execFileAsync('git', args, { cwd, env: { ...process.env, ...env }, maxBuffer: 64 * 1024 * 1024 });
|
|
33
|
+
return stdout.trim();
|
|
34
|
+
}
|
|
35
|
+
const tryGitAsync = async (args, opts) => { try { return await gitAsync(args, opts); } catch { return ''; } };
|
|
36
|
+
|
|
26
37
|
// A link to the repository that is safe to store: no embedded credentials.
|
|
27
38
|
const cleanRepo = (url) => url.replace(/^(\w+:\/\/)[^@/]*@/, '$1');
|
|
28
39
|
// Two clones of one repository rarely spell its address the same way.
|
|
@@ -31,35 +42,37 @@ export const repoKey = (url) => cleanRepo(url || '').toLowerCase().replace(/^\w+
|
|
|
31
42
|
// Snapshot the working tree as a commit nobody sees: built on a scratch index,
|
|
32
43
|
// so the host's own index, branch and stash are untouched. Ignored files
|
|
33
44
|
// (.env, node_modules) stay out, exactly as they would stay out of a commit.
|
|
34
|
-
function snapshot(top) {
|
|
35
|
-
const head =
|
|
45
|
+
async function snapshot(top) {
|
|
46
|
+
const head = await tryGitAsync(['rev-parse', 'HEAD'], { cwd: top });
|
|
36
47
|
if (!head) return null;
|
|
37
|
-
const index = path.join(os.tmpdir(), `agentpen-index-${process.pid}`);
|
|
48
|
+
const index = path.join(os.tmpdir(), `agentpen-index-${process.pid}-${Date.now()}`);
|
|
38
49
|
try {
|
|
39
|
-
const real = path.resolve(top,
|
|
40
|
-
if (fs.existsSync(real)) fs.
|
|
50
|
+
const real = path.resolve(top, await tryGitAsync(['rev-parse', '--git-path', 'index'], { cwd: top }));
|
|
51
|
+
if (fs.existsSync(real)) await fs.promises.copyFile(real, index); // keeps git's stat cache, so unchanged files are not re-read
|
|
41
52
|
const env = { GIT_INDEX_FILE: index };
|
|
42
|
-
|
|
43
|
-
const tree =
|
|
44
|
-
if (tree ===
|
|
45
|
-
|
|
53
|
+
await gitAsync(['add', '-A'], { cwd: top, env });
|
|
54
|
+
const tree = await gitAsync(['write-tree'], { cwd: top, env });
|
|
55
|
+
if (tree === await gitAsync(['rev-parse', 'HEAD^{tree}'], { cwd: top })) return { head, checkpoint: head, tree, changed: 0 };
|
|
56
|
+
const diff = await gitAsync(['diff', '--name-only', head, tree], { cwd: top });
|
|
57
|
+
return { head, tree, changed: diff.split('\n').filter(Boolean).length };
|
|
46
58
|
} catch { return null; } finally { fs.rmSync(index, { force: true }); }
|
|
47
59
|
}
|
|
48
60
|
|
|
49
|
-
function commitSnapshot(top, snap) {
|
|
61
|
+
async function commitSnapshot(top, snap) {
|
|
50
62
|
if (snap.checkpoint) return snap.checkpoint;
|
|
51
63
|
const who = { GIT_AUTHOR_NAME: 'Agentpen', GIT_AUTHOR_EMAIL: 'checkpoint@agentpen.invalid', GIT_COMMITTER_NAME: 'Agentpen', GIT_COMMITTER_EMAIL: 'checkpoint@agentpen.invalid' };
|
|
52
|
-
return
|
|
64
|
+
return gitAsync(['commit-tree', snap.tree, '-p', snap.head, '-m', 'Agentpen checkpoint (uncommitted work)'], { cwd: top, env: who });
|
|
53
65
|
}
|
|
54
66
|
|
|
55
67
|
// Everything the team's remote does not already have: unpushed commits plus the snapshot.
|
|
56
|
-
function bundle(top, commit) {
|
|
57
|
-
const file = path.join(os.tmpdir(), `agentpen-${process.pid}.bundle`);
|
|
68
|
+
async function bundle(top, commit) {
|
|
69
|
+
const file = path.join(os.tmpdir(), `agentpen-${process.pid}-${Date.now()}.bundle`);
|
|
58
70
|
try {
|
|
59
|
-
|
|
60
|
-
|
|
71
|
+
await gitAsync(['update-ref', 'refs/agentpen/checkpoint', commit], { cwd: top });
|
|
72
|
+
await gitAsync(['bundle', 'create', file, 'refs/agentpen/checkpoint', '--not', '--remotes'], { cwd: top });
|
|
61
73
|
return file;
|
|
62
74
|
} catch { fs.rmSync(file, { force: true }); return null; } // git refuses an empty bundle: nothing unpushed
|
|
75
|
+
finally { await tryGitAsync(['update-ref', '-d', 'refs/agentpen/checkpoint'], { cwd: top }); }
|
|
63
76
|
}
|
|
64
77
|
|
|
65
78
|
function newestTranscript(dir, since) {
|
|
@@ -74,18 +87,17 @@ function newestTranscript(dir, since) {
|
|
|
74
87
|
return best?.id || null;
|
|
75
88
|
}
|
|
76
89
|
|
|
77
|
-
export function startCheckpoints({ cfg, getSession, cwd, agentSession, secrets, onError }) {
|
|
90
|
+
export function startCheckpoints({ cfg, getSession, cwd, agentSession, secrets, shareSecrets = false, onError }) {
|
|
78
91
|
const started = Date.now() - 2000;
|
|
79
92
|
const dir = claudeProjectDir(cwd);
|
|
80
93
|
const top = tryGit(['rev-parse', '--show-toplevel'], { cwd });
|
|
81
94
|
const repo = top ? cleanRepo(tryGit(['remote', 'get-url', 'origin'], { cwd: top })) : '';
|
|
82
|
-
const needles = [...secrets].sort((a, b) => b.length - a.length);
|
|
83
95
|
let last = '';
|
|
84
96
|
let busy = false;
|
|
85
97
|
let warned = false;
|
|
86
98
|
|
|
87
99
|
const put = async (sid, part, body) => {
|
|
88
|
-
const r = await fetch(`${cfg.server}/api/sessions/${sid}/handoff/${part}`, { method: 'PUT', headers: { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/octet-stream' }, body });
|
|
100
|
+
const r = await fetch(`${cfg.server}/api/sessions/${sid}/handoff/${part}`, { method: 'PUT', headers: { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/octet-stream' }, body, signal: AbortSignal.timeout(60_000) });
|
|
89
101
|
if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || `HTTP ${r.status}`);
|
|
90
102
|
};
|
|
91
103
|
|
|
@@ -97,32 +109,35 @@ export function startCheckpoints({ cfg, getSession, cwd, agentSession, secrets,
|
|
|
97
109
|
const id = agentSession || newestTranscript(dir, started);
|
|
98
110
|
const file = id && path.join(dir, `${id}.jsonl`);
|
|
99
111
|
if (!file || !fs.existsSync(file)) return; // the agent has not written anything yet
|
|
100
|
-
const st = fs.
|
|
101
|
-
const snap = top ? snapshot(top) : null;
|
|
112
|
+
const st = await fs.promises.stat(file);
|
|
113
|
+
const snap = top ? await snapshot(top) : null;
|
|
102
114
|
const sig = [s.id, id, st.size, st.mtimeMs, snap?.head, snap?.tree].join(':');
|
|
103
115
|
if (sig === last) return;
|
|
104
116
|
|
|
105
117
|
if (st.size > MAX_TRANSCRIPT * 8) throw new Error('the conversation is too large to checkpoint');
|
|
106
|
-
let text = fs.
|
|
118
|
+
let text = await fs.promises.readFile(file, 'utf8');
|
|
119
|
+
const needles = shareSecrets ? [] : [...new Set([...(secrets || []), ...collectSecrets(cwd, top)])].sort((a, b) => b.length - a.length);
|
|
107
120
|
for (const v of needles) text = text.split(v).join('••••••'); // same .env masking as the live stream
|
|
108
|
-
await put(s.id, 'transcript',
|
|
121
|
+
await put(s.id, 'transcript', await gzipAsync(text));
|
|
109
122
|
|
|
110
123
|
let checkpoint = '';
|
|
111
124
|
let hasBundle = false;
|
|
112
125
|
if (snap) {
|
|
113
|
-
checkpoint = commitSnapshot(top, snap);
|
|
114
|
-
const b = bundle(top, checkpoint);
|
|
126
|
+
checkpoint = await commitSnapshot(top, snap);
|
|
127
|
+
const b = await bundle(top, checkpoint);
|
|
115
128
|
if (b) {
|
|
116
129
|
try {
|
|
117
|
-
if (fs.
|
|
118
|
-
await put(s.id, 'bundle', fs.
|
|
130
|
+
if ((await fs.promises.stat(b)).size > MAX_BUNDLE) throw new Error('unpushed work is over 100 MB; only the conversation was checkpointed');
|
|
131
|
+
await put(s.id, 'bundle', await fs.promises.readFile(b));
|
|
119
132
|
hasBundle = true;
|
|
120
133
|
} finally { fs.rmSync(b, { force: true }); }
|
|
121
134
|
}
|
|
122
135
|
}
|
|
136
|
+
const branch = top ? await tryGitAsync(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: top }) : '';
|
|
123
137
|
const r = await fetch(`${cfg.server}/api/sessions/${s.id}/handoff`, {
|
|
124
138
|
method: 'POST', headers: { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/json' },
|
|
125
|
-
body: JSON.stringify({ agentSession: id, cwd, subdir: top ? path.relative(top, cwd) : '', repo, branch
|
|
139
|
+
body: JSON.stringify({ agentSession: id, cwd, subdir: top ? path.relative(top, cwd) : '', repo, branch, head: snap?.head, checkpoint, changed: snap?.changed || 0, hasBundle }),
|
|
140
|
+
signal: AbortSignal.timeout(30_000),
|
|
126
141
|
});
|
|
127
142
|
if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || `HTTP ${r.status}`);
|
|
128
143
|
last = sig;
|
|
@@ -185,6 +200,7 @@ export async function pickup(cfg, ref, opts, ui) {
|
|
|
185
200
|
} catch { ui.die(`could not create branch ${branch}. It may exist already from an earlier pickup.`); }
|
|
186
201
|
// their uncommitted work comes back as uncommitted work, not as a commit
|
|
187
202
|
if (meta.checkpoint !== meta.head) git(['restore', `--source=${meta.checkpoint}`, '--worktree', '--', '.'], { cwd: root });
|
|
203
|
+
if (meta.hasBundle) tryGit(['update-ref', '-d', `refs/agentpen/pickup-${sid}`], { cwd: top });
|
|
188
204
|
cwd = meta.subdir && fs.existsSync(path.join(root, meta.subdir)) ? path.join(root, meta.subdir) : root;
|
|
189
205
|
}
|
|
190
206
|
|