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/web/app.js ADDED
@@ -0,0 +1,515 @@
1
+ // Agentpen web app. No build step: plain ES modules, DOM built with h(),
2
+ // user-supplied text only ever enters the page as text nodes.
3
+ import { sessionPage } from '/session.js';
4
+
5
+ export function h(tag, props, ...kids) {
6
+ const [name, ...cls] = tag.split('.');
7
+ const el = document.createElement(name || 'div');
8
+ if (cls.length) el.className = cls.join(' ');
9
+ for (const [k, v] of Object.entries(props || {})) {
10
+ if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
11
+ else if (k === 'class') { if (v) el.className += ' ' + v; }
12
+ else if (k === 'value') el.value = v;
13
+ else if (v === true) el.setAttribute(k, '');
14
+ else if (v !== false && v != null) el.setAttribute(k, v);
15
+ }
16
+ for (const kid of kids.flat(Infinity)) if (kid != null && kid !== false) el.append(kid);
17
+ return el;
18
+ }
19
+
20
+ // Element.append / replaceChildren do not flatten arrays or skip nulls; these do.
21
+ const kidsOf = (kids) => kids.flat(Infinity).filter((k) => k != null && k !== false);
22
+ export const fill = (el, ...kids) => el.replaceChildren(...kidsOf(kids));
23
+ const put = (el, ...kids) => el.append(...kidsOf(kids));
24
+
25
+ export async function api(method, route, data) {
26
+ const r = await fetch(route, { method, headers: data ? { 'content-type': 'application/json' } : {}, body: data ? JSON.stringify(data) : undefined });
27
+ const out = await r.json().catch(() => ({}));
28
+ if (!r.ok) { const e = new Error(out.error || 'Something went wrong.'); e.status = r.status; throw e; }
29
+ return out;
30
+ }
31
+
32
+ export function toast(text) {
33
+ document.querySelector('.toast')?.remove();
34
+ const t = h('.toast', { role: 'status' }, text);
35
+ document.body.append(t);
36
+ setTimeout(() => t.remove(), 2200);
37
+ }
38
+ export async function copy(text, done = 'Copied') {
39
+ try { await navigator.clipboard.writeText(text); toast(done); } catch { prompt('Copy this:', text); }
40
+ }
41
+
42
+ const COLORS = ['#f0a35e', '#7fca8d', '#7fb4e8', '#e79ad0', '#f5c451', '#9fd8cf', '#c3a6f0', '#ef9a8c'];
43
+ export function avatar(name, title) {
44
+ let n = 0;
45
+ for (const c of name || '?') n = (n * 31 + c.charCodeAt(0)) >>> 0;
46
+ const initials = (name || '?').split(/\s+/).map((p) => p[0]).slice(0, 2).join('').toUpperCase();
47
+ return h('span.avatar', { style: `background:${COLORS[n % COLORS.length]}`, title: title || name }, initials);
48
+ }
49
+ export function avatars(people, max = 4) {
50
+ const shown = people.slice(0, max);
51
+ return h('span.avatars', {}, shown.map((p) => avatar(p.name)), people.length > max && h('span.avatar.more', {}, `+${people.length - max}`));
52
+ }
53
+ export const STATE_LABEL = { working: 'Working', idle: 'Idle', blocked: 'Needs a human', reconnecting: 'Reconnecting' };
54
+ export const pill = (state) => h(`span.pill.${state}`, {}, STATE_LABEL[state] || state);
55
+ export const clock = (t) => new Date(t).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
56
+ export function ago(t) {
57
+ const s = Math.max(0, (Date.now() - t) / 1000);
58
+ if (s < 60) return 'just now';
59
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
60
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
61
+ return new Date(t).toLocaleDateString([], { month: 'short', day: 'numeric' });
62
+ }
63
+ export function duration(ms) {
64
+ const m = Math.max(0, Math.round(ms / 60000));
65
+ return m < 1 ? '<1 min' : m < 60 ? `${m} min` : `${Math.floor(m / 60)}h ${m % 60}m`;
66
+ }
67
+ export const brand = (href = '/') => h('a.brand', { href }, h('i'), 'Agentpen');
68
+
69
+ // ---- notifications ---------------------------------------------------------
70
+
71
+ export const NOTE_KINDS = [
72
+ ['needs_you', 'My agent stops to ask me something'],
73
+ ['done', 'My agent finishes a long piece of work'],
74
+ ['team_blocked', 'A teammate’s agent has been stuck for a minute'],
75
+ ['prompt', 'Someone prompts my agent'],
76
+ ['joined', 'Someone joins my session'],
77
+ ['chat', 'Someone messages me in a session'],
78
+ ['pickup', 'Someone picks up my session to carry it on'],
79
+ ['started', 'A teammate goes live'],
80
+ ];
81
+ const tray = h('.notes', { 'aria-live': 'polite' });
82
+ document.body.append(tray);
83
+ let inbox = null;
84
+
85
+ function showNote(n) {
86
+ const path = new URL(n.url).pathname;
87
+ const here = location.pathname === path;
88
+ if (document.hidden && 'Notification' in window && Notification.permission === 'granted') {
89
+ const sys = new Notification(n.title, { body: n.body, tag: `${n.session}:${n.kind}` });
90
+ sys.onclick = () => { window.focus(); go(path); sys.close(); };
91
+ }
92
+ if (here && !document.hidden) return; // already looking at it
93
+ const card = h(`a.note${n.urgent ? '.urgent' : ''}`, { href: path, 'data-session': n.session || '', 'data-kind': n.kind, onclick: () => card.remove() },
94
+ h('b', {}, n.title), h('span', {}, n.body));
95
+ tray.prepend(card);
96
+ while (tray.children.length > 4) tray.lastChild.remove();
97
+ if (!n.urgent) setTimeout(() => card.remove(), 9000);
98
+ }
99
+
100
+ function connectInbox() {
101
+ if (inbox || !me) return;
102
+ inbox = new WebSocket(`${location.origin.replace(/^http/, 'ws')}/ws/me`);
103
+ inbox.onmessage = (e) => {
104
+ const m = JSON.parse(e.data);
105
+ if (m.t === 'notify') showNote(m.note);
106
+ else if (m.t === 'clear') for (const c of [...tray.children]) if (c.dataset.session === m.session && m.kinds.includes(c.dataset.kind)) c.remove();
107
+ };
108
+ inbox.onclose = () => { inbox = null; setTimeout(connectInbox, 4000); };
109
+ }
110
+
111
+ // ---- router ----------------------------------------------------------------
112
+
113
+ const app = document.getElementById('app');
114
+ let cleanup = null;
115
+ export let me = null;
116
+
117
+ export function go(path, replace = false) {
118
+ if (replace) history.replaceState(null, '', path); else history.pushState(null, '', path);
119
+ render();
120
+ }
121
+ document.addEventListener('click', (e) => {
122
+ const a = e.target.closest('a[href]');
123
+ if (!a || e.metaKey || e.ctrlKey || e.shiftKey || a.target || a.origin !== location.origin) return;
124
+ e.preventDefault();
125
+ go(a.pathname + a.search);
126
+ });
127
+ window.addEventListener('popstate', render);
128
+
129
+ function mount(node, onLeave) {
130
+ fill(app, node);
131
+ cleanup = onLeave || null;
132
+ }
133
+ const loginUrl = () => `/login?next=${encodeURIComponent(location.pathname + location.search)}`;
134
+
135
+ async function render() {
136
+ if (cleanup) { try { cleanup(); } catch {} cleanup = null; }
137
+ document.title = 'Agentpen';
138
+ const path = location.pathname;
139
+ const qs = new URLSearchParams(location.search);
140
+ try { me = await api('GET', '/api/me'); if (!me.user) me = null; } catch { me = null; }
141
+ connectInbox();
142
+ let m;
143
+ try {
144
+ if (path === '/auth/verify') return await verifyPage(qs);
145
+ if (path === '/login') return me ? go(qs.get('next') || '/', true) : loginPage(qs.get('next'));
146
+ if ((m = /^\/s\/([^/]+)$/.exec(path))) return await sessionPage(m[1], qs.get('guest'), { mount, me });
147
+ if ((m = /^\/(invite|join)\/([^/]+)$/.exec(path))) return await invitePage(m[1], m[2]);
148
+ if (!me) return path === '/' ? landing() : go(loginUrl(), true);
149
+ if (path === '/activate') return activatePage(qs.get('code'));
150
+ if (path === '/new') return onboarding(true);
151
+ if ((m = /^\/w\/([^/]+)(?:\/(members|activity|settings))?$/.exec(path))) return await workspacePage(m[1], m[2] || 'sessions');
152
+ if (path === '/') {
153
+ const last = localStorage.getItem('bp_ws');
154
+ const ws = me.workspaces.find((w) => w.slug === last) || me.workspaces[0];
155
+ return ws ? go(`/w/${ws.slug}`, true) : onboarding(false);
156
+ }
157
+ notFound();
158
+ } catch (e) {
159
+ if (e.status === 401) return go(loginUrl(), true);
160
+ notFound(e.message);
161
+ }
162
+ }
163
+
164
+ function notFound(message = 'That page does not exist, or you do not have access to it.') {
165
+ mount(h('.center', {}, h('.card.stack', {}, brand(), h('h1', {}, 'Nothing here'), h('p.muted', {}, message), h('a.btn', { href: '/' }, 'Go home'))));
166
+ }
167
+
168
+ // Wraps a submit handler: disables the button, shows the error inline.
169
+ function form(fields, submitLabel, onSubmit, attrs = {}) {
170
+ const err = h('p.error', { role: 'alert' });
171
+ const btn = h('button.btn.primary', { type: 'submit' }, submitLabel);
172
+ const f = h('form.stack', {
173
+ ...attrs,
174
+ onsubmit: async (e) => {
175
+ e.preventDefault();
176
+ err.textContent = '';
177
+ btn.disabled = true;
178
+ try { await onSubmit(Object.fromEntries(new FormData(f))); } catch (x) { err.textContent = x.message; }
179
+ btn.disabled = false;
180
+ },
181
+ }, fields, btn, err);
182
+ return f;
183
+ }
184
+
185
+ // ---- signed-out pages ------------------------------------------------------
186
+
187
+ function emailSent(email, devLink) {
188
+ return h('.stack', {},
189
+ h('h1', {}, 'Check your email'),
190
+ h('p.muted', {}, 'We sent a sign-in link to ', h('b', {}, email), '. It works once and expires in 15 minutes.'),
191
+ devLink && h('a.btn.primary', { href: devLink.replace(location.origin, '') }, 'Dev mode: open the sign-in link'));
192
+ }
193
+
194
+ // One sentence, one picture, three steps. Everything else waits until they are in.
195
+ function landing() {
196
+ const signup = (id) => {
197
+ const box = h('div.start');
198
+ const f = h('form', {
199
+ onsubmit: async (e) => {
200
+ e.preventDefault();
201
+ const email = new FormData(f).get('email');
202
+ try {
203
+ const r = await api('POST', '/api/auth/start', { email });
204
+ fill(box, h('.card', {}, emailSent(email, r.devLink)));
205
+ } catch (x) { toast(x.message); }
206
+ },
207
+ }, h('input.input', { id, name: 'email', type: 'email', required: true, placeholder: 'you@company.com', 'aria-label': 'Work email', autocomplete: 'email' }), h('button.btn.primary', {}, 'Start free'));
208
+ box.append(f);
209
+ return box;
210
+ };
211
+ const step = (n, title, body) => h('li', {}, h('span.n', {}, n), h('div', {}, h('h3', {}, title), h('p', {}, body)));
212
+
213
+ mount(h('.landing', {},
214
+ h('nav', {}, brand(), h('span.spacer'), h('a.btn.ghost', { href: '/login' }, 'Sign in')),
215
+ h('header.hero', {},
216
+ h('h1', {}, 'See and unblock your team’s ', h('em', {}, 'coding agents.')),
217
+ h('p.lede', {}, 'Keep typing ', h('code', {}, 'claude'), '. Your team can watch the session, answer its questions, and pick it up if your laptop is shut.'),
218
+ signup('email-top'),
219
+ h('p.small.muted', {}, 'Free for teams of up to 5. No credit card.')),
220
+ h('figure.shot', {},
221
+ h('img', { src: '/team-page.png', width: 2560, height: 740, alt: 'The team page: three live agent sessions, one marked “Needs a human”, with an alert that a teammate’s agent is stuck' })),
222
+ h('ol.steps', {},
223
+ step('1', 'Set it up once', [h('code', {}, 'npm i -g agentpen-cli && agentpen install'), ' takes a minute. Nothing changes about how you work.']),
224
+ step('2', 'Run your agent as usual', ['Claude Code in the terminal or Codex in the app. It shows up on your team’s page.']),
225
+ step('3', 'Anyone can step in', ['Teammates join from a browser. No install, no VPN.'])),
226
+ h('footer.foot', {}, h('span', {}, 'Secrets in .env files are masked before anything leaves your machine.'), h('a', { href: '/login' }, 'Sign in'))));
227
+ }
228
+
229
+ function loginPage(next) {
230
+ const card = h('.card.stack');
231
+ put(card, brand(), h('h1', {}, 'Sign in to Agentpen'), h('p.muted', {}, 'Use your work email. We will send you a one-time link, no password needed.'),
232
+ form(h('input.input', { name: 'email', type: 'email', required: true, placeholder: 'you@company.com', 'aria-label': 'Work email', autocomplete: 'email', autofocus: true }), 'Email me a sign-in link', async ({ email }) => {
233
+ const r = await api('POST', '/api/auth/start', { email, next });
234
+ fill(card, brand(), emailSent(email, r.devLink));
235
+ }));
236
+ mount(h('.center', {}, card));
237
+ }
238
+
239
+ async function verifyPage(qs) {
240
+ mount(h('.center', {}, h('p.muted', {}, 'Signing you in…')));
241
+ try {
242
+ await api('POST', '/api/auth/verify', { token: qs.get('token') });
243
+ go(qs.get('next') || '/', true);
244
+ } catch (e) {
245
+ mount(h('.center', {}, h('.card.stack', {}, brand(), h('h1', {}, 'That link did not work'), h('p.muted', {}, e.message), h('a.btn.primary', { href: '/login' }, 'Get a new link'))));
246
+ }
247
+ }
248
+
249
+ async function invitePage(kind, token) {
250
+ let info;
251
+ try { info = await api('GET', `/api/invite-preview/${kind}/${token}`); } catch (e) { return notFound(e.message); }
252
+ const card = h('.card.stack', {}, brand(), h('h1', {}, `Join ${info.workspace} on Agentpen`));
253
+ if (!me) {
254
+ put(card, h('p.muted', {}, info.email ? `This invite is for ${info.email}. Sign in with that address to accept it.` : 'Sign in to join the team’s live coding-agent sessions.'),
255
+ h('a.btn.primary', { href: loginUrl() }, 'Sign in to accept'));
256
+ } else {
257
+ put(card, h('p.muted', {}, `You are signed in as ${me.user.email}.`),
258
+ form([], 'Join workspace', async () => {
259
+ const r = await api('POST', '/api/invites/accept', kind === 'join' ? { code: token } : { token });
260
+ go(`/w/${r.slug}`);
261
+ }));
262
+ }
263
+ mount(h('.center', {}, card));
264
+ }
265
+
266
+ function activatePage(code) {
267
+ const card = h('.card.stack');
268
+ const approve = async (user_code) => {
269
+ const r = await api('POST', '/api/device/approve', { user_code });
270
+ fill(card, brand(), h('h1', {}, 'Terminal connected'), h('p.muted', {}, `${r.label} is signed in as ${me.user.name}. You can close this tab and go back to your terminal.`));
271
+ };
272
+ put(card, brand(), h('h1', {}, 'Connect your terminal'),
273
+ h('p.muted', {}, code ? 'Check that this code matches the one in your terminal.' : 'Enter the code shown in your terminal.'),
274
+ code ? [h('.bigcode', {}, code), form([], `Approve as ${me.user.name}`, () => approve(code))]
275
+ : form(h('input.input.mono', { name: 'code', required: true, placeholder: 'ABCD-EFGH', 'aria-label': 'Code', autofocus: true }), 'Connect', (d) => approve(d.code)));
276
+ mount(h('.center', {}, card));
277
+ }
278
+
279
+ function onboarding(extra) {
280
+ const card = h('.card.stack', {}, brand(), h('h1', {}, extra ? 'Create another workspace' : `Welcome, ${me.user.name.split(' ')[0]}`));
281
+ if (me.suggested.length) {
282
+ put(card, h('p.muted', {}, 'Your team is already here:'), me.suggested.map((s) => h('.row', {},
283
+ h('div', {}, h('b', {}, s.name), h('div.small.muted', {}, `${s.members} ${s.members === 1 ? 'person' : 'people'}`)), h('span.spacer'),
284
+ h('button.btn.primary', { onclick: async () => { try { await api('POST', `/api/workspaces/${s.slug}/join`); go(`/w/${s.slug}`); } catch (e) { toast(e.message); } } }, 'Join'))),
285
+ h('p.small.muted', { style: 'border-top:1px solid var(--line);padding-top:14px' }, 'Or start a new workspace:'));
286
+ } else if (!extra) put(card, h('p.muted', {}, 'A workspace is where your team’s agent sessions live. Name it after your company or team.'));
287
+ put(card, form(h('input.input', { name: 'name', required: true, minlength: 2, maxlength: 48, placeholder: 'Acme Engineering', 'aria-label': 'Workspace name', autofocus: !me.suggested.length }), 'Create workspace', async ({ name }) => {
288
+ const r = await api('POST', '/api/workspaces', { name });
289
+ go(`/w/${r.slug}`);
290
+ }));
291
+ mount(h('.center', {}, card));
292
+ }
293
+
294
+ // ---- workspace -------------------------------------------------------------
295
+
296
+ function shell(ws, tab, content) {
297
+ const tabs = [['sessions', 'Sessions', ''], ['members', 'People', '/members'], ['activity', 'Activity', '/activity'], ['settings', 'Settings', '/settings']];
298
+ const picker = h('select.input.ws', { 'aria-label': 'Workspace', onchange: (e) => go(e.target.value === '+' ? '/new' : `/w/${e.target.value}`) },
299
+ me.workspaces.map((w) => h('option', { value: w.slug, selected: w.slug === ws.slug }, w.name)), h('option', { value: '+' }, '+ New workspace'));
300
+ return h('div', { style: 'display:contents' },
301
+ h('header.topbar', {}, brand(`/w/${ws.slug}`), picker,
302
+ tabs.map(([k, label, p]) => h(`a.tab${k === tab ? '.on' : ''}`, { href: `/w/${ws.slug}${p}` }, label)),
303
+ h('span.spacer'), h('span.hide-sm', {}, avatar(me.user.name, me.user.email)),
304
+ h('button.btn.ghost.small', { onclick: async () => { await api('POST', '/api/auth/logout'); location.href = '/'; } }, 'Sign out')),
305
+ h('main.page', {}, content));
306
+ }
307
+
308
+ async function workspacePage(slug, tab) {
309
+ const data = await api('GET', `/api/workspaces/${slug}`);
310
+ const ws = data.workspace;
311
+ localStorage.setItem('bp_ws', slug);
312
+ document.title = `${ws.name} · Agentpen`;
313
+ const admin = ws.role !== 'member';
314
+ const reload = () => workspacePage(slug, tab);
315
+ if (tab === 'sessions') return sessionsTab(ws, data);
316
+ if (tab === 'members') return mount(shell(ws, tab, membersTab(ws, data, admin, reload)));
317
+ if (tab === 'settings') return mount(shell(ws, tab, settingsTab(ws, admin, reload)));
318
+ const { events } = await api('GET', `/api/workspaces/${slug}/activity`);
319
+ mount(shell(ws, tab, activityTab(events)));
320
+ }
321
+
322
+ const INSTALL_CMD = 'npm i -g agentpen-cli && agentpen install';
323
+ const startCommand = () => h('.cmd', {}, h('span', {}, INSTALL_CMD), h('button.btn.small', { onclick: () => copy(INSTALL_CMD) }, 'Copy'));
324
+
325
+ function sessionsTab(ws, data) {
326
+ const liveBox = h('div');
327
+ const order = { blocked: 0, working: 1, idle: 2, reconnecting: 3 };
328
+ const draw = (live) => {
329
+ const stuck = live.filter((s) => s.state === 'blocked').length;
330
+ document.title = `${stuck ? `(${stuck}) ` : ''}${ws.name} · Agentpen`;
331
+ if (!live.length) {
332
+ return fill(liveBox, h('.card.empty', {},
333
+ h('h3', {}, 'No one is live right now'),
334
+ h('p.muted', {}, 'Run this once in a terminal. After that, just type ', h('code', {}, 'claude'), ' and your session shows up here.'),
335
+ startCommand(),
336
+ h('p.small.muted', { style: 'margin-top:12px' }, 'It covers the Codex desktop app too. Prefer to share one session at a time? Use ', h('code', {}, 'agentpen claude'), '.')));
337
+ }
338
+ live.sort((a, b) => order[a.state] - order[b.state] || b.started_at - a.started_at);
339
+ fill(liveBox, h('.sessions', {}, live.map((s) => h(`a.session.card${s.state === 'blocked' ? '.blocked' : ''}`, { href: `/s/${s.id}` },
340
+ h('.row', {}, pill(s.state), h('span.spacer'), s.access === 'private' ? h('span.pill', {}, 'Private') : s.people.length ? avatars(s.people) : h('span.small.muted', {}, 'No one watching')),
341
+ h('h3', {}, s.title),
342
+ h('.meta', {}, [s.project, s.branch].filter(Boolean).join(' · ') || s.agent),
343
+ h('span.spacer'),
344
+ h('.row.small.muted', {}, avatar(s.host.name), h('span', {}, s.host.name), h('span.spacer'), h('span', {}, `${s.agent} · ${ago(s.started_at).replace(' ago', '')}`))))));
345
+ };
346
+ draw(data.live);
347
+
348
+ let feed;
349
+ let closed = false;
350
+ let retry;
351
+ const connect = () => {
352
+ feed = new WebSocket(`${location.origin.replace(/^http/, 'ws')}/ws/workspace/${ws.slug}`);
353
+ feed.onmessage = (e) => { const m = JSON.parse(e.data); if (m.t === 'sessions') draw(m.live); };
354
+ feed.onclose = () => { if (!closed) retry = setTimeout(connect, 2500); };
355
+ };
356
+ connect();
357
+
358
+ // search across everything past sessions recorded; the lists step aside while there is a query
359
+ const lists = h('div');
360
+ const found = h('div');
361
+ let searchTimer;
362
+ let lastQuery = '';
363
+ const runSearch = async (text) => {
364
+ lastQuery = text;
365
+ if (!text.trim()) { found.hidden = true; lists.hidden = false; return; }
366
+ let results;
367
+ try { results = (await api('GET', `/api/workspaces/${ws.slug}/search?q=${encodeURIComponent(text)}`)).results; } catch (x) { return toast(x.message); }
368
+ if (text !== lastQuery) return; // a newer search has started
369
+ const marked = (snip) => snip.split(/[\u0002\u0003]/).map((part, n) => (n % 2 ? h('mark', {}, part) : part));
370
+ fill(found, h('.h2', {}, results.length ? (results.length === 1 ? '1 session mentions this' : `${results.length} sessions mention this`) : 'Nothing found'),
371
+ results.length ? h('.card', { style: 'padding:0' }, results.map((r) => h('a.hit', { href: `/s/${r.id}` },
372
+ h('b', {}, r.title), h('.meta', {}, [r.host_name, r.project, r.branch, ago(r.started_at)].filter(Boolean).join(' · ')),
373
+ h('.snip', {}, marked(r.snippet)))))
374
+ : h('p.muted', {}, 'Sessions become searchable when they end. Try fewer or different words.'));
375
+ found.hidden = false; lists.hidden = true;
376
+ };
377
+ const searchBox = h('form.search', { role: 'search', onsubmit: (e) => { e.preventDefault(); clearTimeout(searchTimer); runSearch(e.target.q.value); } },
378
+ h('input.input', { id: 'session-search', name: 'q', type: 'search', placeholder: 'Search every session: an error message, a file, a decision…', 'aria-label': 'Search sessions', autocomplete: 'off',
379
+ oninput: (e) => { clearTimeout(searchTimer); const v = e.target.value; searchTimer = setTimeout(() => runSearch(v), 250); } }));
380
+ found.hidden = true;
381
+ put(lists,
382
+ h('.h2', {}, 'Live now'), liveBox,
383
+ data.recent.length ? [h('.h2', {}, 'Recent'), h('.card.tablecard', {}, h('table.list', {}, h('tbody', {}, data.recent.map((s) => h('tr', {},
384
+ h('td', {}, s.has_recording || s.handoff_at ? h('a', { href: `/s/${s.id}` }, s.title) : s.title,
385
+ s.access === 'private' && h('span.small.muted', {}, ' · private'),
386
+ s.end_reason === 'host disconnected' && h('span.small.muted', {}, ' · went offline')),
387
+ h('td.muted.hide-sm', {}, [s.project, s.branch].filter(Boolean).join(' · ')),
388
+ h('td', {}, h('span.row', {}, avatar(s.host_name), h('span.hide-sm', {}, s.host_name))),
389
+ h('td.num', {}, duration((s.ended_at || s.started_at) - s.started_at)),
390
+ h('td.num', {}, ago(s.started_at)),
391
+ h('td', { style: 'text-align:right;white-space:nowrap' },
392
+ s.handoff_at ? h('a.btn.small.primary', { href: `/s/${s.id}`, style: 'margin-right:6px' }, 'Pick up') : null,
393
+ s.has_recording ? h('a.btn.small', { href: `/s/${s.id}` }, 'Replay') : null))))))] : null);
394
+ mount(shell(ws, 'sessions', [
395
+ h('.row', {}, h('h1', { style: 'font-size:22px' }, 'Sessions'), h('span.spacer'), h('a.btn.small', { href: `/w/${ws.slug}/members` }, 'Invite people')),
396
+ searchBox, found, lists,
397
+ ]), () => { closed = true; clearTimeout(retry); feed.close(); });
398
+ }
399
+
400
+ function membersTab(ws, data, admin, reload) {
401
+ const act = (fn) => async () => { try { await fn(); await reload(); } catch (e) { toast(e.message); } };
402
+ const out = [h('h1', {}, 'People'),
403
+ h('p.sub.row', {}, h('span', {}, `${ws.seatsUsed}${ws.seats ? ` of ${ws.seats}` : ''} seats used on the ${ws.planLabel} plan`),
404
+ ws.seats && h('span.meter', {}, h('i', { style: `width:${Math.min(100, (ws.seatsUsed / ws.seats) * 100)}%` })),
405
+ ws.seats && ws.seatsUsed >= ws.seats && me.upgradeUrl && h('a.btn.small.primary', { href: me.upgradeUrl, target: '_blank', rel: 'noopener' }, 'Upgrade'))];
406
+
407
+ if (admin) {
408
+ const sent = h('div.small.stack');
409
+ out.push(h('.card.stack', {},
410
+ h('h3', {}, 'Invite teammates'),
411
+ form([
412
+ h('textarea.input', { name: 'emails', required: true, rows: 2, placeholder: 'ana@acme.com, ben@acme.com', 'aria-label': 'Email addresses' }),
413
+ h('label.field', { style: 'max-width:200px' }, 'Role', h('select.input', { name: 'role' }, h('option', { value: 'member' }, 'Member'), h('option', { value: 'admin' }, 'Admin')))],
414
+ 'Send invites', async (d) => {
415
+ const r = await api('POST', `/api/workspaces/${ws.slug}/invites`, d);
416
+ if (!r.sent.length) return toast('Everyone on that list is already a member');
417
+ toast(`Invited ${r.sent.length} ${r.sent.length === 1 ? 'person' : 'people'}`);
418
+ const dev = r.sent.filter((s) => s.link);
419
+ if (dev.length) fill(sent, h('span.muted', {}, 'Dev mode (no mailer configured) - invite links:'), dev.map((s) => h('code', {}, `${s.email} ${s.link}`)));
420
+ else await reload();
421
+ }),
422
+ sent,
423
+ h('.row.wrap', { style: 'border-top:1px solid var(--line);padding-top:14px' },
424
+ h('div', {}, h('b', {}, 'Invite link'), h('div.small.muted', {}, 'Anyone with this link can join as a member.')), h('span.spacer'),
425
+ h('button.btn.small', { onclick: () => copy(ws.inviteLink, 'Invite link copied') }, 'Copy link'),
426
+ h('button.btn.small.ghost', { onclick: act(async () => { if (confirm('Reset the invite link? The old link stops working.')) await api('POST', `/api/workspaces/${ws.slug}/invite-link/rotate`); }) }, 'Reset'))));
427
+ }
428
+
429
+ out.push(h('.h2', {}, `Members · ${data.members.length}`), h('.card.tablecard', {}, h('table.list', {}, h('tbody', {}, data.members.map((m) => h('tr', {},
430
+ h('td', {}, h('span.row', {}, avatar(m.name), h('span', {}, h('b', {}, m.name), m.id === me.user.id && h('span.muted', {}, ' (you)'), h('div.small.muted', {}, m.email)))),
431
+ h('td', {}, ws.role === 'owner' && m.role !== 'owner'
432
+ ? h('select.input', { style: 'width:120px;height:32px', 'aria-label': `Role for ${m.name}`, onchange: (e) => act(() => api('PATCH', `/api/workspaces/${ws.slug}/members/${m.id}`, { role: e.target.value }))() },
433
+ ['member', 'admin'].map((r) => h('option', { value: r, selected: r === m.role }, r[0].toUpperCase() + r.slice(1))))
434
+ : h('span.muted', {}, m.role[0].toUpperCase() + m.role.slice(1))),
435
+ h('td', { style: 'text-align:right' },
436
+ m.role !== 'owner' && (m.id === me.user.id
437
+ ? h('button.btn.small.ghost', { onclick: async () => { if (!confirm(`Leave ${ws.name}?`)) return; await api('DELETE', `/api/workspaces/${ws.slug}/members/${m.id}`); localStorage.removeItem('bp_ws'); go('/'); } }, 'Leave')
438
+ : admin && (ws.role === 'owner' || m.role === 'member') && h('button.btn.small.ghost.danger', { onclick: act(async () => { if (confirm(`Remove ${m.name} from ${ws.name}? They lose access immediately.`)) await api('DELETE', `/api/workspaces/${ws.slug}/members/${m.id}`); }) }, 'Remove')))))))));
439
+
440
+ if (data.invites.length) {
441
+ out.push(h('.h2', {}, `Pending invites · ${data.invites.length}`), h('.card.tablecard', {}, h('table.list', {}, h('tbody', {}, data.invites.map((i) => h('tr', {},
442
+ h('td', {}, i.email), h('td.muted', {}, i.role[0].toUpperCase() + i.role.slice(1)), h('td.num', {}, `expires ${new Date(i.expires_at).toLocaleDateString([], { month: 'short', day: 'numeric' })}`),
443
+ h('td', { style: 'text-align:right' }, h('button.btn.small.ghost', { onclick: act(() => api('DELETE', `/api/workspaces/${ws.slug}/invites`, { email: i.email })) }, 'Revoke'))))))));
444
+ }
445
+ return out;
446
+ }
447
+
448
+ const EVENT_TEXT = {
449
+ 'session.start': 'started a session', 'session.end': 'session ended', 'session.join': 'joined', 'session.prompt': 'sent a prompt',
450
+ 'session.access': 'changed access', 'session.guest_link': 'created a guest link', 'session.pickup': 'picked up the session', 'session.agent': 'brought in an agent', 'member.join': 'joined the workspace', 'member.invite': 'invited',
451
+ 'member.remove': 'removed', 'member.leave': 'left the workspace', 'member.role': 'changed a role', 'workspace.create': 'created the workspace', 'workspace.settings': 'changed settings',
452
+ };
453
+ export const eventText = (t) => EVENT_TEXT[t] || t;
454
+
455
+ function activityTab(events) {
456
+ return [h('h1', {}, 'Activity'), h('p.sub', {}, 'Who started, joined and prompted what. The latest 200 events.'),
457
+ h('.card.tablecard', {}, events.length ? h('table.list', {},
458
+ h('thead', {}, h('tr', {}, h('th', {}, 'When'), h('th', {}, 'Who'), h('th', {}, 'What'), h('th', {}, 'Session'))),
459
+ h('tbody', {}, events.map((e) => h('tr', {},
460
+ h('td.num', { title: new Date(e.at).toLocaleString() }, ago(e.at)),
461
+ h('td', {}, e.actor || 'System'),
462
+ h('td', {}, eventText(e.type), e.detail && h('span.muted', {}, ` - ${e.detail.length > 120 ? e.detail.slice(0, 120) + '…' : e.detail}`)),
463
+ h('td', {}, e.session_id ? h('a', { href: `/s/${e.session_id}` }, e.session_title || 'session') : ''))))) : h('p.muted', { style: 'padding:16px' }, 'Nothing yet.'))];
464
+ }
465
+
466
+ function settingsTab(ws, admin, reload) {
467
+ const save = async (patch, msg = 'Saved') => { try { await api('PATCH', `/api/workspaces/${ws.slug}`, patch); toast(msg); await reload(); } catch (e) { toast(e.message); } };
468
+ const setting = (title, desc, ctl) => h('.setting', {}, h('div', {}, h('h3', {}, title), h('p', {}, desc)), h('.ctl', {}, ctl));
469
+ const dis = !admin;
470
+ const name = h('input.input', { value: ws.name, style: 'width:220px', 'aria-label': 'Workspace name', disabled: dis });
471
+ const hook = h('input.input', { type: 'url', placeholder: 'https://hooks.slack.com/services/…', style: 'width:300px', 'aria-label': 'Slack webhook URL', disabled: dis });
472
+ const claudeKey = h('input.input', { type: 'password', placeholder: ws.claude ? 'Key saved' : 'sk-ant-…', style: 'width:240px', 'aria-label': 'Anthropic API key', autocomplete: 'off', disabled: dis });
473
+ const claudeBtn = h('button.btn', { disabled: dis, onclick: () => save({ anthropicKey: claudeKey.value }, claudeKey.value ? 'Claude connected' : 'Claude disconnected') }, ws.claude ? 'Disconnect' : 'Save');
474
+ claudeKey.addEventListener('input', () => { claudeBtn.textContent = ws.claude && !claudeKey.value ? 'Disconnect' : 'Save'; });
475
+ const slackBtn = h('button.btn', { disabled: dis, onclick: () => save({ slackWebhook: hook.value }, hook.value ? 'Slack connected' : 'Slack disconnected') }, ws.slackWebhook ? 'Disconnect' : 'Save');
476
+ hook.addEventListener('input', () => { slackBtn.textContent = ws.slackWebhook && !hook.value ? 'Disconnect' : 'Save'; });
477
+ return [h('h1', {}, 'Settings'), h('p.sub', {}, admin ? `${ws.name} · ${ws.planLabel} plan` : 'Only workspace admins can change these.'),
478
+ h('.card', {},
479
+ setting('Workspace name', 'Shown to your team and on invites.', [name, h('button.btn', { disabled: dis, onclick: () => save({ name: name.value }) }, 'Save')]),
480
+ setting('Company sign-up', ws.domain
481
+ ? `Anyone who signs in with a verified @${ws.domain} address can join without an invite.`
482
+ : 'Not available: this workspace was created from a personal email address. Use invites instead.',
483
+ h('select.input', { style: 'width:150px', 'aria-label': 'Company sign-up', disabled: dis || !ws.domain, onchange: (e) => save({ domainJoin: e.target.value === 'on' }) },
484
+ h('option', { value: 'on', selected: ws.domainJoin }, 'On'), h('option', { value: 'off', selected: !ws.domainJoin }, 'Off'))),
485
+ setting('Default session access', 'How a new session starts. “Private until shared” means nobody sees a session until its host shares it. Hosts can change any session at any time.',
486
+ h('select.input', { style: 'width:190px', 'aria-label': 'Default session access', disabled: dis, onchange: (e) => save({ defaultAccess: e.target.value }) },
487
+ h('option', { value: 'private', selected: ws.defaultAccess === 'private' }, 'Private until shared'), h('option', { value: 'control', selected: ws.defaultAccess === 'control' }, 'Watch and type'), h('option', { value: 'view', selected: ws.defaultAccess === 'view' }, 'Watch only'))),
488
+ setting('Checkpoints', 'While a Claude Code session runs, save its conversation and unpushed code to the workspace, so a teammate can pick it up if the host’s laptop is shut. Ignored files such as .env are never included. Kept for 14 days after a session ends.',
489
+ h('select.input', { style: 'width:150px', 'aria-label': 'Checkpoints', disabled: dis, onchange: (e) => save({ handoff: e.target.value === 'on' }) },
490
+ h('option', { value: 'on', selected: ws.handoff }, 'On'), h('option', { value: 'off', selected: !ws.handoff }, 'Off'))),
491
+ setting('Claude', `From Anthropic. Invited agents give a second opinion in chat (@claude), write catch-up summaries, and steer the host’s agent when the host hands over the wheel. When someone invites one, the visible part of that session is sent to that provider using your key. ${ws.claude ? 'Claude is connected.' : 'Paste an Anthropic API key to turn it on.'}`,
492
+ [claudeKey, claudeBtn]),
493
+ ...['grok', 'muse'].map((id) => {
494
+ const a = ws.agents[id];
495
+ const key = h('input.input', { type: 'password', placeholder: a.connected ? 'Key saved' : 'API key', style: 'width:170px', 'aria-label': `${a.name} API key`, autocomplete: 'off', disabled: dis });
496
+ const model = h('input.input', { value: a.model || '', placeholder: id === 'grok' ? 'Model, e.g. grok-4.7' : 'Model, e.g. muse-spark-1.3', style: 'width:190px', 'aria-label': `${a.name} model`, autocomplete: 'off', disabled: dis });
497
+ return setting(a.name, `${id === 'grok' ? 'From xAI.' : 'From Meta.'} Invite it with @${id}, just like Claude. Enter the model name exactly as the provider lists it. ${a.connected ? `${a.name} is connected.` : ''}`,
498
+ [key, model,
499
+ h('button.btn', { disabled: dis, onclick: () => save({ agent: { id, key: key.value, model: model.value } }, `${a.name} connected`) }, 'Save'),
500
+ a.connected && h('button.btn.ghost', { disabled: dis, onclick: () => save({ agent: { id, key: '', model: '' } }, `${a.name} disconnected`) }, 'Disconnect')]);
501
+ }),
502
+ setting('Slack alerts', `Post to a channel when an agent stops to wait for a human. ${ws.slackWebhook ? 'Currently connected.' : 'Paste a Slack incoming-webhook URL.'}`,
503
+ [hook, slackBtn])),
504
+ h('.h2', {}, 'Your notifications'),
505
+ h('.card.stack', {},
506
+ h('p.muted.small', {}, 'These follow you across the web and the Mac app. Alerts about a stuck agent are taken down automatically once someone answers it.'),
507
+ NOTE_KINDS.map(([k, label]) => h('label.check', {},
508
+ h('input', { type: 'checkbox', checked: me.prefs[k], onchange: async (e) => { try { me.prefs = (await api('PATCH', '/api/me', { prefs: { [k]: e.target.checked } })).prefs; } catch (x) { toast(x.message); } } }), label)),
509
+ 'Notification' in window && h('.row.wrap', { style: 'border-top:1px solid var(--line);padding-top:14px' },
510
+ h('div', {}, h('b', {}, 'Desktop notifications in this browser'), h('div.small.muted', {}, Notification.permission === 'granted' ? 'On. Shown when this tab is in the background.' : Notification.permission === 'denied' ? 'Blocked in your browser settings for this site.' : 'Get alerts while this tab is in the background.')),
511
+ h('span.spacer'),
512
+ Notification.permission === 'default' && h('button.btn.small', { onclick: async () => { await Notification.requestPermission(); reload(); } }, 'Turn on')))];
513
+ }
514
+
515
+ render();
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#1a1613"/><circle cx="11" cy="16" r="4" fill="#f0a35e"/><circle cx="21" cy="16" r="4" fill="none" stroke="#f0a35e" stroke-width="2"/></svg>
package/web/index.html ADDED
@@ -0,0 +1,16 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Agentpen - the team room for your coding agents</title>
7
+ <meta name="description" content="Run Claude Code or Codex as usual. Your whole team can watch, help and unblock it live from a browser.">
8
+ <link rel="icon" href="/favicon.svg">
9
+ <link rel="stylesheet" href="/vendor/xterm.css">
10
+ <link rel="stylesheet" href="/styles.css">
11
+ </head>
12
+ <body>
13
+ <div id="app"></div>
14
+ <script type="module" src="/app.js"></script>
15
+ </body>
16
+ </html>