@khanglvm/relay 0.22.1 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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. 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
 
@@ -837,6 +839,9 @@ ignored. A small toast "Board updated by the agent" appears for 4 seconds.
837
839
 
838
840
  Stdout: `{"status":"updated","boardId":"…","rev":2,"url":"…"}`.
839
841
 
842
+ The new spec reads local files only under the roots the board was created with;
843
+ `--root` is refused on update, so start a new board with `rly ask --root PATH` to read elsewhere.
844
+
840
845
  **Caution:** the page reloads for the user. Batch your changes into one `rly update`
841
846
  call rather than calling it repeatedly in a loop.
842
847
 
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,7 +1,7 @@
1
1
  {
2
2
  "name": "@khanglvm/relay",
3
- "version": "0.22.1",
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, \u2026): ask users structured questions, present interactive visuals, collect inline comments, read answers as JSON \u2014 in a local browser board OR rendered INLINE inside the Claude & Codex apps as an MCP App (SEP-1865).",
3
+ "version": "0.23.0",
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",
7
7
  "claude-code",
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/boards.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import path from 'node:path';
3
3
  import { openUrl } from '../open.js';
4
4
  import { assertSpecReady, normalizeSpec, questionFromInline } from '../spec/index.js';
5
- import { HOME, controlUrl, createBoard, deleteBoard, isAlive, listBoards, listRunning, loadBoard, loadRunning, removeRunning, saveBoard } from '../store.js';
5
+ import { HOME, boardFileRoots, controlUrl, createBoard, deleteBoard, isAlive, listBoards, listRunning, loadBoard, loadRunning, removeRunning, saveBoard } from '../store.js';
6
6
  import { CliError, pollFor } from '../util.js';
7
7
  import { cliFileRoots, mustLoad, parseJson, printJson, readFileOrThrow, readStdin, runOrDetach } from './io.js';
8
8
 
@@ -139,7 +139,7 @@ export async function cmdReuse(args) {
139
139
  console.log(JSON.stringify(src.spec, null, 2));
140
140
  return 0;
141
141
  }
142
- const record = createBoard(src.spec, { fileRoots: src.fileRoots });
142
+ const record = createBoard(src.spec, { fileRoots: boardFileRoots(src) });
143
143
  return runOrDetach(record, args);
144
144
  }
145
145
 
@@ -156,7 +156,8 @@ export async function cmdUpdate(args) {
156
156
  throw new CliError(`board "${id}" is not running — \`rly reopen ${id}\` to serve it, then update.`, 5);
157
157
  }
158
158
 
159
- const fileRoots = [...new Set([...(record.fileRoots ?? [record.cwd]), ...cliFileRoots(args)])];
159
+ if (args.root.length) throw new CliError('update cannot add file roots: they are set when the board is created. Start a new board with `rly ask --root PATH`.', 4);
160
+ const fileRoots = boardFileRoots(record);
160
161
  let spec;
161
162
  if (args.file) {
162
163
  const raw =
@@ -183,7 +184,7 @@ export async function cmdUpdate(args) {
183
184
  res = await fetch(new URL('/api/update', controlUrl(running)), {
184
185
  method: 'POST',
185
186
  headers: { 'content-type': 'application/json', 'x-relay-token': running.token || '' },
186
- body: JSON.stringify({ spec, fileRoots }),
187
+ body: JSON.stringify({ spec }),
187
188
  });
188
189
  } catch (err) {
189
190
  throw new CliError(`could not reach board "${id}" at ${running.url}: ${String((err && err.message) || err)}`, 5);
package/src/cli/help.js CHANGED
@@ -52,7 +52,8 @@ USAGE
52
52
  disconnected browser tab auto-reconnects & re-saves (no new tab
53
53
  unless --open). Use when a tab shows "connection lost".
54
54
  rly reuse <id> [--dump] re-run a past board as a new board (--dump prints its spec)
55
- rly update <id> --file spec.json live-mutate a RUNNING board (or --title/--intro/-q); page reloads
55
+ rly update <id> --file spec.json live-mutate a RUNNING board (or --title/--intro/-q); page reloads;
56
+ files are read under the roots the board was created with
56
57
  rly stop <id> | --all stop running board(s) (status: cancelled, draft preserved)
57
58
  rly history [--limit n] [--json] saved boards
58
59
  rly spec <id> print a saved board's spec JSON (edit, then ask --file again)
@@ -72,6 +73,7 @@ USAGE
72
73
  rly mcp --http [--port N] serve over Streamable HTTP for web/mobile/remote hosts
73
74
  [--host H --token-file PATH --allow-origin ORIGIN]
74
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)
75
77
  (token: --token-file, $RLY_MCP_TOKEN, or --token, which shows in the process list)
76
78
  rly mcp config | install --target print host setup, or write it (claude | codex)
77
79
 
package/src/cli/mcp.js CHANGED
@@ -2,8 +2,9 @@
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
- import { envFileRoots, expandHome } from '../file-access.js';
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,15 @@ 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, [process.cwd()]) });
40
+ return runMcp({ fileRoots: mcpFileRoots(args, stdioDefaultRoots(process.cwd())), retentionDays: mcpRetention(args) });
41
+ }
42
+
43
+ /** The working directory as the stdio root, unless it is `/` or the home directory. */
44
+ function stdioDefaultRoots(cwd) {
45
+ if (!isBroadRoot(cwd)) return [cwd];
46
+ // stdout is the MCP channel, so the notice goes to stderr.
47
+ process.stderr.write(`relay mcp: the working directory ${cwd} is too wide to read files from by default; pass --root PATH to allow a folder.\n`);
48
+ return [];
39
49
  }
40
50
 
41
51
  /**
@@ -47,6 +57,13 @@ function mcpFileRoots(args, defaults) {
47
57
  return [...defaults, ...args.root, ...envFileRoots()].map((p) => path.resolve(expandHome(p)));
48
58
  }
49
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
+
50
67
  /**
51
68
  * The bearer token for --http. `--token` shows up in `ps`, so prefer `--token-file PATH`
52
69
  * or $RLY_MCP_TOKEN; the flag keeps working. A file that cannot be read is an error,
@@ -56,6 +56,18 @@ export function realRoots(list, cwd) {
56
56
  return [...new Set(out)];
57
57
  }
58
58
 
59
+ /**
60
+ * True when `dir` is a filesystem root or the home directory. Such a folder is
61
+ * too wide to grant by default: a desktop host often starts a stdio server at
62
+ * `/`, which would let a spec read the whole disk. Passing it as `--root` still works.
63
+ */
64
+ export function isBroadRoot(dir) {
65
+ let real;
66
+ try { real = fs.realpathSync.native(path.resolve(dir)); } catch { return false; }
67
+ if (path.parse(real).root === real) return true;
68
+ try { return real === fs.realpathSync.native(os.homedir()); } catch { return false; }
69
+ }
70
+
59
71
  /** Roots named by `RLY_FILE_ROOTS`. */
60
72
  export function envFileRoots(env = process.env) {
61
73
  return String(env[FILE_ROOTS_ENV] || '').split(path.delimiter).filter(Boolean);
@@ -82,22 +94,75 @@ export function isInsideRoots(target, roots) {
82
94
  * @param {FileAccess} access
83
95
  * @param {unknown} raw the path as written; `~` and relative paths are expanded
84
96
  * @param {{ allowDirectory?: boolean }} [options] directories are refused unless a caller opens them in an app
85
- * @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
86
98
  */
87
99
  export function checkReadable(access, raw, { allowDirectory = false } = {}) {
88
100
  const text = typeof raw === 'string' ? raw.trim() : '';
89
- if (!text || text.includes('\0')) return { ok: false, reason: 'invalid', resolved: text };
101
+ if (!text || text.includes('\0')) return { ok: false, reason: 'invalid' };
90
102
  const resolved = path.resolve(access.cwd, expandHome(text));
91
103
  const real = realpathOrAncestor(resolved);
92
- if (!isInsideRoots(real, access.roots)) return { ok: false, reason: 'outside', resolved: real };
104
+ if (!isInsideRoots(real, access.roots)) return { ok: false, reason: 'outside' };
93
105
  let stat;
94
- try { stat = fs.statSync(real); } catch { return { ok: false, reason: 'missing', resolved: real }; }
95
- 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' };
96
108
  return { ok: true, file: real, stat };
97
109
  }
98
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
+ /** True when `file` still resolves to itself, inside the roots, and is the very file `fd` has open. */
116
+ function isStillTheCheckedFile(access, file, fd) {
117
+ try {
118
+ if (fs.realpathSync.native(file) !== file || !isInsideRoots(file, access.roots)) return false;
119
+ const open = fs.fstatSync(fd);
120
+ const named = fs.statSync(file);
121
+ return open.isFile() && open.dev === named.dev && open.ino === named.ino;
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Like `checkReadable`, but also opens a regular file, and keeps the open
129
+ * descriptor as the only way to read it. A path checked and then read by name
130
+ * can be swapped for a symlink in between; the descriptor cannot. After the
131
+ * open, the path must still resolve to the same file inside the roots, or the
132
+ * read is refused. A directory (when allowed) comes back with `fd: null`.
133
+ * The caller closes `fd`, or hands it to `streamFile`, which does.
134
+ * @param {FileAccess} access
135
+ * @param {unknown} raw
136
+ * @param {{ allowDirectory?: boolean }} [options]
137
+ * @returns {{ ok: boolean, file?: string, stat?: fs.Stats, fd?: number | null, reason?: 'invalid' | 'outside' | 'missing' | 'not-file' | 'changed' }}
138
+ */
139
+ export function openReadable(access, raw, options = {}) {
140
+ const checked = checkReadable(access, raw, options);
141
+ if (!checked.ok) return { ok: false, reason: /** @type {any} */ (checked.reason) };
142
+ const file = /** @type {string} */ (checked.file);
143
+ if (!/** @type {fs.Stats} */ (checked.stat).isFile()) return { ok: true, file, stat: /** @type {fs.Stats} */ (checked.stat), fd: null };
144
+ let fd;
145
+ try { fd = fs.openSync(file, OPEN_FLAGS); } catch { return { ok: false, reason: 'changed' }; }
146
+ if (!isStillTheCheckedFile(access, file, fd)) {
147
+ fs.closeSync(fd);
148
+ return { ok: false, reason: 'changed' };
149
+ }
150
+ return { ok: true, file, stat: fs.fstatSync(fd), fd };
151
+ }
152
+
153
+ /**
154
+ * One message for every refusal, so it says nothing about whether the path
155
+ * exists, where a symlink leads or what the folders look like. It echoes the
156
+ * path as the caller wrote it.
157
+ */
158
+ function refusal(where, field, raw) {
159
+ const given = typeof raw === 'string' ? raw : String(raw);
160
+ return new CliError(`${where}: ${field}: cannot read "${given}": no such file, not a regular file, or path outside allowed roots; ${FIX_HINT}.`);
161
+ }
162
+
99
163
  /**
100
164
  * The real path of a file a spec names, or a CliError worded for the agent.
165
+ * Use `readReadable` to read it.
101
166
  * @param {FileAccess} access
102
167
  * @param {unknown} raw
103
168
  * @param {string} where which block, e.g. `board.blocks[0]`
@@ -106,12 +171,26 @@ export function checkReadable(access, raw, { allowDirectory = false } = {}) {
106
171
  */
107
172
  export function resolveReadable(access, raw, where, field) {
108
173
  const checked = checkReadable(access, raw);
109
- if (checked.ok) return { file: /** @type {string} */ (checked.file), stat: /** @type {fs.Stats} */ (checked.stat) };
110
- const given = typeof raw === 'string' ? raw : String(raw);
111
- const prefix = `${where}: ${field}: `;
112
- if (checked.reason === 'outside') {
113
- throw new CliError(`${prefix}path outside allowed roots (\"${given}\" resolves to ${checked.resolved}); ${FIX_HINT}.`);
174
+ if (!checked.ok) throw refusal(where, field, raw);
175
+ return { file: /** @type {string} */ (checked.file), stat: /** @type {fs.Stats} */ (checked.stat) };
176
+ }
177
+
178
+ /**
179
+ * The bytes of a file a spec names, read through one opened descriptor.
180
+ * @param {FileAccess} access
181
+ * @param {unknown} raw
182
+ * @param {string} where which block, e.g. `board.blocks[0]`
183
+ * @param {string} field which field, e.g. `codeFile`
184
+ * @returns {{ file: string, stat: fs.Stats, buf: Buffer }}
185
+ */
186
+ export function readReadable(access, raw, where, field) {
187
+ const opened = openReadable(access, raw);
188
+ if (!opened.ok || opened.fd === null) throw refusal(where, field, raw);
189
+ try {
190
+ return { file: opened.file, stat: opened.stat, buf: fs.readFileSync(opened.fd) };
191
+ } catch {
192
+ throw refusal(where, field, raw);
193
+ } finally {
194
+ fs.closeSync(opened.fd);
114
195
  }
115
- if (checked.reason === 'not-file') throw new CliError(`${prefix}\"${given}\" is not a regular file (resolved: ${checked.resolved}).`);
116
- throw new CliError(`${prefix}cannot read \"${given}\" (resolved: ${checked.resolved})`);
117
196
  }
@@ -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) {