agentpen-cli 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,338 @@
1
+ // Share a conversation from the Codex desktop app. There is no terminal to
2
+ // mirror, so this bridges the app's own local control socket instead: it reads
3
+ // the chosen thread, streams it to the team, and queues teammates' prompts
4
+ // into it. Tool approvals are never answered from here; they stay in the app.
5
+ import fs from 'node:fs';
6
+ import net from 'node:net';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import readline from 'node:readline';
10
+ import { randomUUID } from 'node:crypto';
11
+ import WebSocket from 'ws';
12
+ import { collectSecrets } from './redact.js';
13
+
14
+ const TAG = /^\[(.{1,60}) via Agentpen\]\n/;
15
+
16
+ function socketPath(opts) {
17
+ const p = opts.socket || path.join(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), 'app-server-control', 'app-server-control.sock');
18
+ // Codex publishes a symlink to a short path; unix socket paths cannot be long.
19
+ try { return fs.realpathSync(p); } catch { return null; }
20
+ }
21
+
22
+ class Codex {
23
+ constructor(sock) {
24
+ this.sock = sock;
25
+ this.pending = new Map();
26
+ this.nextId = 1;
27
+ }
28
+
29
+ async connect() {
30
+ this.ws = new WebSocket('ws://localhost', { createConnection: () => net.connect(this.sock), handshakeTimeout: 8000, maxPayload: 64 * 1024 * 1024 });
31
+ await new Promise((resolve, reject) => { this.ws.once('open', resolve); this.ws.once('error', reject); });
32
+ this.ws.on('error', () => {});
33
+ this.ws.on('close', () => this.fail(new Error('Codex connection closed')));
34
+ this.ws.on('message', (data) => {
35
+ let m;
36
+ try { m = JSON.parse(data); } catch { return; }
37
+ if (m.method) {
38
+ // a request from Codex (for example a tool approval): decline to handle it
39
+ if (m.id !== undefined) this.ws.send(JSON.stringify({ id: m.id, error: { code: -32601, message: 'Handled in the Codex app' } }));
40
+ return;
41
+ }
42
+ const p = this.pending.get(m.id);
43
+ if (!p) return;
44
+ this.pending.delete(m.id);
45
+ clearTimeout(p.timer);
46
+ if (m.error) p.reject(new Error(m.error.message)); else p.resolve(m.result);
47
+ });
48
+ await this.request('initialize', { clientInfo: { name: 'agentpen', version: '0.1.0' }, capabilities: { experimentalApi: true } });
49
+ this.ws.send(JSON.stringify({ method: 'initialized', params: {} }));
50
+ }
51
+
52
+ get open() { return this.ws?.readyState === 1; }
53
+
54
+ request(method, params = {}) {
55
+ if (!this.open) return Promise.reject(new Error('Codex connection closed'));
56
+ const id = this.nextId++;
57
+ return new Promise((resolve, reject) => {
58
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Codex did not answer ${method}`)); }, 20_000);
59
+ this.pending.set(id, { resolve, reject, timer });
60
+ this.ws.send(JSON.stringify({ id, method, params }));
61
+ });
62
+ }
63
+
64
+ fail(err) {
65
+ for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(err); }
66
+ this.pending.clear();
67
+ }
68
+
69
+ async readThread(threadId) {
70
+ try { return (await this.request('thread/read', { threadId, includeTurns: true })).thread; } catch (e) {
71
+ if (!this.open) throw e;
72
+ // a brand-new conversation has no turns to load yet
73
+ return { ...(await this.request('thread/read', { threadId })).thread, turns: [] };
74
+ }
75
+ }
76
+
77
+ // Prompts waiting for the app to pick them up; shown to the team as "queued".
78
+ async queued(threadId) {
79
+ try { return (await this.request('thread/queue/list', { threadId, limit: 20 })).data || []; } catch { return []; }
80
+ }
81
+ }
82
+
83
+ const tail = (s, n) => (s && s.length > n ? '…' + s.slice(-n) : s || '');
84
+
85
+ // Codex's thread -> the small transcript shape Agentpen shows. Reasoning and
86
+ // system instructions are left out on purpose.
87
+ export function transcript(thread, mask = (s) => s, queue = []) {
88
+ const turns = (thread.turns || []).slice(-300).map((turn) => ({
89
+ id: turn.id,
90
+ status: turn.status,
91
+ error: turn.error?.message ? mask(turn.error.message) : undefined,
92
+ items: (turn.items || []).flatMap((it) => {
93
+ if (it.type === 'userMessage') {
94
+ let text = (it.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n');
95
+ const by = TAG.exec(text)?.[1];
96
+ if (by) text = text.replace(TAG, '');
97
+ return [{ id: it.id, role: 'user', text: mask(text), by }];
98
+ }
99
+ if (it.type === 'agentMessage') return [{ id: it.id, role: 'assistant', text: mask(it.text || '') }];
100
+ if (it.type === 'plan') return [{ id: it.id, role: 'plan', text: mask(it.text || '') }];
101
+ if (it.type === 'commandExecution') return [{ id: it.id, role: 'tool', text: mask(it.command || ''), detail: mask(tail(it.aggregatedOutput, 3000)), status: it.status }];
102
+ if (it.type === 'fileChange') return [{ id: it.id, role: 'tool', text: `Edited ${(it.changes || []).map((c) => c.path).join(', ') || 'files'}`, status: it.status }];
103
+ if (it.type === 'mcpToolCall') return [{ id: it.id, role: 'tool', text: `${it.server}.${it.tool}`, status: it.status }];
104
+ if (it.type === 'webSearch') return [{ id: it.id, role: 'tool', text: `Web search${it.query ? `: ${mask(it.query)}` : ''}` }];
105
+ return [];
106
+ }),
107
+ }));
108
+ const waiting = queue.map((sub) => {
109
+ let text = (sub.input || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n');
110
+ const by = TAG.exec(text)?.[1];
111
+ if (by) text = text.replace(TAG, '');
112
+ return { id: sub.id, role: 'user', text: mask(text), by, status: 'queued' };
113
+ });
114
+ if (waiting.length) turns.push({ id: 'queued', status: 'completed', items: waiting });
115
+ const flags = thread.status?.activeFlags || [];
116
+ const busy = thread.status?.type === 'active' || turns.at(-1)?.status === 'inProgress';
117
+ return { title: thread.name || thread.preview?.split('\n')[0].slice(0, 80) || 'Codex conversation', turns, status: flags.length ? 'blocked' : busy ? 'working' : 'idle' };
118
+ }
119
+
120
+ async function pickThread(codex, opts, ui) {
121
+ if (opts.thread) return opts.thread;
122
+ const list = await codex.request('thread/list', { limit: 30, sortKey: 'updated_at', sortDirection: 'desc' });
123
+ const threads = list.data.filter((t) => !t.parentThreadId && !t.ephemeral).slice(0, 9);
124
+ if (!threads.length) ui.die('no Codex conversations found. Start one in the Codex app, then run this again.');
125
+ if (threads.length === 1 || opts.latest || !process.stdin.isTTY) return threads[0].id;
126
+ ui.say(`\n ${ui.bold('Which Codex conversation?')}`);
127
+ threads.forEach((t, i) => {
128
+ const name = (t.name || t.preview || 'Untitled').split('\n')[0].slice(0, 60);
129
+ ui.say(` ${ui.accent(String(i + 1))} ${name} ${ui.dim(path.basename(t.cwd || ''))}`);
130
+ });
131
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
132
+ const answer = await new Promise((r) => rl.question(` Number ${ui.dim('(Enter for 1)')}: `, r));
133
+ rl.close();
134
+ const n = answer.trim() === '' ? 1 : Number(answer);
135
+ if (!Number.isInteger(n) || n < 1 || n > threads.length) ui.die('that is not one of the listed conversations.');
136
+ return threads[n - 1].id;
137
+ }
138
+
139
+ // A connection to the Codex app that is reopened whenever it has dropped.
140
+ function codexLink(sock) {
141
+ let codex = null;
142
+ return { async get() { if (!codex?.open) { codex = new Codex(sock); await codex.connect(); } return codex; } };
143
+ }
144
+
145
+ /**
146
+ * Share one conversation. Throws if it cannot start. After that it keeps the
147
+ * team's copy up to date until stop() is called or the server ends the session.
148
+ */
149
+ async function shareThread(cfg, link, threadId, opts, ui, onEnd) {
150
+ let thread;
151
+ try { thread = await (await link.get()).readThread(threadId); } catch (e) { throw new Error(`could not read that conversation: ${e.message}`); }
152
+ // fail now, not on a teammate's first prompt, if this Codex cannot queue messages
153
+ 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
+
155
+ const secrets = opts.shareSecrets ? [] : collectSecrets(thread.cwd || process.cwd()).sort((a, b) => b.length - a.length);
156
+ const mask = (s) => { for (const v of secrets) s = s.split(v).join('••••••'); return s; };
157
+ const read = async () => { const c = await link.get(); return transcript(await c.readThread(threadId), mask, await c.queued(threadId)); };
158
+ let snap = await read();
159
+
160
+ const hello = {
161
+ t: 'hello', kind: 'thread', workspace: opts.workspace, title: opts.title || snap.title, agent: 'codex app',
162
+ project: path.basename(thread.cwd || ''), branch: thread.gitInfo?.branch || '', access: opts.access,
163
+ };
164
+
165
+ let ws = null;
166
+ let session = null;
167
+ let stopping = false;
168
+ let retry = 0;
169
+ let sent = new Map(); // turn id -> JSON last sent
170
+ let sentMeta = '';
171
+ let people = [];
172
+
173
+ const push = () => {
174
+ if (ws?.readyState !== 1 || !session) return;
175
+ const changed = snap.turns.filter((t) => sent.get(t.id) !== JSON.stringify(t));
176
+ const meta = JSON.stringify([snap.title, snap.status, snap.turns.map((t) => t.id)]);
177
+ if (!changed.length && meta === sentMeta) return;
178
+ // big histories go up in slices so no single frame is huge
179
+ for (let i = 0; i < Math.max(1, changed.length); i += 40) {
180
+ ws.send(JSON.stringify({ t: 'thread', title: opts.title || snap.title, status: snap.status, turns: changed.slice(i, i + 40), order: i + 40 >= changed.length ? snap.turns.map((t) => t.id) : undefined }));
181
+ }
182
+ for (const t of changed) sent.set(t.id, JSON.stringify(t));
183
+ sentMeta = meta;
184
+ };
185
+
186
+ const onPrompt = async (m) => {
187
+ let ok = true;
188
+ try {
189
+ await (await link.get()).request('thread/queue/add', {
190
+ threadId, clientUserMessageId: randomUUID(),
191
+ input: [{ type: 'text', text: `[${m.by} via Agentpen]\n${m.text}`, text_elements: [] }],
192
+ });
193
+ ui.say(` ${ui.dim('›')} ${m.by} queued a prompt`);
194
+ snap = await read();
195
+ push();
196
+ } catch { ok = false; ui.say(` ${ui.dim('›')} could not queue ${m.by}'s prompt (Codex did not confirm it)`); }
197
+ if (ws?.readyState === 1) ws.send(JSON.stringify({ t: 'prompt-result', rid: m.rid, ok }));
198
+ };
199
+
200
+ await new Promise((resolve, reject) => {
201
+ const connect = () => {
202
+ ws = new WebSocket(cfg.server.replace(/^http/, 'ws') + '/ws/host', { headers: { authorization: `Bearer ${cfg.token}` } });
203
+ ws.on('open', () => ws.send(JSON.stringify(session ? { t: 'hello', resume: { id: session.id, key: session.key } } : hello)));
204
+ ws.on('message', (data, isBinary) => {
205
+ if (isBinary) return;
206
+ let m;
207
+ try { m = JSON.parse(data); } catch { return; }
208
+ if (m.t === 'ready') {
209
+ session = { ...session, ...m };
210
+ retry = 0;
211
+ if (!m.resumed) { sent = new Map(); sentMeta = ''; }
212
+ push();
213
+ resolve();
214
+ } else if (m.t === 'error') {
215
+ if (session && m.code === 'gone') session = null; // server restarted: start a fresh session
216
+ else if (!session) { stopping = true; reject(new Error(m.message)); }
217
+ } else if (m.t === 'prompt') onPrompt(m);
218
+ else if (m.t === 'people') {
219
+ for (const p of m.people) if (!people.some((o) => o.name === p.name)) ui.say(` ${ui.dim('›')} ${p.name} joined “${snap.title}”`);
220
+ people = m.people;
221
+ } else if (m.t === 'end') { stopping = true; onEnd?.(m.reason); }
222
+ });
223
+ ws.on('close', () => {
224
+ if (stopping) return;
225
+ if (!session && retry >= 3 && !sentMeta) { stopping = true; return reject(new Error(`cannot reach ${cfg.server}`)); }
226
+ setTimeout(connect, Math.min(8000, 500 * 2 ** retry++));
227
+ });
228
+ ws.on('error', () => {});
229
+ };
230
+ connect();
231
+ });
232
+
233
+ (async () => {
234
+ let codexDown = false;
235
+ while (!stopping) {
236
+ await new Promise((r) => setTimeout(r, snap.status === 'idle' ? 1200 : 500));
237
+ if (stopping) return;
238
+ try {
239
+ snap = await read();
240
+ if (codexDown) { codexDown = false; ui.say(` ${ui.dim('›')} Codex is back`); }
241
+ push();
242
+ } catch {
243
+ if (!codexDown) { codexDown = true; ui.say(` ${ui.dim('›')} lost the Codex app, waiting for it to come back…`); }
244
+ await new Promise((r) => setTimeout(r, 2000));
245
+ }
246
+ }
247
+ })();
248
+
249
+ return {
250
+ get session() { return session; },
251
+ get title() { return snap.title; },
252
+ stop: () => new Promise((resolve) => {
253
+ if (stopping) return resolve();
254
+ stopping = true;
255
+ if (ws?.readyState === 1) { ws.send(JSON.stringify({ t: 'exit' }), () => ws.close()); setTimeout(resolve, 600); } else resolve();
256
+ }),
257
+ };
258
+ }
259
+
260
+ export async function shareCodexApp(cfg, opts, ui) {
261
+ const sock = socketPath(opts);
262
+ if (!sock) ui.die('cannot find the Codex app on this machine. Open the Codex app (or run `codex app-server daemon start`) and try again.');
263
+ const link = codexLink(sock);
264
+ let codex;
265
+ try { codex = await link.get(); } catch { ui.die('the Codex app is not answering. Make sure it is open and up to date, then try again.'); }
266
+ const threadId = await pickThread(codex, opts, ui);
267
+ let share;
268
+ try {
269
+ share = await shareThread(cfg, link, threadId, opts, ui, (reason) => { ui.say(`\n Sharing stopped (${reason}).`); process.exit(0); });
270
+ } catch (e) { ui.die(e.message); }
271
+
272
+ const session = share.session;
273
+ ui.say();
274
+ ui.say(` ${ui.accent('●')} ${ui.bold(`Sharing “${share.title}”`)} ${ui.dim(`live in ${session.workspace.name}`)}`);
275
+ ui.say(` ${ui.accent(session.url)}`);
276
+ 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
+ ui.say(ui.dim(' Approvals stay with you in the app. Ctrl-C stops sharing.\n'));
278
+
279
+ const stop = async () => { await share.stop(); ui.say(`\n ${ui.dim('Sharing stopped. Transcript:')} ${share.session?.url || ''}`); process.exit(0); };
280
+ process.on('SIGINT', stop);
281
+ process.on('SIGTERM', stop);
282
+ await new Promise(() => {}); // runs until stopped
283
+ }
284
+
285
+ /**
286
+ * Background mode: nobody types a command. Any Codex app conversation that is
287
+ * doing work inside a git repository is shared while it is active, and the
288
+ * share ends once it has been quiet for a while. Conversations outside a
289
+ * repository (general chat) are never shared.
290
+ */
291
+ export async function watchCodexApp(cfg, opts, ui, isPaused = () => false) {
292
+ const POLL = Number(process.env.AGENTPEN_WATCH_POLL_MS) || 4000;
293
+ const IDLE = Number(process.env.AGENTPEN_WATCH_IDLE_MS) || 20 * 60_000;
294
+ const FRESH = 90; // seconds since the last change that still count as "in use"
295
+ const shares = new Map(); // thread id -> { share, last }
296
+ const starting = new Set();
297
+ let link = null;
298
+ let stopped = false;
299
+
300
+ const stopAll = async () => { stopped = true; await Promise.all([...shares.values()].map((s) => s.share.stop())); process.exit(0); };
301
+ process.on('SIGINT', stopAll);
302
+ process.on('SIGTERM', stopAll);
303
+ ui.say(` ${ui.accent('●')} Watching the Codex app. Coding conversations are shared while they are active.`);
304
+
305
+ while (!stopped) {
306
+ try {
307
+ if (isPaused()) {
308
+ for (const [id, s] of shares) { await s.share.stop(); shares.delete(id); }
309
+ } else {
310
+ const sock = socketPath(opts);
311
+ if (!sock) throw new Error('Codex is not running');
312
+ link ||= codexLink(sock);
313
+ const list = await (await link.get()).request('thread/list', { limit: 20, sortKey: 'updated_at', sortDirection: 'desc' });
314
+ const nowS = Date.now() / 1000;
315
+ for (const t of list.data) {
316
+ if (t.parentThreadId || t.ephemeral) continue;
317
+ const active = t.status?.type === 'active' || nowS - (t.updatedAt || 0) < FRESH;
318
+ const s = shares.get(t.id);
319
+ if (s) { if (active) s.last = Date.now(); continue; }
320
+ const inRepo = !!(t.gitInfo && (t.gitInfo.branch || t.gitInfo.sha || t.gitInfo.originUrl));
321
+ if (!active || !inRepo || starting.has(t.id) || shares.size + starting.size >= 5) continue;
322
+ starting.add(t.id);
323
+ 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(() => {})
326
+ .finally(() => starting.delete(t.id));
327
+ }
328
+ for (const [id, s] of shares) {
329
+ if (Date.now() - s.last < IDLE) continue;
330
+ ui.say(` ${ui.dim('›')} “${s.share.title}” has gone quiet; sharing stopped`);
331
+ await s.share.stop();
332
+ shares.delete(id);
333
+ }
334
+ }
335
+ } catch { link = null; } // Codex closed or not started yet: keep waiting
336
+ await new Promise((r) => setTimeout(r, POLL));
337
+ }
338
+ }
package/cli/handoff.js ADDED
@@ -0,0 +1,216 @@
1
+ // Checkpoints and pickup. While a Claude Code session runs, the conversation
2
+ // and the unpushed code are checkpointed to the workspace, so that when the
3
+ // host's laptop is shut a teammate can carry on from their own machine.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import zlib from 'node:zlib';
8
+ import { execFileSync } from 'node:child_process';
9
+
10
+ const INTERVAL_MS = Number(process.env.AGENTPEN_CHECKPOINT_MS) || 20_000;
11
+ const MAX_BUNDLE = 100 * 1024 * 1024;
12
+ const MAX_TRANSCRIPT = 64 * 1024 * 1024;
13
+
14
+ // Where Claude Code keeps a project's conversations: the working directory
15
+ // with every character that is not a letter or digit turned into "-".
16
+ export function claudeProjectDir(cwd) {
17
+ const base = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
18
+ return path.join(base, 'projects', cwd.replace(/[^A-Za-z0-9]/g, '-'));
19
+ }
20
+
21
+ function git(args, { cwd, env, input } = {}) {
22
+ return execFileSync('git', args, { cwd, env: { ...process.env, ...env }, input, stdio: ['pipe', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 }).toString().trim();
23
+ }
24
+ const tryGit = (args, opts) => { try { return git(args, opts); } catch { return ''; } };
25
+
26
+ // A link to the repository that is safe to store: no embedded credentials.
27
+ const cleanRepo = (url) => url.replace(/^(\w+:\/\/)[^@/]*@/, '$1');
28
+ // Two clones of one repository rarely spell its address the same way.
29
+ export const repoKey = (url) => cleanRepo(url || '').toLowerCase().replace(/^\w+:\/\//, '').replace(/^git@/, '').replace(':', '/').replace(/\.git$/, '').replace(/\/$/, '');
30
+
31
+ // Snapshot the working tree as a commit nobody sees: built on a scratch index,
32
+ // so the host's own index, branch and stash are untouched. Ignored files
33
+ // (.env, node_modules) stay out, exactly as they would stay out of a commit.
34
+ function snapshot(top) {
35
+ const head = tryGit(['rev-parse', 'HEAD'], { cwd: top });
36
+ if (!head) return null;
37
+ const index = path.join(os.tmpdir(), `agentpen-index-${process.pid}`);
38
+ try {
39
+ const real = path.resolve(top, tryGit(['rev-parse', '--git-path', 'index'], { cwd: top }));
40
+ if (fs.existsSync(real)) fs.copyFileSync(real, index); // keeps git's stat cache, so unchanged files are not re-read
41
+ const env = { GIT_INDEX_FILE: index };
42
+ git(['add', '-A'], { cwd: top, env });
43
+ const tree = git(['write-tree'], { cwd: top, env });
44
+ if (tree === git(['rev-parse', 'HEAD^{tree}'], { cwd: top })) return { head, checkpoint: head, tree, changed: 0 };
45
+ return { head, tree, changed: git(['diff', '--name-only', head, tree], { cwd: top }).split('\n').filter(Boolean).length };
46
+ } catch { return null; } finally { fs.rmSync(index, { force: true }); }
47
+ }
48
+
49
+ function commitSnapshot(top, snap) {
50
+ if (snap.checkpoint) return snap.checkpoint;
51
+ const who = { GIT_AUTHOR_NAME: 'Agentpen', GIT_AUTHOR_EMAIL: 'checkpoint@agentpen.invalid', GIT_COMMITTER_NAME: 'Agentpen', GIT_COMMITTER_EMAIL: 'checkpoint@agentpen.invalid' };
52
+ return git(['commit-tree', snap.tree, '-p', snap.head, '-m', 'Agentpen checkpoint (uncommitted work)'], { cwd: top, env: who });
53
+ }
54
+
55
+ // 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`);
58
+ try {
59
+ git(['update-ref', 'refs/agentpen/checkpoint', commit], { cwd: top });
60
+ git(['bundle', 'create', file, 'refs/agentpen/checkpoint', '--not', '--remotes'], { cwd: top });
61
+ return file;
62
+ } catch { fs.rmSync(file, { force: true }); return null; } // git refuses an empty bundle: nothing unpushed
63
+ }
64
+
65
+ function newestTranscript(dir, since) {
66
+ let best = null;
67
+ try {
68
+ for (const f of fs.readdirSync(dir)) {
69
+ if (!f.endsWith('.jsonl')) continue;
70
+ const st = fs.statSync(path.join(dir, f));
71
+ if (st.mtimeMs >= since && (!best || st.mtimeMs > best.mtimeMs)) best = { id: f.slice(0, -6), mtimeMs: st.mtimeMs };
72
+ }
73
+ } catch {}
74
+ return best?.id || null;
75
+ }
76
+
77
+ export function startCheckpoints({ cfg, getSession, cwd, agentSession, secrets, onError }) {
78
+ const started = Date.now() - 2000;
79
+ const dir = claudeProjectDir(cwd);
80
+ const top = tryGit(['rev-parse', '--show-toplevel'], { cwd });
81
+ const repo = top ? cleanRepo(tryGit(['remote', 'get-url', 'origin'], { cwd: top })) : '';
82
+ const needles = [...secrets].sort((a, b) => b.length - a.length);
83
+ let last = '';
84
+ let busy = false;
85
+ let warned = false;
86
+
87
+ 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 });
89
+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || `HTTP ${r.status}`);
90
+ };
91
+
92
+ async function run() {
93
+ const s = getSession();
94
+ if (busy || !s || !s.handoff || s.dead) return;
95
+ busy = true;
96
+ try {
97
+ const id = agentSession || newestTranscript(dir, started);
98
+ const file = id && path.join(dir, `${id}.jsonl`);
99
+ if (!file || !fs.existsSync(file)) return; // the agent has not written anything yet
100
+ const st = fs.statSync(file);
101
+ const snap = top ? snapshot(top) : null;
102
+ const sig = [s.id, id, st.size, st.mtimeMs, snap?.head, snap?.tree].join(':');
103
+ if (sig === last) return;
104
+
105
+ if (st.size > MAX_TRANSCRIPT * 8) throw new Error('the conversation is too large to checkpoint');
106
+ let text = fs.readFileSync(file, 'utf8');
107
+ for (const v of needles) text = text.split(v).join('••••••'); // same .env masking as the live stream
108
+ await put(s.id, 'transcript', zlib.gzipSync(text));
109
+
110
+ let checkpoint = '';
111
+ let hasBundle = false;
112
+ if (snap) {
113
+ checkpoint = commitSnapshot(top, snap);
114
+ const b = bundle(top, checkpoint);
115
+ if (b) {
116
+ try {
117
+ if (fs.statSync(b).size > MAX_BUNDLE) throw new Error('unpushed work is over 100 MB; only the conversation was checkpointed');
118
+ await put(s.id, 'bundle', fs.readFileSync(b));
119
+ hasBundle = true;
120
+ } finally { fs.rmSync(b, { force: true }); }
121
+ }
122
+ }
123
+ const r = await fetch(`${cfg.server}/api/sessions/${s.id}/handoff`, {
124
+ 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: top ? tryGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: top }) : '', head: snap?.head, checkpoint, changed: snap?.changed || 0, hasBundle }),
126
+ });
127
+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || `HTTP ${r.status}`);
128
+ last = sig;
129
+ } catch (e) {
130
+ if (!warned) { warned = true; onError?.(e.message); }
131
+ } finally { busy = false; }
132
+ }
133
+
134
+ const timer = setInterval(run, INTERVAL_MS);
135
+ timer.unref();
136
+ return { now: run, stop: () => clearInterval(timer) };
137
+ }
138
+
139
+ // ---- pickup ----------------------------------------------------------------
140
+
141
+ async function download(cfg, sid, part) {
142
+ const r = await fetch(`${cfg.server}/api/sessions/${sid}/handoff/${part}`, { headers: { authorization: `Bearer ${cfg.token}` } });
143
+ if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || `could not download the ${part}`);
144
+ return Buffer.from(await r.arrayBuffer());
145
+ }
146
+
147
+ /**
148
+ * Rebuild a teammate's session here: their code state on a new branch, their
149
+ * conversation where Claude Code will find it. Returns what to run next.
150
+ */
151
+ export async function pickup(cfg, ref, opts, ui) {
152
+ const sid = /([A-Za-z0-9]{6,})\/?$/.exec(String(ref).split('?')[0])?.[1];
153
+ if (!sid) ui.die('give the session link or id, for example: agentpen pickup https://…/s/k3Pq9xTz');
154
+ const r = await fetch(`${cfg.server}/api/sessions/${sid}/pickup`, { method: 'POST', headers: { authorization: `Bearer ${cfg.token}`, 'content-type': 'application/json' }, body: '{}' });
155
+ const meta = await r.json().catch(() => ({}));
156
+ if (!r.ok) ui.die(meta.error || 'could not pick up that session.');
157
+
158
+ let cwd = fs.realpathSync(process.cwd());
159
+ let branch = '';
160
+ if (meta.head) {
161
+ const top = tryGit(['rev-parse', '--show-toplevel'], { cwd });
162
+ if (!top) ui.die(`run this inside your clone of ${meta.repo || 'the repository'}; ${meta.host} was working in a git repository.`);
163
+ const mine = repoKey(tryGit(['remote', 'get-url', 'origin'], { cwd: top }));
164
+ if (meta.repo && mine !== repoKey(meta.repo) && !opts.force) ui.die(`this clone is ${mine || 'not connected to a remote'}, but ${meta.host} was working in ${repoKey(meta.repo)}. Run it in that repository, or pass --force.`);
165
+ if (!opts.worktree && tryGit(['status', '--porcelain'], { cwd: top })) ui.die('you have uncommitted changes here. Commit or stash them, or pass --worktree to pick up in a separate folder.');
166
+
167
+ tryGit(['fetch', '--all', '--quiet'], { cwd: top });
168
+ if (meta.hasBundle) {
169
+ const file = path.join(os.tmpdir(), `agentpen-pickup-${process.pid}.bundle`);
170
+ fs.writeFileSync(file, await download(cfg, sid, 'bundle'));
171
+ try { git(['fetch', '--quiet', file, `+refs/agentpen/checkpoint:refs/agentpen/pickup-${sid}`], { cwd: top }); } catch {
172
+ ui.die(`could not apply ${meta.host}'s work on top of this clone. Run git fetch and try again; their branch may build on commits you do not have.`);
173
+ } finally { fs.rmSync(file, { force: true }); }
174
+ }
175
+ if (!tryGit(['cat-file', '-t', meta.checkpoint], { cwd: top })) ui.die(`this clone does not have ${meta.host}'s commit ${meta.head.slice(0, 8)}. Run git fetch and try again.`);
176
+
177
+ const slug = meta.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 30) || 'session';
178
+ branch = `pickup/${slug}-${sid.slice(0, 4).toLowerCase()}`;
179
+ let root = top;
180
+ try {
181
+ if (opts.worktree) {
182
+ root = path.join(path.dirname(top), `${path.basename(top)}-${slug}-${sid.slice(0, 4).toLowerCase()}`);
183
+ git(['worktree', 'add', '--quiet', '-b', branch, root, meta.head], { cwd: top });
184
+ } else git(['checkout', '--quiet', '-b', branch, meta.head], { cwd: top });
185
+ } catch { ui.die(`could not create branch ${branch}. It may exist already from an earlier pickup.`); }
186
+ // their uncommitted work comes back as uncommitted work, not as a commit
187
+ if (meta.checkpoint !== meta.head) git(['restore', `--source=${meta.checkpoint}`, '--worktree', '--', '.'], { cwd: root });
188
+ cwd = meta.subdir && fs.existsSync(path.join(root, meta.subdir)) ? path.join(root, meta.subdir) : root;
189
+ }
190
+
191
+ // The conversation refers to the host's folder; point it at this one.
192
+ let text = zlib.gunzipSync(await download(cfg, sid, 'transcript')).toString('utf8');
193
+ const esc = (p) => JSON.stringify(p).slice(1, -1);
194
+ if (meta.cwd && meta.cwd !== cwd) {
195
+ const from = meta.subdir && meta.cwd.endsWith(meta.subdir) ? meta.cwd.slice(0, -meta.subdir.length).replace(/\/$/, '') : meta.cwd;
196
+ const to = meta.subdir && cwd.endsWith(meta.subdir) ? cwd.slice(0, -meta.subdir.length).replace(/\/$/, '') : cwd;
197
+ text = text.split(esc(from)).join(esc(to));
198
+ }
199
+ const dir = claudeProjectDir(cwd);
200
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
201
+ fs.writeFileSync(path.join(dir, `${meta.agentSession}.jsonl`), text, { mode: 0o600 });
202
+
203
+ const mins = Math.max(0, Math.round((Date.now() - meta.at) / 60000));
204
+ ui.say();
205
+ ui.say(` ${ui.bold(`Picked up “${meta.title}” from ${meta.host}`)}`);
206
+ ui.say(ui.dim(` Checkpoint from ${mins < 1 ? 'under a minute' : `${mins} min`} ago${meta.live ? `. ${meta.host}'s session is still live, so you are now working in parallel` : ''}.`));
207
+ if (branch) ui.say(ui.dim(` Branch ${branch}${meta.changed ? `, with ${meta.changed} uncommitted file${meta.changed === 1 ? '' : 's'} restored` : ''}${opts.worktree ? `, in ${cwd}` : ''}.`));
208
+ if (meta.summary) {
209
+ ui.say();
210
+ ui.say(` ${ui.bold('Catch-up')} ${ui.dim(`by ${meta.summary.by || 'Claude'}`)}`);
211
+ ui.say(` ${meta.summary.goal}`);
212
+ ui.say(ui.dim(` Now: ${meta.summary.state}`));
213
+ ui.say(ui.dim(` Next: ${meta.summary.next}`));
214
+ }
215
+ return { cwd, agentSession: meta.agentSession, title: meta.title };
216
+ }