mandrel 2.124.0 → 2.125.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.
Files changed (54) hide show
  1. package/.agents/docs/agentrc-reference.json +1 -0
  2. package/.agents/docs/configuration.md +2 -0
  3. package/.agents/docs/runbooks/dispatch-board.md +174 -0
  4. package/.agents/docs/runbooks/dispatch.md +219 -0
  5. package/.agents/docs/runbooks/session-titles.md +52 -0
  6. package/.agents/schemas/agentrc.schema.json +60 -0
  7. package/.agents/scripts/acceptance-eval.js +11 -2
  8. package/.agents/scripts/dispatch.js +400 -0
  9. package/.agents/scripts/lib/child-detached.js +48 -0
  10. package/.agents/scripts/lib/child-exec.js +11 -0
  11. package/.agents/scripts/lib/config/delivery-routing.js +15 -12
  12. package/.agents/scripts/lib/config/temp-paths.js +26 -0
  13. package/.agents/scripts/lib/config-settings-schema-delivery.js +45 -0
  14. package/.agents/scripts/lib/dispatch/environments.js +135 -0
  15. package/.agents/scripts/lib/dispatch/launch-cloud.js +164 -0
  16. package/.agents/scripts/lib/dispatch/launch-local.js +77 -0
  17. package/.agents/scripts/lib/dispatch/liveness.js +21 -0
  18. package/.agents/scripts/lib/dispatch/record.js +54 -0
  19. package/.agents/scripts/lib/dispatch/status.js +285 -0
  20. package/.agents/scripts/lib/dispatch/targets.js +101 -0
  21. package/.agents/scripts/lib/dispatch/verdict.js +207 -0
  22. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  23. package/.agents/scripts/lib/observability/source-classifier.js +2 -0
  24. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +2 -0
  25. package/.agents/scripts/lib/orchestration/story-handoff.js +6 -0
  26. package/.agents/scripts/lib/orchestration/story-stage-publish.js +147 -0
  27. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  28. package/.agents/scripts/session-title.js +187 -0
  29. package/.agents/scripts/single-story-confirm-merge.js +7 -0
  30. package/.agents/scripts/single-story-init.js +3 -0
  31. package/.agents/workflows/helpers/audit-lens-core.md +4 -0
  32. package/.agents/workflows/helpers/deliver-light.md +4 -1
  33. package/.agents/workflows/helpers/qa-core.md +2 -0
  34. package/.agents/workflows/mandrel-deliver.md +7 -3
  35. package/.agents/workflows/mandrel-orchestrate.md +2 -0
  36. package/.agents/workflows/mandrel-plan.md +4 -0
  37. package/README.md +8 -0
  38. package/bin/mandrel.js +35 -13
  39. package/docs/CHANGELOG.md +14 -0
  40. package/lib/cli/dispatch.js +27 -0
  41. package/lib/cli/ui/accounts.js +81 -0
  42. package/lib/cli/ui/board-model.js +372 -0
  43. package/lib/cli/ui/board.css +525 -0
  44. package/lib/cli/ui/board.html +80 -0
  45. package/lib/cli/ui/board.js +676 -0
  46. package/lib/cli/ui/log-tail.js +89 -0
  47. package/lib/cli/ui/panel-model.js +100 -0
  48. package/lib/cli/ui/preferences.js +136 -0
  49. package/lib/cli/ui/request-guard.js +108 -0
  50. package/lib/cli/ui/server.js +211 -0
  51. package/lib/cli/ui/sources.js +202 -0
  52. package/lib/cli/ui/story-detail.js +92 -0
  53. package/lib/cli/ui.js +114 -0
  54. package/package.json +1 -1
@@ -0,0 +1,89 @@
1
+ // lib/cli/ui/log-tail.js
2
+ /**
3
+ * The last lines of a dispatched delivery's log, one readable line per
4
+ * event. A log is read only when its recorded path resolves inside the
5
+ * dispatch directory, and only its last 64 KiB.
6
+ *
7
+ * @module cli/ui/log-tail
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ const TAIL_BYTES = 64 * 1024;
14
+ const TAIL_LINES = 50;
15
+ const TEXT_MAX = 200;
16
+ const ARG_MAX = 120;
17
+
18
+ const oneLine = (text, max) =>
19
+ String(text).replace(/\s+/g, ' ').trim().slice(0, max);
20
+
21
+ function blockLine(block) {
22
+ if (block?.type === 'text') return oneLine(block.text ?? '', TEXT_MAX);
23
+ if (block?.type !== 'tool_use') return '';
24
+ const input = block.input ?? {};
25
+ const arg = input.command ?? input.file_path ?? input.path ?? '';
26
+ return oneLine(`tool: ${block.name} ${oneLine(arg, ARG_MAX)}`, TEXT_MAX);
27
+ }
28
+
29
+ /**
30
+ * The readable lines one log line becomes: assistant text and tool calls,
31
+ * a result's subtype, a non-JSON line as it is; any other event is dropped.
32
+ *
33
+ * @param {string} line
34
+ * @returns {string[]}
35
+ */
36
+ function summarizeLine(line) {
37
+ let event;
38
+ try {
39
+ event = JSON.parse(line);
40
+ } catch {
41
+ const raw = line.slice(0, TEXT_MAX);
42
+ return raw.trim() ? [raw] : [];
43
+ }
44
+ if (event?.type === 'result') return [`result: ${event.subtype}`];
45
+ if (event?.type !== 'assistant') return [];
46
+ const content = event.message?.content;
47
+ return (Array.isArray(content) ? content : []).map(blockLine).filter(Boolean);
48
+ }
49
+
50
+ /** Whether `file` resolves inside `dir`. */
51
+ function isInside(dir, file) {
52
+ const rel = path.relative(path.resolve(dir), path.resolve(file));
53
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
54
+ }
55
+
56
+ function readLastBytes(file, fsImpl) {
57
+ const fd = fsImpl.openSync(file, 'r');
58
+ try {
59
+ const { size } = fsImpl.fstatSync(fd);
60
+ const length = Math.min(size, TAIL_BYTES);
61
+ const buffer = Buffer.alloc(length);
62
+ fsImpl.readSync(fd, buffer, 0, length, size - length);
63
+ return { text: buffer.toString('utf8'), partial: size > length };
64
+ } finally {
65
+ fsImpl.closeSync(fd);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * At most 50 summarized lines from the end of `logPath`; `[]` when the path
71
+ * is missing, outside `dir`, or unreadable.
72
+ *
73
+ * @param {string|null|undefined} logPath
74
+ * @param {{ dir: string, fsImpl?: typeof fs }} opts
75
+ * @returns {string[]}
76
+ */
77
+ export function readLogTail(logPath, { dir, fsImpl = fs }) {
78
+ if (typeof logPath !== 'string' || !isInside(dir, logPath)) return [];
79
+ let tail;
80
+ try {
81
+ tail = readLastBytes(logPath, fsImpl);
82
+ } catch {
83
+ return [];
84
+ }
85
+ const lines = tail.text.split(/\r?\n/);
86
+ // A cut-off first line is the end of an event, not one.
87
+ if (tail.partial) lines.shift();
88
+ return lines.flatMap(summarizeLine).slice(-TAIL_LINES);
89
+ }
@@ -0,0 +1,100 @@
1
+ // lib/cli/ui/panel-model.js
2
+ /**
3
+ * The side panel's view model: which view a header button or card opens,
4
+ * and the Connections view built from `/api/connections`. Pure and
5
+ * import-free, so it runs in the browser and under `node --test`.
6
+ *
7
+ * @module cli/ui/panel-model
8
+ */
9
+
10
+ const CLOUD_NOTE =
11
+ 'Local launches run as these accounts. A cloud environment runs as its routine owner.';
12
+
13
+ /** The view to show after `requested` is asked for: the open one again closes. */
14
+ export function nextPanelView(open, requested) {
15
+ return open === requested ? null : requested;
16
+ }
17
+
18
+ /** The Story id a `story-<id>` view shows, or `null` for any other view. */
19
+ export function storyOfView(view) {
20
+ return view?.startsWith('story-') ? Number(view.slice(6)) : null;
21
+ }
22
+
23
+ /**
24
+ * The header buttons' badge, labels and Connections tint.
25
+ *
26
+ * @param {number} offline Offline environment count.
27
+ * @param {object|null} connections A `/api/connections` response.
28
+ */
29
+ export function headerView(offline, connections) {
30
+ const { ok } = connectionsView(connections);
31
+ const status = ok ? 'connected' : 'needs attention';
32
+ return {
33
+ badge: offline > 0 ? String(offline) : '',
34
+ environments:
35
+ offline > 0 ? `Environments, ${offline} offline` : 'Environments',
36
+ connections: `Connections: ${status}`,
37
+ ok,
38
+ };
39
+ }
40
+
41
+ /** An Environments card's rows from an `environmentCards` entry. */
42
+ export function environmentRows(env) {
43
+ return [
44
+ ['Target', env.target],
45
+ ['Load', env.load],
46
+ ['State', env.online ? 'online' : `offline (${env.reason})`],
47
+ ['Defined in', env.definedIn],
48
+ ['Stories', env.stories.map((id) => `#${id}`).join(', ') || 'none'],
49
+ ];
50
+ }
51
+
52
+ function githubRows(github) {
53
+ return [
54
+ ['Login', github.login ?? 'unavailable', 'connections-github-login'],
55
+ ['Token', github.ok ? `from ${github.source}` : 'not found'],
56
+ ['Status', github.ok ? 'connected' : 'not connected'],
57
+ ];
58
+ }
59
+
60
+ function claudeRows(account) {
61
+ if (!account) {
62
+ return [['Account', 'not signed in', 'connections-claude-account']];
63
+ }
64
+ return [
65
+ ['Account', account.email ?? 'unknown', 'connections-claude-account'],
66
+ ['Org', account.orgName],
67
+ ['Plan', account.subscriptionType],
68
+ ['Login method', account.authMethod],
69
+ ['API provider', account.apiProvider],
70
+ ].filter(([, value]) => value !== undefined);
71
+ }
72
+
73
+ function environmentLine(env) {
74
+ const state = env.online ? 'online' : `offline (${env.reason})`;
75
+ if (!env.routine) return `${env.name}: ${state}`;
76
+ return `${env.name}: ${state}, runs as the routine owner (routine ${env.routine})`;
77
+ }
78
+
79
+ /**
80
+ * The Connections view and the header tint (`ok`).
81
+ *
82
+ * @param {object|null} connections A `/api/connections` response.
83
+ */
84
+ export function connectionsView(connections) {
85
+ const github = connections?.github ?? { ok: false, source: null };
86
+ const claude = connections?.claude ?? { ok: false, account: null };
87
+ return {
88
+ ok: Boolean(connections) && github.ok && claude.ok,
89
+ sections: [
90
+ { title: 'GitHub', rows: githubRows(github) },
91
+ { title: 'Claude account', rows: claudeRows(claude.account) },
92
+ {
93
+ title: 'claude CLI',
94
+ rows: [['Status', claude.ok ? 'available' : 'not found']],
95
+ },
96
+ ],
97
+ environments: (connections?.environments ?? []).map(environmentLine),
98
+ note: CLOUD_NOTE,
99
+ };
100
+ }
@@ -0,0 +1,136 @@
1
+ // lib/cli/ui/preferences.js
2
+ /**
3
+ * The board's per-browser preferences: one JSON object in browser storage,
4
+ * every value one of a fixed set of choices, and the Done column header
5
+ * they drive. Pure apart from the storage handed in, so it runs in the
6
+ * browser and under `node --test`.
7
+ *
8
+ * @module cli/ui/preferences
9
+ */
10
+
11
+ const SETTINGS_KEY = 'mandrel-board-settings';
12
+
13
+ /** Where the theme lived before Settings; read once, then removed. */
14
+ const LEGACY_THEME_KEY = 'mandrel-ui-theme';
15
+
16
+ const FIELDS = Object.freeze([
17
+ {
18
+ name: 'theme',
19
+ label: 'Theme',
20
+ testId: 'settings-theme',
21
+ choices: ['auto', 'light', 'dark'],
22
+ text: String,
23
+ },
24
+ {
25
+ name: 'doneLimit',
26
+ label: 'Done Stories shown',
27
+ testId: 'settings-done-limit',
28
+ choices: [10, 20, 50, 100],
29
+ text: String,
30
+ },
31
+ {
32
+ name: 'refreshSeconds',
33
+ label: 'Refresh every',
34
+ testId: 'settings-refresh',
35
+ choices: [15, 30, 60],
36
+ text: (seconds) => `${seconds} s`,
37
+ },
38
+ ]);
39
+
40
+ export const DEFAULT_PREFERENCES = Object.freeze({
41
+ theme: 'auto',
42
+ doneLimit: 20,
43
+ refreshSeconds: 15,
44
+ });
45
+
46
+ function pick(field, value) {
47
+ return (
48
+ field.choices.find((choice) => String(choice) === String(value)) ??
49
+ DEFAULT_PREFERENCES[field.name]
50
+ );
51
+ }
52
+
53
+ function normalize(stored) {
54
+ const source = stored !== null && typeof stored === 'object' ? stored : {};
55
+ return Object.fromEntries(
56
+ FIELDS.map((field) => [field.name, pick(field, source[field.name])]),
57
+ );
58
+ }
59
+
60
+ function parseJson(text) {
61
+ try {
62
+ return JSON.parse(text);
63
+ } catch {
64
+ return null;
65
+ }
66
+ }
67
+
68
+ function readStored(storage) {
69
+ try {
70
+ return {
71
+ stored: parseJson(storage.getItem(SETTINGS_KEY)),
72
+ legacy: storage.getItem(LEGACY_THEME_KEY),
73
+ };
74
+ } catch {
75
+ return { stored: null, legacy: null };
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Write `prefs`; a blocked store keeps them for this page only.
81
+ *
82
+ * @param {Storage|null} storage
83
+ * @param {object} prefs
84
+ */
85
+ export function savePreferences(storage, prefs) {
86
+ try {
87
+ storage.setItem(SETTINGS_KEY, JSON.stringify(prefs));
88
+ storage.removeItem(LEGACY_THEME_KEY);
89
+ } catch {
90
+ // Nothing to recover: the defaults return on the next load.
91
+ }
92
+ }
93
+
94
+ /**
95
+ * The saved preferences: anything missing, unparsable or not a choice is
96
+ * its default, and a theme saved under the legacy key is carried over.
97
+ *
98
+ * @param {Storage|null} storage
99
+ * @returns {{ theme: string, doneLimit: number, refreshSeconds: number }}
100
+ */
101
+ export function loadPreferences(storage) {
102
+ const { stored, legacy } = readStored(storage);
103
+ if (legacy === null) return normalize(stored);
104
+ const migrated = normalize({ theme: legacy, ...stored });
105
+ savePreferences(storage, migrated);
106
+ return migrated;
107
+ }
108
+
109
+ /** `prefs` with `name` set from a control's value; an unknown value is the default. */
110
+ export function withPreference(prefs, name, value) {
111
+ const field = FIELDS.find((f) => f.name === name);
112
+ return field ? { ...prefs, [name]: pick(field, value) } : prefs;
113
+ }
114
+
115
+ /** The Settings view's labelled choices, each with its current value. */
116
+ export function settingsFields(prefs) {
117
+ return FIELDS.map((field) => ({
118
+ name: field.name,
119
+ label: field.label,
120
+ testId: field.testId,
121
+ value: String(prefs[field.name]),
122
+ options: field.choices.map((choice) => ({
123
+ value: String(choice),
124
+ text: field.text(choice),
125
+ })),
126
+ }));
127
+ }
128
+
129
+ /** `Done · <shown> of <total>`, or `Done · <shown>` when the total is unknown. */
130
+ export function doneHeader(state) {
131
+ const shown = state?.doneShown;
132
+ if (!Number.isInteger(shown)) return 'Done';
133
+ return Number.isInteger(state.doneTotal)
134
+ ? `Done · ${shown} of ${state.doneTotal}`
135
+ : `Done · ${shown}`;
136
+ }
@@ -0,0 +1,108 @@
1
+ // lib/cli/ui/request-guard.js
2
+ /**
3
+ * The `mandrel ui` request checks: the Host allowlist, the per-process
4
+ * token, the POST origin and content type, and strict validation of an
5
+ * action body. Pure; the server answers 403 or 400 from what these return.
6
+ *
7
+ * @module cli/ui/request-guard
8
+ */
9
+
10
+ import { timingSafeEqual } from 'node:crypto';
11
+
12
+ import {
13
+ DEFAULT_DONE_LIMIT,
14
+ DONE_LIMITS,
15
+ } from '../../../.agents/scripts/lib/dispatch/status.js';
16
+
17
+ /** A POST body larger than this is refused unread. */
18
+ export const MAX_BODY_BYTES = 4096;
19
+
20
+ /** `delivery.environments` key pattern, as `agentrc.schema.json` declares it. */
21
+ const ENV_NAME_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;
22
+
23
+ const ACTIONS = new Set(['dispatch', 'resume', 'stop']);
24
+ const BODY_KEYS = new Set(['action', 'storyId', 'environment']);
25
+
26
+ /**
27
+ * @param {string|undefined} host The request's `Host` header.
28
+ * @param {number} port The port the server is bound to.
29
+ * @returns {boolean}
30
+ */
31
+ export function isAllowedHost(host, port) {
32
+ return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
33
+ }
34
+
35
+ /**
36
+ * Constant-time token comparison; a missing or differently sized value is
37
+ * refused without comparing.
38
+ *
39
+ * @param {unknown} presented
40
+ * @param {string} expected
41
+ * @returns {boolean}
42
+ */
43
+ export function tokenMatches(presented, expected) {
44
+ if (typeof presented !== 'string') return false;
45
+ const a = Buffer.from(presented);
46
+ const b = Buffer.from(expected);
47
+ return a.length === b.length && timingSafeEqual(a, b);
48
+ }
49
+
50
+ /**
51
+ * A POST must come from the page this server served, as JSON.
52
+ *
53
+ * @param {{ origin?: string, 'content-type'?: string, host?: string }} headers
54
+ * @returns {boolean}
55
+ */
56
+ export function isSameOriginJson(headers) {
57
+ const mediaType = String(headers['content-type'] ?? '')
58
+ .split(';')[0]
59
+ .trim()
60
+ .toLowerCase();
61
+ return (
62
+ mediaType === 'application/json' &&
63
+ headers.origin === `http://${headers.host}`
64
+ );
65
+ }
66
+
67
+ /**
68
+ * Validate a parsed action body against the configured environment names.
69
+ *
70
+ * @param {unknown} body
71
+ * @param {string[]} environmentNames
72
+ * @returns {{ ok: true, value: { action: string, storyId: number, environment: string } }
73
+ * | { ok: false, error: string }}
74
+ */
75
+ export function validateAction(body, environmentNames) {
76
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
77
+ return { ok: false, error: 'invalid-body' };
78
+ }
79
+ if (Object.keys(body).some((key) => !BODY_KEYS.has(key))) {
80
+ return { ok: false, error: 'unknown-property' };
81
+ }
82
+ const { action, storyId, environment } = body;
83
+ if (!ACTIONS.has(action)) return { ok: false, error: 'invalid-action' };
84
+ if (!Number.isInteger(storyId) || storyId < 1) {
85
+ return { ok: false, error: 'invalid-story-id' };
86
+ }
87
+ if (
88
+ typeof environment !== 'string' ||
89
+ !ENV_NAME_RE.test(environment) ||
90
+ !environmentNames.includes(environment)
91
+ ) {
92
+ return { ok: false, error: 'invalid-environment' };
93
+ }
94
+ return { ok: true, value: { action, storyId, environment } };
95
+ }
96
+
97
+ /**
98
+ * The `done` query parameter: the default when absent, `null` when it is
99
+ * not one of `dispatch --done-limit`'s values.
100
+ *
101
+ * @param {string} url
102
+ * @returns {number|null}
103
+ */
104
+ export function doneLimitFrom(url) {
105
+ const raw = new URL(url, 'http://localhost').searchParams.get('done');
106
+ if (raw === null) return DEFAULT_DONE_LIMIT;
107
+ return DONE_LIMITS.map(String).includes(raw) ? Number(raw) : null;
108
+ }
@@ -0,0 +1,211 @@
1
+ // lib/cli/ui/server.js
2
+ /**
3
+ * The `mandrel ui` HTTP server, Node built-ins only. It stores nothing: a
4
+ * state read is recomputed through `sources.readState` (reused for at most
5
+ * `cacheMs` to coalesce polls), and an action runs through
6
+ * `sources.runAction`. Every response carries the security headers; every
7
+ * error body is `{ "error": "<code>" }`.
8
+ *
9
+ * @module cli/ui/server
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import http from 'node:http';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ import {
18
+ doneLimitFrom,
19
+ isAllowedHost,
20
+ isSameOriginJson,
21
+ MAX_BODY_BYTES,
22
+ tokenMatches,
23
+ validateAction,
24
+ } from './request-guard.js';
25
+ import { storyIdFrom } from './story-detail.js';
26
+
27
+ const UI_DIR = path.dirname(fileURLToPath(import.meta.url));
28
+
29
+ const SECURITY_HEADERS = Object.freeze({
30
+ 'Content-Security-Policy':
31
+ "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
32
+ 'X-Content-Type-Options': 'nosniff',
33
+ 'X-Frame-Options': 'DENY',
34
+ 'Strict-Transport-Security': 'max-age=31536000',
35
+ 'Referrer-Policy': 'no-referrer',
36
+ 'Cache-Control': 'no-store',
37
+ });
38
+
39
+ /** The only files served; nothing else on disk is reachable. */
40
+ const STATIC_FILES = Object.freeze({
41
+ '/board.js': 'text/javascript; charset=utf-8',
42
+ '/board-model.js': 'text/javascript; charset=utf-8',
43
+ '/panel-model.js': 'text/javascript; charset=utf-8',
44
+ '/preferences.js': 'text/javascript; charset=utf-8',
45
+ '/board.css': 'text/css; charset=utf-8',
46
+ });
47
+
48
+ const TOKEN_PLACEHOLDER = '__MANDREL_TOKEN__';
49
+
50
+ /** HTTP status for a dispatch exit code: success, refusal, failure. */
51
+ const ACTION_STATUS = { 0: 200, 2: 409 };
52
+
53
+ function send(res, status, contentType, body) {
54
+ res.writeHead(status, { ...SECURITY_HEADERS, 'Content-Type': contentType });
55
+ res.end(body);
56
+ }
57
+
58
+ function sendJson(res, status, value) {
59
+ send(res, status, 'application/json; charset=utf-8', JSON.stringify(value));
60
+ }
61
+
62
+ class RequestError extends Error {
63
+ constructor(status, code) {
64
+ super(code);
65
+ this.status = status;
66
+ this.code = code;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Read a body of at most MAX_BODY_BYTES; larger is a 400 before parsing.
72
+ * Bytes past the cap are drained, not kept, so the response still reaches
73
+ * the client.
74
+ */
75
+ async function readJsonBody(req) {
76
+ if (Number(req.headers['content-length']) > MAX_BODY_BYTES) {
77
+ throw new RequestError(400, 'body-too-large');
78
+ }
79
+ const chunks = [];
80
+ let size = 0;
81
+ for await (const chunk of req) {
82
+ size += chunk.length;
83
+ if (size <= MAX_BODY_BYTES) chunks.push(chunk);
84
+ }
85
+ if (size > MAX_BODY_BYTES) throw new RequestError(400, 'body-too-large');
86
+ try {
87
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
88
+ } catch {
89
+ throw new RequestError(400, 'invalid-json');
90
+ }
91
+ }
92
+
93
+ /**
94
+ * @param {{
95
+ * token: string,
96
+ * sources: {
97
+ * readState: (doneLimit: number) => Promise<object>,
98
+ * readConnections: () => Promise<object>,
99
+ * readStory: (id: number, state: object) => Promise<object|null>,
100
+ * runAction: (a: { action: string, storyId: number, environment: string }) => Promise<{ code: number, envelope: object }>,
101
+ * environmentNames: () => string[],
102
+ * },
103
+ * cacheMs?: number,
104
+ * now?: () => number,
105
+ * uiDir?: string,
106
+ * }} options
107
+ * @returns {import('node:http').Server} Not yet listening.
108
+ */
109
+ export function createUiServer({
110
+ token,
111
+ sources,
112
+ cacheMs = 5000,
113
+ now = Date.now,
114
+ uiDir = UI_DIR,
115
+ }) {
116
+ /** One cached read per Done limit. */
117
+ const cached = new Map();
118
+ const isFresh = (entry) => entry && now() - entry.at < cacheMs;
119
+ const evict = (key, entry) => {
120
+ if (cached.get(key) === entry) cached.delete(key);
121
+ };
122
+
123
+ function readState(doneLimit) {
124
+ const hit = cached.get(doneLimit);
125
+ if (isFresh(hit)) return hit.promise;
126
+ const entry = { at: now(), promise: sources.readState(doneLimit) };
127
+ cached.set(doneLimit, entry);
128
+ entry.promise.catch(() => evict(doneLimit, entry));
129
+ return entry.promise;
130
+ }
131
+
132
+ /** The state for the request's `done` parameter; any other value is a 400. */
133
+ function stateFor(req) {
134
+ const doneLimit = doneLimitFrom(req.url);
135
+ if (doneLimit === null) throw new RequestError(400, 'invalid-done-limit');
136
+ return readState(doneLimit);
137
+ }
138
+
139
+ async function postAction(req, res) {
140
+ if (!isSameOriginJson(req.headers))
141
+ throw new RequestError(403, 'forbidden');
142
+ const body = await readJsonBody(req);
143
+ const checked = validateAction(body, sources.environmentNames());
144
+ if (!checked.ok) throw new RequestError(400, checked.error);
145
+ const { code, envelope } = await sources.runAction(checked.value);
146
+ cached.clear();
147
+ const status = ACTION_STATUS[code];
148
+ if (!status) throw new RequestError(500, 'action-failed');
149
+ sendJson(res, status, envelope);
150
+ }
151
+
152
+ async function getStory(req, res) {
153
+ const id = storyIdFrom(req.url);
154
+ if (id === null) throw new RequestError(400, 'invalid-id');
155
+ const detail = await sources.readStory(id, await stateFor(req));
156
+ if (!detail) throw new RequestError(404, 'not-found');
157
+ sendJson(res, 200, detail);
158
+ }
159
+
160
+ const API = {
161
+ 'GET /api/state': async (req, res) =>
162
+ sendJson(res, 200, await stateFor(req)),
163
+ 'GET /api/story': getStory,
164
+ 'GET /api/connections': async (_req, res) =>
165
+ sendJson(res, 200, await sources.readConnections()),
166
+ 'POST /api/action': postAction,
167
+ };
168
+
169
+ function serveStatic(req, res, pathname) {
170
+ if (req.method !== 'GET') throw new RequestError(405, 'method-not-allowed');
171
+ if (pathname === '/') {
172
+ const html = fs.readFileSync(path.join(uiDir, 'board.html'), 'utf8');
173
+ send(
174
+ res,
175
+ 200,
176
+ 'text/html; charset=utf-8',
177
+ html.replace(TOKEN_PLACEHOLDER, token),
178
+ );
179
+ return;
180
+ }
181
+ const type = STATIC_FILES[pathname];
182
+ if (!type) throw new RequestError(404, 'not-found');
183
+ send(res, 200, type, fs.readFileSync(path.join(uiDir, pathname.slice(1))));
184
+ }
185
+
186
+ async function route(req, res, port) {
187
+ if (!isAllowedHost(req.headers.host, port)) {
188
+ throw new RequestError(403, 'forbidden');
189
+ }
190
+ const { pathname } = new URL(req.url, 'http://localhost');
191
+ if (!pathname.startsWith('/api/')) {
192
+ serveStatic(req, res, pathname);
193
+ return;
194
+ }
195
+ if (!tokenMatches(req.headers['x-mandrel-token'], token)) {
196
+ throw new RequestError(403, 'forbidden');
197
+ }
198
+ const handler = API[`${req.method} ${pathname}`];
199
+ if (!handler) throw new RequestError(404, 'not-found');
200
+ await handler(req, res);
201
+ }
202
+
203
+ const server = http.createServer((req, res) => {
204
+ route(req, res, server.address().port).catch((err) => {
205
+ const status = err instanceof RequestError ? err.status : 500;
206
+ const code = err instanceof RequestError ? err.code : 'internal';
207
+ sendJson(res, status, { error: code });
208
+ });
209
+ });
210
+ return server;
211
+ }