@khanglvm/relay 0.22.2 → 0.23.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/README.md CHANGED
@@ -76,6 +76,13 @@ A board listens on this machine only until you give it a link. Two generic ways:
76
76
  `--devlink`. Run `rly config link <off|auto|devlink|url|command:CMD>` to make a choice the
77
77
  default. The details are in the [agent guide](docs/AGENT.md).
78
78
 
79
+ ## Saved boards
80
+
81
+ Boards live in `~/.relay` (set `RLY_HOME` to move it). A board that has not changed for 30 days is
82
+ removed, with its result and artifacts, the next time a board is created. A board whose server is
83
+ still running is kept. Set `RLY_RETENTION_DAYS=60` to change the window, or `off` to keep every board.
84
+ `rly mcp --retention-days N` and `registerRelay(server, { retentionDays: N })` set it for a server.
85
+
79
86
  ## More help
80
87
 
81
88
  - [Setup and MCP Apps](docs/SETUP.md): agent configuration, in-chat boards, sharing, and updates.
package/docs/AGENT.md CHANGED
@@ -148,7 +148,7 @@ Tools:
148
148
 
149
149
  The flow: call `relay_board`, tell the person the board is on screen, and carry on or wait. When they submit, the host posts a one-line message naming the board. Read the answers with `relay_result`. Do not ask the same questions again in chat.
150
150
 
151
- `rly mcp` speaks stdio to a local desktop host. `rly mcp --http [--port N] [--token-file PATH] [--allow-origin ORIGIN]` serves Streamable HTTP at `/mcp` for hosts that connect over a network. The bearer token comes from `--token-file`, `RLY_MCP_TOKEN` or `--token`; the flag shows in `ps`, so prefer the file or the variable. Boards are stored in the relay home of the machine that runs the server, so `codeFile` and local images resolve there and nowhere else, and only under the server's file roots: none over HTTP unless the operator passes `--root PATH` (repeatable) or `RLY_FILE_ROOTS`, the working directory over stdio (but not when it is `/` or the home directory, where desktop hosts often start it). A host that draws A2UI can show the whole board natively instead of the iframe. It declares the board catalog, `https://github.com/khanglvm/relay/a2ui/catalog/board/v1`, under `extensions.a2ui["1.0"].supportedCatalogIds` when it connects, or per call in `_meta.a2ui`; the call wins over the connection. `relay_view` then returns the board as A2UI messages (`application/a2ui+json`, `application/json+a2ui` is accepted when declared) and the host sends button events to `a2ui_action` with the surface's data model. The catalog is `src/a2ui/board-catalog.json`; `toA2ui(spec)` and `fromA2ui(dataModel, spec)` from `@khanglvm/relay/a2ui-board` convert in both directions, and the result matches what the web board stores. Hosts that did not declare it keep the iframe.
151
+ `rly mcp` speaks stdio to a local desktop host. `rly mcp --http [--port N] [--token-file PATH] [--allow-origin ORIGIN]` serves Streamable HTTP at `/mcp` for hosts that connect over a network. The bearer token comes from `--token-file`, `RLY_MCP_TOKEN` or `--token`; the flag shows in `ps`, so prefer the file or the variable. Boards are stored in the relay home of the machine that runs the server, so `codeFile` and local images resolve there and nowhere else, and only under the server's file roots: none over HTTP unless the operator passes `--root PATH` (repeatable) or `RLY_FILE_ROOTS`, the working directory over stdio (but not when it is `/` or the home directory, where desktop hosts often start it). `--retention-days N` (or `RLY_RETENTION_DAYS`, `off` to keep every board) sets how long unchanged boards stay in the relay home; the default is 30. A host that draws A2UI can show the whole board natively instead of the iframe. It declares the board catalog, `https://github.com/khanglvm/relay/a2ui/catalog/board/v1`, under `extensions.a2ui["1.0"].supportedCatalogIds` when it connects, or per call in `_meta.a2ui`; the call wins over the connection. `relay_view` then returns the board as A2UI messages (`application/a2ui+json`, `application/json+a2ui` is accepted when declared) and the host sends button events to `a2ui_action` with the surface's data model. The catalog is `src/a2ui/board-catalog.json`; `toA2ui(spec)` and `fromA2ui(dataModel, spec)` from `@khanglvm/relay/a2ui-board` convert in both directions, and the result matches what the web board stores. Hosts that did not declare it keep the iframe.
152
152
 
153
153
  To add the tools to a server you already run, call `registerRelay(server, {store, assetUrl, linkUrl})` from `@khanglvm/relay/mcp`.
154
154
 
@@ -818,7 +818,9 @@ rly rm <id> | --all # delete saved board(s)
818
818
  Multiple boards can run at once (each gets its own port on 127.0.0.1).
819
819
  Detached boards are durable: they keep serving past timeout, `reopen`/`rescue`
820
820
  prefer the last port, and active same-Wi-Fi share links keep the same token until
821
- revoked. Storage lives in `~/.relay` (override with `RLY_HOME`).
821
+ revoked. Storage lives in `~/.relay` (override with `RLY_HOME`). A board unchanged for 30 days is
822
+ deleted when the next board is created, unless its server is still running; set `RLY_RETENTION_DAYS`
823
+ (a number of days, or `off`) to change that.
822
824
 
823
825
  ## Live board mutation — `rly update`
824
826
 
package/docs/SETUP.md CHANGED
@@ -63,6 +63,13 @@ Boards autosave answers and comments. Detached boards keep serving after
63
63
  a wait times out, until submission or `rly stop <board-id>`. Multiple boards
64
64
  can run at once.
65
65
 
66
+ Boards are stored under `RLY_HOME` (default `~/.relay`). A board unchanged for 30 days is deleted, along
67
+ with its result file and artifacts, when the next board is created; boards with a running server stay.
68
+ `RLY_RETENTION_DAYS` changes the number of days and `off` (or `0`) keeps every board. `rly mcp
69
+ --retention-days N` and the `retentionDays` option of `registerRelay` do the same for an MCP server.
70
+ Several processes can share one `RLY_HOME`: only one sweeps at a time, and a home is swept at most once an
71
+ hour. A custom `store` given to `registerRelay` does its own cleanup.
72
+
66
73
  Relay has no npm runtime dependencies. It bundles the browser libraries for
67
74
  charts and diagrams and loads them only when a board needs them. Local
68
75
  file links open referenced paths in the default app; `RLY_OPEN_CMD` overrides
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@khanglvm/relay",
3
- "version": "0.22.2",
3
+ "version": "0.23.1",
4
4
  "description": "Question boards with rich blocks (markdown, charts, mermaid, tables, code, diffs, video, sandboxed HTML), clickable local file-links, and element-level annotations for AI coding agents (Claude Code, Codex, …): ask users structured questions, present interactive visuals, collect inline comments, read answers as JSON — in a local browser board OR rendered INLINE inside the Claude & Codex apps as an MCP App (SEP-1865).",
5
5
  "keywords": [
6
6
  "ai-agents",
package/src/cli/args.js CHANGED
@@ -5,7 +5,7 @@ const VALUED_FLAGS = new Set([
5
5
  'file', 'html', 'html-file', 'title', 'intro', 'timeout', 'port',
6
6
  'submit-label', 'height', 'limit', 'target', 'id', 'replies',
7
7
  'on-result', 'notify-cmd', 'idle-grace', 'scope', 'range',
8
- 'host', 'token', 'token-file', 'root', 'allow-origin', 'role', 'public-url', 'link', 'link-command',
8
+ 'host', 'token', 'token-file', 'root', 'allow-origin', 'retention-days', 'role', 'public-url', 'link', 'link-command',
9
9
  ]);
10
10
 
11
11
  function camel(key) {
package/src/cli/help.js CHANGED
@@ -73,6 +73,7 @@ USAGE
73
73
  rly mcp --http [--port N] serve over Streamable HTTP for web/mobile/remote hosts
74
74
  [--host H --token-file PATH --allow-origin ORIGIN]
75
75
  [--root PATH ...] folders a spec may read local files from (none by default over HTTP; also $RLY_FILE_ROOTS)
76
+ [--retention-days N|off] delete boards unchanged for N days (default 30; also $RLY_RETENTION_DAYS)
76
77
  (token: --token-file, $RLY_MCP_TOKEN, or --token, which shows in the process list)
77
78
  rly mcp config | install --target print host setup, or write it (claude | codex)
78
79
 
package/src/cli/mcp.js CHANGED
@@ -4,6 +4,7 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { envFileRoots, expandHome, isBroadRoot } from '../file-access.js';
6
6
  import { mcpConfig } from '../mcp/config.js';
7
+ import { resolveRetentionDays } from '../retention.js';
7
8
  import { CliError } from '../util.js';
8
9
  import { parseArgs } from './args.js';
9
10
  import { printJson } from './io.js';
@@ -26,6 +27,7 @@ export async function cmdMcp(rest) {
26
27
  const { runMcpHttp } = await import('../mcp/serve.js');
27
28
  return runMcpHttp({
28
29
  fileRoots: mcpFileRoots(args, []),
30
+ retentionDays: mcpRetention(args),
29
31
  port: args.port ? Number(args.port) : (envPort ? Number(envPort) : undefined),
30
32
  host: typeof args.host === 'string' ? args.host : (process.env.RLY_MCP_HOST || '127.0.0.1'),
31
33
  token: resolveToken(args),
@@ -35,7 +37,7 @@ export async function cmdMcp(rest) {
35
37
  // Default: be the stdio server. main() never resolves this, so the CLI's
36
38
  // post-run exit timer never arms — the server lives until stdin closes.
37
39
  const { runMcp } = await import('../mcp/serve.js');
38
- return runMcp({ fileRoots: mcpFileRoots(args, stdioDefaultRoots(process.cwd())) });
40
+ return runMcp({ fileRoots: mcpFileRoots(args, stdioDefaultRoots(process.cwd())), retentionDays: mcpRetention(args) });
39
41
  }
40
42
 
41
43
  /** The working directory as the stdio root, unless it is `/` or the home directory. */
@@ -55,6 +57,13 @@ function mcpFileRoots(args, defaults) {
55
57
  return [...defaults, ...args.root, ...envFileRoots()].map((p) => path.resolve(expandHome(p)));
56
58
  }
57
59
 
60
+ /** `--retention-days N` (or "off"), checked now so a typo stops the server instead of the first board. */
61
+ function mcpRetention(args) {
62
+ const option = typeof args.retentionDays === 'string' ? args.retentionDays : undefined;
63
+ resolveRetentionDays(option);
64
+ return option;
65
+ }
66
+
58
67
  /**
59
68
  * The bearer token for --http. `--token` shows up in `ps`, so prefer `--token-file PATH`
60
69
  * or $RLY_MCP_TOKEN; the flag keeps working. A file that cannot be read is an error,
@@ -94,22 +94,90 @@ export function isInsideRoots(target, roots) {
94
94
  * @param {FileAccess} access
95
95
  * @param {unknown} raw the path as written; `~` and relative paths are expanded
96
96
  * @param {{ allowDirectory?: boolean }} [options] directories are refused unless a caller opens them in an app
97
- * @returns {{ ok: boolean, file?: string, stat?: fs.Stats, reason?: 'invalid' | 'outside' | 'missing' | 'not-file', resolved?: string }} `file` and `stat` when ok; otherwise `reason` and the real path it was refused at
97
+ * @returns {{ ok: boolean, file?: string, stat?: fs.Stats, reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed' }} `file` and `stat` when ok; otherwise the `reason`, which callers keep to themselves
98
98
  */
99
99
  export function checkReadable(access, raw, { allowDirectory = false } = {}) {
100
100
  const text = typeof raw === 'string' ? raw.trim() : '';
101
- if (!text || text.includes('\0')) return { ok: false, reason: 'invalid', resolved: text };
101
+ if (!text || text.includes('\0')) return { ok: false, reason: 'invalid' };
102
102
  const resolved = path.resolve(access.cwd, expandHome(text));
103
103
  const real = realpathOrAncestor(resolved);
104
- if (!isInsideRoots(real, access.roots)) return { ok: false, reason: 'outside', resolved: real };
104
+ if (!isInsideRoots(real, access.roots)) return { ok: false, reason: 'outside' };
105
105
  let stat;
106
- try { stat = fs.statSync(real); } catch { return { ok: false, reason: 'missing', resolved: real }; }
107
- if (!stat.isFile() && !(allowDirectory && stat.isDirectory())) return { ok: false, reason: 'not-file', resolved: real };
106
+ try { stat = fs.statSync(real); } catch { return { ok: false, reason: 'missing' }; }
107
+ if (!stat.isFile() && !(allowDirectory && stat.isDirectory())) return { ok: false, reason: 'not-file' };
108
108
  return { ok: true, file: real, stat };
109
109
  }
110
110
 
111
+ // O_NOFOLLOW refuses a final component that became a symlink after the check.
112
+ // O_NONBLOCK keeps a file swapped for a FIFO from hanging the open; the identity check below then refuses it.
113
+ const OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
114
+
115
+ /**
116
+ * The path the kernel holds for an open descriptor, or null where Node cannot ask (macOS, Windows).
117
+ * Linux keeps it in /proc/self/fd, which no rename of a parent folder can fake.
118
+ */
119
+ function openedPath(fd) {
120
+ if (process.platform !== 'linux') return null;
121
+ try { return fs.readlinkSync(`/proc/self/fd/${fd}`); } catch { return null; }
122
+ }
123
+
124
+ /**
125
+ * True when `file` still resolves to itself, inside the roots, and is the very file `fd` has open.
126
+ * Known open risk on macOS and Windows: the name checks below walk the path again, so a writer inside a
127
+ * root who swaps a parent folder for a symlink and back between those calls can still win the race.
128
+ */
129
+ function isStillTheCheckedFile(access, file, fd) {
130
+ try {
131
+ const opened = openedPath(fd);
132
+ if (opened !== null && opened !== file) return false;
133
+ if (fs.realpathSync.native(file) !== file || !isInsideRoots(file, access.roots)) return false;
134
+ const open = fs.fstatSync(fd);
135
+ const named = fs.statSync(file);
136
+ return open.isFile() && open.dev === named.dev && open.ino === named.ino;
137
+ } catch {
138
+ return false;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Like `checkReadable`, but also opens a regular file, and keeps the open
144
+ * descriptor as the only way to read it. A path checked and then read by name
145
+ * can be swapped for a symlink in between; the descriptor cannot. After the
146
+ * open, the path must still resolve to the same file inside the roots, or the
147
+ * read is refused. A directory (when allowed) comes back with `fd: null`.
148
+ * The caller closes `fd`, or hands it to `streamFile`, which does.
149
+ * @param {FileAccess} access
150
+ * @param {unknown} raw
151
+ * @param {{ allowDirectory?: boolean }} [options]
152
+ * @returns {{ ok: boolean, file?: string, stat?: fs.Stats, fd?: number | null, reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed' }}
153
+ */
154
+ export function openReadable(access, raw, options = {}) {
155
+ const checked = checkReadable(access, raw, options);
156
+ if (!checked.ok) return { ok: false, reason: /** @type {any} */ (checked.reason) };
157
+ const file = /** @type {string} */ (checked.file);
158
+ if (!/** @type {fs.Stats} */ (checked.stat).isFile()) return { ok: true, file, stat: /** @type {fs.Stats} */ (checked.stat), fd: null };
159
+ let fd;
160
+ try { fd = fs.openSync(file, OPEN_FLAGS); } catch { return { ok: false, reason: 'changed' }; }
161
+ if (!isStillTheCheckedFile(access, file, fd)) {
162
+ fs.closeSync(fd);
163
+ return { ok: false, reason: 'changed' };
164
+ }
165
+ return { ok: true, file, stat: fs.fstatSync(fd), fd };
166
+ }
167
+
168
+ /**
169
+ * One message for every refusal, so it says nothing about whether the path
170
+ * exists, where a symlink leads or what the folders look like. It echoes the
171
+ * path as the caller wrote it.
172
+ */
173
+ function refusal(where, field, raw) {
174
+ const given = typeof raw === 'string' ? raw : String(raw);
175
+ return new CliError(`${where}: ${field}: cannot read "${given}": no such file, not a regular file, or path outside allowed roots; ${FIX_HINT}.`);
176
+ }
177
+
111
178
  /**
112
179
  * The real path of a file a spec names, or a CliError worded for the agent.
180
+ * Use `readReadable` to read it.
113
181
  * @param {FileAccess} access
114
182
  * @param {unknown} raw
115
183
  * @param {string} where which block, e.g. `board.blocks[0]`
@@ -118,12 +186,26 @@ export function checkReadable(access, raw, { allowDirectory = false } = {}) {
118
186
  */
119
187
  export function resolveReadable(access, raw, where, field) {
120
188
  const checked = checkReadable(access, raw);
121
- if (checked.ok) return { file: /** @type {string} */ (checked.file), stat: /** @type {fs.Stats} */ (checked.stat) };
122
- const given = typeof raw === 'string' ? raw : String(raw);
123
- const prefix = `${where}: ${field}: `;
124
- if (checked.reason === 'outside') {
125
- throw new CliError(`${prefix}path outside allowed roots (\"${given}\" resolves to ${checked.resolved}); ${FIX_HINT}.`);
189
+ if (!checked.ok) throw refusal(where, field, raw);
190
+ return { file: /** @type {string} */ (checked.file), stat: /** @type {fs.Stats} */ (checked.stat) };
191
+ }
192
+
193
+ /**
194
+ * The bytes of a file a spec names, read through one opened descriptor.
195
+ * @param {FileAccess} access
196
+ * @param {unknown} raw
197
+ * @param {string} where which block, e.g. `board.blocks[0]`
198
+ * @param {string} field which field, e.g. `codeFile`
199
+ * @returns {{ file: string, stat: fs.Stats, buf: Buffer }}
200
+ */
201
+ export function readReadable(access, raw, where, field) {
202
+ const opened = openReadable(access, raw);
203
+ if (!opened.ok || opened.fd === null) throw refusal(where, field, raw);
204
+ try {
205
+ return { file: opened.file, stat: opened.stat, buf: fs.readFileSync(opened.fd) };
206
+ } catch {
207
+ throw refusal(where, field, raw);
208
+ } finally {
209
+ fs.closeSync(opened.fd);
126
210
  }
127
- if (checked.reason === 'not-file') throw new CliError(`${prefix}\"${given}\" is not a regular file (resolved: ${checked.resolved}).`);
128
- throw new CliError(`${prefix}cannot read \"${given}\" (resolved: ${checked.resolved})`);
129
211
  }
@@ -28,7 +28,12 @@ export function mediaType(target) {
28
28
  return MEDIA[path.extname(target).toLowerCase()] || null;
29
29
  }
30
30
 
31
- export function filePreview(target, stat, reference) {
31
+ /**
32
+ * @param {{ file: string, stat: fs.Stats, fd: number | null }} opened a file from `openReadable`; the caller closes it
33
+ * @param {{ line: number | null, endLine: number | null }} reference
34
+ */
35
+ export function filePreview(opened, reference) {
36
+ const { file: target, stat, fd } = opened;
32
37
  const base = { name: path.basename(target), size: stat.size, line: reference.line, endLine: reference.endLine };
33
38
  const unavailable = (reason) => ({ ...base, kind: 'unsupported', reason });
34
39
  if (!stat.isFile()) return unavailable('Directories cannot be previewed. Open this location in an app.');
@@ -36,12 +41,9 @@ export function filePreview(target, stat, reference) {
36
41
  if (media) return { ...base, kind: media[0], mime: media[1] };
37
42
  if (stat.size > TEXT_LIMIT) return unavailable('Text previews are limited to 1 MiB. Open this file in an app.');
38
43
  // Read at most the limit + 1 even if a file grows between stat and read.
39
- const fd = fs.openSync(target, 'r');
40
- let bytes;
41
- try {
42
- const buffer = Buffer.alloc(TEXT_LIMIT + 1);
43
- bytes = buffer.subarray(0, fs.readSync(fd, buffer, 0, buffer.length, 0));
44
- } finally { fs.closeSync(fd); }
44
+ if (fd === null) return unavailable('This file cannot be read.');
45
+ const buffer = Buffer.alloc(TEXT_LIMIT + 1);
46
+ const bytes = buffer.subarray(0, fs.readSync(fd, buffer, 0, buffer.length, 0));
45
47
  if (bytes.length > TEXT_LIMIT) return unavailable('Text previews are limited to 1 MiB. Open this file in an app.');
46
48
  let text;
47
49
  try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
package/src/mcp/boards.js CHANGED
@@ -84,6 +84,7 @@ export async function saveDraft(store, id, draft, spec) {
84
84
  comment: limit(d.comment, MAX_TEXT),
85
85
  notes: asObject(d.notes),
86
86
  annotations: sanitizeAnnotations(d.annotations, id),
87
+ blockEdits: sanitizeBlockEdits(d.blockEdits),
87
88
  updatedAt: new Date().toISOString(),
88
89
  },
89
90
  });
package/src/mcp/serve.js CHANGED
@@ -6,12 +6,15 @@ import { loadServerKey } from './token.js';
6
6
 
7
7
  const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
8
8
 
9
- /** Serves MCP over this process's stdin and stdout until the host closes stdin. */
10
- export async function runMcp({ fileRoots = [] } = {}) {
9
+ /**
10
+ * Serves MCP over this process's stdin and stdout until the host closes stdin.
11
+ * @param {{ fileRoots?: string[], retentionDays?: string | number }} [options]
12
+ */
13
+ export async function runMcp({ fileRoots = [], retentionDays } = {}) {
11
14
  const { serveStdio } = await import('@modelcontextprotocol/server/stdio');
12
15
  const { createRelayServer } = await import('./server.js');
13
16
  const tokenKey = loadServerKey();
14
- const handle = serveStdio(() => createRelayServer({ tokenKey, fileRoots }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
17
+ const handle = serveStdio(() => createRelayServer({ tokenKey, fileRoots, retentionDays }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
15
18
  // Resolves only once the host disconnects, so the CLI's exit timer never fires.
16
19
  return new Promise((resolve) => {
17
20
  const finish = () => handle.close().finally(() => resolve(0));
@@ -89,13 +92,14 @@ const bearerOk = (header = '', token) => /^bearer /i.test(header) && safeEqual(h
89
92
  /**
90
93
  * Serves MCP over Streamable HTTP. Localhost by default; a bearer token and an
91
94
  * allowed Origin are the controls for anything wider.
95
+ * @param {{ port?: number, host?: string, token?: string, allowOrigin?: string, fileRoots?: string[], retentionDays?: string | number }} [options]
92
96
  */
93
- export async function runMcpHttp({ port = DEFAULT_HTTP_PORT, host = '127.0.0.1', token = '', allowOrigin = '', fileRoots = [] } = {}) {
97
+ export async function runMcpHttp({ port = DEFAULT_HTTP_PORT, host = '127.0.0.1', token = '', allowOrigin = '', fileRoots = [], retentionDays } = {}) {
94
98
  const { createMcpHandler } = await import('@modelcontextprotocol/server');
95
99
  const { toNodeHandler } = await import('@modelcontextprotocol/node');
96
100
  const { createRelayServer } = await import('./server.js');
97
101
  const tokenKey = loadServerKey();
98
- const handler = createMcpHandler(() => createRelayServer({ tokenKey, fileRoots }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
102
+ const handler = createMcpHandler(() => createRelayServer({ tokenKey, fileRoots, retentionDays }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
99
103
  const serve = toNodeHandler(handler, { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
100
104
 
101
105
  const server = http.createServer(requestListener({ serve, token, allowOrigin, endpoint: `http://${host === '0.0.0.0' ? 'localhost' : host}:${port}${HTTP_PATH}` }));
package/src/mcp/server.js CHANGED
@@ -16,7 +16,11 @@ export function createRelayServer(options = {}) {
16
16
  { instructions: INSTRUCTIONS, capabilities: { extensions: { [UI_EXT]: { mimeTypes: [UI_MIME] } } } },
17
17
  );
18
18
  const appTools = registerRelay(server, options);
19
- // The iframe tools only matter to a host that renders the board; others never see them.
19
+ // MCP Apps (spec 2026-01-26, "Resource Discovery > Visibility") makes the host drop
20
+ // app-only tools from the model's tool list (MUST NOT include them), and only
21
+ // asks servers to check client capabilities (SHOULD). A server that learns the
22
+ // client at initialize (stdio) hides the tools here; a stateless HTTP request
23
+ // carries no initialize, so those tools stay listed and the host filters them.
20
24
  server.server.oninitialized = () => {
21
25
  if (!clientRendersBoards(server.server.getClientCapabilities())) for (const tool of appTools) tool.disable();
22
26
  };
package/src/mcp/store.js CHANGED
@@ -17,11 +17,14 @@ import { createBoard, loadBoard, saveBoard, saveResultFile } from '../store.js';
17
17
  * @property {(id: string, patch: Partial<BoardRecord>) => BoardRecord | null | Promise<BoardRecord | null>} update
18
18
  */
19
19
 
20
- /** The default store: one JSON file per board under the relay home, shared with the CLI. */
21
- export function fileStore() {
20
+ /**
21
+ * The default store: one JSON file per board under the relay home, shared with the CLI.
22
+ * @param {{ retentionDays?: number | string | boolean }} [options] how long old boards stay; see `resolveRetentionDays`
23
+ */
24
+ export function fileStore({ retentionDays } = {}) {
22
25
  const get = (id) => (/^b-[a-z0-9]+$/i.test(String(id)) ? loadBoard(id) : null);
23
26
  return {
24
- create: (spec, options) => createBoard(spec, options),
27
+ create: (spec, options) => createBoard(spec, { ...options, retentionDays }),
25
28
  get,
26
29
  update(id, patch) {
27
30
  const record = get(id);
package/src/mcp/tools.js CHANGED
@@ -36,6 +36,7 @@ const json = (value, structured) => ({ content: [{ type: 'text', text: JSON.stri
36
36
  * @param {any} server an McpServer
37
37
  * @param {object} [options]
38
38
  * @param {import('./store.js').RelayStore} [options.store] where boards live; defaults to the relay home on disk
39
+ * @param {number | string | boolean} [options.retentionDays] with the default store, boards unchanged for this many days are removed when a new board is made (default 30; `0`, `false` or "off" keeps every board). `RLY_RETENTION_DAYS` sets it when the option is absent. A custom `store` does its own cleanup
39
40
  * @param {string[]} [options.fileRoots] folders a spec may read local files from (`codeFile`, images, `rowsFile`...); none by default, so a remote client cannot read the server's disk
40
41
  * @param {string | Buffer} [options.tokenKey] the secret behind board tokens; defaults to a key file in the relay home
41
42
  * @param {(name: string) => string} [options.assetUrl] URL of a vendor file, for hosts that can fetch it
@@ -43,7 +44,7 @@ const json = (value, structured) => ({ content: [{ type: 'text', text: JSON.stri
43
44
  * @returns the app-only tools, so a server can hide them from a client that cannot render the board
44
45
  */
45
46
  export function registerRelay(server, options = {}) {
46
- const ctx = { server, options, store: options.store ?? fileStore(), key: options.tokenKey ?? loadServerKey() };
47
+ const ctx = { server, options, store: options.store ?? fileStore({ retentionDays: options.retentionDays }), key: options.tokenKey ?? loadServerKey() };
47
48
  registerBoardTools(ctx);
48
49
  registerReadTools(ctx);
49
50
  const appTools = registerAppTools(ctx);
@@ -0,0 +1,30 @@
1
+ // ======================================================================
2
+ // draft restore: the answers the person had entered before the board was reloaded
3
+ // ======================================================================
4
+ // Mirrors the browser board's seedFromPrefill (ui/app/drafts.js): an answer that
5
+ // matches no option goes back into the "Other" field, and one for a question the
6
+ // agent has since removed is dropped.
7
+ function restoreDraft(draft) {
8
+ if (!draft || typeof draft !== 'object') return;
9
+ state.comment = typeof draft.comment === 'string' ? draft.comment : '';
10
+ if (draft.notes && typeof draft.notes === 'object') state.notes = { ...draft.notes };
11
+ if (draft.blockEdits && typeof draft.blockEdits === 'object') state.blockEdits = { ...draft.blockEdits };
12
+ state.annotations = Array.isArray(draft.annotations) ? draft.annotations : [];
13
+ const saved = draft.answers && typeof draft.answers === 'object' ? draft.answers : {};
14
+ for (const q of QS) {
15
+ const v = saved[q.id];
16
+ if (v === undefined || v === null) continue;
17
+ if (q.type === 'multi' && Array.isArray(v)) {
18
+ const known = new Set((q.options || []).map((o) => o.value));
19
+ state.answers[q.id] = v.filter((x) => known.has(x));
20
+ const extra = v.filter((x) => !known.has(x));
21
+ if (extra.length && q.other) state.other[q.id] = { on: true, text: extra.join(', ') };
22
+ } else if (q.type === 'single' && typeof v === 'string') {
23
+ if ((q.options || []).some((o) => o.value === v)) state.answers[q.id] = v;
24
+ else if (q.other) state.other[q.id] = { on: true, text: v };
25
+ } else {
26
+ state.answers[q.id] = v;
27
+ }
28
+ }
29
+ completeAnswers();
30
+ }
@@ -7,7 +7,7 @@
7
7
  }
8
8
 
9
9
  let booted = false;
10
- async function boot(rawOrNormalized, alreadyNormalized) {
10
+ async function boot(rawOrNormalized, alreadyNormalized, draft) {
11
11
  if (booted || submitted) return;
12
12
  const next = alreadyNormalized ? rawOrNormalized : clientNormalize(rawOrNormalized);
13
13
  if (!next || (!Array.isArray(next.questions)) ) { return; }
@@ -18,10 +18,11 @@
18
18
  spec = next;
19
19
  QS = spec.questions || [];
20
20
  seedDefaults();
21
+ restoreDraft(draft);
21
22
  indexHtmlBlocks(spec);
22
23
  setStatus('Preparing…');
23
24
  if (Annotate && spec.responseRequired !== false) {
24
- Annotate.init({ initial: [], onChange: (a) => { state.annotations = Array.isArray(a) ? a : []; } });
25
+ Annotate.init({ initial: state.annotations, onChange: (a) => { state.annotations = Array.isArray(a) ? a : []; } });
25
26
  } else if (Annotate && typeof Annotate.teardown === 'function') {
26
27
  Annotate.teardown();
27
28
  }
@@ -83,7 +84,7 @@
83
84
  const view = await callServerTool('relay_view', { boardId: BOARD.id, token: BOARD.token });
84
85
  if (!view.spec) return false;
85
86
  vendorUrls = view.vendorUrls || null;
86
- await boot(view.spec, true);
87
+ await boot(view.spec, true, view.draft);
87
88
  if (view.finished) {
88
89
  submitted = true;
89
90
  showDone(true, false);
@@ -26,6 +26,10 @@
26
26
 
27
27
  function seedDefaults() {
28
28
  for (const q of QS) if (q.default !== undefined) state.answers[q.id] = q.default;
29
+ completeAnswers();
30
+ }
31
+ // Brings every answer to a complete, valid shape (see the per-type seeders below).
32
+ function completeAnswers() {
29
33
  // Rank questions carry a full, valid permutation so an untouched rank still
30
34
  // submits a meaningful order (mirrors the browser board's seedRankOrder).
31
35
  for (const q of QS) {
@@ -0,0 +1,116 @@
1
+ // How long boards stay on disk, and the sweep that removes the ones past it.
2
+ // The sweep takes plain paths and callbacks, so store.js wires it to the relay home.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { CliError } from './util.js';
6
+
7
+ export const RETENTION_ENV = 'RLY_RETENTION_DAYS';
8
+ export const DEFAULT_RETENTION_DAYS = 30;
9
+
10
+ const DAY_MS = 24 * 60 * 60 * 1000;
11
+ // Boards are swept at most once an hour per relay home, however many boards are created.
12
+ const SWEEP_INTERVAL_MS = 60 * 60 * 1000;
13
+ // A sweep that died without releasing its lock is taken over after this long.
14
+ const STALE_LOCK_MS = 10 * 60 * 1000;
15
+ // A temp file left by a write that crashed before its rename.
16
+ const STALE_TEMP_MS = DAY_MS;
17
+ const LOCK_NAME = 'prune.lock';
18
+ const STAMP_NAME = 'prune.stamp';
19
+ const OFF_WORDS = new Set(['0', 'off', 'never', 'none', 'false', 'no']);
20
+
21
+ /**
22
+ * The retention window in days; 0 means boards are kept forever.
23
+ * The option wins over `RLY_RETENTION_DAYS`, which wins over the 30-day default.
24
+ * @param {unknown} [option] a number of days, a numeric string, or `0`, `false` or "off" to keep every board
25
+ * @param {Record<string, string | undefined>} [env]
26
+ */
27
+ export function resolveRetentionDays(option, env = process.env) {
28
+ const fromEnv = env[RETENTION_ENV];
29
+ const raw = option !== undefined && option !== null && option !== '' ? option : fromEnv;
30
+ if (raw === undefined || raw === null || raw === '') return DEFAULT_RETENTION_DAYS;
31
+ if (raw === false) return 0;
32
+ const text = String(raw).trim().toLowerCase();
33
+ if (OFF_WORDS.has(text)) return 0;
34
+ const days = Number(text);
35
+ if (!Number.isFinite(days) || days < 0) {
36
+ const source = option !== undefined && option !== null && option !== '' ? 'retentionDays' : RETENTION_ENV;
37
+ throw new CliError(`${source} must be a number of days (0 or "off" keeps every board), got "${text}".`);
38
+ }
39
+ return days;
40
+ }
41
+
42
+ /** Takes the sweep lock; false when another process holds it. */
43
+ function takeLock(lockDir) {
44
+ try {
45
+ fs.mkdirSync(lockDir);
46
+ return true;
47
+ } catch (err) {
48
+ if (err?.code !== 'EEXIST') return false;
49
+ }
50
+ try {
51
+ if (Date.now() - fs.statSync(lockDir).mtimeMs > STALE_LOCK_MS) fs.rmdirSync(lockDir);
52
+ } catch { /* the holder finished, or another process took it over first */ }
53
+ return false;
54
+ }
55
+
56
+ const releaseLock = (lockDir) => { try { fs.rmdirSync(lockDir); } catch { /* already gone */ } };
57
+
58
+ /** True when the last sweep of this home was less than an hour ago. */
59
+ function sweptRecently(stampFile, now) {
60
+ try { return now - fs.statSync(stampFile).mtimeMs < SWEEP_INTERVAL_MS; } catch { return false; }
61
+ }
62
+
63
+ const isOlderThan = (file, ms, now) => {
64
+ try { return now - fs.statSync(file).mtimeMs > ms; } catch { return false; }
65
+ };
66
+
67
+ /** Ids of board files not touched for `days`; every save and draft updates a board file. */
68
+ function expiredBoardIds(boardsDir, days, now, keep) {
69
+ const expired = [];
70
+ for (const name of fs.readdirSync(boardsDir)) {
71
+ const match = /^(b-[a-z0-9]+)\.json$/i.exec(name);
72
+ if (match && !keep.has(match[1]) && isOlderThan(path.join(boardsDir, name), days * DAY_MS, now)) expired.push(match[1]);
73
+ }
74
+ return expired;
75
+ }
76
+
77
+ function removeStaleTempFiles(dir, now) {
78
+ for (const name of fs.readdirSync(dir)) {
79
+ const file = path.join(dir, name);
80
+ if (!name.endsWith('.tmp') || !isOlderThan(file, STALE_TEMP_MS, now)) continue;
81
+ try { fs.unlinkSync(file); } catch { /* removed by another process */ }
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Removes boards whose files have not changed for `days`. Several processes can
87
+ * share one relay home: a lock directory keeps two sweeps apart, and a stamp
88
+ * file keeps a busy home from sweeping on every new board. A board a running
89
+ * server still serves, and any board younger than the window, stays.
90
+ * @param {object} options
91
+ * @param {string} options.home the relay home; holds the lock and the stamp
92
+ * @param {string} options.boardsDir
93
+ * @param {number} options.days window in days; 0 or less does nothing
94
+ * @param {Set<string>} [options.keep] ids that must stay, such as boards with a live server
95
+ * @param {(id: string) => boolean} options.remove deletes one board and its sidecar files
96
+ * @param {number} [options.now] ms since the epoch
97
+ * @param {boolean} [options.force] sweep even when one ran in the last hour
98
+ * @returns {string[]} the ids removed
99
+ */
100
+ export function pruneBoards({ home, boardsDir, days, keep = new Set(), remove, now = Date.now(), force = false }) {
101
+ if (!(days > 0)) return [];
102
+ const lockDir = path.join(home, LOCK_NAME);
103
+ const stampFile = path.join(home, STAMP_NAME);
104
+ if (!takeLock(lockDir)) return [];
105
+ try {
106
+ if (!force && sweptRecently(stampFile, now)) return [];
107
+ // A board saved since the scan is checked again, so a draft that lands mid-sweep keeps its board.
108
+ const removed = expiredBoardIds(boardsDir, days, now, keep)
109
+ .filter((id) => isOlderThan(path.join(boardsDir, `${id}.json`), days * DAY_MS, now) && remove(id));
110
+ removeStaleTempFiles(boardsDir, now);
111
+ fs.writeFileSync(stampFile, new Date(now).toISOString());
112
+ return removed;
113
+ } finally {
114
+ releaseLock(lockDir);
115
+ }
116
+ }
@@ -3,7 +3,6 @@ import crypto from 'node:crypto';
3
3
  import fs from 'node:fs';
4
4
  import http from 'node:http';
5
5
  import path from 'node:path';
6
- import { filePreview, mediaType, splitFileReference } from '../file-preview.js';
7
6
  import { resolveLink } from '../link.js';
8
7
  import { openUrl } from '../open.js';
9
8
  import { assertSpecReady, cleanAnswers } from '../spec/index.js';
@@ -14,8 +13,8 @@ import { isDirectLocalRequest, readBody, sameOrigin, sendDataImage, sendFromDir,
14
13
  import { UI_DIR, VENDOR_DIR } from './paths.js';
15
14
  import { findBlock, findHtmlBlock, firstBoardHtml, firstQuestionHtml, sanitizeAnnotations, sanitizeBlockEdits } from './sanitize.js';
16
15
  import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, artifactBytesMatch, runOnResult } from './result.js';
17
- import { checkReadable } from '../file-access.js';
18
- import { buildOpenAllowlist, recordFileAccess, resolveLocalPath, streamFile } from './files.js';
16
+ import { openReadable } from '../file-access.js';
17
+ import { buildOpenAllowlist, recordFileAccess, resolveLocalPath, respondWithOpenedFile, streamFile } from './files.js';
19
18
 
20
19
  // Serves one board on 127.0.0.1 and resolves `done` when it finishes
21
20
  // (submitted / acknowledged / timeout / cancelled). The result is also
@@ -332,17 +331,17 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
332
331
  const blockId = decodeURIComponent(pathname.slice('/video/b/'.length));
333
332
  const block = findBlock(record.spec, blockId, 'video');
334
333
  if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local video block "${blockId}"` });
335
- const video = checkReadable(fileAccess, block.file);
336
- if (!video.ok) return sendJson(res, 404, { error: `no local video block "${blockId}"` });
337
- streamFile(req, res, video.file, block.mime || 'application/octet-stream');
334
+ const video = openReadable(fileAccess, block.file);
335
+ if (!video.ok || video.fd === null) return sendJson(res, 404, { error: `no local video block "${blockId}"` });
336
+ streamFile(req, res, video, block.mime || 'application/octet-stream');
338
337
  } else if ((req.method === 'GET' || req.method === 'HEAD') && pathname.startsWith('/pdf/b/')) {
339
338
  // Local PDF bytes, Range-streamed for the browser's built-in PDF viewer.
340
339
  const blockId = decodeURIComponent(pathname.slice('/pdf/b/'.length));
341
340
  const block = findBlock(record.spec, blockId, 'pdf');
342
341
  if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
343
- const pdf = checkReadable(fileAccess, block.file);
344
- if (!pdf.ok) return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
345
- streamFile(req, res, pdf.file, block.mime || 'application/pdf');
342
+ const pdf = openReadable(fileAccess, block.file);
343
+ if (!pdf.ok || pdf.fd === null) return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
344
+ streamFile(req, res, pdf, block.mime || 'application/pdf');
346
345
  } else if (req.method === 'GET' && pathname === '/html/board') {
347
346
  // Legacy alias → the board's first html block.
348
347
  const block = firstBoardHtml(record.spec);
@@ -381,24 +380,12 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
381
380
  if (!buildOpenAllowlist(record.spec, baseCwd).has(target)) {
382
381
  return sendJson(res, 403, { error: 'this path is not referenced on the board' });
383
382
  }
384
- const checked = checkReadable(fileAccess, target, { allowDirectory: true });
385
- if (!checked.ok) {
386
- if (checked.reason === 'missing') return sendJson(res, 404, { error: 'file not found', path: target });
387
- return sendJson(res, 403, { error: checked.reason === 'outside' ? 'this path is outside the board\'s file roots' : 'this path is not a file or folder' });
383
+ const opened = openReadable(fileAccess, target, { allowDirectory: true });
384
+ if (!opened.ok) {
385
+ if (opened.reason === 'missing') return sendJson(res, 404, { error: 'file not found', path: target });
386
+ return sendJson(res, 403, { error: opened.reason === 'outside' ? 'this path is outside the board\'s file roots' : 'this path is not a file or folder' });
388
387
  }
389
- const { file: real, stat } = checked;
390
- if (pathname === '/api/file-preview') {
391
- return sendJson(res, 200, { ok: true, ...filePreview(real, stat, splitFileReference(raw)) });
392
- }
393
- if (pathname === '/api/file-content') {
394
- const media = mediaType(real);
395
- if (!stat.isFile() || !media) return sendJson(res, 415, { error: 'this file type cannot be streamed' });
396
- res.setHeader('X-Content-Type-Options', 'nosniff');
397
- res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
398
- return streamFile(req, res, real, media[1]);
399
- }
400
- if (!openUrl(real)) return sendJson(res, 500, { error: 'could not open the file' });
401
- sendJson(res, 200, { ok: true, path: target, name: path.basename(target) });
388
+ respondWithOpenedFile(req, res, pathname, opened, raw, target);
402
389
  } else if (req.method === 'POST' && pathname === '/api/draft') {
403
390
  if (record.spec.responseRequired === false) return sendJson(res, 409, { error: 'display-only boards do not collect feedback' });
404
391
  const access = accessFor(req, reqUrl);
@@ -4,7 +4,8 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { createFileAccess } from '../file-access.js';
7
- import { splitFileReference } from '../file-preview.js';
7
+ import { filePreview, mediaType, splitFileReference } from '../file-preview.js';
8
+ import { openUrl } from '../open.js';
8
9
  import { boardFileRoots } from '../store.js';
9
10
  import { sendJson } from './http.js';
10
11
 
@@ -96,17 +97,13 @@ export function buildOpenAllowlist(spec, baseCwd) {
96
97
  return set;
97
98
  }
98
99
 
99
- // Streams a file with HTTP Range support so a <video>/<audio> element can seek
100
- // and the browser can request byte ranges instead of the whole clip. Honors a
101
- // single "bytes=start-end" range; falls back to the full body otherwise. Safe
102
- // for a HEAD probe (sends headers, no body).
103
- export function streamFile(req, res, filePath, contentType) {
104
- let stat;
105
- try {
106
- stat = fs.statSync(filePath);
107
- } catch {
108
- return sendJson(res, 404, { error: 'file not found' });
109
- }
100
+ // Streams an opened file (`openReadable`'s `fd` and `stat`) with HTTP Range
101
+ // support so a <video>/<audio> element can seek and the browser can request byte
102
+ // ranges instead of the whole clip. Honors a single "bytes=start-end" range;
103
+ // falls back to the full body otherwise. Safe for a HEAD probe (sends headers,
104
+ // no body). Takes ownership of the descriptor and closes it on every path.
105
+ export function streamFile(req, res, opened, contentType) {
106
+ const { fd, stat } = opened;
110
107
  const total = stat.size;
111
108
  const range = req.headers.range;
112
109
  const baseHeaders = {
@@ -130,6 +127,7 @@ export function streamFile(req, res, filePath, contentType) {
130
127
  }
131
128
  }
132
129
  if (start > end || start >= total) {
130
+ fs.closeSync(fd);
133
131
  res.writeHead(416, { 'content-range': `bytes */${total}`, 'cache-control': 'no-store' });
134
132
  return res.end();
135
133
  }
@@ -138,11 +136,46 @@ export function streamFile(req, res, filePath, contentType) {
138
136
  }
139
137
  baseHeaders['content-length'] = String(end - start + 1);
140
138
  res.writeHead(status, baseHeaders);
141
- if (req.method === 'HEAD') return res.end();
142
- const stream = fs.createReadStream(filePath, { start, end });
139
+ if (req.method === 'HEAD' || total === 0) {
140
+ fs.closeSync(fd);
141
+ return res.end();
142
+ }
143
+ const stream = fs.createReadStream('', { fd, start, end });
143
144
  stream.on('error', () => {
144
145
  if (!res.headersSent) sendJson(res, 500, { error: 'stream error' });
145
146
  else res.destroy();
146
147
  });
148
+ res.on('close', () => stream.destroy());
147
149
  stream.pipe(res);
148
150
  }
151
+
152
+ export function closeOpened(opened) {
153
+ if (opened.fd !== null && opened.fd !== undefined) fs.closeSync(opened.fd);
154
+ }
155
+
156
+ /**
157
+ * Answers /api/file-preview, /api/file-content and /api/open for a file that
158
+ * `openReadable` already checked. Every branch closes the descriptor.
159
+ */
160
+ export function respondWithOpenedFile(req, res, pathname, opened, raw, target) {
161
+ const { file: real, stat } = opened;
162
+ if (pathname === '/api/file-content') {
163
+ const media = mediaType(real);
164
+ if (!stat.isFile() || !media) {
165
+ closeOpened(opened);
166
+ return sendJson(res, 415, { error: 'this file type cannot be streamed' });
167
+ }
168
+ res.setHeader('X-Content-Type-Options', 'nosniff');
169
+ res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
170
+ return streamFile(req, res, opened, media[1]);
171
+ }
172
+ try {
173
+ if (pathname === '/api/file-preview') {
174
+ return sendJson(res, 200, { ok: true, ...filePreview(opened, splitFileReference(raw)) });
175
+ }
176
+ if (!openUrl(real)) return sendJson(res, 500, { error: 'could not open the file' });
177
+ sendJson(res, 200, { ok: true, path: target, name: path.basename(target) });
178
+ } finally {
179
+ closeOpened(opened);
180
+ }
181
+ }
@@ -1,7 +1,6 @@
1
1
  // The image block, and the image reader that compare blocks share.
2
- import fs from 'node:fs';
3
2
  import path from 'node:path';
4
- import { resolveReadable } from '../../file-access.js';
3
+ import { readReadable } from '../../file-access.js';
5
4
  import { CliError } from '../../util.js';
6
5
  import { asStr, clampInt } from '../sources.js';
7
6
  import { BLOCK_HEIGHT, IMAGE_MAX_BYTES, IMAGE_MIMES } from '../constants.js';
@@ -16,9 +15,7 @@ export function resolveImageSrc(srcRaw, files, where, field) {
16
15
  const ext = path.extname(src).slice(1).toLowerCase();
17
16
  const mime = IMAGE_MIMES[ext];
18
17
  if (!mime) throw new CliError(`${where}: ${field}: unsupported image extension ".${ext}" — use ${Object.keys(IMAGE_MIMES).join('/')}, or an http(s)/data URL.`);
19
- const { file: p } = resolveReadable(files, src, where, field);
20
- let buf;
21
- try { buf = fs.readFileSync(p); } catch { throw new CliError(`${where}: ${field}: cannot read image "${src}" (resolved: ${p})`); }
18
+ const { buf } = readReadable(files, src, where, field);
22
19
  if (buf.length > IMAGE_MAX_BYTES) throw new CliError(`${where}: ${field}: image "${src}" is ${(buf.length / 1024 / 1024).toFixed(1)}MB — max ${IMAGE_MAX_BYTES / 1024 / 1024}MB.`);
23
20
  return `data:${mime};base64,${buf.toString('base64')}`;
24
21
  }
@@ -1,7 +1,6 @@
1
1
  // The table block: CSV, TSV and JSON row files, and normalization.
2
- import fs from 'node:fs';
3
2
  import path from 'node:path';
4
- import { resolveReadable } from '../../file-access.js';
3
+ import { readReadable } from '../../file-access.js';
5
4
  import { CliError } from '../../util.js';
6
5
  import { BLOCK_HEIGHT, TEXT_FILE_MAX_BYTES } from '../constants.js';
7
6
  import { asStr, clampInt } from '../sources.js';
@@ -40,9 +39,7 @@ function parseDelimited(text, delim) {
40
39
  // CSV/TSV: first row = header → column keys. JSON: an array of objects (columns
41
40
  // from the union of keys) or arrays (needs explicit "columns").
42
41
  function loadRowsFile(file, files, where) {
43
- const { file: p } = resolveReadable(files, file, where, 'rowsFile');
44
- let buf;
45
- try { buf = fs.readFileSync(p); } catch { throw new CliError(`${where}: cannot read rowsFile "${file}" (resolved: ${p})`); }
42
+ const { file: p, buf } = readReadable(files, file, where, 'rowsFile');
46
43
  if (buf.length > TEXT_FILE_MAX_BYTES) {
47
44
  throw new CliError(`${where}: rowsFile "${file}" is ${(buf.length / 1024).toFixed(0)}KB — max ${TEXT_FILE_MAX_BYTES / 1024}KB.`);
48
45
  }
@@ -1,6 +1,5 @@
1
1
  // Readers for text that a block takes inline or from a file next to the spec.
2
- import fs from 'node:fs';
3
- import { resolveReadable } from '../file-access.js';
2
+ import { readReadable } from '../file-access.js';
4
3
  import { CliError } from '../util.js';
5
4
  import { TEXT_FILE_MAX_BYTES } from './constants.js';
6
5
 
@@ -26,12 +25,7 @@ export function readBlockHtml(block, files, where) {
26
25
 
27
26
  function readHtmlFile(obj, files, where) {
28
27
  if (typeof obj.htmlFile !== 'string' || !obj.htmlFile.trim()) return '';
29
- const { file } = resolveReadable(files, obj.htmlFile, where, 'htmlFile');
30
- try {
31
- return fs.readFileSync(file, 'utf8');
32
- } catch {
33
- throw new CliError(`${where}: cannot read htmlFile "${obj.htmlFile}" (resolved: ${file})`);
34
- }
28
+ return readReadable(files, obj.htmlFile, where, 'htmlFile').buf.toString('utf8');
35
29
  }
36
30
 
37
31
  // Reads a code/diff block body from an inline string field or a local file.
@@ -40,13 +34,7 @@ function readHtmlFile(obj, files, where) {
40
34
  export function readTextSource(block, inlineKey, fileKey, files, where) {
41
35
  if (typeof block[inlineKey] === 'string' && block[inlineKey] !== '') return block[inlineKey];
42
36
  if (typeof block[fileKey] === 'string' && block[fileKey].trim()) {
43
- const { file: p } = resolveReadable(files, block[fileKey], where, fileKey);
44
- let buf;
45
- try {
46
- buf = fs.readFileSync(p);
47
- } catch {
48
- throw new CliError(`${where}: cannot read ${fileKey} "${block[fileKey]}" (resolved: ${p})`);
49
- }
37
+ const { buf } = readReadable(files, block[fileKey], where, fileKey);
50
38
  if (buf.length > TEXT_FILE_MAX_BYTES) {
51
39
  throw new CliError(`${where}: ${fileKey} "${block[fileKey]}" is ${(buf.length / 1024).toFixed(0)}KB — max ${TEXT_FILE_MAX_BYTES / 1024}KB.`);
52
40
  }
@@ -61,13 +49,7 @@ export function readAnyTextSource(block, inlineKeys, fileKeys, files, where, lab
61
49
  }
62
50
  for (const key of fileKeys) {
63
51
  if (typeof block[key] === 'string' && block[key].trim()) {
64
- const { file: p } = resolveReadable(files, block[key], where, label);
65
- let buf;
66
- try {
67
- buf = fs.readFileSync(p);
68
- } catch {
69
- throw new CliError(`${where}: cannot read ${label} "${block[key]}" (resolved: ${p})`);
70
- }
52
+ const { file: p, buf } = readReadable(files, block[key], where, label);
71
53
  if (buf.length > TEXT_FILE_MAX_BYTES) {
72
54
  throw new CliError(`${where}: ${label} "${block[key]}" is ${(buf.length / 1024).toFixed(0)}KB — max ${TEXT_FILE_MAX_BYTES / 1024}KB.`);
73
55
  }
package/src/store.js CHANGED
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
4
  import crypto from 'node:crypto';
5
+ import { pruneBoards, resolveRetentionDays } from './retention.js';
5
6
 
6
7
  // All state lives under one dir so multiple boards/instances never collide.
7
8
  // RLY_HOME override exists for tests and sandboxed agents.
@@ -20,6 +21,21 @@ export function newId() {
20
21
  return `b-${t}${r}`;
21
22
  }
22
23
 
24
+ /**
25
+ * Writes through a temp file in the same folder and renames it over the target,
26
+ * so a crash mid-write leaves the old file, never half a new one.
27
+ */
28
+ function writeFileAtomic(file, data) {
29
+ const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
30
+ try {
31
+ fs.writeFileSync(temp, data);
32
+ fs.renameSync(temp, file);
33
+ } catch (err) {
34
+ try { fs.unlinkSync(temp); } catch { /* never written */ }
35
+ throw err;
36
+ }
37
+ }
38
+
23
39
  const boardPath = (id) => path.join(BOARDS_DIR, `${id}.json`);
24
40
  const runningPath = (id) => path.join(RUNNING_DIR, `${id}.json`);
25
41
  export const artifactDirPath = (id) => path.join(BOARDS_DIR, `${id}.artifacts`);
@@ -43,9 +59,11 @@ export function boardFileRoots(record) {
43
59
 
44
60
  /**
45
61
  * @param {any} spec a normalized spec
46
- * @param {{ fileRoots?: string[] }} [options] the roots the spec was read under; the live server opens only files inside them
62
+ * @param {{ fileRoots?: string[], retentionDays?: number | string | boolean }} [options] `fileRoots`: the roots the spec was read under; the live server opens only files inside them. `retentionDays`: how long old boards stay (see `resolveRetentionDays`)
47
63
  */
48
- export function createBoard(spec, { fileRoots } = {}) {
64
+ export function createBoard(spec, { fileRoots, retentionDays } = {}) {
65
+ // A bad retention setting throws here, before any file is written.
66
+ const days = resolveRetentionDays(retentionDays);
49
67
  ensureDirs();
50
68
  const record = {
51
69
  id: newId(),
@@ -61,12 +79,33 @@ export function createBoard(spec, { fileRoots } = {}) {
61
79
  result: null,
62
80
  };
63
81
  saveBoard(record);
82
+ pruneOldBoards(days);
64
83
  return record;
65
84
  }
66
85
 
86
+ /**
87
+ * Removes boards unchanged for `days`, except those a live server still serves.
88
+ * A failed sweep never blocks the board being created, so errors stay here.
89
+ * @returns {string[]} the ids removed
90
+ */
91
+ export function pruneOldBoards(days, { force = false } = {}) {
92
+ try {
93
+ return pruneBoards({
94
+ home: HOME,
95
+ boardsDir: BOARDS_DIR,
96
+ days,
97
+ keep: new Set(listRunning().map((r) => r.id)),
98
+ remove: deleteBoard,
99
+ force,
100
+ });
101
+ } catch {
102
+ return [];
103
+ }
104
+ }
105
+
67
106
  export function saveBoard(record) {
68
107
  ensureDirs();
69
- fs.writeFileSync(boardPath(record.id), JSON.stringify(record, null, 2));
108
+ writeFileAtomic(boardPath(record.id), JSON.stringify(record, null, 2));
70
109
  }
71
110
 
72
111
  export function loadBoard(id) {
@@ -85,7 +124,7 @@ export function saveResultFile(id, result) {
85
124
  try {
86
125
  ensureDirs();
87
126
  const p = path.join(BOARDS_DIR, `${id}.result.json`);
88
- fs.writeFileSync(p, JSON.stringify(result, null, 2));
127
+ writeFileAtomic(p, JSON.stringify(result, null, 2));
89
128
  return p;
90
129
  } catch {
91
130
  return null;
@@ -120,7 +159,7 @@ export function listBoards(limit = 20) {
120
159
 
121
160
  export function saveRunning(info) {
122
161
  ensureDirs();
123
- fs.writeFileSync(runningPath(info.id), JSON.stringify(info, null, 2));
162
+ writeFileAtomic(runningPath(info.id), JSON.stringify(info, null, 2));
124
163
  }
125
164
 
126
165
  export function loadRunning(id) {
@@ -159,7 +198,7 @@ export function loadPref() {
159
198
 
160
199
  export function savePref(patch) {
161
200
  ensureDirs();
162
- fs.writeFileSync(prefPath(), JSON.stringify({ ...loadPref(), ...patch }, null, 2));
201
+ writeFileAtomic(prefPath(), JSON.stringify({ ...loadPref(), ...patch }, null, 2));
163
202
  }
164
203
 
165
204
  export function isAlive(pid) {
@@ -103,6 +103,7 @@ export const BOARD_SCRIPT_PARTS = [
103
103
  'mcp-ui/board/vendors.js',
104
104
  'mcp-ui/board/block-ctx.js',
105
105
  'mcp-ui/board/state.js',
106
+ 'mcp-ui/board/draft.js',
106
107
  'mcp-ui/board/controls.js',
107
108
  'mcp-ui/board/render.js',
108
109
  'mcp-ui/board/lifecycle.js',
@@ -43,7 +43,7 @@ export declare function isInsideRoots(target: any, roots: any): any;
43
43
  * @param {FileAccess} access
44
44
  * @param {unknown} raw the path as written; `~` and relative paths are expanded
45
45
  * @param {{ allowDirectory?: boolean }} [options] directories are refused unless a caller opens them in an app
46
- * @returns {{ ok: boolean, file?: string, stat?: fs.Stats, reason?: 'invalid' | 'outside' | 'missing' | 'not-file', resolved?: string }} `file` and `stat` when ok; otherwise `reason` and the real path it was refused at
46
+ * @returns {{ ok: boolean, file?: string, stat?: fs.Stats, reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed' }} `file` and `stat` when ok; otherwise the `reason`, which callers keep to themselves
47
47
  */
48
48
  export declare function checkReadable(access: FileAccess, raw: unknown, { allowDirectory }?: {
49
49
  allowDirectory?: boolean;
@@ -51,11 +51,32 @@ export declare function checkReadable(access: FileAccess, raw: unknown, { allowD
51
51
  ok: boolean;
52
52
  file?: string;
53
53
  stat?: fs.Stats;
54
- reason?: 'invalid' | 'outside' | 'missing' | 'not-file';
55
- resolved?: string;
54
+ reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed';
55
+ };
56
+ /**
57
+ * Like `checkReadable`, but also opens a regular file, and keeps the open
58
+ * descriptor as the only way to read it. A path checked and then read by name
59
+ * can be swapped for a symlink in between; the descriptor cannot. After the
60
+ * open, the path must still resolve to the same file inside the roots, or the
61
+ * read is refused. A directory (when allowed) comes back with `fd: null`.
62
+ * The caller closes `fd`, or hands it to `streamFile`, which does.
63
+ * @param {FileAccess} access
64
+ * @param {unknown} raw
65
+ * @param {{ allowDirectory?: boolean }} [options]
66
+ * @returns {{ ok: boolean, file?: string, stat?: fs.Stats, fd?: number | null, reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed' }}
67
+ */
68
+ export declare function openReadable(access: FileAccess, raw: unknown, options?: {
69
+ allowDirectory?: boolean;
70
+ }): {
71
+ ok: boolean;
72
+ file?: string;
73
+ stat?: fs.Stats;
74
+ fd?: number | null;
75
+ reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed';
56
76
  };
57
77
  /**
58
78
  * The real path of a file a spec names, or a CliError worded for the agent.
79
+ * Use `readReadable` to read it.
59
80
  * @param {FileAccess} access
60
81
  * @param {unknown} raw
61
82
  * @param {string} where which block, e.g. `board.blocks[0]`
@@ -66,3 +87,16 @@ export declare function resolveReadable(access: FileAccess, raw: unknown, where:
66
87
  file: string;
67
88
  stat: fs.Stats;
68
89
  };
90
+ /**
91
+ * The bytes of a file a spec names, read through one opened descriptor.
92
+ * @param {FileAccess} access
93
+ * @param {unknown} raw
94
+ * @param {string} where which block, e.g. `board.blocks[0]`
95
+ * @param {string} field which field, e.g. `codeFile`
96
+ * @returns {{ file: string, stat: fs.Stats, buf: Buffer }}
97
+ */
98
+ export declare function readReadable(access: FileAccess, raw: unknown, where: string, field: string): {
99
+ file: string;
100
+ stat: fs.Stats;
101
+ buf: Buffer;
102
+ };
@@ -1,6 +1,10 @@
1
- /** Serves MCP over this process's stdin and stdout until the host closes stdin. */
2
- export declare function runMcp({ fileRoots }?: {
3
- fileRoots?: any[];
1
+ /**
2
+ * Serves MCP over this process's stdin and stdout until the host closes stdin.
3
+ * @param {{ fileRoots?: string[], retentionDays?: string | number }} [options]
4
+ */
5
+ export declare function runMcp({ fileRoots, retentionDays }?: {
6
+ fileRoots?: string[];
7
+ retentionDays?: string | number;
4
8
  }): Promise<any>;
5
9
  /** A browser Origin is trusted when it is local or the one the operator allowed. A client with no Origin is not a browser. */
6
10
  export declare function originAllowed(origin: any, allowOrigin: any): boolean;
@@ -9,11 +13,13 @@ export declare function safeEqual(a: any, b: any): boolean;
9
13
  /**
10
14
  * Serves MCP over Streamable HTTP. Localhost by default; a bearer token and an
11
15
  * allowed Origin are the controls for anything wider.
16
+ * @param {{ port?: number, host?: string, token?: string, allowOrigin?: string, fileRoots?: string[], retentionDays?: string | number }} [options]
12
17
  */
13
- export declare function runMcpHttp({ port, host, token, allowOrigin, fileRoots }?: {
14
- allowOrigin?: string;
15
- fileRoots?: any[];
16
- host?: string;
18
+ export declare function runMcpHttp({ port, host, token, allowOrigin, fileRoots, retentionDays }?: {
17
19
  port?: number;
20
+ host?: string;
18
21
  token?: string;
22
+ allowOrigin?: string;
23
+ fileRoots?: string[];
24
+ retentionDays?: string | number;
19
25
  }): Promise<any>;
@@ -38,8 +38,13 @@ export type RelayStore = {
38
38
  * @property {(id: string) => BoardRecord | null | Promise<BoardRecord | null>} get
39
39
  * @property {(id: string, patch: Partial<BoardRecord>) => BoardRecord | null | Promise<BoardRecord | null>} update
40
40
  */
41
- /** The default store: one JSON file per board under the relay home, shared with the CLI. */
42
- export declare function fileStore(): {
41
+ /**
42
+ * The default store: one JSON file per board under the relay home, shared with the CLI.
43
+ * @param {{ retentionDays?: number | string | boolean }} [options] how long old boards stay; see `resolveRetentionDays`
44
+ */
45
+ export declare function fileStore({ retentionDays }?: {
46
+ retentionDays?: number | string | boolean;
47
+ }): {
43
48
  create: (spec: any, options: any) => {
44
49
  id: string;
45
50
  createdAt: string;
@@ -4,6 +4,7 @@
4
4
  * @param {any} server an McpServer
5
5
  * @param {object} [options]
6
6
  * @param {import('./store.js').RelayStore} [options.store] where boards live; defaults to the relay home on disk
7
+ * @param {number | string | boolean} [options.retentionDays] with the default store, boards unchanged for this many days are removed when a new board is made (default 30; `0`, `false` or "off" keeps every board). `RLY_RETENTION_DAYS` sets it when the option is absent. A custom `store` does its own cleanup
7
8
  * @param {string[]} [options.fileRoots] folders a spec may read local files from (`codeFile`, images, `rowsFile`...); none by default, so a remote client cannot read the server's disk
8
9
  * @param {string | Buffer} [options.tokenKey] the secret behind board tokens; defaults to a key file in the relay home
9
10
  * @param {(name: string) => string} [options.assetUrl] URL of a vendor file, for hosts that can fetch it
@@ -12,6 +13,7 @@
12
13
  */
13
14
  export declare function registerRelay(server: any, options?: {
14
15
  store?: import('./store.js').RelayStore;
16
+ retentionDays?: number | string | boolean;
15
17
  fileRoots?: string[];
16
18
  tokenKey?: string | Buffer;
17
19
  assetUrl?: (name: string) => string;
@@ -0,0 +1,33 @@
1
+ export declare const RETENTION_ENV = "RLY_RETENTION_DAYS";
2
+ export declare const DEFAULT_RETENTION_DAYS = 30;
3
+ /**
4
+ * The retention window in days; 0 means boards are kept forever.
5
+ * The option wins over `RLY_RETENTION_DAYS`, which wins over the 30-day default.
6
+ * @param {unknown} [option] a number of days, a numeric string, or `0`, `false` or "off" to keep every board
7
+ * @param {Record<string, string | undefined>} [env]
8
+ */
9
+ export declare function resolveRetentionDays(option?: unknown, env?: Record<string, string | undefined>): number;
10
+ /**
11
+ * Removes boards whose files have not changed for `days`. Several processes can
12
+ * share one relay home: a lock directory keeps two sweeps apart, and a stamp
13
+ * file keeps a busy home from sweeping on every new board. A board a running
14
+ * server still serves, and any board younger than the window, stays.
15
+ * @param {object} options
16
+ * @param {string} options.home the relay home; holds the lock and the stamp
17
+ * @param {string} options.boardsDir
18
+ * @param {number} options.days window in days; 0 or less does nothing
19
+ * @param {Set<string>} [options.keep] ids that must stay, such as boards with a live server
20
+ * @param {(id: string) => boolean} options.remove deletes one board and its sidecar files
21
+ * @param {number} [options.now] ms since the epoch
22
+ * @param {boolean} [options.force] sweep even when one ran in the last hour
23
+ * @returns {string[]} the ids removed
24
+ */
25
+ export declare function pruneBoards({ home, boardsDir, days, keep, remove, now, force }: {
26
+ home: string;
27
+ boardsDir: string;
28
+ days: number;
29
+ keep?: Set<string>;
30
+ remove: (id: string) => boolean;
31
+ now?: number;
32
+ force?: boolean;
33
+ }): string[];
@@ -1,10 +1,10 @@
1
1
  export declare function normalizeCodeBlock(rawBlock: any, id: any, files: any, where: any, hasHeight: any): {
2
2
  id: any;
3
3
  type: string;
4
- code: any;
4
+ code: string;
5
5
  };
6
6
  export declare function normalizeDiffBlock(rawBlock: any, id: any, files: any, where: any, hasHeight: any): {
7
7
  id: any;
8
8
  type: string;
9
- diff: any;
9
+ diff: string;
10
10
  };
@@ -1,5 +1,5 @@
1
1
  export declare function normalizeMarkdownBlock(rawBlock: any, id: any, files: any, where: any, hasHeight: any): {
2
2
  id: any;
3
3
  type: string;
4
- md: any;
4
+ md: string;
5
5
  };
@@ -3,13 +3,13 @@ export declare function clampInt(v: any, min: any, max: any, def: any): any;
3
3
  /** Reads `htmlFile` through the file roots; an inline `html` string wins. */
4
4
  export declare function readHtml(obj: any, files: any, where: any): any;
5
5
  export declare function readBlockHtml(block: any, files: any, where: any): any;
6
- export declare function readTextSource(block: any, inlineKey: any, fileKey: any, files: any, where: any): any;
6
+ export declare function readTextSource(block: any, inlineKey: any, fileKey: any, files: any, where: any): string;
7
7
  export declare function readAnyTextSource(block: any, inlineKeys: any, fileKeys: any, files: any, where: any, label: any): {
8
8
  text: string;
9
9
  sourceKey: any;
10
10
  file?: undefined;
11
11
  } | {
12
- text: any;
12
+ text: string;
13
13
  sourceKey: any;
14
14
  file: string;
15
15
  };
package/types/store.d.ts CHANGED
@@ -9,10 +9,11 @@ export declare function saveBoardArtifact(id: any, bytes: any, ext?: string): st
9
9
  export declare function boardFileRoots(record: any): any;
10
10
  /**
11
11
  * @param {any} spec a normalized spec
12
- * @param {{ fileRoots?: string[] }} [options] the roots the spec was read under; the live server opens only files inside them
12
+ * @param {{ fileRoots?: string[], retentionDays?: number | string | boolean }} [options] `fileRoots`: the roots the spec was read under; the live server opens only files inside them. `retentionDays`: how long old boards stay (see `resolveRetentionDays`)
13
13
  */
14
- export declare function createBoard(spec: any, { fileRoots }?: {
14
+ export declare function createBoard(spec: any, { fileRoots, retentionDays }?: {
15
15
  fileRoots?: string[];
16
+ retentionDays?: number | string | boolean;
16
17
  }): {
17
18
  id: string;
18
19
  createdAt: string;
@@ -23,6 +24,14 @@ export declare function createBoard(spec: any, { fileRoots }?: {
23
24
  draft: any;
24
25
  result: any;
25
26
  };
27
+ /**
28
+ * Removes boards unchanged for `days`, except those a live server still serves.
29
+ * A failed sweep never blocks the board being created, so errors stay here.
30
+ * @returns {string[]} the ids removed
31
+ */
32
+ export declare function pruneOldBoards(days: any, { force }?: {
33
+ force?: boolean;
34
+ }): string[];
26
35
  export declare function saveBoard(record: any): void;
27
36
  export declare function loadBoard(id: any): any;
28
37
  export declare function saveResultFile(id: any, result: any): string;