agentpen-cli 0.0.0-stage → 0.1.1
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/LICENSE +27 -0
- package/README.md +295 -2
- package/cli/agentpen.js +469 -0
- package/cli/claude-share.js +289 -0
- package/cli/codex-app.js +338 -0
- package/cli/handoff.js +216 -0
- package/cli/install.js +173 -0
- package/cli/postinstall.js +14 -0
- package/cli/redact.js +63 -0
- package/package.json +43 -4
- package/server/agents.js +250 -0
- package/server/db.js +161 -0
- package/server/hub.js +621 -0
- package/server/index.js +745 -0
- package/server/notify.js +91 -0
- package/server/search.js +34 -0
- package/web/app.js +518 -0
- package/web/favicon.svg +1 -0
- package/web/index.html +16 -0
- package/web/session.js +451 -0
- package/web/styles.css +263 -0
- package/web/team-page.png +0 -0
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
|
+
}
|
package/cli/install.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// `agentpen install`: after this, nobody has to remember a prefix.
|
|
2
|
+
// - A small shell hook makes plain `claude` go through Agentpen.
|
|
3
|
+
// - On macOS a background helper shares Codex app conversations while they are active.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
|
|
10
|
+
const START = '# >>> agentpen >>>';
|
|
11
|
+
const END = '# <<< agentpen <<<';
|
|
12
|
+
// If agentpen ever goes missing, `claude` must still be claude: the hook falls back to the real program.
|
|
13
|
+
const HOOK = `${START}
|
|
14
|
+
# Plain \`claude\` is shared with your Agentpen workspace. Remove with: agentpen uninstall
|
|
15
|
+
if alias claude >/dev/null 2>&1; then
|
|
16
|
+
AGENTPEN_CLAUDE="$(alias claude | sed -E "s/^(alias )?claude=//; s/^'//; s/'$//")"; export AGENTPEN_CLAUDE
|
|
17
|
+
unalias claude
|
|
18
|
+
fi
|
|
19
|
+
function claude {
|
|
20
|
+
if command -v agentpen >/dev/null 2>&1; then command agentpen --auto claude "$@"
|
|
21
|
+
else command "\${AGENTPEN_CLAUDE:-claude}" "$@"; fi
|
|
22
|
+
}
|
|
23
|
+
${END}
|
|
24
|
+
`;
|
|
25
|
+
|
|
26
|
+
const LABEL = 'dev.agentpen.watch';
|
|
27
|
+
const plistPath = () => path.join(os.homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
|
|
28
|
+
const rcFiles = () => {
|
|
29
|
+
const home = os.homedir();
|
|
30
|
+
const files = [path.join(home, '.zshrc'), path.join(home, '.bashrc')].filter((f) => fs.existsSync(f));
|
|
31
|
+
// zsh is the default shell on a Mac; make its file if this machine has neither
|
|
32
|
+
return files.length ? files : [path.join(home, '.zshrc')];
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
function strip(text) {
|
|
36
|
+
const a = text.indexOf(START);
|
|
37
|
+
const b = text.indexOf(END);
|
|
38
|
+
if (a < 0 || b < a) return text;
|
|
39
|
+
return (text.slice(0, a).replace(/\n+$/, '\n') + text.slice(b + END.length).replace(/^\n/, '')).replace(/^\n+$/, '');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function writeHook(file) {
|
|
43
|
+
const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
|
|
44
|
+
const clean = strip(before);
|
|
45
|
+
fs.writeFileSync(file, `${clean}${clean && !clean.endsWith('\n') ? '\n' : ''}${clean ? '\n' : ''}${HOOK}`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const xml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
49
|
+
function launchAgent() {
|
|
50
|
+
const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), 'agentpen.js');
|
|
51
|
+
const log = path.join(process.env.AGENTPEN_HOME || path.join(os.homedir(), '.agentpen'), 'watch.log');
|
|
52
|
+
const args = [process.execPath, cli, 'watch'].map((a) => ` <string>${xml(a)}</string>`).join('\n');
|
|
53
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
54
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
55
|
+
<plist version="1.0">
|
|
56
|
+
<dict>
|
|
57
|
+
<key>Label</key><string>${LABEL}</string>
|
|
58
|
+
<key>ProgramArguments</key>
|
|
59
|
+
<array>
|
|
60
|
+
${args}
|
|
61
|
+
</array>
|
|
62
|
+
<key>RunAtLoad</key><true/>
|
|
63
|
+
<key>KeepAlive</key><true/>
|
|
64
|
+
<key>ThrottleInterval</key><integer>30</integer>
|
|
65
|
+
<key>StandardOutPath</key><string>${xml(log)}</string>
|
|
66
|
+
<key>StandardErrorPath</key><string>${xml(log)}</string>
|
|
67
|
+
<key>EnvironmentVariables</key>
|
|
68
|
+
<dict><key>PATH</key><string>${xml(process.env.PATH || '/usr/bin:/bin')}</string></dict>
|
|
69
|
+
</dict>
|
|
70
|
+
</plist>
|
|
71
|
+
`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const launchctl = (...args) => { try { execFileSync('launchctl', args, { stdio: 'ignore' }); return true; } catch { return false; } };
|
|
75
|
+
|
|
76
|
+
// ---- /agentpen inside Claude Code -------------------------------------------
|
|
77
|
+
// A personal skill, so typing /agentpen in a session that is already running
|
|
78
|
+
// shares it. It runs `agentpen share` for that conversation and nothing else.
|
|
79
|
+
const SKILL = `---
|
|
80
|
+
name: agentpen
|
|
81
|
+
description: Share this Claude Code session with your Agentpen workspace so teammates can watch it live. "/agentpen stop" stops sharing.
|
|
82
|
+
argument-hint: "[stop | --private]"
|
|
83
|
+
disable-model-invocation: true
|
|
84
|
+
allowed-tools: Bash(agentpen share *)
|
|
85
|
+
---
|
|
86
|
+
<!-- installed by agentpen. Remove with: agentpen uninstall -->
|
|
87
|
+
The user asked to share this session with their team through Agentpen. This command has already run:
|
|
88
|
+
|
|
89
|
+
!\`agentpen share --in-claude --session \${CLAUDE_SESSION_ID} $ARGUMENTS\`
|
|
90
|
+
|
|
91
|
+
Reply with one or two short lines that pass on what it printed: the link if there is one, or the problem and the fix it suggests. Do not run anything else.
|
|
92
|
+
`;
|
|
93
|
+
const skillFile = () => path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'skills', 'agentpen', 'SKILL.md');
|
|
94
|
+
|
|
95
|
+
/** Adds /agentpen to Claude Code. Returns true if it is in place. Does nothing where Claude Code has never run. */
|
|
96
|
+
export function installSkill() {
|
|
97
|
+
try {
|
|
98
|
+
const f = skillFile();
|
|
99
|
+
if (!fs.existsSync(path.dirname(path.dirname(path.dirname(f))))) return false;
|
|
100
|
+
if (fs.existsSync(f) && !fs.readFileSync(f, 'utf8').includes('installed by agentpen')) return false; // someone else's skill of the same name: leave it
|
|
101
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
102
|
+
fs.writeFileSync(f, SKILL);
|
|
103
|
+
return true;
|
|
104
|
+
} catch { return false; }
|
|
105
|
+
}
|
|
106
|
+
export function removeSkill() {
|
|
107
|
+
try {
|
|
108
|
+
const f = skillFile();
|
|
109
|
+
if (!fs.readFileSync(f, 'utf8').includes('installed by agentpen')) return false;
|
|
110
|
+
fs.rmSync(path.dirname(f), { recursive: true, force: true });
|
|
111
|
+
return true;
|
|
112
|
+
} catch { return false; }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function install({ workspace, shellOnly }, ui) {
|
|
116
|
+
const files = rcFiles();
|
|
117
|
+
for (const f of files) writeHook(f);
|
|
118
|
+
|
|
119
|
+
const skill = installSkill();
|
|
120
|
+
let codex = 'skipped';
|
|
121
|
+
if (!shellOnly && process.platform === 'darwin') {
|
|
122
|
+
const p = plistPath();
|
|
123
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
124
|
+
fs.writeFileSync(p, launchAgent());
|
|
125
|
+
const target = `gui/${process.getuid()}`;
|
|
126
|
+
launchctl('bootout', `${target}/${LABEL}`);
|
|
127
|
+
codex = launchctl('bootstrap', target, p) ? 'on' : 'failed';
|
|
128
|
+
} else if (!shellOnly) codex = 'manual';
|
|
129
|
+
|
|
130
|
+
ui.say();
|
|
131
|
+
ui.say(` ${ui.bold('Automatic sharing is set up')} ${ui.dim(`for ${workspace}`)}`);
|
|
132
|
+
ui.say();
|
|
133
|
+
ui.say(` ${ui.accent('claude')} Typing plain ${ui.bold('claude')} in a new terminal now starts a shared session.`);
|
|
134
|
+
ui.say(ui.dim(` Hook added to ${files.map((f) => f.replace(os.homedir(), '~')).join(' and ')}. Open a new terminal for it to take effect.`));
|
|
135
|
+
ui.say(ui.dim(' One-off commands (claude -p, claude mcp, claude update) are never shared.'));
|
|
136
|
+
if (skill) {
|
|
137
|
+
ui.say();
|
|
138
|
+
ui.say(` ${ui.accent('/agentpen')} In a Claude Code session that is already running, type ${ui.bold('/agentpen')} to share it.`);
|
|
139
|
+
ui.say(ui.dim(' Teammates can watch that one and chat. They cannot type into it.'));
|
|
140
|
+
}
|
|
141
|
+
ui.say();
|
|
142
|
+
if (codex === 'on') {
|
|
143
|
+
ui.say(` ${ui.accent('Codex app')} A background helper shares coding conversations while they are active.`);
|
|
144
|
+
ui.say(ui.dim(' Only conversations inside a git repository. It starts again at login.'));
|
|
145
|
+
} else if (codex === 'failed') {
|
|
146
|
+
ui.say(` ${ui.accent('Codex app')} Could not start the background helper. Run ${ui.bold('agentpen watch')} in a terminal instead.`);
|
|
147
|
+
} else if (codex === 'manual') {
|
|
148
|
+
ui.say(` ${ui.accent('Codex app')} The background helper is set up on macOS only. Here, keep ${ui.bold('agentpen watch')} running.`);
|
|
149
|
+
}
|
|
150
|
+
ui.say();
|
|
151
|
+
ui.say(ui.dim(' Everyone in the workspace can see shared sessions.'));
|
|
152
|
+
ui.say(ui.dim(' agentpen pause stop sharing new sessions for now'));
|
|
153
|
+
ui.say(ui.dim(' AGENTPEN_OFF=1 claude keep one session private'));
|
|
154
|
+
ui.say(ui.dim(' agentpen uninstall undo all of this'));
|
|
155
|
+
ui.say();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function uninstall(ui) {
|
|
159
|
+
const touched = [];
|
|
160
|
+
for (const f of rcFiles()) {
|
|
161
|
+
if (!fs.existsSync(f)) continue;
|
|
162
|
+
const before = fs.readFileSync(f, 'utf8');
|
|
163
|
+
const after = strip(before);
|
|
164
|
+
if (after !== before) { fs.writeFileSync(f, after); touched.push(f.replace(os.homedir(), '~')); }
|
|
165
|
+
}
|
|
166
|
+
if (process.platform === 'darwin') {
|
|
167
|
+
launchctl('bootout', `gui/${process.getuid()}/${LABEL}`);
|
|
168
|
+
fs.rmSync(plistPath(), { force: true });
|
|
169
|
+
}
|
|
170
|
+
if (removeSkill()) ui.say('Removed /agentpen from Claude Code.');
|
|
171
|
+
ui.say(touched.length ? `Removed the claude hook from ${touched.join(' and ')}. Open a new terminal for it to take effect.` : 'No claude hook was installed.');
|
|
172
|
+
if (process.platform === 'darwin') ui.say('Stopped the Codex app helper.');
|
|
173
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// node-pty's prebuilt spawn-helper sometimes loses its executable bit when npm unpacks it.
|
|
2
|
+
// Find node-pty wherever npm placed it (nested or hoisted) and restore the bit. Never fails the install.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
|
|
7
|
+
try {
|
|
8
|
+
const dir = path.dirname(createRequire(import.meta.url).resolve('node-pty/package.json'));
|
|
9
|
+
const prebuilds = path.join(dir, 'prebuilds');
|
|
10
|
+
for (const d of fs.readdirSync(prebuilds)) {
|
|
11
|
+
const helper = path.join(prebuilds, d, 'spawn-helper');
|
|
12
|
+
if (fs.existsSync(helper)) fs.chmodSync(helper, 0o755);
|
|
13
|
+
}
|
|
14
|
+
} catch {}
|
package/cli/redact.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Masks .env values in everything that leaves the machine. The local screen
|
|
2
|
+
// stays raw. Literal byte matching (an idea borrowed from manycode, MIT): a
|
|
3
|
+
// seatbelt against a stray `cat .env`, not a vault.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const BORING = new Set(['true', 'false', 'null', 'undefined', 'localhost', 'development', 'production', 'staging', 'test', 'debug', 'info', 'warn', 'error', 'example', 'changeme', 'change-me', 'password', 'secret', 'default']);
|
|
8
|
+
const MASK = Buffer.from('••••••').toString('latin1');
|
|
9
|
+
|
|
10
|
+
export function collectSecrets(dir) {
|
|
11
|
+
const values = new Set();
|
|
12
|
+
let files = [];
|
|
13
|
+
try { files = fs.readdirSync(dir).filter((f) => f === '.env' || f.startsWith('.env.')); } catch {}
|
|
14
|
+
for (const f of files) {
|
|
15
|
+
let text;
|
|
16
|
+
try { text = fs.readFileSync(path.join(dir, f), 'utf8'); } catch { continue; }
|
|
17
|
+
for (let line of text.split('\n')) {
|
|
18
|
+
line = line.trim().replace(/^export\s+/, '');
|
|
19
|
+
const eq = line.indexOf('=');
|
|
20
|
+
if (eq <= 0 || line.startsWith('#')) continue;
|
|
21
|
+
let v = line.slice(eq + 1).trim();
|
|
22
|
+
const quoted = /^(["'])(.*)\1$/.exec(v);
|
|
23
|
+
if (quoted) v = quoted[2];
|
|
24
|
+
if (v.length >= 8 && !BORING.has(v.toLowerCase())) values.add(v);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return [...values];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Streaming: bytes that could be the start of a secret are held until the next
|
|
31
|
+
// chunk (or a 25ms timer) settles it. latin1 keeps the splice byte-exact.
|
|
32
|
+
export function makeRedactor(values, emit) {
|
|
33
|
+
if (!values.length) return { write: emit, flush() {} };
|
|
34
|
+
const needles = values.map((v) => Buffer.from(v).toString('latin1')).sort((a, b) => b.length - a.length);
|
|
35
|
+
const mask = (t) => { for (const n of needles) t = t.split(n).join(MASK); return t; };
|
|
36
|
+
let carry = '';
|
|
37
|
+
let timer = null;
|
|
38
|
+
const flush = () => {
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
timer = null;
|
|
41
|
+
if (!carry) return;
|
|
42
|
+
const out = carry;
|
|
43
|
+
carry = '';
|
|
44
|
+
emit(Buffer.from(out, 'latin1'));
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
write(buf) {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
const text = mask(carry + buf.toString('latin1'));
|
|
50
|
+
let hold = 0;
|
|
51
|
+
for (const n of needles) {
|
|
52
|
+
for (let k = Math.min(text.length, n.length - 1); k > hold; k--) {
|
|
53
|
+
if (text.endsWith(n.slice(0, k))) { hold = k; break; }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
carry = hold ? text.slice(-hold) : '';
|
|
57
|
+
const out = hold ? text.slice(0, -hold) : text;
|
|
58
|
+
if (out) emit(Buffer.from(out, 'latin1'));
|
|
59
|
+
if (carry) timer = setTimeout(flush, 25);
|
|
60
|
+
},
|
|
61
|
+
flush,
|
|
62
|
+
};
|
|
63
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentpen-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "The team room for your coding agents - share live Claude Code / Codex sessions with your whole company",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://agentpen.app",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"claude-code",
|
|
9
|
+
"codex",
|
|
10
|
+
"ai-agents",
|
|
11
|
+
"coding-agent",
|
|
12
|
+
"terminal-sharing",
|
|
13
|
+
"collaboration",
|
|
14
|
+
"cli"
|
|
15
|
+
],
|
|
16
|
+
"type": "module",
|
|
17
|
+
"bin": {
|
|
18
|
+
"agentpen": "cli/agentpen.js"
|
|
19
|
+
},
|
|
20
|
+
"scripts": {
|
|
21
|
+
"start": "node server/index.js",
|
|
22
|
+
"dev": "AGENTPEN_DEV=1 node --watch server/index.js",
|
|
23
|
+
"test": "node --test test/*.test.js",
|
|
24
|
+
"postinstall": "node cli/postinstall.js"
|
|
25
|
+
},
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=22.13"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@anthropic-ai/sdk": "^1.12.0",
|
|
31
|
+
"@xterm/addon-fit": "^0.11.0",
|
|
32
|
+
"@xterm/xterm": "^6.0.0",
|
|
33
|
+
"ws": "^8.18.0"
|
|
34
|
+
},
|
|
35
|
+
"optionalDependencies": {
|
|
36
|
+
"node-pty": "^1.0.0"
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"cli/",
|
|
40
|
+
"server/",
|
|
41
|
+
"web/",
|
|
42
|
+
"README.md",
|
|
43
|
+
"LICENSE"
|
|
44
|
+
]
|
|
45
|
+
}
|