@khanglvm/relay 0.17.1 → 0.18.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.
@@ -0,0 +1,29 @@
1
+ [The "BSD license"]
2
+ Copyright (c) 2012-2023 The ANTLR Project. All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions
6
+ are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright
9
+ notice, this list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright
12
+ notice, this list of conditions and the following disclaimer in the
13
+ documentation and/or other materials provided with the distribution.
14
+
15
+ 3. Neither name of copyright holders nor the names of its contributors
16
+ may be used to endorse or promote products derived from this software
17
+ without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
+ ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
23
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/src/cli.js CHANGED
@@ -16,11 +16,13 @@ import {
16
16
  removeRunning,
17
17
  isAlive,
18
18
  saveResultFile,
19
+ controlUrl,
19
20
  HOME,
20
21
  } from './store.js';
21
22
  import { runBoard } from './server.js';
22
23
  import { runMcp, runMcpHttp, mcpConfig } from './mcp.js';
23
24
  import { openUrl } from './open.js';
25
+ import { linkSetting, loadConfig, parseLinkValue, saveConfig, serializeLink } from './link.js';
24
26
 
25
27
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
26
28
  const PKG_ROOT = path.join(__dirname, '..');
@@ -35,7 +37,7 @@ const VALUED_FLAGS = new Set([
35
37
  'file', 'html', 'html-file', 'title', 'intro', 'timeout', 'port',
36
38
  'submit-label', 'height', 'limit', 'target', 'id', 'replies',
37
39
  'on-result', 'notify-cmd', 'idle-grace', 'scope', 'range',
38
- 'host', 'token', 'allow-origin', 'role',
40
+ 'host', 'token', 'allow-origin', 'role', 'public-url', 'link',
39
41
  ]);
40
42
 
41
43
  function camel(key) {
@@ -204,6 +206,7 @@ async function runOrDetach(record, args) {
204
206
  const timeoutSec = args.timeout !== undefined ? Math.max(0, Number.parseInt(args.timeout, 10) || 0) : DEFAULT_BOARD_TIMEOUT_SEC;
205
207
  const port = args.port !== undefined ? Number.parseInt(args.port, 10) || 0 : 0;
206
208
  const open = args.open !== false;
209
+ const link = linkSetting({ args, config: loadConfig(HOME) });
207
210
 
208
211
  // Push-wake: persist the agent's --on-result command on the record so BOTH
209
212
  // the inline runBoard path and the detached __serve path pick it up (the
@@ -223,12 +226,15 @@ async function runOrDetach(record, args) {
223
226
  '--port', String(port),
224
227
  '--timeout', String(timeoutSec),
225
228
  ...(open ? [] : ['--no-open']),
229
+ '--link', serializeLink(link),
226
230
  ],
227
231
  { detached: true, stdio: 'ignore' }
228
232
  );
229
233
  child.unref();
230
- const info = await pollFor(() => loadRunning(record.id), 8000);
231
- if (!info) throw new CliError(`board ${record.id} failed to start (no server after 8s).`, 1);
234
+ // A link setting adds a devlink round trip before the board is announced.
235
+ const startSec = link.mode === 'off' ? 8 : 40;
236
+ const info = await pollFor(() => loadRunning(record.id), startSec * 1000);
237
+ if (!info) throw new CliError(`board ${record.id} failed to start (no server after ${startSec}s).`, 1);
232
238
  printJson({
233
239
  status: 'open',
234
240
  boardId: record.id,
@@ -241,7 +247,7 @@ async function runOrDetach(record, args) {
241
247
  return 0;
242
248
  }
243
249
 
244
- const { done } = await runBoard({ id: record.id, port, open, timeoutSec });
250
+ const { done } = await runBoard({ id: record.id, port, open, timeoutSec, link });
245
251
  const result = await done;
246
252
  printResult(result);
247
253
  return exitCodeFor(result.status);
@@ -261,13 +267,13 @@ async function cmdAsk(args, mode) {
261
267
  // `rly diff HEAD~1`, `rly diff main -- src/` all work. rly flags: --detach,
262
268
  // --no-open, --split (side-by-side), --title.
263
269
  async function cmdDiff(rest) {
264
- const RLY_FLAGS = new Set(['--detach', '--no-open', '--split']);
270
+ const RLY_FLAGS = new Set(['--detach', '--no-open', '--split', '--devlink', '--no-devlink']);
265
271
  const gitArgs = [];
266
272
  const rlyArgv = [];
267
273
  for (let i = 0; i < rest.length; i++) {
268
274
  const t = rest[i];
269
- if (t === '--title') { rlyArgv.push(t, rest[++i]); continue; }
270
- if (t.startsWith('--title=')) { rlyArgv.push(t); continue; }
275
+ if (t === '--title' || t === '--public-url') { rlyArgv.push(t, rest[++i]); continue; }
276
+ if (t.startsWith('--title=') || t.startsWith('--public-url=')) { rlyArgv.push(t); continue; }
271
277
  if (RLY_FLAGS.has(t)) { rlyArgv.push(t); continue; }
272
278
  gitArgs.push(t);
273
279
  }
@@ -508,8 +514,8 @@ async function cmdReopen(args) {
508
514
  }
509
515
  const running = loadRunning(record.id);
510
516
  if (running && isAlive(running.pid)) {
511
- openUrl(running.url);
512
- printJson({ status: 'open', boardId: record.id, url: running.url, note: 'already running — browser re-opened' });
517
+ if (!running.link) openUrl(running.url);
518
+ printJson({ status: 'open', boardId: record.id, url: running.url, note: running.link ? 'already running' : 'already running — browser re-opened' });
513
519
  return 0;
514
520
  }
515
521
  // Reuse the board's last port (unless the user forced one) so a tab still open
@@ -529,7 +535,7 @@ async function cmdRescue(args) {
529
535
  const record = mustLoad(args._[0]);
530
536
  const running = loadRunning(record.id);
531
537
  if (running && isAlive(running.pid)) {
532
- if (args.open) openUrl(running.url);
538
+ if (args.open && !running.link) openUrl(running.url);
533
539
  printJson({
534
540
  status: 'open',
535
541
  boardId: record.id,
@@ -600,7 +606,7 @@ async function cmdUpdate(args) {
600
606
 
601
607
  let res;
602
608
  try {
603
- res = await fetch(new URL('/api/update', running.url), {
609
+ res = await fetch(new URL('/api/update', controlUrl(running)), {
604
610
  method: 'POST',
605
611
  headers: { 'content-type': 'application/json', 'x-relay-token': running.token || '' },
606
612
  body: JSON.stringify({ spec }),
@@ -684,7 +690,7 @@ async function cmdWait(args) {
684
690
 
685
691
  // Deadline hit while the board is still OPEN. Fetch presence (cheaply).
686
692
  const running = loadRunning(id);
687
- const presence = running && isAlive(running.pid) ? await fetchPresence(running.url) : null;
693
+ const presence = running && isAlive(running.pid) ? await fetchPresence(controlUrl(running)) : null;
688
694
 
689
695
  // --while-active: if the user is present + recently active, EXTEND and keep
690
696
  // waiting (repeat indefinitely while they stay active).
@@ -743,7 +749,7 @@ async function cmdWaitLoop(id, deadline, opts) {
743
749
  await sleep(400);
744
750
  }
745
751
  const running = loadRunning(id);
746
- const presence = running && isAlive(running.pid) ? await fetchPresence(running.url) : null;
752
+ const presence = running && isAlive(running.pid) ? await fetchPresence(controlUrl(running)) : null;
747
753
  if (
748
754
  whileActive &&
749
755
  presence &&
@@ -781,7 +787,7 @@ async function cmdResult(args) {
781
787
  // While open, expose the real-time autosaved draft so agents can peek, plus
782
788
  // best-effort presence (whether the user is still viewing/focused/active).
783
789
  const out = { status: 'open', boardId: record.id, url: running.url, draft: record.draft ?? null, sideReviews };
784
- const presence = await fetchPresence(running.url);
790
+ const presence = await fetchPresence(controlUrl(running));
785
791
  if (presence) out.presence = presence;
786
792
  printResult(out); // draft can hold many annotations — sidecar it too
787
793
  return 0;
@@ -801,23 +807,24 @@ async function cmdShare(args) {
801
807
  if (role !== undefined && !['collab', 'review', 'read', 'all'].includes(role)) {
802
808
  throw new CliError('--role must be collab, review, or read.', 4);
803
809
  }
804
- const shareUrl = new URL('/api/share', running.url);
810
+ const shareUrl = new URL('/api/share', controlUrl(running));
811
+ const headers = { 'content-type': 'application/json', 'x-relay-token': running.token || '' };
805
812
  let res;
806
813
  try {
807
814
  if (args.revoke) {
808
815
  res = await fetch(shareUrl, {
809
816
  method: 'DELETE',
810
- headers: { 'content-type': 'application/json' },
817
+ headers,
811
818
  body: JSON.stringify({ role: role || 'all' }),
812
819
  });
813
820
  } else if (role && role !== 'all') {
814
821
  res = await fetch(shareUrl, {
815
822
  method: 'POST',
816
- headers: { 'content-type': 'application/json' },
823
+ headers,
817
824
  body: JSON.stringify({ role }),
818
825
  });
819
826
  } else {
820
- res = await fetch(shareUrl, { method: 'GET' });
827
+ res = await fetch(shareUrl, { method: 'GET', headers });
821
828
  }
822
829
  } catch (err) {
823
830
  throw new CliError(`could not reach board "${record.id}" at ${running.url}: ${String((err && err.message) || err)}`, 5);
@@ -856,7 +863,7 @@ function cmdOpen(args) {
856
863
  }
857
864
  const info = running.find((r) => r.id === id);
858
865
  if (!info) throw new CliError(`board "${id}" is not running. Use \`rly reopen ${id}\` to serve it again (with saved answers).`, 5);
859
- openUrl(info.url);
866
+ if (!info.link) openUrl(info.url);
860
867
  printJson({ status: 'open', boardId: id, url: info.url });
861
868
  return 0;
862
869
  }
@@ -1082,6 +1089,11 @@ const SKILL_RULES = `## relay — visual boards and structured feedback
1082
1089
  For inline MCP or shared reviewers, embed file content as blocks instead.
1083
1090
  - Reconnect existing boards by ID with \`rly rescue\` / \`rly reopen\`; update
1084
1091
  content with \`rly update\`. Preserve the original port and saved input.
1092
+ - On a setup with \`devlink\`, add \`--devlink\` (or run \`rly config link devlink\` once)
1093
+ so the board opens on a private URL that phones and other Macs can reach.
1094
+ Share that printed URL, never a localhost one.
1095
+ - Small live widgets (status lists, numbers, buttons) are \`a2ui\` blocks; the
1096
+ grammar is in \`rly a2ui\`. Questions you depend on stay normal questions.
1085
1097
  - Read answers, notes, comment, annotations, and blockEdits together. Use the
1086
1098
  returned resultFile when stdout is truncated; a timeout is not an answer.
1087
1099
  - Full skill: \`rly skill path\`; fields: \`rly schema\`; advanced recipes and
@@ -1323,6 +1335,11 @@ function cmdInstall(args) {
1323
1335
  return 0;
1324
1336
  }
1325
1337
 
1338
+ function cmdA2ui() {
1339
+ console.log(fs.readFileSync(path.join(PKG_ROOT, 'docs', 'A2UI.md'), 'utf8'));
1340
+ return 0;
1341
+ }
1342
+
1326
1343
  function cmdAgent() {
1327
1344
  console.log(fs.readFileSync(path.join(PKG_ROOT, 'docs', 'AGENT.md'), 'utf8'));
1328
1345
  return 0;
@@ -1536,6 +1553,25 @@ function cmdMcpConfig(args, sub) {
1536
1553
  throw new CliError(`unknown --target "${target}". Use claude or codex (or \`rly mcp config\` to print all).`, 4);
1537
1554
  }
1538
1555
 
1556
+ // `rly config [link [off|auto|devlink|<url>]]` — the saved link default, so
1557
+ // every board prints a cross-device URL without a flag.
1558
+ function cmdConfig(args) {
1559
+ const [key, value] = args._;
1560
+ if (key === undefined) {
1561
+ printJson(loadConfig(HOME));
1562
+ return 0;
1563
+ }
1564
+ if (key !== 'link') throw new CliError(`unknown config key "${key}". Use: link.`, 4);
1565
+ if (value === undefined) {
1566
+ printJson({ link: loadConfig(HOME).link ?? 'off' });
1567
+ return 0;
1568
+ }
1569
+ const setting = parseLinkValue(value, 'link');
1570
+ const next = saveConfig(HOME, { link: setting.mode === 'off' ? null : serializeLink(setting) });
1571
+ printJson({ status: 'saved', link: next.link ?? 'off' });
1572
+ return 0;
1573
+ }
1574
+
1539
1575
  async function cmdServeInternal(args) {
1540
1576
  const id = args.id;
1541
1577
  if (!id) throw new CliError('__serve: missing --id');
@@ -1548,6 +1584,7 @@ async function cmdServeInternal(args) {
1548
1584
  // Detached board: timeout hands back to the agent but keeps the same
1549
1585
  // URL/port serving until Submit or explicit stop.
1550
1586
  keepAliveOnTimeout: true,
1587
+ link: args.link !== undefined ? parseLinkValue(args.link, '--link') : { mode: 'off' },
1551
1588
  });
1552
1589
  await done;
1553
1590
  return 0;
@@ -1590,6 +1627,11 @@ USAGE
1590
1627
  rly share <id> --role review --revoke
1591
1628
  revoke one share role; use --revoke --all to disable all roles
1592
1629
  active links survive same-port reopen/rescue until revoked
1630
+ rly ask ... --devlink serve the board on a private cross-device URL through the optional
1631
+ devlink command (https over Tailscale); no local browser opens
1632
+ rly ask ... --public-url <url> same, through your own proxy or tunnel: https://relay.example.com:{port}
1633
+ rly config link <off|auto|devlink|url>
1634
+ save that choice for every board (auto = devlink when installed)
1593
1635
  rly list [--json] running boards
1594
1636
  rly open [id] re-open the browser tab of a running board
1595
1637
  rly reopen <id> [--replies f.json] serve a saved board again, prefilled with saved answers
@@ -1605,6 +1647,7 @@ USAGE
1605
1647
  rly rm <id> | --all delete saved board(s)
1606
1648
  rly schema JSON Schema of the board spec
1607
1649
  rly agent FULL GUIDE for AI agents (spec format, blocks, sizing, patterns)
1650
+ rly a2ui A2UI widget blocks: Express grammar, components, examples
1608
1651
  rly skill [install|rules|path] bundled universal agent skill (Claude Code, Codex, …)
1609
1652
  \`rly skill rules >> CLAUDE.md\` adds always-read usage rules
1610
1653
  rly install --target <agent> inject relay's rules into an agent's instruction file
@@ -1621,6 +1664,7 @@ USAGE
1621
1664
  COMMON FLAGS
1622
1665
  --title <s> --intro <s> --html-file <f> --height <px> --submit-label <s>
1623
1666
  --timeout <sec> (default 86400; 0 = none) --port <n> --no-open --detach --display-only
1667
+ --devlink | --no-devlink | --public-url <url> where the board link points (see rly config link)
1624
1668
 
1625
1669
  EXIT CODES 0 submitted/acknowledged · 2 timeout · 3 cancelled · 4 usage · 5 not found
1626
1670
 
@@ -1676,6 +1720,8 @@ export async function main(argv) {
1676
1720
  return await cmdResult(parseArgs(rest));
1677
1721
  case 'share':
1678
1722
  return await cmdShare(parseArgs(rest));
1723
+ case 'config':
1724
+ return cmdConfig(parseArgs(rest));
1679
1725
  case 'list':
1680
1726
  return cmdList(parseArgs(rest));
1681
1727
  case 'open':
@@ -1697,6 +1743,8 @@ export async function main(argv) {
1697
1743
  return await cmdUpgrade(parseArgs(rest));
1698
1744
  case 'agent':
1699
1745
  return cmdAgent();
1746
+ case 'a2ui':
1747
+ return cmdA2ui();
1700
1748
  case 'schema':
1701
1749
  console.log(JSON.stringify(SPEC_SCHEMA, null, 2));
1702
1750
  return 0;
package/src/link.js ADDED
@@ -0,0 +1,120 @@
1
+ // Where a board can be opened from other devices. By default a board lives on a
2
+ // loopback port. A link setting turns that into a URL a phone or another Mac can
3
+ // reach: through `devlink` (private HTTPS over Tailscale) when it is installed,
4
+ // or through a URL template for any reverse proxy or tunnel the user runs.
5
+ // Nothing here is required; with no setting Relay behaves as before.
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { execFile } from 'node:child_process';
10
+ import { CliError } from './util.js';
11
+
12
+ const DEVLINK_TIMEOUT_MS = 30_000;
13
+ export const LINK_MODES = ['off', 'auto', 'devlink'];
14
+
15
+ const LOOPBACK_HOST = /^(localhost|0\.0\.0\.0|127(?:\.\d{1,3}){3}|\[?::1?\]?)$/i;
16
+
17
+ export const isLoopbackHost = (host) => LOOPBACK_HOST.test(String(host || ''));
18
+
19
+ /** 'devlink' | 'auto' | 'off' | an http(s) URL template -> a normalized setting. */
20
+ export function parseLinkValue(raw, where = 'link') {
21
+ const value = String(raw ?? '').trim();
22
+ const lower = value.toLowerCase();
23
+ if (lower === 'off' || lower === 'local') return { mode: 'off' };
24
+ if (lower === 'auto' || lower === 'devlink') return { mode: lower };
25
+ if (/^http:\/\//i.test(value)) throw new CliError(`${where}: use https://, because the board's share token travels in the URL.`);
26
+ if (/^https:\/\//i.test(value)) {
27
+ let host;
28
+ try { host = new URL(value.replace('{port}', '1')).hostname; } catch { throw new CliError(`${where}: "${value}" is not a valid URL.`); }
29
+ if (isLoopbackHost(host)) throw new CliError(`${where}: ${host} only works on this machine. Use a host other devices can reach.`);
30
+ return { mode: 'url', template: value.replace(/\/+$/, '') };
31
+ }
32
+ throw new CliError(`${where}: use off, auto, devlink, or an https:// URL (with {port} for the board port).`);
33
+ }
34
+
35
+ /**
36
+ * Picks the link setting. Highest first: --no-devlink, --devlink, --public-url,
37
+ * RLY_PUBLIC_URL, RLY_LINK, the saved config, then off.
38
+ */
39
+ export function linkSetting({ args = {}, env = process.env, config = {} } = {}) {
40
+ if (args.noDevlink === true) return { mode: 'off' };
41
+ if (args.devlink === true) return { mode: 'devlink' };
42
+ if (typeof args.publicUrl === 'string') return parseLinkValue(args.publicUrl, '--public-url');
43
+ if (env.RLY_PUBLIC_URL) return parseLinkValue(env.RLY_PUBLIC_URL, 'RLY_PUBLIC_URL');
44
+ if (env.RLY_LINK) return parseLinkValue(env.RLY_LINK, 'RLY_LINK');
45
+ if (config.link) return parseLinkValue(config.link, 'config link');
46
+ return { mode: 'off' };
47
+ }
48
+
49
+ /** The setting in the one-string form `__serve` takes on its command line. */
50
+ export const serializeLink = (s) => (s.mode === 'url' ? s.template : s.mode);
51
+
52
+ /** devlink's own binary: RLY_DEVLINK_BIN, then PATH, then its usual install folder. */
53
+ export function findDevlink({ env = process.env, exists = fs.existsSync } = {}) {
54
+ if (env.RLY_DEVLINK_BIN) return env.RLY_DEVLINK_BIN;
55
+ const dirs = String(env.PATH || '').split(path.delimiter).filter(Boolean);
56
+ dirs.push(path.join(os.homedir(), '.local', 'bin'));
57
+ return dirs.map((d) => path.join(d, 'devlink')).find((f) => exists(f)) || null;
58
+ }
59
+
60
+ /** The verified private https URL out of `devlink --json internal PORT` output. */
61
+ export function pickDevlinkUrl(stdout) {
62
+ let records;
63
+ try { records = JSON.parse(stdout).records; } catch { throw new CliError('devlink printed something that is not JSON.', 1); }
64
+ const url = Array.isArray(records) ? records.map((r) => r && r.url).find((u) => typeof u === 'string') : null;
65
+ if (!url) throw new CliError('devlink returned no URL for this board.', 1);
66
+ let parsed;
67
+ try { parsed = new URL(url); } catch { throw new CliError(`devlink returned "${url}", which is not a URL.`, 1); }
68
+ if (parsed.protocol !== 'https:' || isLoopbackHost(parsed.hostname)) throw new CliError(`devlink returned ${url}, which is not a private https URL.`, 1);
69
+ return parsed.origin;
70
+ }
71
+
72
+ const runFile = (file, args) => new Promise((resolve, reject) => {
73
+ execFile(file, args, { timeout: DEVLINK_TIMEOUT_MS, maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
74
+ if (err) reject(Object.assign(err, { stderr }));
75
+ else resolve({ stdout });
76
+ });
77
+ });
78
+
79
+ /**
80
+ * Turns a setting and the board's listening port into a shareable origin, or
81
+ * null when the board stays local (mode off, or auto without devlink). Returns
82
+ * `{kind, origin, release}`; call `release()` when the board closes.
83
+ * `deps` lets tests replace the filesystem and the devlink process.
84
+ */
85
+ export async function resolveLink(setting, port, { env = process.env, exec = runFile, exists = fs.existsSync } = {}) {
86
+ if (setting.mode === 'off') return null;
87
+ if (setting.mode === 'url') {
88
+ const origin = new URL(setting.template.replace('{port}', String(port))).origin;
89
+ return { kind: 'url', origin, release: () => {} };
90
+ }
91
+ const bin = findDevlink({ env, exists });
92
+ if (!bin) {
93
+ if (setting.mode === 'auto') return null;
94
+ throw new CliError('--devlink needs the devlink command, and it is not on PATH. Install it, set RLY_DEVLINK_BIN, or drop --devlink.', 1);
95
+ }
96
+ let out;
97
+ try {
98
+ out = await exec(bin, ['--json', 'internal', String(port)]);
99
+ } catch (err) {
100
+ const detail = String((err && (err.stderr || err.message)) || err).trim().split('\n').pop();
101
+ throw new CliError(`devlink could not publish port ${port}: ${detail}`, 1);
102
+ }
103
+ const origin = pickDevlinkUrl(out.stdout);
104
+ const release = () => { exec(bin, ['forget', String(port)]).catch(() => {}); };
105
+ return { kind: 'devlink', origin, release };
106
+ }
107
+
108
+ const configPath = (home) => path.join(home, 'config.json');
109
+
110
+ export function loadConfig(home) {
111
+ try { return JSON.parse(fs.readFileSync(configPath(home), 'utf8')); } catch { return {}; }
112
+ }
113
+
114
+ export function saveConfig(home, patch) {
115
+ fs.mkdirSync(home, { recursive: true });
116
+ const next = { ...loadConfig(home), ...patch };
117
+ for (const key of Object.keys(next)) if (next[key] === null) delete next[key];
118
+ fs.writeFileSync(configPath(home), JSON.stringify(next, null, 2));
119
+ return next;
120
+ }
package/src/mcp.js CHANGED
@@ -62,9 +62,9 @@ function buildBoardPage() {
62
62
  const page = html
63
63
  .split('__TITLE__').join('Relay')
64
64
  .split('/*__CSS__*/').join(readAsset(UI_DIR, 'style.css'))
65
- .split('/*__BLOCKS_CSS__*/').join(readAsset(UI_DIR, 'blocks.css'))
65
+ .split('/*__BLOCKS_CSS__*/').join(readAsset(UI_DIR, 'blocks.css') + '\n' + readAsset(UI_DIR, 'a2ui.css'))
66
66
  .split('/*__ANNOTATE_CSS__*/').join(readAsset(UI_DIR, 'annotate.css'))
67
- .split('/*__BLOCKS_JS__*/').join(readAsset(UI_DIR, 'blocks.js'))
67
+ .split('/*__BLOCKS_JS__*/').join(readAsset(UI_DIR, 'a2ui-state.js') + '\n' + readAsset(UI_DIR, 'a2ui.js') + '\n' + readAsset(UI_DIR, 'blocks.js'))
68
68
  .split('/*__ANNOTATE_JS__*/').join(readAsset(UI_DIR, 'annotate.js'))
69
69
  .split('/*__BOARD_JS__*/').join(readAsset(MCP_UI_DIR, 'board.js'))
70
70
  .split('__BOOT_JSON__').join(JSON.stringify(boot).replace(/</g, '\\u003c'));
package/src/server.js CHANGED
@@ -17,6 +17,8 @@ import {
17
17
  } from './store.js';
18
18
  import { openUrl } from './open.js';
19
19
  import { assertSpecReady } from './spec.js';
20
+ import { assertSafeJson } from './a2ui/compile.js';
21
+ import { resolveLink } from './link.js';
20
22
  import { splitFileReference, filePreview, mediaType } from './file-preview.js';
21
23
 
22
24
  const UI_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), 'ui');
@@ -154,9 +156,9 @@ function shareHost() {
154
156
  function buildPage(record, rev, { access = null, draftRev = 0 } = {}) {
155
157
  const html = fs.readFileSync(path.join(UI_DIR, 'index.html'), 'utf8');
156
158
  const css = readUi('style.css');
157
- const blocksCss = readUi('blocks.css');
159
+ const blocksCss = readUi('blocks.css') + '\n' + readUi('a2ui.css');
158
160
  const annotateCss = readUi('annotate.css');
159
- const blocksJs = readUi('blocks.js');
161
+ const blocksJs = readUi('a2ui-state.js') + '\n' + readUi('a2ui.js') + '\n' + readUi('blocks.js');
160
162
  const annotateJs = readUi('annotate.js');
161
163
  const appJs = readUi('app.js');
162
164
  const spec = record.spec;
@@ -406,6 +408,29 @@ function sanitizeDiffReview(value) {
406
408
  return Object.keys(out.hunks).length ? out : null;
407
409
  }
408
410
 
411
+ // An a2ui block's state: the widget's data model (inputs the user changed) and
412
+ // the button events they fired, in order. Bounded like every other edit.
413
+ const A2UI_STATE_MAX_BYTES = 64 * 1024;
414
+ const A2UI_EVENTS_MAX = 50;
415
+ function sanitizeA2uiState(value) {
416
+ if (!value || typeof value !== 'object' || Array.isArray(value) || value.type !== 'a2ui') return null;
417
+ try {
418
+ assertSafeJson(value.data ?? {}, 'a2ui state');
419
+ const events = (Array.isArray(value.events) ? value.events : []).slice(-A2UI_EVENTS_MAX).flatMap((e) => {
420
+ if (!e || typeof e !== 'object' || typeof e.name !== 'string' || !/^[a-z][a-z0-9_-]{0,39}$/.test(e.name)) return [];
421
+ const context = e.context && typeof e.context === 'object' && !Array.isArray(e.context) ? e.context : {};
422
+ assertSafeJson(context, 'a2ui event');
423
+ if (JSON.stringify(context).length > 4096) return [];
424
+ return [{ name: e.name, context, at: limitString(e.at, 40) }];
425
+ });
426
+ const data = value.data && typeof value.data === 'object' && !Array.isArray(value.data) ? value.data : {};
427
+ if (JSON.stringify(data).length > A2UI_STATE_MAX_BYTES) return null;
428
+ return { type: 'a2ui', data, events };
429
+ } catch {
430
+ return null;
431
+ }
432
+ }
433
+
409
434
  // Validates + sanitizes an incoming blockEdits map (from draft/submit).
410
435
  // String values are editable Mermaid source. Structured git-conflict-resolution
411
436
  // and diff-review values carry bounded per-hunk choices. Caps prevent a draft
@@ -422,7 +447,7 @@ function sanitizeBlockEdits(value) {
422
447
  if (v.length > 20000) continue;
423
448
  out[key] = v;
424
449
  } else {
425
- const edit = sanitizeConflictResolution(v) || sanitizeDiffReview(v);
450
+ const edit = sanitizeConflictResolution(v) || sanitizeDiffReview(v) || sanitizeA2uiState(v);
426
451
  if (!edit) continue;
427
452
  out[key] = edit;
428
453
  }
@@ -544,15 +569,28 @@ function buildOpenAllowlist(spec, baseCwd) {
544
569
  return set;
545
570
  }
546
571
 
572
+ const PROXY_HEADERS = ['forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-real-ip'];
573
+
574
+ // Security: a local reverse proxy can send a loopback Host (the devlink gateway
575
+ // sends `Host: localhost:PORT`), so a request carrying proxy headers is never the
576
+ // tokenless owner. A proxy that adds none is covered by the control token runBoard
577
+ // requires for the owner while a link is set.
578
+ function isDirectLocalRequest(req) {
579
+ const host = String(req.headers.host || '').split(':')[0];
580
+ if (host !== '127.0.0.1' && host !== 'localhost') return false;
581
+ return !PROXY_HEADERS.some((name) => req.headers[name] !== undefined);
582
+ }
583
+
547
584
  // True when an Origin header (if present) belongs to this board's own server.
548
585
  // Same-origin fetches send no Origin or our own; a foreign Origin is a
549
586
  // cross-site POST and must not be allowed to open a local file.
550
- function sameOrigin(req, port, extraHosts = []) {
587
+ function sameOrigin(req, port, extraHosts = [], extraOrigins = []) {
551
588
  if (req.headers['sec-fetch-site'] === 'cross-site') return false;
552
589
  const origin = req.headers.origin;
553
590
  if (!origin) return true;
554
591
  try {
555
592
  const u = new URL(origin);
593
+ if (extraOrigins.includes(u.origin)) return true;
556
594
  if (u.port !== String(port)) return false;
557
595
  return new Set(['127.0.0.1', 'localhost', ...extraHosts.filter(Boolean)]).has(u.hostname);
558
596
  } catch {
@@ -746,7 +784,7 @@ function runOnResult(cmd, result, { quiet = false } = {}) {
746
784
  // (submitted / acknowledged / timeout / cancelled). The result is also
747
785
  // persisted into the board record so `rly wait` / `rly result` can read it
748
786
  // from another process.
749
- export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400, quiet = false, keepAliveOnTimeout = false }) {
787
+ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400, quiet = false, keepAliveOnTimeout = false, link = { mode: 'off' } }) {
750
788
  const record = loadBoard(id);
751
789
  if (!record) throw new Error(`board ${id} not found`);
752
790
  const spec = record.spec;
@@ -813,10 +851,11 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
813
851
  const presenceByRole = { owner: null, collab: null, review: null, read: null };
814
852
  let actualPort = 0;
815
853
  let url = '';
854
+ // The cross-device origin from a link setting (devlink or a URL template), once resolved.
855
+ let publicLink = null;
816
856
  const advertisedHost = shareHost();
817
857
  const accessFor = (req, reqUrl = null) => {
818
- const host = String(req.headers.host || '').split(':')[0];
819
- if (host === '127.0.0.1' || host === 'localhost') {
858
+ if (isDirectLocalRequest(req) && (!publicLink || req.headers['x-relay-token'] === token)) {
820
859
  return {
821
860
  role: 'owner',
822
861
  canShare: true,
@@ -885,7 +924,10 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
885
924
  canFinalize: false,
886
925
  };
887
926
  };
888
- const shareUrlFor = (role) => advertisedHost ? `http://${advertisedHost}:${actualPort}/?share=${role}&token=${shareTokens[role]}` : null;
927
+ const shareUrlFor = (role) => {
928
+ const base = publicLink ? publicLink.origin : advertisedHost ? `http://${advertisedHost}:${actualPort}` : null;
929
+ return base ? `${base}/?share=${role}&token=${shareTokens[role]}` : null;
930
+ };
889
931
  const persistShareState = () => {
890
932
  record.share = {
891
933
  version: SHARE_STATE_VERSION,
@@ -1017,7 +1059,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
1017
1059
  res.end(Buffer.from(m[2], 'base64'));
1018
1060
  } else if (req.method === 'POST' && pathname === '/api/artifact') {
1019
1061
  if (record.spec.responseRequired === false) return sendJson(res, 409, { error: 'display-only boards do not collect feedback' });
1020
- if (!sameOrigin(req, actualPort, [advertisedHost])) return sendJson(res, 403, { error: 'cross-origin artifact upload rejected' });
1062
+ if (!sameOrigin(req, actualPort, [advertisedHost], [publicLink?.origin])) return sendJson(res, 403, { error: 'cross-origin artifact upload rejected' });
1021
1063
  const access = accessFor(req, reqUrl);
1022
1064
  if (!access.canComment) return sendJson(res, 403, { error: 'this share cannot add comments' });
1023
1065
  const body = JSON.parse((await readBody(req, 6 * 1024 * 1024)) || '{}');
@@ -1076,7 +1118,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
1076
1118
  (['GET', 'HEAD'].includes(req.method) && pathname === '/api/file-content')) {
1077
1119
  // Preview, stream, or open only a board-referenced local file. All three
1078
1120
  // paths share the same origin, role, and reference allowlist checks.
1079
- if (!sameOrigin(req, actualPort, [advertisedHost])) return sendJson(res, 403, { error: 'cross-origin requests cannot open files' });
1121
+ if (!sameOrigin(req, actualPort, [advertisedHost], [publicLink?.origin])) return sendJson(res, 403, { error: 'cross-origin requests cannot open files' });
1080
1122
  const access = accessFor(req, reqUrl);
1081
1123
  if (access.role !== 'owner' && access.role !== 'collab') return sendJson(res, 403, { error: 'this share cannot open local files' });
1082
1124
  const body = req.method === 'POST' ? JSON.parse((await readBody(req)) || '{}') : { path: reqUrl.searchParams.get('path') };
@@ -1262,7 +1304,20 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
1262
1304
  bind(port, true);
1263
1305
  });
1264
1306
  actualPort = server.address().port;
1265
- url = `http://127.0.0.1:${actualPort}/`;
1307
+ const localUrl = `http://127.0.0.1:${actualPort}/`;
1308
+ url = localUrl;
1309
+ try {
1310
+ publicLink = await resolveLink(link, actualPort);
1311
+ } catch (err) {
1312
+ server.close();
1313
+ throw err;
1314
+ }
1315
+ if (publicLink) {
1316
+ // Requests through the link are never the owner; the collaborator token in
1317
+ // the URL is what lets the owner's browsers answer and submit.
1318
+ activeShares.collab = true;
1319
+ url = shareUrlFor('collab');
1320
+ }
1266
1321
  // Remember the port this board last bound, so `rly rescue <id>` can re-serve
1267
1322
  // on the SAME port — letting a still-open (but disconnected) browser tab
1268
1323
  // reconnect to its relative /api/* URLs without the user touching anything.
@@ -1275,6 +1330,8 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
1275
1330
  pid: process.pid,
1276
1331
  port: actualPort,
1277
1332
  url,
1333
+ localUrl,
1334
+ link: publicLink ? publicLink.kind : null,
1278
1335
  title: spec.title,
1279
1336
  token,
1280
1337
  startedAt: new Date().toISOString(),
@@ -1336,6 +1393,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
1336
1393
  // and auto-closes first). The result is assumed already persisted.
1337
1394
  function closeServer(result) {
1338
1395
  removeRunning(record.id);
1396
+ if (publicLink) publicLink.release();
1339
1397
  if (timer) clearTimeout(timer);
1340
1398
  process.removeListener('SIGINT', onSignal);
1341
1399
  process.removeListener('SIGTERM', onSignal);
@@ -1372,7 +1430,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
1372
1430
  runOnResult(record.onResult, result, { quiet });
1373
1431
  }
1374
1432
 
1375
- if (open) openUrl(url);
1433
+ if (open && !publicLink) openUrl(url);
1376
1434
  if (!quiet) {
1377
1435
  process.stderr.write(
1378
1436
  `[relay] ${record.id} open: ${url} (waiting for submit; timeout: ${timeoutSec > 0 ? `${timeoutSec}s` : 'none'})\n`