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.
- package/LICENSE +27 -0
- package/README.md +279 -2
- package/cli/agentpen.js +442 -0
- package/cli/codex-app.js +338 -0
- package/cli/handoff.js +216 -0
- package/cli/install.js +127 -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 +619 -0
- package/server/index.js +744 -0
- package/server/notify.js +91 -0
- package/server/search.js +34 -0
- package/web/app.js +515 -0
- package/web/favicon.svg +1 -0
- package/web/index.html +16 -0
- package/web/session.js +447 -0
- package/web/styles.css +260 -0
- package/web/team-page.png +0 -0
package/server/index.js
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
1
|
+
// Agentpen server: HTTP API + static web app + WebSocket hub in one process.
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { WebSocketServer } from 'ws';
|
|
7
|
+
import { pipeline } from 'node:stream/promises';
|
|
8
|
+
import { q, id as newId, secret, sha, now, audit, PLANS, seatsUsed, hasSeat, RECORDINGS_DIR, HANDOFF_DIR } from './db.js';
|
|
9
|
+
import { attachHost, attachViewer, attachFeed, getLive, liveList, liveForUser, dropUser, newGuestLink } from './hub.js';
|
|
10
|
+
import { attachUser, setLiveProvider, prefsOf, savePrefs, dropUserStreams, notify, KINDS } from './notify.js';
|
|
11
|
+
|
|
12
|
+
import { AGENTS, AgentError, seal, claudeConnected, connectedAgents, agentConfig, sessionContext, summarize } from './agents.js';
|
|
13
|
+
import { indexSession, search } from './search.js';
|
|
14
|
+
|
|
15
|
+
setLiveProvider(liveForUser);
|
|
16
|
+
|
|
17
|
+
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
18
|
+
const PORT = Number(process.env.PORT) || 4400;
|
|
19
|
+
const BASE_URL = (process.env.AGENTPEN_URL || `http://localhost:${PORT}`).replace(/\/$/, '');
|
|
20
|
+
process.env.AGENTPEN_URL = BASE_URL;
|
|
21
|
+
const SECURE = BASE_URL.startsWith('https://');
|
|
22
|
+
const IS_LOCAL = /^http:\/\/(localhost|127\.0\.0\.1)(:|$)/.test(BASE_URL);
|
|
23
|
+
// Without a mailer, sign-in links can only be shown on screen. That is fine on
|
|
24
|
+
// a laptop and a takeover hole anywhere else, so it is limited to local use.
|
|
25
|
+
const DEV_LINKS = !process.env.RESEND_API_KEY && (IS_LOCAL || process.env.AGENTPEN_DEV === '1');
|
|
26
|
+
const MAIL_FROM = process.env.AGENTPEN_MAIL_FROM || 'Agentpen <login@agentpen.app>';
|
|
27
|
+
|
|
28
|
+
const DAY = 86_400_000;
|
|
29
|
+
const PUBLIC_DOMAINS = new Set(['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'yahoo.com', 'icloud.com', 'me.com', 'proton.me', 'protonmail.com', 'aol.com', 'hey.com', 'fastmail.com', 'gmx.com', 'mail.com', 'qq.com', '163.com', 'yandex.com', 'duck.com', 'pm.me']);
|
|
30
|
+
const RANK = { member: 1, admin: 2, owner: 3 };
|
|
31
|
+
|
|
32
|
+
class HttpError extends Error {
|
|
33
|
+
constructor(status, message) { super(message); this.status = status; }
|
|
34
|
+
}
|
|
35
|
+
const bad = (status, message) => { throw new HttpError(status, message); };
|
|
36
|
+
|
|
37
|
+
// ---- small helpers ---------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
const hits = new Map();
|
|
40
|
+
function rateLimit(key, max, windowMs) {
|
|
41
|
+
const t = now();
|
|
42
|
+
const h = (hits.get(key) || []).filter((x) => t - x < windowMs);
|
|
43
|
+
h.push(t);
|
|
44
|
+
hits.set(key, h);
|
|
45
|
+
if (h.length > max) bad(429, 'Too many attempts. Try again in a minute.');
|
|
46
|
+
}
|
|
47
|
+
setInterval(() => { const t = now(); for (const [k, h] of hits) if (t - h.at(-1) > 3_600_000) hits.delete(k); }, 600_000).unref();
|
|
48
|
+
|
|
49
|
+
// X-Forwarded-For is only believed behind a proxy we were told about; otherwise anyone could dodge rate limits.
|
|
50
|
+
const TRUST_PROXY = process.env.AGENTPEN_TRUST_PROXY === '1';
|
|
51
|
+
const AUTH_RATE = Number(process.env.AGENTPEN_AUTH_RATE) || 10;
|
|
52
|
+
const ip = (req) => (TRUST_PROXY && (req.headers['x-forwarded-for'] || '').split(',')[0].trim()) || req.socket.remoteAddress;
|
|
53
|
+
const cookies = (req) => Object.fromEntries((req.headers.cookie || '').split(';').map((c) => c.trim().split('=')).filter((p) => p[0]).map(([k, ...v]) => [k, decodeURIComponent(v.join('='))]));
|
|
54
|
+
const emailOk = (e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e) && e.length <= 200;
|
|
55
|
+
const normEmail = (e) => String(e || '').trim().toLowerCase();
|
|
56
|
+
const domainOf = (email) => email.split('@')[1];
|
|
57
|
+
const clip = (s, n) => String(s ?? '').replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, n);
|
|
58
|
+
const nameFromEmail = (email) => email.split('@')[0].split(/[._+-]/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join(' ').slice(0, 40) || 'Someone';
|
|
59
|
+
|
|
60
|
+
async function body(req) {
|
|
61
|
+
const chunks = [];
|
|
62
|
+
let n = 0;
|
|
63
|
+
for await (const c of req) {
|
|
64
|
+
n += c.length;
|
|
65
|
+
if (n > 100_000) bad(413, 'Request too large.');
|
|
66
|
+
chunks.push(c);
|
|
67
|
+
}
|
|
68
|
+
if (!n) return {};
|
|
69
|
+
try { return JSON.parse(Buffer.concat(chunks).toString()) || {}; } catch { bad(400, 'Invalid JSON.'); }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function sendMail(to, subject, text) {
|
|
73
|
+
if (!process.env.RESEND_API_KEY) {
|
|
74
|
+
console.log(`[mail -> ${to}] ${subject}\n${text}\n`);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const r = await fetch('https://api.resend.com/emails', {
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: { authorization: `Bearer ${process.env.RESEND_API_KEY}`, 'content-type': 'application/json' },
|
|
80
|
+
body: JSON.stringify({ from: MAIL_FROM, to, subject, text }),
|
|
81
|
+
});
|
|
82
|
+
if (!r.ok) console.error(`mail to ${to} failed: ${r.status} ${await r.text()}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function issueToken(kind, { userId = null, email = null, label = null, ttl }) {
|
|
86
|
+
const token = secret();
|
|
87
|
+
q.run(`INSERT INTO tokens (hash, kind, user_id, email, label, expires_at, created_at) VALUES (?,?,?,?,?,?,?)`, sha(token), kind, userId, email, label, now() + ttl, now());
|
|
88
|
+
return token;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function userByToken(token, kind) {
|
|
92
|
+
if (!token) return null;
|
|
93
|
+
return q.get(`SELECT u.* FROM tokens t JOIN users u ON u.id=t.user_id WHERE t.hash=? AND t.kind=? AND t.expires_at>?`, sha(token), kind, now()) || null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function auth(req) {
|
|
97
|
+
const h = req.headers.authorization;
|
|
98
|
+
if (h?.startsWith('Bearer ')) return userByToken(h.slice(7), 'cli');
|
|
99
|
+
return userByToken(cookies(req).bp_session, 'web');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const sameOrigin = (req) => {
|
|
103
|
+
const o = req.headers.origin;
|
|
104
|
+
if (!o) return true; // non-browser client
|
|
105
|
+
try { return new URL(o).host === req.headers.host; } catch { return false; }
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
function member(user, slug, minRole = 'member') {
|
|
109
|
+
const row = q.get(`SELECT w.*, m.role FROM workspaces w JOIN memberships m ON m.workspace_id=w.id WHERE w.slug=? AND m.user_id=?`, slug, user.id);
|
|
110
|
+
if (!row) bad(404, 'Workspace not found.');
|
|
111
|
+
if (RANK[row.role] < RANK[minRole]) bad(403, 'You need to be a workspace admin to do that.');
|
|
112
|
+
return row;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function addMember(ws, user, role, how) {
|
|
116
|
+
if (q.get(`SELECT 1 FROM memberships WHERE workspace_id=? AND user_id=?`, ws.id, user.id)) return;
|
|
117
|
+
if (!hasSeat(ws)) bad(402, `${ws.name} has used all ${PLANS[ws.plan].seats} seats on the ${PLANS[ws.plan].label} plan. Ask an admin to upgrade.`);
|
|
118
|
+
q.run(`INSERT INTO memberships (workspace_id, user_id, role, created_at) VALUES (?,?,?,?)`, ws.id, user.id, role, now());
|
|
119
|
+
audit(ws.id, 'member.join', { actor: user, detail: how });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function slugFor(name) {
|
|
123
|
+
const base = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32) || 'team';
|
|
124
|
+
let slug = base;
|
|
125
|
+
while (q.get(`SELECT 1 FROM workspaces WHERE slug=?`, slug)) slug = `${base}-${newId(4).toLowerCase()}`;
|
|
126
|
+
return slug;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const publicWs = (w) => ({
|
|
130
|
+
id: w.id, slug: w.slug, name: w.name, role: w.role, plan: w.plan, planLabel: (PLANS[w.plan] || PLANS.free).label,
|
|
131
|
+
seats: (PLANS[w.plan] || PLANS.free).seats === Infinity ? null : (PLANS[w.plan] || PLANS.free).seats,
|
|
132
|
+
seatsUsed: seatsUsed(w.id), domain: w.domain, domainJoin: !!w.domain_join, defaultAccess: w.default_access, handoff: !!w.handoff, claude: claudeConnected(w),
|
|
133
|
+
// which agents people can invite; for Grok and Muse also the model name, never a key
|
|
134
|
+
agents: Object.fromEntries(Object.values(AGENTS).map((a) => [a.id, { name: a.name, connected: a.connected(w), model: a.needsModel ? agentConfig(w)[a.id]?.model || '' : undefined }])),
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// ---- API routes ------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
const routes = [];
|
|
140
|
+
const route = (method, pattern, fn, { open = false, raw = false } = {}) => {
|
|
141
|
+
const keys = [];
|
|
142
|
+
const re = new RegExp('^' + pattern.replace(/:(\w+)/g, (_, k) => { keys.push(k); return '([^/]+)'; }) + '$');
|
|
143
|
+
routes.push({ method, re, keys, fn, open, raw });
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
route('POST', '/api/auth/start', async ({ req, data }) => {
|
|
147
|
+
const email = normEmail(data.email);
|
|
148
|
+
if (!emailOk(email)) bad(400, 'Enter a valid email address.');
|
|
149
|
+
rateLimit(`auth:${ip(req)}`, AUTH_RATE, 600_000);
|
|
150
|
+
rateLimit(`auth:${email}`, 5, 600_000);
|
|
151
|
+
const token = issueToken('login', { email, ttl: 15 * 60_000 });
|
|
152
|
+
const next = typeof data.next === 'string' && /^\/[^/\\]/.test(data.next) ? data.next : '';
|
|
153
|
+
const link = `${BASE_URL}/auth/verify?token=${token}${next ? `&next=${encodeURIComponent(next)}` : ''}`;
|
|
154
|
+
await sendMail(email, 'Your Agentpen sign-in link', `Click to sign in to Agentpen:\n\n${link}\n\nThis link works once and expires in 15 minutes. If you did not ask for it, ignore this email.`);
|
|
155
|
+
return { ok: true, devLink: DEV_LINKS ? link : undefined };
|
|
156
|
+
}, { open: true });
|
|
157
|
+
|
|
158
|
+
route('POST', '/api/auth/verify', async ({ req, res, data }) => {
|
|
159
|
+
rateLimit(`verify:${ip(req)}`, AUTH_RATE * 2, 600_000);
|
|
160
|
+
const hash = sha(String(data.token || ''));
|
|
161
|
+
const t = q.get(`SELECT * FROM tokens WHERE hash=? AND kind='login' AND expires_at>?`, hash, now());
|
|
162
|
+
if (!t) bad(400, 'This sign-in link has expired or was already used. Request a new one.');
|
|
163
|
+
q.run(`DELETE FROM tokens WHERE hash=?`, hash);
|
|
164
|
+
let user = q.get(`SELECT * FROM users WHERE email=?`, t.email);
|
|
165
|
+
let isNew = false;
|
|
166
|
+
if (!user) {
|
|
167
|
+
user = { id: newId(), email: t.email, name: nameFromEmail(t.email), created_at: now() };
|
|
168
|
+
q.run(`INSERT INTO users (id, email, name, created_at) VALUES (?,?,?,?)`, user.id, user.email, user.name, user.created_at);
|
|
169
|
+
isNew = true;
|
|
170
|
+
}
|
|
171
|
+
const session = issueToken('web', { userId: user.id, ttl: 30 * DAY });
|
|
172
|
+
res.setHeader('set-cookie', `bp_session=${session}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${30 * 86400}${SECURE ? '; Secure' : ''}`);
|
|
173
|
+
return { ok: true, isNew };
|
|
174
|
+
}, { open: true });
|
|
175
|
+
|
|
176
|
+
route('POST', '/api/auth/logout', async ({ req, res }) => {
|
|
177
|
+
const c = cookies(req).bp_session;
|
|
178
|
+
if (c) q.run(`DELETE FROM tokens WHERE hash=?`, sha(c));
|
|
179
|
+
res.setHeader('set-cookie', `bp_session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
|
|
180
|
+
return { ok: true };
|
|
181
|
+
}, { open: true });
|
|
182
|
+
|
|
183
|
+
route('GET', '/api/me', async ({ user }) => {
|
|
184
|
+
if (!user) return { user: null };
|
|
185
|
+
const workspaces = q.all(`SELECT w.*, m.role FROM workspaces w JOIN memberships m ON m.workspace_id=w.id WHERE m.user_id=? ORDER BY m.created_at`, user.id).map(publicWs);
|
|
186
|
+
const domain = domainOf(user.email);
|
|
187
|
+
const suggested = PUBLIC_DOMAINS.has(domain) ? [] : q.all(
|
|
188
|
+
`SELECT w.slug, w.name, (SELECT COUNT(*) FROM memberships WHERE workspace_id=w.id) members FROM workspaces w
|
|
189
|
+
WHERE w.domain=? AND w.domain_join=1 AND NOT EXISTS (SELECT 1 FROM memberships WHERE workspace_id=w.id AND user_id=?)`, domain, user.id);
|
|
190
|
+
return { user: { id: user.id, email: user.email, name: user.name }, prefs: prefsOf(user.id), workspaces, suggested, upgradeUrl: process.env.AGENTPEN_UPGRADE_URL || null };
|
|
191
|
+
}, { open: true });
|
|
192
|
+
|
|
193
|
+
route('PATCH', '/api/me', async ({ user, data }) => {
|
|
194
|
+
if (data.name !== undefined) {
|
|
195
|
+
const name = clip(data.name, 40);
|
|
196
|
+
if (!name) bad(400, 'Name cannot be empty.');
|
|
197
|
+
q.run(`UPDATE users SET name=? WHERE id=?`, name, user.id);
|
|
198
|
+
}
|
|
199
|
+
if (data.prefs !== undefined) {
|
|
200
|
+
if (!data.prefs || Object.keys(data.prefs).some((k) => !(k in KINDS) || typeof data.prefs[k] !== 'boolean')) bad(400, 'Unknown notification setting.');
|
|
201
|
+
savePrefs(user.id, data.prefs);
|
|
202
|
+
}
|
|
203
|
+
return { ok: true, prefs: prefsOf(user.id) };
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
// CLI login: the terminal shows a short code, the browser approves it.
|
|
207
|
+
route('POST', '/api/device/start', async ({ req, data }) => {
|
|
208
|
+
rateLimit(`device:${ip(req)}`, 20, 600_000);
|
|
209
|
+
const device = secret();
|
|
210
|
+
const raw = newId(8).toUpperCase().replace(/[^A-Z0-9]/g, 'X');
|
|
211
|
+
const userCode = `${raw.slice(0, 4)}-${raw.slice(4)}`;
|
|
212
|
+
q.run(`INSERT INTO device_codes (device_hash, user_code, label, expires_at) VALUES (?,?,?,?)`, sha(device), userCode, clip(data.label, 60) || 'CLI', now() + 10 * 60_000);
|
|
213
|
+
return { device_code: device, user_code: userCode, verify_url: `${BASE_URL}/activate?code=${userCode}`, interval: 2 };
|
|
214
|
+
}, { open: true });
|
|
215
|
+
|
|
216
|
+
route('POST', '/api/device/approve', async ({ user, req, data }) => {
|
|
217
|
+
rateLimit(`approve:${ip(req)}`, 20, 600_000);
|
|
218
|
+
const code = String(data.user_code || '').trim().toUpperCase();
|
|
219
|
+
const d = q.get(`SELECT * FROM device_codes WHERE user_code=? AND expires_at>? AND user_id IS NULL`, code, now());
|
|
220
|
+
if (!d) bad(404, 'That code is not valid or has expired. Run the command again for a fresh one.');
|
|
221
|
+
q.run(`UPDATE device_codes SET user_id=? WHERE device_hash=?`, user.id, d.device_hash);
|
|
222
|
+
return { ok: true, label: d.label };
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
route('POST', '/api/device/poll', async ({ data }) => {
|
|
226
|
+
const hash = sha(String(data.device_code || ''));
|
|
227
|
+
const d = q.get(`SELECT * FROM device_codes WHERE device_hash=?`, hash);
|
|
228
|
+
if (!d || d.expires_at < now()) { q.run(`DELETE FROM device_codes WHERE device_hash=?`, hash); bad(410, 'Login request expired.'); }
|
|
229
|
+
if (!d.user_id) return { pending: true };
|
|
230
|
+
q.run(`DELETE FROM device_codes WHERE device_hash=?`, hash);
|
|
231
|
+
const u = q.get(`SELECT * FROM users WHERE id=?`, d.user_id);
|
|
232
|
+
return { token: issueToken('cli', { userId: u.id, label: d.label, ttl: 365 * DAY }), user: { name: u.name, email: u.email } };
|
|
233
|
+
}, { open: true });
|
|
234
|
+
|
|
235
|
+
route('POST', '/api/workspaces', async ({ user, data }) => {
|
|
236
|
+
const name = clip(data.name, 48);
|
|
237
|
+
if (name.length < 2) bad(400, 'Give your workspace a name.');
|
|
238
|
+
if (q.get(`SELECT COUNT(*) n FROM memberships WHERE user_id=? AND role='owner'`, user.id).n >= 10) bad(400, 'You already own 10 workspaces.');
|
|
239
|
+
const domain = PUBLIC_DOMAINS.has(domainOf(user.email)) ? null : domainOf(user.email);
|
|
240
|
+
const ws = { id: newId(), slug: slugFor(name), name };
|
|
241
|
+
q.run(`INSERT INTO workspaces (id, slug, name, domain, domain_join, invite_code, created_at) VALUES (?,?,?,?,?,?,?)`, ws.id, ws.slug, name, domain, domain ? 1 : 0, newId(16), now());
|
|
242
|
+
q.run(`INSERT INTO memberships (workspace_id, user_id, role, created_at) VALUES (?,?,?,?)`, ws.id, user.id, 'owner', now());
|
|
243
|
+
audit(ws.id, 'workspace.create', { actor: user, detail: name });
|
|
244
|
+
return { slug: ws.slug };
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
route('GET', '/api/workspaces/:slug', async ({ user, params }) => {
|
|
248
|
+
const ws = member(user, params.slug);
|
|
249
|
+
const admin = RANK[ws.role] >= RANK.admin;
|
|
250
|
+
return {
|
|
251
|
+
workspace: { ...publicWs(ws), slackWebhook: admin ? !!ws.slack_webhook : undefined, inviteLink: admin ? `${BASE_URL}/join/${ws.invite_code}` : undefined },
|
|
252
|
+
members: q.all(`SELECT u.id, u.name, u.email, m.role FROM memberships m JOIN users u ON u.id=m.user_id WHERE m.workspace_id=? ORDER BY m.created_at`, ws.id),
|
|
253
|
+
invites: admin ? q.all(`SELECT email, role, expires_at FROM invites WHERE workspace_id=? AND expires_at>? ORDER BY created_at DESC`, ws.id, now()) : [],
|
|
254
|
+
live: liveList(ws.id, user.id),
|
|
255
|
+
recent: q.all(`SELECT s.id, s.title, s.agent, s.kind, s.project, s.branch, s.started_at, s.ended_at, s.has_recording, s.handoff_at, s.end_reason, s.access, u.name host_name
|
|
256
|
+
FROM sessions s JOIN users u ON u.id=s.host_id WHERE s.workspace_id=? AND s.status='ended' AND (s.access!='private' OR s.host_id=?) ORDER BY s.started_at DESC LIMIT 30`, ws.id, user.id),
|
|
257
|
+
};
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
route('PATCH', '/api/workspaces/:slug', async ({ user, params, data }) => {
|
|
261
|
+
const ws = member(user, params.slug, 'admin');
|
|
262
|
+
if (data.name !== undefined) {
|
|
263
|
+
const name = clip(data.name, 48);
|
|
264
|
+
if (name.length < 2) bad(400, 'Give your workspace a name.');
|
|
265
|
+
q.run(`UPDATE workspaces SET name=? WHERE id=?`, name, ws.id);
|
|
266
|
+
}
|
|
267
|
+
if (data.domainJoin !== undefined) {
|
|
268
|
+
if (!ws.domain) bad(400, 'Domain sign-up needs a workspace created from a company email address.');
|
|
269
|
+
q.run(`UPDATE workspaces SET domain_join=? WHERE id=?`, data.domainJoin ? 1 : 0, ws.id);
|
|
270
|
+
}
|
|
271
|
+
if (data.defaultAccess !== undefined) {
|
|
272
|
+
if (!['control', 'view', 'private'].includes(data.defaultAccess)) bad(400, 'Invalid access level.');
|
|
273
|
+
q.run(`UPDATE workspaces SET default_access=? WHERE id=?`, data.defaultAccess, ws.id);
|
|
274
|
+
}
|
|
275
|
+
if (data.anthropicKey !== undefined) {
|
|
276
|
+
const key = String(data.anthropicKey || '').trim();
|
|
277
|
+
if (key && (key.length < 20 || key.length > 400 || /\s/.test(key))) bad(400, 'That does not look like an Anthropic API key.');
|
|
278
|
+
q.run(`UPDATE workspaces SET anthropic_key=? WHERE id=?`, key ? seal(key) : null, ws.id);
|
|
279
|
+
data = { ...data, anthropicKey: key ? 'set' : 'removed' }; // never let the key itself reach the audit trail
|
|
280
|
+
}
|
|
281
|
+
if (data.agent !== undefined) {
|
|
282
|
+
// { id: 'grok' | 'muse', key, model }: an empty key disconnects it
|
|
283
|
+
const agent = AGENTS[data.agent?.id];
|
|
284
|
+
if (!agent?.needsModel) bad(400, 'Unknown agent.');
|
|
285
|
+
const key = String(data.agent.key || '').trim();
|
|
286
|
+
const model = String(data.agent.model || '').trim();
|
|
287
|
+
const cfg = agentConfig(q.get(`SELECT agent_config FROM workspaces WHERE id=?`, ws.id));
|
|
288
|
+
if (!key && !model) delete cfg[agent.id];
|
|
289
|
+
else {
|
|
290
|
+
if (key && (key.length < 12 || key.length > 400 || /\s/.test(key))) bad(400, `That does not look like a ${agent.name} API key.`);
|
|
291
|
+
if (!/^[\w.:\/-]{2,80}$/.test(model)) bad(400, `Enter the ${agent.name} model to use, exactly as its provider names it.`);
|
|
292
|
+
if (!key && !cfg[agent.id]?.key) bad(400, `Paste a ${agent.name} API key.`);
|
|
293
|
+
cfg[agent.id] = { key: key ? seal(key) : cfg[agent.id].key, model }; // leaving the key blank keeps the saved one
|
|
294
|
+
}
|
|
295
|
+
q.run(`UPDATE workspaces SET agent_config=? WHERE id=?`, JSON.stringify(cfg), ws.id);
|
|
296
|
+
data = { ...data, agent: `${agent.id} ${key || model ? 'updated' : 'removed'}` };
|
|
297
|
+
}
|
|
298
|
+
if (data.handoff !== undefined) q.run(`UPDATE workspaces SET handoff=? WHERE id=?`, data.handoff ? 1 : 0, ws.id);
|
|
299
|
+
if (data.slackWebhook !== undefined) {
|
|
300
|
+
const url = String(data.slackWebhook || '').trim();
|
|
301
|
+
if (url && !/^https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/_-]+$/.test(url)) bad(400, 'That is not a Slack incoming-webhook URL (https://hooks.slack.com/services/...).');
|
|
302
|
+
q.run(`UPDATE workspaces SET slack_webhook=? WHERE id=?`, url || null, ws.id);
|
|
303
|
+
}
|
|
304
|
+
audit(ws.id, 'workspace.settings', { actor: user, detail: Object.keys(data).join(', ') });
|
|
305
|
+
return { ok: true };
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
route('POST', '/api/workspaces/:slug/join', async ({ user, params }) => {
|
|
309
|
+
const ws = q.get(`SELECT * FROM workspaces WHERE slug=?`, params.slug);
|
|
310
|
+
if (!ws || !ws.domain_join || ws.domain !== domainOf(user.email)) bad(404, 'Workspace not found.');
|
|
311
|
+
addMember(ws, user, 'member', `@${ws.domain} sign-up`);
|
|
312
|
+
return { slug: ws.slug };
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
route('POST', '/api/workspaces/:slug/invites', async ({ user, params, data, req }) => {
|
|
316
|
+
const ws = member(user, params.slug, 'admin');
|
|
317
|
+
rateLimit(`invite:${user.id}`, 60, 3_600_000);
|
|
318
|
+
const role = data.role === 'admin' ? 'admin' : 'member';
|
|
319
|
+
const emails = [...new Set((Array.isArray(data.emails) ? data.emails : String(data.emails || '').split(/[\s,;]+/)).map(normEmail).filter(Boolean))];
|
|
320
|
+
if (!emails.length) bad(400, 'Add at least one email address.');
|
|
321
|
+
if (emails.length > 50) bad(400, 'Invite up to 50 people at a time.');
|
|
322
|
+
const invalid = emails.filter((e) => !emailOk(e));
|
|
323
|
+
if (invalid.length) bad(400, `Not a valid email: ${invalid[0]}`);
|
|
324
|
+
const links = [];
|
|
325
|
+
for (const email of emails) {
|
|
326
|
+
if (q.get(`SELECT 1 FROM memberships m JOIN users u ON u.id=m.user_id WHERE m.workspace_id=? AND u.email=?`, ws.id, email)) continue;
|
|
327
|
+
q.run(`DELETE FROM invites WHERE workspace_id=? AND email=?`, ws.id, email);
|
|
328
|
+
const token = secret();
|
|
329
|
+
q.run(`INSERT INTO invites (token_hash, workspace_id, email, role, invited_by, expires_at, created_at) VALUES (?,?,?,?,?,?,?)`, sha(token), ws.id, email, role, user.id, now() + 14 * DAY, now());
|
|
330
|
+
const link = `${BASE_URL}/invite/${token}`;
|
|
331
|
+
links.push({ email, link: DEV_LINKS ? link : undefined });
|
|
332
|
+
await sendMail(email, `${user.name} invited you to ${ws.name} on Agentpen`, `${user.name} invited you to join ${ws.name} on Agentpen, where the team shares live coding-agent sessions.\n\nAccept the invite:\n${link}\n\nThe link expires in 14 days.`);
|
|
333
|
+
}
|
|
334
|
+
audit(ws.id, 'member.invite', { actor: user, detail: emails.join(', ') });
|
|
335
|
+
return { ok: true, sent: links };
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
route('DELETE', '/api/workspaces/:slug/invites', async ({ user, params, data }) => {
|
|
339
|
+
const ws = member(user, params.slug, 'admin');
|
|
340
|
+
q.run(`DELETE FROM invites WHERE workspace_id=? AND email=?`, ws.id, normEmail(data.email));
|
|
341
|
+
return { ok: true };
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
route('POST', '/api/workspaces/:slug/invite-link/rotate', async ({ user, params }) => {
|
|
345
|
+
const ws = member(user, params.slug, 'admin');
|
|
346
|
+
q.run(`UPDATE workspaces SET invite_code=? WHERE id=?`, newId(16), ws.id);
|
|
347
|
+
audit(ws.id, 'workspace.settings', { actor: user, detail: 'invite link reset' });
|
|
348
|
+
return { ok: true };
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
// What an invite or join link points at, shown before sign-in.
|
|
352
|
+
route('GET', '/api/invite-preview/:kind/:token', async ({ params }) => {
|
|
353
|
+
const ws = params.kind === 'join'
|
|
354
|
+
? q.get(`SELECT name FROM workspaces WHERE invite_code=?`, params.token)
|
|
355
|
+
: q.get(`SELECT w.name, i.email FROM invites i JOIN workspaces w ON w.id=i.workspace_id WHERE i.token_hash=? AND i.expires_at>?`, sha(params.token), now());
|
|
356
|
+
if (!ws) bad(404, 'This invite is no longer valid. Ask for a new one.');
|
|
357
|
+
return { workspace: ws.name, email: ws.email };
|
|
358
|
+
}, { open: true });
|
|
359
|
+
|
|
360
|
+
route('POST', '/api/invites/accept', async ({ user, data }) => {
|
|
361
|
+
if (data.code) {
|
|
362
|
+
const ws = q.get(`SELECT * FROM workspaces WHERE invite_code=?`, String(data.code));
|
|
363
|
+
if (!ws) bad(404, 'This invite link is no longer valid. Ask for a new one.');
|
|
364
|
+
addMember(ws, user, 'member', 'invite link');
|
|
365
|
+
return { slug: ws.slug };
|
|
366
|
+
}
|
|
367
|
+
const hash = sha(String(data.token || ''));
|
|
368
|
+
const inv = q.get(`SELECT * FROM invites WHERE token_hash=? AND expires_at>?`, hash, now());
|
|
369
|
+
if (!inv) bad(404, 'This invite is no longer valid. Ask for a new one.');
|
|
370
|
+
if (inv.email !== user.email) bad(403, `This invite was sent to ${inv.email}. Sign in with that address to accept it.`);
|
|
371
|
+
const ws = q.get(`SELECT * FROM workspaces WHERE id=?`, inv.workspace_id);
|
|
372
|
+
addMember(ws, user, inv.role, 'email invite');
|
|
373
|
+
q.run(`DELETE FROM invites WHERE token_hash=?`, hash);
|
|
374
|
+
return { slug: ws.slug };
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
route('PATCH', '/api/workspaces/:slug/members/:uid', async ({ user, params, data }) => {
|
|
378
|
+
const ws = member(user, params.slug, 'owner');
|
|
379
|
+
if (!['admin', 'member'].includes(data.role)) bad(400, 'Invalid role.');
|
|
380
|
+
if (params.uid === user.id) bad(400, 'You cannot change your own role.');
|
|
381
|
+
q.run(`UPDATE memberships SET role=? WHERE workspace_id=? AND user_id=? AND role!='owner'`, data.role, ws.id, params.uid);
|
|
382
|
+
audit(ws.id, 'member.role', { actor: user, detail: `${params.uid} -> ${data.role}` });
|
|
383
|
+
return { ok: true };
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
route('DELETE', '/api/workspaces/:slug/members/:uid', async ({ user, params }) => {
|
|
387
|
+
const self = params.uid === user.id;
|
|
388
|
+
const ws = member(user, params.slug, self ? 'member' : 'admin');
|
|
389
|
+
const target = q.get(`SELECT m.role, u.name FROM memberships m JOIN users u ON u.id=m.user_id WHERE m.workspace_id=? AND m.user_id=?`, ws.id, params.uid);
|
|
390
|
+
if (!target) bad(404, 'Member not found.');
|
|
391
|
+
if (target.role === 'owner') bad(400, 'The workspace owner cannot be removed.');
|
|
392
|
+
if (!self && RANK[target.role] >= RANK[ws.role]) bad(403, 'You cannot remove another admin.');
|
|
393
|
+
q.run(`DELETE FROM memberships WHERE workspace_id=? AND user_id=?`, ws.id, params.uid);
|
|
394
|
+
dropUser(ws.id, params.uid);
|
|
395
|
+
dropUserStreams(params.uid);
|
|
396
|
+
audit(ws.id, self ? 'member.leave' : 'member.remove', { actor: user, detail: target.name });
|
|
397
|
+
return { ok: true };
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
route('GET', '/api/workspaces/:slug/activity', async ({ user, params }) => {
|
|
401
|
+
const ws = member(user, params.slug);
|
|
402
|
+
return {
|
|
403
|
+
events: q.all(`SELECT e.id, e.session_id, e.actor, e.type, e.detail, e.at, s.title session_title FROM events e LEFT JOIN sessions s ON s.id=e.session_id
|
|
404
|
+
WHERE e.workspace_id=? AND (s.id IS NULL OR s.access!='private' OR s.host_id=?) ORDER BY e.id DESC LIMIT 200`, ws.id, user.id),
|
|
405
|
+
};
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
// Session access: workspace members, or anyone holding the live guest link.
|
|
409
|
+
function sessionFor(user, sessionId, guestToken) {
|
|
410
|
+
const s = q.get(`SELECT s.*, u.name host_name, w.slug ws_slug, w.name ws_name FROM sessions s JOIN users u ON u.id=s.host_id JOIN workspaces w ON w.id=s.workspace_id WHERE s.id=?`, sessionId);
|
|
411
|
+
if (!s) return null;
|
|
412
|
+
if (user) {
|
|
413
|
+
const m = q.get(`SELECT role FROM memberships WHERE workspace_id=? AND user_id=?`, s.workspace_id, user.id);
|
|
414
|
+
// a private session, live or ended, exists for its host and nobody else, admins included
|
|
415
|
+
if (m && (s.access !== 'private' || s.host_id === user.id)) return { s, role: m.role, guest: false };
|
|
416
|
+
}
|
|
417
|
+
if (guestToken && s.access !== 'private' && s.guest_hash && s.status === 'live' && sha(guestToken) === s.guest_hash) return { s, role: null, guest: true };
|
|
418
|
+
return null;
|
|
419
|
+
}
|
|
420
|
+
const canManage = (a, user) => !a.guest && (a.s.host_id === user.id || RANK[a.role] >= RANK.admin);
|
|
421
|
+
|
|
422
|
+
route('GET', '/api/sessions/:id', async ({ user, params, url }) => {
|
|
423
|
+
const a = sessionFor(user, params.id, url.searchParams.get('guest'));
|
|
424
|
+
if (!a) bad(user ? 404 : 401, 'Session not found.');
|
|
425
|
+
const { s } = a;
|
|
426
|
+
return {
|
|
427
|
+
id: s.id, title: s.title, agent: s.agent, kind: s.kind, project: s.project, branch: s.branch, status: s.status, access: s.access,
|
|
428
|
+
started_at: s.started_at, ended_at: s.ended_at, hasRecording: !!s.has_recording, host: { id: s.host_id, name: s.host_name },
|
|
429
|
+
endReason: s.end_reason, handoff: a.guest ? null : handoffSummary(s),
|
|
430
|
+
summary: a.guest ? null : sessionSummary(s), agents: a.guest ? [] : connectedAgents(q.get(`SELECT anthropic_key, agent_config FROM workspaces WHERE id=?`, s.workspace_id)),
|
|
431
|
+
workspace: a.guest ? { name: s.ws_name } : { name: s.ws_name, slug: s.ws_slug },
|
|
432
|
+
guest: a.guest, canManage: canManage(a, user), isHost: !!user && s.host_id === user.id,
|
|
433
|
+
events: a.guest ? [] : q.all(`SELECT actor, type, detail, at FROM events WHERE session_id=? ORDER BY id DESC LIMIT 100`, s.id).reverse(),
|
|
434
|
+
};
|
|
435
|
+
}, { open: true });
|
|
436
|
+
|
|
437
|
+
route('PATCH', '/api/sessions/:id', async ({ user, params, data }) => {
|
|
438
|
+
const a = sessionFor(user, params.id);
|
|
439
|
+
if (!a) bad(404, 'Session not found.');
|
|
440
|
+
if (!canManage(a, user)) bad(403, 'Only the host or a workspace admin can change this session.');
|
|
441
|
+
if (!['control', 'view', 'private'].includes(data.access)) bad(400, 'Invalid access level.');
|
|
442
|
+
if (data.access === 'private' && a.s.host_id !== user.id) bad(403, 'Only the host can make a session private.');
|
|
443
|
+
const l = getLive(params.id);
|
|
444
|
+
if (l) l.setAccess(data.access, user);
|
|
445
|
+
else {
|
|
446
|
+
// an ended session: this decides who can open its recording and checkpoint
|
|
447
|
+
q.run(`UPDATE sessions SET access=? WHERE id=?`, data.access, a.s.id);
|
|
448
|
+
audit(a.s.workspace_id, 'session.access', { session: a.s.id, actor: user, detail: data.access === 'private' ? 'private' : 'visible to the workspace' });
|
|
449
|
+
}
|
|
450
|
+
return { ok: true };
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
route('POST', '/api/sessions/:id/end', async ({ user, params }) => {
|
|
454
|
+
const a = sessionFor(user, params.id);
|
|
455
|
+
if (!a) bad(404, 'Session not found.');
|
|
456
|
+
if (!canManage(a, user)) bad(403, 'Only the host or a workspace admin can end this session.');
|
|
457
|
+
getLive(params.id)?.end(`ended by ${user.name}`);
|
|
458
|
+
return { ok: true };
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
// ---- invited agents, summaries, search ----
|
|
462
|
+
|
|
463
|
+
function sessionSummary(s) { try { return s.summary ? { ...JSON.parse(s.summary), at: s.summary_at } : null; } catch { return null; } }
|
|
464
|
+
const agentFail = (e) => { if (e instanceof AgentError) bad(409, e.message); throw e; };
|
|
465
|
+
// The agent a request names, or the first one the workspace has connected.
|
|
466
|
+
function pickAgent(workspaceId, id) {
|
|
467
|
+
const ws = q.get(`SELECT anthropic_key, agent_config FROM workspaces WHERE id=?`, workspaceId);
|
|
468
|
+
if (id !== undefined && !AGENTS[id]) bad(400, 'Unknown agent.');
|
|
469
|
+
const agent = id ? AGENTS[id] : Object.values(AGENTS).find((a) => a.connected(ws));
|
|
470
|
+
if (!agent) bad(409, 'No agent is connected to this workspace yet. An admin can add one under Settings.');
|
|
471
|
+
if (!agent.connected(ws)) bad(409, `${agent.name} is not connected to this workspace yet. An admin can add it under Settings.`);
|
|
472
|
+
return agent;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// "Catch me up": a note written from what the session shows right now.
|
|
476
|
+
route('POST', '/api/sessions/:id/summary', async ({ user, params, data }) => {
|
|
477
|
+
const a = sessionFor(user, params.id);
|
|
478
|
+
if (!a || a.guest) bad(404, 'Session not found.');
|
|
479
|
+
rateLimit(`summary:${user.id}`, 20, 600_000);
|
|
480
|
+
const live = getLive(params.id);
|
|
481
|
+
const agent = pickAgent(a.s.workspace_id, data.agent);
|
|
482
|
+
let out;
|
|
483
|
+
try { out = await summarize(agent, a.s.workspace_id, sessionContext({ row: live?.row || a.s, live, hostName: a.s.host_name })); } catch (e) { agentFail(e); }
|
|
484
|
+
const summary = { goal: String(out.goal || '').slice(0, 400), done: (Array.isArray(out.done) ? out.done : []).slice(0, 6).map((x) => String(x).slice(0, 300)), state: String(out.state || '').slice(0, 600), next: String(out.next || '').slice(0, 400), by: agent.name };
|
|
485
|
+
q.run(`UPDATE sessions SET summary=?, summary_at=? WHERE id=?`, JSON.stringify(summary), now(), a.s.id);
|
|
486
|
+
audit(a.s.workspace_id, 'session.agent', { session: a.s.id, actor: user, detail: `asked ${agent.name} for a catch-up summary` });
|
|
487
|
+
if (!live) indexSession(a.s.id);
|
|
488
|
+
return { summary: { ...summary, at: now() } };
|
|
489
|
+
});
|
|
490
|
+
|
|
491
|
+
// Only the host can hand the wheel to an agent; the host or an admin can take it back.
|
|
492
|
+
route('POST', '/api/sessions/:id/driver', async ({ user, params, data }) => {
|
|
493
|
+
const a = sessionFor(user, params.id);
|
|
494
|
+
const live = a && !a.guest && getLive(params.id);
|
|
495
|
+
if (!live) bad(404, 'Session not found.');
|
|
496
|
+
if (a.s.host_id !== user.id) bad(403, 'Only the host can hand the wheel to an agent.');
|
|
497
|
+
const goal = clip(data.goal, 600);
|
|
498
|
+
if (goal.length < 8) bad(400, 'Say what you want done, in a sentence.');
|
|
499
|
+
if (live.driver) bad(409, `${live.driver.name} already has the wheel.`);
|
|
500
|
+
live.drive(pickAgent(a.s.workspace_id, data.agent), { id: user.id, name: user.name }, goal); // runs in the background
|
|
501
|
+
return { ok: true };
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
route('DELETE', '/api/sessions/:id/driver', async ({ user, params }) => {
|
|
505
|
+
const a = sessionFor(user, params.id);
|
|
506
|
+
const live = a && !a.guest && getLive(params.id);
|
|
507
|
+
if (!live) bad(404, 'Session not found.');
|
|
508
|
+
if (!canManage(a, user)) bad(403, 'Only the host or a workspace admin can take the wheel back.');
|
|
509
|
+
live.stopDriver(`${user.name} took the wheel back.`, user);
|
|
510
|
+
return { ok: true };
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
route('GET', '/api/workspaces/:slug/search', async ({ user, params, url }) => {
|
|
514
|
+
const ws = member(user, params.slug);
|
|
515
|
+
const text = (url.searchParams.get('q') || '').slice(0, 200);
|
|
516
|
+
return { results: search(ws.id, user.id, text) };
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
// ---- checkpoints and pickup ------------------------------------------------
|
|
520
|
+
|
|
521
|
+
const PART = { transcript: { file: 'jsonl.gz', max: 64 * 1024 * 1024 }, bundle: { file: 'bundle', max: 100 * 1024 * 1024 } };
|
|
522
|
+
const handoffFile = (sid, part) => path.join(HANDOFF_DIR, `${sid}.${PART[part].file}`);
|
|
523
|
+
function handoffMeta(s) { try { return s.handoff_at ? JSON.parse(s.handoff_meta) : null; } catch { return null; } }
|
|
524
|
+
// What a teammate sees before deciding to pick a session up. No paths from the host's machine.
|
|
525
|
+
function handoffSummary(s) {
|
|
526
|
+
const m = handoffMeta(s);
|
|
527
|
+
return m && { at: s.handoff_at, branch: m.branch || null, changed: m.changed || 0, hasCode: !!m.head, agent: s.agent };
|
|
528
|
+
}
|
|
529
|
+
function ownLive(user, sid) {
|
|
530
|
+
const l = getLive(sid);
|
|
531
|
+
if (!l || l.row.host_id !== user.id) bad(404, 'Session not found.');
|
|
532
|
+
if (!q.get(`SELECT handoff FROM workspaces WHERE id=?`, l.row.workspace_id)?.handoff) bad(403, 'Checkpoints are turned off for this workspace.');
|
|
533
|
+
return l;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// The host's CLI streams a part up; it only counts once the metadata is posted.
|
|
537
|
+
route('PUT', '/api/sessions/:id/handoff/:part', async ({ user, params, req }) => {
|
|
538
|
+
const part = PART[params.part];
|
|
539
|
+
if (!part) bad(404, 'Not found.');
|
|
540
|
+
ownLive(user, params.id);
|
|
541
|
+
if (Number(req.headers['content-length']) > part.max) bad(413, 'Checkpoint too large.');
|
|
542
|
+
const tmp = `${handoffFile(params.id, params.part)}.${newId(6)}.tmp`;
|
|
543
|
+
let n = 0;
|
|
544
|
+
try {
|
|
545
|
+
await pipeline(req, async function* (src) { for await (const c of src) { n += c.length; if (n > part.max) throw new HttpError(413, 'Checkpoint too large.'); yield c; } }, fs.createWriteStream(tmp));
|
|
546
|
+
fs.renameSync(tmp, handoffFile(params.id, params.part));
|
|
547
|
+
} catch (e) { fs.rmSync(tmp, { force: true }); throw e; }
|
|
548
|
+
return { ok: true, bytes: n };
|
|
549
|
+
}, { raw: true });
|
|
550
|
+
|
|
551
|
+
route('POST', '/api/sessions/:id/handoff', async ({ user, params, data }) => {
|
|
552
|
+
ownLive(user, params.id);
|
|
553
|
+
if (!fs.existsSync(handoffFile(params.id, 'transcript'))) bad(409, 'Upload the conversation first.');
|
|
554
|
+
const str = (v, n) => (typeof v === 'string' ? v.slice(0, n) : '');
|
|
555
|
+
const hex = (v) => (/^[0-9a-f]{40,64}$/.test(v) ? v : '');
|
|
556
|
+
const meta = {
|
|
557
|
+
agentSession: /^[0-9a-f-]{36}$/.test(data.agentSession) ? data.agentSession : '', cwd: str(data.cwd, 1000), subdir: str(data.subdir, 500),
|
|
558
|
+
repo: str(data.repo, 300), branch: str(data.branch, 200), head: hex(data.head), checkpoint: hex(data.checkpoint),
|
|
559
|
+
changed: Math.max(0, Math.min(100000, Number(data.changed) || 0)), hasBundle: !!data.hasBundle,
|
|
560
|
+
};
|
|
561
|
+
if (!meta.agentSession) bad(400, 'Missing agent session.');
|
|
562
|
+
if (!meta.hasBundle) fs.rmSync(handoffFile(params.id, 'bundle'), { force: true });
|
|
563
|
+
q.run(`UPDATE sessions SET handoff_at=?, handoff_meta=? WHERE id=?`, now(), JSON.stringify(meta), params.id);
|
|
564
|
+
return { ok: true };
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
route('GET', '/api/sessions/:id/handoff/:part', async ({ user, params, res }) => {
|
|
568
|
+
const a = sessionFor(user, params.id);
|
|
569
|
+
if (!a || a.guest || !PART[params.part] || !handoffMeta(a.s)) bad(404, 'No checkpoint for this session.');
|
|
570
|
+
const file = handoffFile(a.s.id, params.part);
|
|
571
|
+
if (!fs.existsSync(file)) bad(404, 'No checkpoint for this session.');
|
|
572
|
+
res.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': fs.statSync(file).size, 'cache-control': 'no-store' });
|
|
573
|
+
fs.createReadStream(file).pipe(res);
|
|
574
|
+
return null;
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
// A teammate takes the work over. Logged, and the original host is told.
|
|
578
|
+
route('POST', '/api/sessions/:id/pickup', async ({ user, params }) => {
|
|
579
|
+
const a = sessionFor(user, params.id);
|
|
580
|
+
const meta = a && !a.guest && handoffMeta(a.s);
|
|
581
|
+
if (!meta) bad(404, a && !a.guest ? 'This session has no checkpoint to pick up. Checkpoints are made for Claude Code sessions started through Agentpen.' : 'Session not found.');
|
|
582
|
+
audit(a.s.workspace_id, 'session.pickup', { session: a.s.id, actor: user, detail: `checkpoint from ${new Date(a.s.handoff_at).toISOString()}` });
|
|
583
|
+
if (user.id !== a.s.host_id) notify(a.s.host_id, { kind: 'pickup', title: `${user.name} picked up your session`, body: `${a.s.title}: they are carrying on from your last checkpoint.`, session: a.s.id });
|
|
584
|
+
return { ...meta, title: a.s.title, host: a.s.host_name, at: a.s.handoff_at, live: a.s.status === 'live', summary: sessionSummary(a.s) };
|
|
585
|
+
});
|
|
586
|
+
|
|
587
|
+
// Answer from a notification without opening the session: a prompt for the agent, or a chat reply.
|
|
588
|
+
for (const verb of ['prompt', 'chat']) route('POST', `/api/sessions/:id/${verb}`, async ({ user, params, data }) => {
|
|
589
|
+
const a = sessionFor(user, params.id);
|
|
590
|
+
if (!a) bad(404, 'Session not found.');
|
|
591
|
+
const l = getLive(params.id);
|
|
592
|
+
if (!l) bad(409, 'This session has ended.');
|
|
593
|
+
const who = { id: user.id, name: user.name };
|
|
594
|
+
if (verb === 'chat') { if (!l.say(who, data.text)) bad(400, 'Write a message first.'); return { ok: true }; }
|
|
595
|
+
if (!l.canType(who)) bad(403, 'This session is watch-only for teammates.');
|
|
596
|
+
if (!l.prompt(who, data.text)) bad(409, 'Could not reach the agent. The host may be offline.');
|
|
597
|
+
return { ok: true };
|
|
598
|
+
});
|
|
599
|
+
|
|
600
|
+
route('POST', '/api/sessions/:id/guest-link', async ({ user, params }) => {
|
|
601
|
+
const a = sessionFor(user, params.id);
|
|
602
|
+
if (!a) bad(404, 'Session not found.');
|
|
603
|
+
if (!canManage(a, user)) bad(403, 'Only the host or a workspace admin can create guest links.');
|
|
604
|
+
const l = getLive(params.id);
|
|
605
|
+
if (!l) bad(409, 'This session has ended.');
|
|
606
|
+
if (a.s.access === 'private') bad(409, 'This session is private. Share it with the workspace before making a guest link.');
|
|
607
|
+
return { url: newGuestLink(l, user) };
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
route('GET', '/api/sessions/:id/recording', async ({ user, params, res }) => {
|
|
611
|
+
const a = sessionFor(user, params.id);
|
|
612
|
+
if (!a || a.s.status !== 'ended' || !a.s.has_recording) bad(404, 'Recording not found.');
|
|
613
|
+
const thread = a.s.kind === 'thread';
|
|
614
|
+
const file = path.join(RECORDINGS_DIR, `${a.s.id}.${thread ? 'json' : 'cast'}`);
|
|
615
|
+
if (!fs.existsSync(file)) bad(404, 'Recording not found.');
|
|
616
|
+
res.writeHead(200, { 'content-type': thread ? 'application/json' : 'application/x-asciicast', 'cache-control': 'private, max-age=3600' });
|
|
617
|
+
fs.createReadStream(file).pipe(res);
|
|
618
|
+
return null;
|
|
619
|
+
});
|
|
620
|
+
|
|
621
|
+
// ---- static files ----------------------------------------------------------
|
|
622
|
+
|
|
623
|
+
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.sh': 'text/plain' };
|
|
624
|
+
const VENDOR = {
|
|
625
|
+
'/vendor/xterm.mjs': 'node_modules/@xterm/xterm/lib/xterm.mjs',
|
|
626
|
+
'/vendor/xterm.css': 'node_modules/@xterm/xterm/css/xterm.css',
|
|
627
|
+
'/vendor/addon-fit.mjs': 'node_modules/@xterm/addon-fit/lib/addon-fit.mjs',
|
|
628
|
+
};
|
|
629
|
+
const WEB = path.join(ROOT, 'web');
|
|
630
|
+
const SECURITY_HEADERS = {
|
|
631
|
+
'x-content-type-options': 'nosniff',
|
|
632
|
+
'x-frame-options': 'DENY',
|
|
633
|
+
'referrer-policy': 'same-origin',
|
|
634
|
+
'content-security-policy': "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ws: wss:; frame-ancestors 'none'",
|
|
635
|
+
};
|
|
636
|
+
|
|
637
|
+
function serveStatic(req, res, pathname) {
|
|
638
|
+
let file = VENDOR[pathname] ? path.join(ROOT, VENDOR[pathname]) : path.join(WEB, path.normalize(pathname));
|
|
639
|
+
if (!VENDOR[pathname] && !file.startsWith(WEB + path.sep)) file = path.join(WEB, 'index.html');
|
|
640
|
+
if (!path.extname(file) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
|
|
641
|
+
if (path.extname(pathname)) { res.writeHead(404, SECURITY_HEADERS); return res.end('Not found'); }
|
|
642
|
+
file = path.join(WEB, 'index.html');
|
|
643
|
+
}
|
|
644
|
+
const isHtml = file.endsWith('.html');
|
|
645
|
+
res.writeHead(200, {
|
|
646
|
+
...SECURITY_HEADERS,
|
|
647
|
+
'content-type': MIME[path.extname(file)] || 'application/octet-stream',
|
|
648
|
+
'cache-control': isHtml || IS_LOCAL ? 'no-cache' : 'public, max-age=3600',
|
|
649
|
+
});
|
|
650
|
+
fs.createReadStream(file).pipe(res);
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// ---- server ----------------------------------------------------------------
|
|
654
|
+
|
|
655
|
+
const server = http.createServer(async (req, res) => {
|
|
656
|
+
const url = new URL(req.url, 'http://x');
|
|
657
|
+
if (url.pathname === '/healthz') { res.writeHead(200); return res.end('ok'); }
|
|
658
|
+
if (!url.pathname.startsWith('/api/')) {
|
|
659
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); return res.end(); }
|
|
660
|
+
return serveStatic(req, res, url.pathname);
|
|
661
|
+
}
|
|
662
|
+
try {
|
|
663
|
+
for (const r of routes) {
|
|
664
|
+
if (r.method !== req.method) continue;
|
|
665
|
+
const m = r.re.exec(url.pathname);
|
|
666
|
+
if (!m) continue;
|
|
667
|
+
if (req.method !== 'GET' && !sameOrigin(req)) bad(403, 'Cross-origin request blocked.');
|
|
668
|
+
const user = auth(req);
|
|
669
|
+
if (!user && !r.open) bad(401, 'Sign in to continue.');
|
|
670
|
+
const params = Object.fromEntries(r.keys.map((k, i) => [k, decodeURIComponent(m[i + 1])]));
|
|
671
|
+
const data = req.method === 'GET' || r.raw ? {} : await body(req);
|
|
672
|
+
const out = await r.fn({ req, res, url, user, params, data });
|
|
673
|
+
if (out !== null) {
|
|
674
|
+
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
675
|
+
res.end(JSON.stringify(out));
|
|
676
|
+
}
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
bad(404, 'Not found.');
|
|
680
|
+
} catch (e) {
|
|
681
|
+
const status = e instanceof HttpError ? e.status : 500;
|
|
682
|
+
if (status === 500) console.error(e);
|
|
683
|
+
if (!res.headersSent) res.writeHead(status, { 'content-type': 'application/json' });
|
|
684
|
+
res.end(JSON.stringify({ error: status === 500 ? 'Something went wrong on our side.' : e.message }));
|
|
685
|
+
}
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: 4 * 1024 * 1024 });
|
|
689
|
+
server.on('upgrade', (req, socket, head) => {
|
|
690
|
+
const url = new URL(req.url, 'http://x');
|
|
691
|
+
const deny = (code) => { socket.write(`HTTP/1.1 ${code}\r\n\r\n`); socket.destroy(); };
|
|
692
|
+
const accept = (fn) => wss.handleUpgrade(req, socket, head, (ws) => { ws.isAlive = true; ws.on('pong', () => { ws.isAlive = true; }); fn(ws); });
|
|
693
|
+
const user = auth(req);
|
|
694
|
+
|
|
695
|
+
if (url.pathname === '/ws/host') {
|
|
696
|
+
if (!user || !req.headers.authorization) return deny('401 Unauthorized');
|
|
697
|
+
return accept((ws) => attachHost(ws, user));
|
|
698
|
+
}
|
|
699
|
+
if (!sameOrigin(req)) return deny('403 Forbidden');
|
|
700
|
+
let m;
|
|
701
|
+
if ((m = /^\/ws\/session\/([^/]+)$/.exec(url.pathname))) {
|
|
702
|
+
const a = sessionFor(user, m[1], url.searchParams.get('guest'));
|
|
703
|
+
const l = a && getLive(m[1]);
|
|
704
|
+
if (!l) return deny('404 Not Found');
|
|
705
|
+
const who = a.guest
|
|
706
|
+
? { id: null, name: `${clip(url.searchParams.get('name'), 24) || 'Guest'} (guest)`, guest: true }
|
|
707
|
+
: { id: user.id, name: user.name };
|
|
708
|
+
return accept((ws) => attachViewer(ws, l, who));
|
|
709
|
+
}
|
|
710
|
+
if (url.pathname === '/ws/me') {
|
|
711
|
+
if (!user) return deny('401 Unauthorized');
|
|
712
|
+
return accept((sock) => attachUser(sock, user, Number(url.searchParams.get('since'))));
|
|
713
|
+
}
|
|
714
|
+
if ((m = /^\/ws\/workspace\/([^/]+)$/.exec(url.pathname))) {
|
|
715
|
+
const ws = user && q.get(`SELECT w.id FROM workspaces w JOIN memberships m ON m.workspace_id=w.id WHERE w.slug=? AND m.user_id=?`, m[1], user.id);
|
|
716
|
+
if (!ws) return deny('404 Not Found');
|
|
717
|
+
return accept((sock) => attachFeed(sock, ws.id, user.id));
|
|
718
|
+
}
|
|
719
|
+
deny('404 Not Found');
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
setInterval(() => {
|
|
723
|
+
for (const ws of wss.clients) {
|
|
724
|
+
if (ws.isAlive === false) { ws.terminate(); continue; }
|
|
725
|
+
ws.isAlive = false;
|
|
726
|
+
try { ws.ping(); } catch {}
|
|
727
|
+
}
|
|
728
|
+
}, 30_000).unref();
|
|
729
|
+
setInterval(() => {
|
|
730
|
+
q.run(`DELETE FROM tokens WHERE expires_at<?`, now());
|
|
731
|
+
q.run(`DELETE FROM device_codes WHERE expires_at<?`, now());
|
|
732
|
+
q.run(`DELETE FROM invites WHERE expires_at<?`, now());
|
|
733
|
+
// checkpoints hold source code: do not keep them around after they stop being useful
|
|
734
|
+
for (const s of q.all(`SELECT id FROM sessions WHERE handoff_at IS NOT NULL AND status='ended' AND ended_at<?`, now() - 14 * DAY)) {
|
|
735
|
+
for (const part of Object.keys(PART)) fs.rmSync(handoffFile(s.id, part), { force: true });
|
|
736
|
+
q.run(`UPDATE sessions SET handoff_at=NULL, handoff_meta=NULL WHERE id=?`, s.id);
|
|
737
|
+
}
|
|
738
|
+
}, 3_600_000).unref();
|
|
739
|
+
|
|
740
|
+
server.listen(PORT, () => {
|
|
741
|
+
console.log(`agentpen listening on ${BASE_URL}${DEV_LINKS ? ' (dev mode: sign-in links are shown on screen)' : ''}`);
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
export { server };
|