@khanglvm/relay 0.17.1 → 0.19.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;
@@ -1509,6 +1526,7 @@ function cmdMcpConfig(args, sub) {
1509
1526
 
1510
1527
  if (target === 'claude' || target === 'claude-desktop') {
1511
1528
  const file = claudeDesktopConfigPath();
1529
+ /** @type {Record<string, any>} */
1512
1530
  let existing = {};
1513
1531
  try { existing = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { existing = {}; }
1514
1532
  if (existing === null || typeof existing !== 'object' || Array.isArray(existing)) existing = {};
@@ -1536,6 +1554,25 @@ function cmdMcpConfig(args, sub) {
1536
1554
  throw new CliError(`unknown --target "${target}". Use claude or codex (or \`rly mcp config\` to print all).`, 4);
1537
1555
  }
1538
1556
 
1557
+ // `rly config [link [off|auto|devlink|<url>]]` — the saved link default, so
1558
+ // every board prints a cross-device URL without a flag.
1559
+ function cmdConfig(args) {
1560
+ const [key, value] = args._;
1561
+ if (key === undefined) {
1562
+ printJson(loadConfig(HOME));
1563
+ return 0;
1564
+ }
1565
+ if (key !== 'link') throw new CliError(`unknown config key "${key}". Use: link.`, 4);
1566
+ if (value === undefined) {
1567
+ printJson({ link: loadConfig(HOME).link ?? 'off' });
1568
+ return 0;
1569
+ }
1570
+ const setting = parseLinkValue(value, 'link');
1571
+ const next = saveConfig(HOME, { link: setting.mode === 'off' ? null : serializeLink(setting) });
1572
+ printJson({ status: 'saved', link: next.link ?? 'off' });
1573
+ return 0;
1574
+ }
1575
+
1539
1576
  async function cmdServeInternal(args) {
1540
1577
  const id = args.id;
1541
1578
  if (!id) throw new CliError('__serve: missing --id');
@@ -1548,6 +1585,7 @@ async function cmdServeInternal(args) {
1548
1585
  // Detached board: timeout hands back to the agent but keeps the same
1549
1586
  // URL/port serving until Submit or explicit stop.
1550
1587
  keepAliveOnTimeout: true,
1588
+ link: args.link !== undefined ? parseLinkValue(args.link, '--link') : { mode: 'off' },
1551
1589
  });
1552
1590
  await done;
1553
1591
  return 0;
@@ -1590,6 +1628,11 @@ USAGE
1590
1628
  rly share <id> --role review --revoke
1591
1629
  revoke one share role; use --revoke --all to disable all roles
1592
1630
  active links survive same-port reopen/rescue until revoked
1631
+ rly ask ... --devlink serve the board on a private cross-device URL through the optional
1632
+ devlink command (https over Tailscale); no local browser opens
1633
+ rly ask ... --public-url <url> same, through your own proxy or tunnel: https://relay.example.com:{port}
1634
+ rly config link <off|auto|devlink|url>
1635
+ save that choice for every board (auto = devlink when installed)
1593
1636
  rly list [--json] running boards
1594
1637
  rly open [id] re-open the browser tab of a running board
1595
1638
  rly reopen <id> [--replies f.json] serve a saved board again, prefilled with saved answers
@@ -1605,6 +1648,7 @@ USAGE
1605
1648
  rly rm <id> | --all delete saved board(s)
1606
1649
  rly schema JSON Schema of the board spec
1607
1650
  rly agent FULL GUIDE for AI agents (spec format, blocks, sizing, patterns)
1651
+ rly a2ui A2UI widget blocks: Express grammar, components, examples
1608
1652
  rly skill [install|rules|path] bundled universal agent skill (Claude Code, Codex, …)
1609
1653
  \`rly skill rules >> CLAUDE.md\` adds always-read usage rules
1610
1654
  rly install --target <agent> inject relay's rules into an agent's instruction file
@@ -1621,6 +1665,7 @@ USAGE
1621
1665
  COMMON FLAGS
1622
1666
  --title <s> --intro <s> --html-file <f> --height <px> --submit-label <s>
1623
1667
  --timeout <sec> (default 86400; 0 = none) --port <n> --no-open --detach --display-only
1668
+ --devlink | --no-devlink | --public-url <url> where the board link points (see rly config link)
1624
1669
 
1625
1670
  EXIT CODES 0 submitted/acknowledged · 2 timeout · 3 cancelled · 4 usage · 5 not found
1626
1671
 
@@ -1676,6 +1721,8 @@ export async function main(argv) {
1676
1721
  return await cmdResult(parseArgs(rest));
1677
1722
  case 'share':
1678
1723
  return await cmdShare(parseArgs(rest));
1724
+ case 'config':
1725
+ return cmdConfig(parseArgs(rest));
1679
1726
  case 'list':
1680
1727
  return cmdList(parseArgs(rest));
1681
1728
  case 'open':
@@ -1697,6 +1744,8 @@ export async function main(argv) {
1697
1744
  return await cmdUpgrade(parseArgs(rest));
1698
1745
  case 'agent':
1699
1746
  return cmdAgent();
1747
+ case 'a2ui':
1748
+ return cmdA2ui();
1700
1749
  case 'schema':
1701
1750
  console.log(JSON.stringify(SPEC_SCHEMA, null, 2));
1702
1751
  return 0;
package/src/index.js ADDED
@@ -0,0 +1,104 @@
1
+ // Public library entry (`import ... from '@khanglvm/relay'`). It exposes the
2
+ // spec checks and the board store without starting a server or a browser.
3
+ import { compileExpress, validateSurface } from './a2ui/compile.js';
4
+ import { normalizeSpec } from './spec.js';
5
+ import { createBoard as storeBoard } from './store.js';
6
+
7
+ /**
8
+ * A board spec as an agent writes it: `questions`, `blocks`, or both. Run
9
+ * `rly agent` or read schema/spec.v1.json for every field.
10
+ * @typedef {object} RelaySpec
11
+ * @property {1} [version] Spec version; a spec without it is read as version 1.
12
+ * @property {string} [$schema] Schema URL, ignored by Relay.
13
+ * @property {string} [title]
14
+ * @property {string} [intro]
15
+ * @property {Array<Record<string, unknown>>} [blocks] Board-level blocks.
16
+ * @property {Array<Record<string, unknown>>} [questions]
17
+ * @property {boolean} [allowPartial] Let the user submit with unanswered questions.
18
+ * @property {boolean} [note] Show the free-text "Anything else?" box.
19
+ * @property {boolean} [autoClose] Close the browser tab after submit.
20
+ * @property {boolean} [responseRequired] False for a display-only board.
21
+ * @property {string} [submitLabel]
22
+ */
23
+
24
+ /**
25
+ * A comment the user attached to one element of a block.
26
+ * @typedef {object} Annotation
27
+ * @property {string} id
28
+ * @property {string | null} questionId
29
+ * @property {string | null} blockId
30
+ * @property {{ kind: string } & Record<string, unknown>} target What the comment points at.
31
+ * @property {string} text
32
+ * @property {string} createdAt ISO timestamp.
33
+ */
34
+
35
+ /**
36
+ * What `rly result` prints once the user submits.
37
+ * @typedef {object} RelayResult
38
+ * @property {Record<string, unknown>} answers Answer per question id.
39
+ * @property {Record<string, string>} [notes] Per-question note text.
40
+ * @property {string} [comment] The "Anything else?" text.
41
+ * @property {string[]} [skipped] Question ids left unanswered.
42
+ * @property {Annotation[]} [annotations]
43
+ * @property {Record<string, unknown> | null} [blockEdits] Edited block payloads by block id.
44
+ */
45
+
46
+ /**
47
+ * A board stored on disk under RLY_HOME (default ~/.relay).
48
+ * @typedef {object} BoardRecord
49
+ * @property {string} id
50
+ * @property {string} createdAt ISO timestamp.
51
+ * @property {string} title
52
+ * @property {string} cwd Directory the board was authored in.
53
+ * @property {Record<string, unknown>} spec The normalized spec.
54
+ * @property {unknown} draft
55
+ * @property {RelayResult | null} result
56
+ */
57
+
58
+ /**
59
+ * A validated A2UI surface: a flat component list plus an optional data model.
60
+ * @typedef {object} A2uiSurface
61
+ * @property {Array<Record<string, unknown>>} components
62
+ * @property {Record<string, unknown>} [dataModel]
63
+ */
64
+
65
+ /**
66
+ * Checks a spec without throwing. Reads the files a spec names (`mdFile`,
67
+ * `rowsFile`) relative to `cwd`. Mermaid syntax and A2UI Express are checked
68
+ * later, when a board opens.
69
+ * @param {unknown} raw
70
+ * @param {{ cwd?: string }} [options]
71
+ * @returns {{ ok: boolean, errors: string[] }}
72
+ */
73
+ export function validateSpec(raw, options) {
74
+ try {
75
+ normalizeSpec(raw, options);
76
+ return { ok: true, errors: [] };
77
+ } catch (error) {
78
+ return { ok: false, errors: [error instanceof Error ? error.message : String(error)] };
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Normalizes a spec and stores it as a new board, the way `rly ask` does
84
+ * before it opens one. Throws when the spec is invalid.
85
+ * @param {unknown} raw
86
+ * @param {{ cwd?: string }} [options]
87
+ * @returns {BoardRecord}
88
+ */
89
+ export function createBoard(raw, options) {
90
+ return storeBoard(normalizeSpec(raw, options));
91
+ }
92
+
93
+ /**
94
+ * Compiles A2UI Express text, or checks ready components, into a surface that
95
+ * the board draws.
96
+ * @param {string | A2uiSurface} source
97
+ * @returns {Promise<A2uiSurface>}
98
+ */
99
+ export async function compileA2ui(source) {
100
+ const surface = typeof source === 'string' ? await compileExpress(source) : source;
101
+ return validateSurface(surface);
102
+ }
103
+
104
+ export { normalizeSpec };
package/src/link.js ADDED
@@ -0,0 +1,121 @@
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
+ * @param {{ args?: Record<string, any>, env?: Record<string, string | undefined>, config?: Record<string, any> }} [input]
39
+ */
40
+ export function linkSetting({ args = {}, env = process.env, config = {} } = {}) {
41
+ if (args.noDevlink === true) return { mode: 'off' };
42
+ if (args.devlink === true) return { mode: 'devlink' };
43
+ if (typeof args.publicUrl === 'string') return parseLinkValue(args.publicUrl, '--public-url');
44
+ if (env.RLY_PUBLIC_URL) return parseLinkValue(env.RLY_PUBLIC_URL, 'RLY_PUBLIC_URL');
45
+ if (env.RLY_LINK) return parseLinkValue(env.RLY_LINK, 'RLY_LINK');
46
+ if (config.link) return parseLinkValue(config.link, 'config link');
47
+ return { mode: 'off' };
48
+ }
49
+
50
+ /** The setting in the one-string form `__serve` takes on its command line. */
51
+ export const serializeLink = (s) => (s.mode === 'url' ? s.template : s.mode);
52
+
53
+ /** devlink's own binary: RLY_DEVLINK_BIN, then PATH, then its usual install folder. */
54
+ export function findDevlink({ env = process.env, exists = fs.existsSync } = {}) {
55
+ if (env.RLY_DEVLINK_BIN) return env.RLY_DEVLINK_BIN;
56
+ const dirs = String(env.PATH || '').split(path.delimiter).filter(Boolean);
57
+ dirs.push(path.join(os.homedir(), '.local', 'bin'));
58
+ return dirs.map((d) => path.join(d, 'devlink')).find((f) => exists(f)) || null;
59
+ }
60
+
61
+ /** The verified private https URL out of `devlink --json internal PORT` output. */
62
+ export function pickDevlinkUrl(stdout) {
63
+ let records;
64
+ try { records = JSON.parse(stdout).records; } catch { throw new CliError('devlink printed something that is not JSON.', 1); }
65
+ const url = Array.isArray(records) ? records.map((r) => r && r.url).find((u) => typeof u === 'string') : null;
66
+ if (!url) throw new CliError('devlink returned no URL for this board.', 1);
67
+ let parsed;
68
+ try { parsed = new URL(url); } catch { throw new CliError(`devlink returned "${url}", which is not a URL.`, 1); }
69
+ if (parsed.protocol !== 'https:' || isLoopbackHost(parsed.hostname)) throw new CliError(`devlink returned ${url}, which is not a private https URL.`, 1);
70
+ return parsed.origin;
71
+ }
72
+
73
+ const runFile = (file, args) => new Promise((resolve, reject) => {
74
+ execFile(file, args, { timeout: DEVLINK_TIMEOUT_MS, maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
75
+ if (err) reject(Object.assign(err, { stderr }));
76
+ else resolve({ stdout });
77
+ });
78
+ });
79
+
80
+ /**
81
+ * Turns a setting and the board's listening port into a shareable origin, or
82
+ * null when the board stays local (mode off, or auto without devlink). Returns
83
+ * `{kind, origin, release}`; call `release()` when the board closes.
84
+ * `deps` lets tests replace the filesystem and the devlink process.
85
+ */
86
+ export async function resolveLink(setting, port, { env = process.env, exec = runFile, exists = fs.existsSync } = {}) {
87
+ if (setting.mode === 'off') return null;
88
+ if (setting.mode === 'url') {
89
+ const origin = new URL(setting.template.replace('{port}', String(port))).origin;
90
+ return { kind: 'url', origin, release: () => {} };
91
+ }
92
+ const bin = findDevlink({ env, exists });
93
+ if (!bin) {
94
+ if (setting.mode === 'auto') return null;
95
+ throw new CliError('--devlink needs the devlink command, and it is not on PATH. Install it, set RLY_DEVLINK_BIN, or drop --devlink.', 1);
96
+ }
97
+ let out;
98
+ try {
99
+ out = await exec(bin, ['--json', 'internal', String(port)]);
100
+ } catch (err) {
101
+ const detail = String((err && (err.stderr || err.message)) || err).trim().split('\n').pop();
102
+ throw new CliError(`devlink could not publish port ${port}: ${detail}`, 1);
103
+ }
104
+ const origin = pickDevlinkUrl(out.stdout);
105
+ const release = () => { exec(bin, ['forget', String(port)]).catch(() => {}); };
106
+ return { kind: 'devlink', origin, release };
107
+ }
108
+
109
+ const configPath = (home) => path.join(home, 'config.json');
110
+
111
+ export function loadConfig(home) {
112
+ try { return JSON.parse(fs.readFileSync(configPath(home), 'utf8')); } catch { return {}; }
113
+ }
114
+
115
+ export function saveConfig(home, patch) {
116
+ fs.mkdirSync(home, { recursive: true });
117
+ const next = { ...loadConfig(home), ...patch };
118
+ for (const key of Object.keys(next)) if (next[key] === null) delete next[key];
119
+ fs.writeFileSync(configPath(home), JSON.stringify(next, null, 2));
120
+ return next;
121
+ }
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'));
@@ -174,7 +174,7 @@ async function buildResult(method, params, clientProtocol) {
174
174
  case 'tools/call':
175
175
  return callTool(params);
176
176
  default: {
177
- const err = new Error('method not found: ' + method);
177
+ const err = /** @type {Error & { code?: number }} */ (new Error('method not found: ' + method));
178
178
  err.code = -32601;
179
179
  throw err;
180
180
  }
@@ -189,10 +189,10 @@ function readResource(params) {
189
189
  if (typeof uri === 'string' && uri.startsWith(VENDOR_PREFIX)) {
190
190
  const name = uri.slice(VENDOR_PREFIX.length);
191
191
  const text = vendorText(name);
192
- if (text == null) { const e = new Error('vendor not found: ' + name); e.code = -32002; throw e; }
192
+ if (text == null) { const e = /** @type {Error & { code?: number }} */ (new Error('vendor not found: ' + name)); e.code = -32002; throw e; }
193
193
  return { contents: [{ uri, mimeType: 'application/javascript', text }] };
194
194
  }
195
- const e = new Error('resource not found: ' + uri);
195
+ const e = /** @type {Error & { code?: number }} */ (new Error('resource not found: ' + uri));
196
196
  e.code = -32002;
197
197
  throw e;
198
198
  }