@profullstack/board-saas 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/src/server.js ADDED
@@ -0,0 +1,258 @@
1
+ // Board as a Service: HTTP API, MCP endpoint, report pages and the public site.
2
+ // The public front page is the copy hosted on the c0mpute network (C0MPUTE_SITE_URL),
3
+ // with the bundled build as the fallback when the gateway does not answer.
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import { createServer } from 'node:http';
6
+ import { extname, join, normalize } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { openDb } from './db.js';
9
+ import { allFooters, startFooterRefresh } from './footers.js';
10
+ import { createModel } from './llm.js';
11
+ import { createMailer } from './mail.js';
12
+ import { createMcpHandler, TOOLS } from './mcp.js';
13
+ import { reportDownload, reportPage, statusPage } from './pages.js';
14
+ import { createService, HttpError, PRICE_USD } from './service.js';
15
+
16
+ const ROOT = fileURLToPath(new URL('..', import.meta.url));
17
+ const VERSION = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version;
18
+ const TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.svg': 'image/svg+xml', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8' };
19
+ const STATIC = new Set(['/index.html', '/style.css', '/app.js']);
20
+
21
+ export const API_DOCS = {
22
+ name: 'Board as a Service API',
23
+ version: VERSION,
24
+ base: 'https://board.saas.pit.world/api/v1',
25
+ auth: 'Authorization: Bearer <key>. Get a key: POST /auth/code {email} then POST /auth/verify {email, code}. Keys are full access to your account; a new verify replaces the old key.',
26
+ pricing: `First meeting free per email, then $${PRICE_USD} per meeting via CoinPay (crypto). A meeting the network cannot finish is refunded.`,
27
+ honesty: 'The advisors are AI models on the c0mpute network, not real directors.',
28
+ endpoints: [
29
+ { method: 'POST', path: '/auth/code', body: { email: 'you@example.com' }, does: 'Email a 6-digit sign-in code.' },
30
+ { method: 'POST', path: '/auth/verify', body: { email: 'you@example.com', code: '123456' }, does: 'Exchange the code for an API key.' },
31
+ { method: 'GET', path: '/account', auth: true, does: 'Free meeting left, paid credits.' },
32
+ { method: 'POST', path: '/meetings', auth: true, body: { brief: 'Decision ... Options ... Constraints ...' }, does: 'Start a meeting. 201 with status queued, or awaiting_payment with checkout_url.' },
33
+ { method: 'GET', path: '/meetings', auth: true, does: 'Your meetings, newest first.' },
34
+ { method: 'GET', path: '/meetings/:id', does: 'Status, progress, and the full meeting when done. The id is the capability; share it like a link.' },
35
+ { method: 'POST', path: '/meetings/:id/clarify', body: { answers: '...' }, does: 'Answer the chair\'s one round of questions (status needs_clarification).' },
36
+ { method: 'GET', path: '/meetings/:id/report.html', does: 'The interactive report as a downloadable file.' },
37
+ { method: 'GET', path: '/meetings/:id/meeting.json', does: 'The meeting data (boardroom meeting.json shape).' },
38
+ ],
39
+ mcp: { endpoint: 'https://board.saas.pit.world/mcp', transport: 'streamable HTTP (JSON responses)', auth: 'Authorization: Bearer <key>', tools: TOOLS.map((t) => t.name), stdio: 'npx -y @profullstack/board-saas mcp' },
40
+ cli: 'npm i -g @profullstack/board-saas (board-saas login | meet | get | list | tui | mcp)',
41
+ };
42
+
43
+ function bearer(req) {
44
+ const h = req.headers.authorization ?? '';
45
+ const m = h.match(/^Bearer\s+(.+)$/i);
46
+ return m ? m[1].trim() : null;
47
+ }
48
+
49
+ function readBody(req, limit = 64 * 1024) {
50
+ return new Promise((resolve, reject) => {
51
+ let size = 0;
52
+ const chunks = [];
53
+ req.on('data', (c) => {
54
+ size += c.length;
55
+ if (size > limit) {
56
+ reject(new HttpError(413, 'body too large'));
57
+ req.destroy();
58
+ } else chunks.push(c);
59
+ });
60
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
61
+ req.on('error', reject);
62
+ });
63
+ }
64
+
65
+ async function jsonBody(req) {
66
+ const raw = await readBody(req);
67
+ if (!raw) return {};
68
+ try {
69
+ return JSON.parse(raw);
70
+ } catch {
71
+ throw new HttpError(400, 'body must be JSON');
72
+ }
73
+ }
74
+
75
+ const CORS = {
76
+ 'access-control-allow-origin': '*',
77
+ 'access-control-allow-headers': 'authorization, content-type, mcp-protocol-version, mcp-session-id',
78
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
79
+ };
80
+
81
+ function send(res, status, body, headers = {}) {
82
+ const isStr = typeof body === 'string';
83
+ res.writeHead(status, {
84
+ 'content-type': isStr ? 'text/html; charset=utf-8' : 'application/json',
85
+ 'x-content-type-options': 'nosniff',
86
+ ...headers,
87
+ });
88
+ res.end(isStr ? body : JSON.stringify(body, null, 1));
89
+ }
90
+
91
+ export function createApp({ env = process.env, db, model, mailer, fetchImpl = fetch, log = console.log } = {}) {
92
+ const publicUrl = (env.PUBLIC_URL || 'https://board.saas.pit.world').replace(/\/+$/, '');
93
+ db ??= openDb(env.BOARD_DB || join(env.HOME || '.', '.local/share/board-saas/board.db'));
94
+ model ??= createModel(env);
95
+ mailer ??= createMailer(env, fetchImpl);
96
+ const service = createService({ db, env, model, mailer, log, publicUrl });
97
+
98
+ const mcp = (key) =>
99
+ createMcpHandler(
100
+ {
101
+ runMeeting: (brief) => service.createMeeting(key, brief),
102
+ getMeeting: async (id) => service.getMeeting(id),
103
+ },
104
+ { version: VERSION },
105
+ );
106
+
107
+ // ------------------------------------------------------------ static site
108
+ const builtDir = join(ROOT, 'site');
109
+ const localDir = existsSync(join(builtDir, 'index.html')) ? builtDir : join(ROOT, 'public');
110
+ const siteUrl = (env.C0MPUTE_SITE_URL || '').replace(/\/*$/, '/');
111
+ const cache = new Map();
112
+
113
+ function localFile(path) {
114
+ let body = readFileSync(join(localDir, path.slice(1)), 'utf8');
115
+ if (path === '/index.html') body = body.replace('<!--FOOTERS-->', allFooters());
116
+ return body;
117
+ }
118
+
119
+ async function staticFile(path) {
120
+ if (env.C0MPUTE_SITE_URL) {
121
+ const hit = cache.get(path);
122
+ if (hit && hit.until > Date.now()) return { body: hit.body, source: 'c0mpute' };
123
+ try {
124
+ const r = await fetchImpl(siteUrl + path.slice(1), { signal: AbortSignal.timeout(5000) });
125
+ if (r.ok) {
126
+ const body = await r.text();
127
+ // Only a copy that is really ours: the gateway can answer 200 with its own pages.
128
+ if (path !== '/index.html' || body.includes('Board as a Service')) {
129
+ cache.set(path, { body, until: Date.now() + 5 * 60_000 });
130
+ return { body, source: 'c0mpute' };
131
+ }
132
+ }
133
+ } catch {
134
+ /* fall back below */
135
+ }
136
+ if (hit) return { body: hit.body, source: 'c0mpute-stale' };
137
+ }
138
+ return { body: localFile(path), source: 'local' };
139
+ }
140
+
141
+ // ---------------------------------------------------------------- routes
142
+ async function route(req, res) {
143
+ const url = new URL(req.url, publicUrl);
144
+ const path = url.pathname;
145
+ const method = req.method;
146
+
147
+ if (method === 'OPTIONS') return send(res, 204, '', CORS);
148
+
149
+ if (path === '/healthz') return send(res, 200, { ok: true, version: VERSION, model: 'c0mpute', ...db.stats() });
150
+
151
+ if (path === '/install.sh') {
152
+ return send(res, 200, `#!/bin/sh\n# Board as a Service CLI: board-saas\nset -e\ncommand -v npm >/dev/null 2>&1 || { echo "board-saas needs Node 22+ and npm: https://nodejs.org" >&2; exit 1; }\nnpm install -g @profullstack/board-saas\necho "installed: run 'board-saas login you@example.com' then 'board-saas meet \\"<brief>\\"'"\n`, { 'content-type': 'text/x-shellscript; charset=utf-8' });
153
+ }
154
+
155
+ if (path === '/robots.txt') return send(res, 200, 'User-agent: *\nAllow: /\nDisallow: /m/\nDisallow: /api/\n', { 'content-type': 'text/plain' });
156
+
157
+ if (path === '/mcp') {
158
+ if (method === 'GET') return send(res, 405, { error: 'POST JSON-RPC messages to this endpoint' }, { ...CORS, allow: 'POST' });
159
+ if (method !== 'POST') return send(res, 405, { error: 'method not allowed' }, CORS);
160
+ const msg = await jsonBody(req);
161
+ const handle = mcp(bearer(req));
162
+ if (Array.isArray(msg)) {
163
+ const out = (await Promise.all(msg.map(handle))).filter(Boolean);
164
+ return out.length ? send(res, 200, out, CORS) : send(res, 202, '', CORS);
165
+ }
166
+ const out = await handle(msg);
167
+ return out ? send(res, 200, out, CORS) : send(res, 202, '', CORS);
168
+ }
169
+
170
+ if (path === '/api/v1/coinpay/webhook' && method === 'POST') {
171
+ const raw = await readBody(req, 256 * 1024);
172
+ const r = service.coinpayWebhook(raw, req.headers['x-coinpay-signature']);
173
+ return send(res, r.status, r.body);
174
+ }
175
+
176
+ if (path.startsWith('/api/')) {
177
+ const key = bearer(req);
178
+ let m;
179
+ if (path === '/api/v1' || path === '/api/v1/' || path === '/api') return send(res, 200, API_DOCS, CORS);
180
+ if (path === '/api/v1/auth/code' && method === 'POST') {
181
+ const b = await jsonBody(req);
182
+ const ip = String(req.headers['x-forwarded-for'] ?? req.socket.remoteAddress ?? '').split(',')[0].trim();
183
+ return send(res, 200, await service.startLogin(b.email, ip), CORS);
184
+ }
185
+ if (path === '/api/v1/auth/verify' && method === 'POST') {
186
+ const b = await jsonBody(req);
187
+ return send(res, 200, service.verifyLogin(b.email, b.code), CORS);
188
+ }
189
+ if (path === '/api/v1/account' && method === 'GET') return send(res, 200, service.account(key), CORS);
190
+ if (path === '/api/v1/meetings' && method === 'POST') {
191
+ const b = await jsonBody(req);
192
+ const v = await service.createMeeting(key, b.brief);
193
+ return send(res, v.status === 'awaiting_payment' ? 402 : 201, v, CORS);
194
+ }
195
+ if (path === '/api/v1/meetings' && method === 'GET') return send(res, 200, { meetings: service.listMeetings(key) }, CORS);
196
+ if ((m = path.match(/^\/api\/v1\/meetings\/([\w-]{8,40})$/)) && method === 'GET') return send(res, 200, service.getMeeting(m[1]), CORS);
197
+ if ((m = path.match(/^\/api\/v1\/meetings\/([\w-]{8,40})\/clarify$/)) && method === 'POST') {
198
+ const b = await jsonBody(req);
199
+ return send(res, 200, service.clarify(key, m[1], b.answers), CORS);
200
+ }
201
+ if ((m = path.match(/^\/api\/v1\/meetings\/([\w-]{8,40})\/(report\.html|meeting\.json)$/)) && method === 'GET') {
202
+ const v = service.getMeeting(m[1]);
203
+ if (v.status !== 'done') throw new HttpError(409, `the meeting is ${v.status}; the report exists once it is done`);
204
+ const slug = v.meeting.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 50) || 'meeting';
205
+ if (m[2] === 'meeting.json') return send(res, 200, v.meeting, { ...CORS, 'content-disposition': `inline; filename="${slug}.json"` });
206
+ return send(res, 200, reportDownload(v), { ...CORS, 'content-disposition': `attachment; filename="board-${v.meeting.date}-${slug}.html"` });
207
+ }
208
+ throw new HttpError(404, 'no such endpoint; see /api/v1');
209
+ }
210
+
211
+ if ((method === 'GET' || method === 'HEAD') && path.startsWith('/m/')) {
212
+ const id = path.slice(3).replace(/\/$/, '');
213
+ let v;
214
+ try {
215
+ v = service.getMeeting(id);
216
+ } catch {
217
+ return send(res, 404, '<!doctype html><title>Not found</title><p>No meeting with that link. <a href="/">Board as a Service</a></p>');
218
+ }
219
+ return send(res, 200, v.status === 'done' ? reportPage(v) : statusPage(v), { 'cache-control': 'no-store', 'x-robots-tag': 'noindex' });
220
+ }
221
+
222
+ if (method === 'GET' || method === 'HEAD') {
223
+ const p = path === '/' ? '/index.html' : normalize(path);
224
+ if (STATIC.has(p)) {
225
+ const { body, source } = await staticFile(p);
226
+ return send(res, 200, body, { 'content-type': TYPES[extname(p)], 'x-board-source': source, 'cache-control': 'public, max-age=300' });
227
+ }
228
+ }
229
+ return send(res, 404, '<!doctype html><title>Not found</title><p>Not found. <a href="/">Board as a Service</a></p>');
230
+ }
231
+
232
+ async function handler(req, res) {
233
+ try {
234
+ await route(req, res);
235
+ } catch (e) {
236
+ const status = e instanceof HttpError ? e.status : e?.status && e.status < 600 ? e.status : 500;
237
+ if (status >= 500) log(`error ${req.method} ${req.url}: ${e?.stack ?? e}`);
238
+ if (!res.headersSent) send(res, status, { error: status >= 500 && !(e instanceof HttpError) ? `server error: ${e.message}` : e.message, ...(e.extra ?? {}) }, CORS);
239
+ }
240
+ }
241
+
242
+ return { handler, service, db };
243
+ }
244
+
245
+ export function startServer(env = process.env) {
246
+ if (!env.C0MPUTE_API_KEY) console.warn('warning: C0MPUTE_API_KEY is not set; c0mpute gives 10 free queries a day without a key');
247
+ const app = createApp({ env });
248
+ startFooterRefresh();
249
+ app.service.resume();
250
+ const port = Number(env.PORT) || 8826;
251
+ const host = env.HOST || '127.0.0.1';
252
+ const server = createServer(app.handler);
253
+ server.requestTimeout = 120_000;
254
+ server.listen(port, host, () => console.log(`board-saas ${VERSION} on http://${host}:${port}`));
255
+ return server;
256
+ }
257
+
258
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) startServer();
package/src/service.js ADDED
@@ -0,0 +1,281 @@
1
+ // Business logic shared by the HTTP API, the MCP endpoint and the worker.
2
+ // Meeting statuses:
3
+ // awaiting_payment -> queued -> checking -> (needs_clarification -> queued -> checking) -> running -> done | failed
4
+ import { CoinPay, readWebhook, verifyWebhook } from '@profullstack/coinpay-onboard';
5
+ import { timingSafeEqual } from 'node:crypto';
6
+ import { assumptionsFor, checkBrief, clarifyingQuestions, MAX_BRIEF, runMeeting } from './meeting.js';
7
+ import { codeEmail, meetingDoneEmail } from './mail.js';
8
+
9
+ export const PRICE_USD = 9;
10
+
11
+ export class HttpError extends Error {
12
+ constructor(status, message, extra = {}) {
13
+ super(message);
14
+ this.status = status;
15
+ this.extra = extra;
16
+ }
17
+ }
18
+
19
+ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
20
+ export function normalizeEmail(v) {
21
+ const e = String(v ?? '').trim().toLowerCase();
22
+ if (!EMAIL_RE.test(e) || e.length > 200) throw new HttpError(400, 'a valid email address is required');
23
+ return e;
24
+ }
25
+
26
+ function safeEqual(a, b) {
27
+ const x = Buffer.from(String(a));
28
+ const y = Buffer.from(String(b));
29
+ return x.length === y.length && timingSafeEqual(x, y);
30
+ }
31
+
32
+ export function createService({ db, env = process.env, model, mailer, log = console.log, publicUrl = 'https://board.saas.pit.world' }) {
33
+ const coinpay = env.COINPAY_API_KEY ? new CoinPay({ token: env.COINPAY_API_KEY, base: env.COINPAY_API_URL || undefined }) : null;
34
+ const running = new Set();
35
+ const maxRunning = Number(env.BOARD_MAX_MEETINGS) || 2;
36
+ const ipCodes = new Map();
37
+
38
+ const urlFor = (id) => `${publicUrl}/m/${id}`;
39
+
40
+ /** Bearer key -> { admin } | { account } | null. */
41
+ function actorFor(key) {
42
+ if (!key) return null;
43
+ if (env.BOARD_SAAS_ADMIN_KEY && safeEqual(key, env.BOARD_SAAS_ADMIN_KEY)) return { admin: true, account: null };
44
+ const account = db.accountByKey(key);
45
+ return account ? { admin: false, account } : null;
46
+ }
47
+
48
+ function requireActor(key) {
49
+ const a = actorFor(key);
50
+ if (!a) throw new HttpError(401, 'sign in first: POST /api/v1/auth/code with your email, then /api/v1/auth/verify with the code, and send the key as "Authorization: Bearer <key>"');
51
+ return a;
52
+ }
53
+
54
+ async function startLogin(emailIn, ip = '') {
55
+ const email = normalizeEmail(emailIn);
56
+ const hour = Math.floor(Date.now() / 3_600_000);
57
+ const k = `${ip}:${hour}`;
58
+ const n = (ipCodes.get(k) ?? 0) + 1;
59
+ ipCodes.set(k, n);
60
+ if (ipCodes.size > 5000) ipCodes.clear();
61
+ if (n > 10) throw new HttpError(429, 'too many codes from this address this hour; try again later');
62
+ if (!mailer) throw new HttpError(503, 'email is not configured on this server, so sign-in codes cannot be sent');
63
+ const code = db.newLoginCode(email);
64
+ if (!code) return { sent: false, email, message: 'a code was sent less than a minute ago; check your inbox' };
65
+ await mailer({ to: email, ...codeEmail(code) });
66
+ return { sent: true, email, message: 'check your email for a 6-digit code (valid 15 minutes)' };
67
+ }
68
+
69
+ function verifyLogin(emailIn, code) {
70
+ const email = normalizeEmail(emailIn);
71
+ if (!db.checkLoginCode(email, code)) throw new HttpError(401, 'that code is wrong or expired; ask for a new one');
72
+ const account = db.ensureAccount(email);
73
+ const apiKey = db.rotateKey(account.id);
74
+ return { api_key: apiKey, account: accountView(db.accountById(account.id)) };
75
+ }
76
+
77
+ function accountView(a) {
78
+ return { id: a.id, email: a.email, free_meeting_available: !a.free_used, credits: a.credits, price_usd: PRICE_USD };
79
+ }
80
+
81
+ function meetingView(row) {
82
+ if (!row) return null;
83
+ const v = {
84
+ id: row.id,
85
+ status: row.status,
86
+ url: urlFor(row.id),
87
+ created_at: new Date(row.created_at).toISOString(),
88
+ updated_at: new Date(row.updated_at).toISOString(),
89
+ finished_at: row.finished_at ? new Date(row.finished_at).toISOString() : null,
90
+ progress: row.progress ? JSON.parse(row.progress) : null,
91
+ brief_text: row.brief_text,
92
+ };
93
+ if (row.status === 'needs_clarification') {
94
+ const b = row.brief_json ? JSON.parse(row.brief_json) : { missing: [] };
95
+ v.clarify = { missing: b.missing, questions: clarifyingQuestions(b.missing), how: `POST /api/v1/meetings/${row.id}/clarify {"answers":"..."} (asked once; unanswered gaps become assumptions)` };
96
+ }
97
+ if (row.status === 'awaiting_payment') {
98
+ v.checkout_url = row.checkout_url;
99
+ v.price_usd = PRICE_USD;
100
+ }
101
+ if (row.status === 'failed') v.error = row.error;
102
+ if (row.status === 'done') {
103
+ v.report_url = `${publicUrl}/m/${row.id}`;
104
+ v.download_url = `${publicUrl}/api/v1/meetings/${row.id}/report.html`;
105
+ v.json_url = `${publicUrl}/api/v1/meetings/${row.id}/meeting.json`;
106
+ v.meeting = JSON.parse(row.meeting_json);
107
+ }
108
+ return v;
109
+ }
110
+
111
+ async function createMeeting(key, briefIn) {
112
+ const actor = requireActor(key);
113
+ const briefText = String(briefIn ?? '').trim();
114
+ if (briefText.length < 20) throw new HttpError(400, 'the brief is too short: give the decision, the options and the constraints');
115
+ if (briefText.length > MAX_BRIEF) throw new HttpError(400, `the brief is too long (max ${MAX_BRIEF} characters)`);
116
+ if (actor.admin) {
117
+ const row = db.createMeeting({ accountId: null, briefText, status: 'queued', paidWith: 'admin' });
118
+ kick();
119
+ return meetingView(row);
120
+ }
121
+ const spent = db.spend(actor.account.id);
122
+ if (spent) {
123
+ const row = db.createMeeting({ accountId: actor.account.id, briefText, status: 'queued', paidWith: spent });
124
+ kick();
125
+ return meetingView(row);
126
+ }
127
+ if (!coinpay) throw new HttpError(503, 'payments are not configured on this server');
128
+ const row = db.createMeeting({ accountId: actor.account.id, briefText, status: 'awaiting_payment' });
129
+ const session = await coinpay.createCheckoutSession({
130
+ amount: PRICE_USD,
131
+ description: 'Board as a Service: one board meeting',
132
+ customerEmail: actor.account.email,
133
+ accountId: actor.account.id,
134
+ property: 'board.saas.pit.world',
135
+ metadata: { meeting_id: row.id },
136
+ successUrl: urlFor(row.id),
137
+ cancelUrl: `${publicUrl}/`,
138
+ expiresInMinutes: 120,
139
+ idempotencyKey: `board-${row.id}`,
140
+ });
141
+ db.updateMeeting(row.id, { checkout_id: session.id, checkout_url: session.url });
142
+ return meetingView(db.meeting(row.id));
143
+ }
144
+
145
+ function getMeeting(id) {
146
+ const row = db.meeting(String(id ?? ''));
147
+ if (!row) throw new HttpError(404, 'no meeting with that id');
148
+ return meetingView(row);
149
+ }
150
+
151
+ function listMeetings(key) {
152
+ const actor = requireActor(key);
153
+ if (actor.admin) return [];
154
+ return db.meetingsFor(actor.account.id).map((r) => ({
155
+ id: r.id,
156
+ status: r.status,
157
+ url: urlFor(r.id),
158
+ brief: r.brief_text.slice(0, 140),
159
+ created_at: new Date(r.created_at).toISOString(),
160
+ }));
161
+ }
162
+
163
+ function account(key) {
164
+ const actor = requireActor(key);
165
+ if (actor.admin) return { admin: true, free_meeting_available: true, credits: 'unlimited', price_usd: PRICE_USD };
166
+ return accountView(db.accountById(actor.account.id));
167
+ }
168
+
169
+ // The meeting id is the capability (96 random bits, only its owner has it until they share
170
+ // the link), so answering the chair's one question needs the id, not a key. A key that is
171
+ // given must belong to the owner.
172
+ function clarify(key, id, answersIn) {
173
+ const actor = key ? requireActor(key) : null;
174
+ const row = db.meeting(String(id));
175
+ if (!row) throw new HttpError(404, 'no meeting with that id');
176
+ if (actor && !actor.admin && row.account_id !== actor.account.id) throw new HttpError(403, 'this meeting belongs to another account');
177
+ if (row.status !== 'needs_clarification') throw new HttpError(409, `this meeting is ${row.status}, not waiting for answers`);
178
+ const answers = String(answersIn ?? '').trim().slice(0, 3000);
179
+ if (!db.transition(row.id, 'needs_clarification', 'queued', { answers, clarified: 1 })) throw new HttpError(409, 'already answered');
180
+ kick();
181
+ return meetingView(db.meeting(row.id));
182
+ }
183
+
184
+ /** CoinPay webhook. Returns { status, body }. */
185
+ function coinpayWebhook(rawBody, signature) {
186
+ if (!env.COINPAY_WEBHOOK_SECRET || !verifyWebhook(rawBody, signature, env.COINPAY_WEBHOOK_SECRET)) {
187
+ return { status: 401, body: { error: 'bad signature' } };
188
+ }
189
+ let payload;
190
+ try {
191
+ payload = JSON.parse(rawBody);
192
+ } catch {
193
+ return { status: 400, body: { error: 'bad json' } };
194
+ }
195
+ const ev = readWebhook(payload);
196
+ if (!ev.paid) return { status: 200, body: { ok: true, ignored: ev.type || 'not paid' } };
197
+ const meetingId = ev.metadata?.meeting_id;
198
+ const row = (meetingId && db.meeting(String(meetingId))) || (ev.checkoutSessionId && db.meetingByCheckout(ev.checkoutSessionId));
199
+ if (!row) return { status: 200, body: { ok: true, ignored: 'no matching meeting' } };
200
+ const fresh = db.recordPayment({ eventId: ev.eventId || `${ev.checkoutSessionId}:${ev.paymentId}`, meetingId: row.id, checkoutId: ev.checkoutSessionId, amountUsd: ev.amountUsd, raw: rawBody.slice(0, 20_000) });
201
+ if (!fresh) return { status: 200, body: { ok: true, duplicate: true } };
202
+ if (db.transition(row.id, 'awaiting_payment', 'queued', { paid_with: 'coinpay' })) {
203
+ log(`meeting ${row.id}: paid (${ev.type}), queued`);
204
+ kick();
205
+ } else if (row.account_id) {
206
+ // Paid twice or after the meeting moved on: keep the money as a credit, never lose it.
207
+ db.refund(row.account_id, 'credit');
208
+ log(`meeting ${row.id}: extra payment kept as a credit`);
209
+ }
210
+ return { status: 200, body: { ok: true } };
211
+ }
212
+
213
+ // ---------------------------------------------------------------- worker
214
+
215
+ function kick() {
216
+ setImmediate(pump);
217
+ }
218
+
219
+ function pump() {
220
+ if (running.size >= maxRunning) return;
221
+ for (const row of db.meetingsInStatus('queued')) {
222
+ if (running.size >= maxRunning) break;
223
+ if (!db.transition(row.id, 'queued', 'checking', { progress: JSON.stringify({ stage: 'checking' }) })) continue;
224
+ running.add(row.id);
225
+ work(row.id)
226
+ .catch((e) => log(`meeting ${row.id}: worker crashed: ${e?.stack ?? e}`))
227
+ .finally(() => {
228
+ running.delete(row.id);
229
+ kick();
230
+ });
231
+ }
232
+ }
233
+
234
+ async function work(id) {
235
+ const row = db.meeting(id);
236
+ const mlog = (m) => log(`meeting ${id}: ${m}`);
237
+ try {
238
+ const check = await checkBrief(model, row.brief_text, { answers: row.clarified ? row.answers : null, log: mlog });
239
+ if (check.missing.length && !row.clarified) {
240
+ db.transition(id, 'checking', 'needs_clarification', { brief_json: JSON.stringify(check), progress: JSON.stringify({ stage: 'needs_clarification' }) });
241
+ mlog(`asking once for: ${check.missing.join(', ')}`);
242
+ return;
243
+ }
244
+ const brief = {
245
+ text: row.clarified && row.answers ? `${row.brief_text}\n\nClarification: ${row.answers}` : row.brief_text,
246
+ decision: check.decision || row.brief_text.slice(0, 200),
247
+ options:
248
+ check.options.length >= 2
249
+ ? check.options
250
+ : [check.options[0] || 'Go ahead with what the brief describes', 'Do nothing for now'],
251
+ constraints: check.constraints,
252
+ assumptions: assumptionsFor(check.missing),
253
+ };
254
+ db.transition(id, 'checking', 'running', { brief_json: JSON.stringify(brief), progress: JSON.stringify({ stage: 'round1', done: 0, of: 5 }) });
255
+ const meeting = await runMeeting(model, brief, {
256
+ log: mlog,
257
+ onProgress: (stage, detail) => db.updateMeeting(id, { progress: JSON.stringify({ stage, ...detail }) }),
258
+ });
259
+ db.transition(id, 'running', 'done', { meeting_json: JSON.stringify(meeting), finished_at: Date.now(), progress: JSON.stringify({ stage: 'done' }) });
260
+ mlog('done');
261
+ const acct = row.account_id ? db.accountById(row.account_id) : null;
262
+ if (acct && mailer) mailer({ to: acct.email, ...meetingDoneEmail(meeting, urlFor(id)) }).catch((e) => mlog(`done email failed: ${e.message}`));
263
+ } catch (e) {
264
+ const msg = e?.code === 'bad_json'
265
+ ? `The c0mpute model did not return usable JSON after one retry (${e.message}). Nothing was made up; your meeting was refunded.`
266
+ : `c0mpute could not finish this meeting: ${e?.message ?? e}. Nothing was made up; your meeting was refunded.`;
267
+ const cur = db.meeting(id);
268
+ db.updateMeeting(id, { status: 'failed', error: msg, finished_at: Date.now() });
269
+ if (cur.account_id && cur.paid_with && cur.paid_with !== 'admin') db.refund(cur.account_id, cur.paid_with === 'free' ? 'free' : 'credit');
270
+ mlog(`failed: ${e?.message ?? e}${e?.raw ? ` raw=${JSON.stringify(e.raw.slice(0, 1500))}` : ''}`);
271
+ }
272
+ }
273
+
274
+ /** On boot, meetings a restart interrupted start over. */
275
+ function resume() {
276
+ for (const s of ['checking', 'running']) for (const r of db.meetingsInStatus(s)) db.transition(r.id, s, 'queued');
277
+ kick();
278
+ }
279
+
280
+ return { actorFor, startLogin, verifyLogin, createMeeting, getMeeting, listMeetings, account, clarify, coinpayWebhook, resume, kick, meetingView, urlFor };
281
+ }
package/src/tui.js ADDED
@@ -0,0 +1,119 @@
1
+ // board-saas tui: your meetings on the left, the selected meeting's minutes on the right.
2
+ // Built with @profullstack/hqtui. Keys: up/down select, r refresh, n new meeting, q quit.
3
+ import { createInterface } from 'node:readline/promises';
4
+
5
+ export function detailLines(v) {
6
+ if (!v) return ['Select a meeting.'];
7
+ const out = [`Status: ${v.status}${v.progress?.stage && v.status !== 'done' ? ` (${v.progress.stage}${v.progress.of ? ` ${v.progress.done}/${v.progress.of}` : ''})` : ''}`, `Link: ${v.url}`, ''];
8
+ if (v.checkout_url) out.push(`Pay $${v.price_usd} to start: ${v.checkout_url}`, '');
9
+ if (v.clarify) out.push('The chair asks (once):', ...v.clarify.questions.map((q) => ` - ${q.question}`), `Answer: board-saas clarify ${v.id} "<answers>"`, '');
10
+ if (v.error) out.push(`Error: ${v.error}`, '');
11
+ if (v.meeting) {
12
+ const m = v.meeting;
13
+ out.push(m.title, '', `Decision: ${m.brief.decision}`, '', 'Vote after the debate:');
14
+ for (const x of m.minutes.vote) out.push(` ${x.expert.padEnd(13)} ${x.final}${x.changed ? ' [changed mind]' : ''}`);
15
+ out.push('', `Majority: ${m.minutes.majority}`, '', 'Where they clashed:');
16
+ for (const c of m.minutes.clashes) out.push(` - ${c.topic}: ${c.sides}. Crux: ${c.crux}`);
17
+ out.push('', `Strongest dissent (${m.minutes.dissent.expert}): ${m.minutes.dissent.argument}`, '', `Recommendation: ${m.minutes.recommendation}`, '', `The one question: ${m.minutes.question}`, '', `Report: ${v.report_url}`);
18
+ } else {
19
+ out.push('Brief:', v.brief_text ?? '');
20
+ }
21
+ return out;
22
+ }
23
+
24
+ export function view(state) {
25
+ return ({ ui }) => {
26
+ ui.column({}, (col) => {
27
+ col.grid({ columns: ['1fr', '2fr'], rows: ['1fr'], gap: 0, size: '1fr' }, (g) => {
28
+ g.panel({ title: 'Meetings' }, (p) => {
29
+ if (!state.list.length) p.text(state.error || 'No meetings yet. Press n to convene the board.');
30
+ else
31
+ p.list({
32
+ items: state.list.map((m) => ({ label: `${m.created_at.slice(5, 16).replace('T', ' ')} ${m.brief.replace(/\s+/g, ' ').slice(0, 40)}`, badge: m.status })),
33
+ selected: state.selected,
34
+ followSelection: true,
35
+ });
36
+ });
37
+ g.panel({ title: state.detail?.meeting?.title ?? 'Meeting' }, (p) => {
38
+ p.text(detailLines(state.detail).join('\n'), { wrap: true, scroll: state.scroll || 0 });
39
+ });
40
+ });
41
+ col.statusBar({
42
+ items: [
43
+ { key: 'up/down', label: 'select' },
44
+ { key: 'pgup/pgdn', label: 'scroll' },
45
+ { key: 'r', label: 'refresh' },
46
+ { key: 'n', label: 'new meeting' },
47
+ { key: 'q', label: 'quit' },
48
+ ],
49
+ right: [{ label: state.account ? `${state.account.email ?? 'admin'} - ${state.account.free_meeting_available ? 'free meeting ready' : `${state.account.credits} credit(s)`}` : 'Board as a Service' }],
50
+ });
51
+ });
52
+ };
53
+ }
54
+
55
+ export async function runTui(client) {
56
+ if (!client.key) {
57
+ process.stderr.write('not signed in: run board-saas login <email> first\n');
58
+ return;
59
+ }
60
+ const { createApp } = await import('@profullstack/hqtui');
61
+ const state = { list: [], selected: 0, detail: null, account: null, error: '', scroll: 0 };
62
+
63
+ async function refresh() {
64
+ try {
65
+ state.account = await client.account();
66
+ state.list = await client.listMeetings();
67
+ state.selected = Math.min(state.selected, Math.max(0, state.list.length - 1));
68
+ state.detail = state.list[state.selected] ? await client.getMeeting(state.list[state.selected].id) : null;
69
+ state.error = '';
70
+ } catch (e) {
71
+ state.error = `Could not reach the API: ${e.message}`;
72
+ }
73
+ }
74
+
75
+ for (;;) {
76
+ await refresh();
77
+ const app = await createApp();
78
+ let next = 'quit';
79
+ app.render(view(state));
80
+ const timer = setInterval(() => refresh().then(() => app.invalidate()), 5000);
81
+ app.on('key', (k) => {
82
+ if (k.key === 'q' || k.key === 'ctrl+c' || k.name === 'escape') app.stop();
83
+ else if (k.name === 'up' || k.name === 'down') {
84
+ state.selected = Math.max(0, Math.min(state.list.length - 1, state.selected + (k.name === 'up' ? -1 : 1)));
85
+ state.scroll = 0;
86
+ const m = state.list[state.selected];
87
+ if (m) client.getMeeting(m.id).then((d) => { state.detail = d; app.invalidate(); }, () => {});
88
+ app.invalidate();
89
+ } else if (k.name === 'pagedown' || k.name === 'pageup') {
90
+ state.scroll = Math.max(0, (state.scroll || 0) + (k.name === 'pagedown' ? 10 : -10));
91
+ app.invalidate();
92
+ } else if (k.key === 'r') refresh().then(() => app.invalidate());
93
+ else if (k.key === 'n') {
94
+ next = 'new';
95
+ app.stop();
96
+ }
97
+ });
98
+ await app.start();
99
+ clearInterval(timer);
100
+ if (next !== 'new') return;
101
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
102
+ const brief = (await rl.question('Brief (decision, options, constraints; Enter to cancel):\n> ')).trim();
103
+ rl.close();
104
+ if (brief) {
105
+ try {
106
+ const v = await client.runMeeting(brief);
107
+ if (v.status === 'awaiting_payment') {
108
+ process.stdout.write(`Pay $${v.price_usd} to start it: ${v.checkout_url}\nPress Enter to go back.`);
109
+ const r2 = createInterface({ input: process.stdin, output: process.stdout });
110
+ await r2.question('');
111
+ r2.close();
112
+ }
113
+ state.selected = 0;
114
+ } catch (e) {
115
+ process.stdout.write(`Could not start: ${e.message}\n`);
116
+ }
117
+ }
118
+ }
119
+ }