@khanglvm/relay 0.19.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +11 -4
  2. package/bin/rly.js +1 -1
  3. package/package.json +4 -4
  4. package/src/cli/args.js +46 -0
  5. package/src/cli/ask.js +12 -0
  6. package/src/cli/boards.js +326 -0
  7. package/src/cli/config.js +56 -0
  8. package/src/cli/context.js +13 -0
  9. package/src/cli/git.js +183 -0
  10. package/src/cli/help.js +91 -0
  11. package/src/cli/index.js +103 -0
  12. package/src/cli/install.js +197 -0
  13. package/src/cli/io.js +186 -0
  14. package/src/cli/mcp.js +94 -0
  15. package/src/cli/share.js +45 -0
  16. package/src/cli/skill.js +192 -0
  17. package/src/cli/upgrade.js +130 -0
  18. package/src/cli/wait.js +172 -0
  19. package/src/file-preview.js +1 -1
  20. package/src/index.js +1 -1
  21. package/src/link.js +57 -9
  22. package/src/mcp-ui/board/block-ctx.js +43 -0
  23. package/src/mcp-ui/board/bridge.js +165 -0
  24. package/src/mcp-ui/board/controls.js +310 -0
  25. package/src/mcp-ui/board/core.js +20 -0
  26. package/src/mcp-ui/board/lifecycle.js +118 -0
  27. package/src/mcp-ui/board/normalize.js +95 -0
  28. package/src/mcp-ui/board/render.js +200 -0
  29. package/src/mcp-ui/board/state.js +106 -0
  30. package/src/mcp-ui/board/vendors.js +86 -0
  31. package/src/mcp.js +12 -18
  32. package/src/{server.js → server/board.js} +16 -779
  33. package/src/server/files.js +141 -0
  34. package/src/server/http.js +114 -0
  35. package/src/server/index.js +2 -0
  36. package/src/server/page.js +183 -0
  37. package/src/server/paths.js +7 -0
  38. package/src/server/result.js +58 -0
  39. package/src/server/reviews.js +41 -0
  40. package/src/server/sanitize.js +231 -0
  41. package/src/spec/blocks/a2ui.js +25 -0
  42. package/src/spec/blocks/chart.js +49 -0
  43. package/src/spec/blocks/code.js +38 -0
  44. package/src/spec/blocks/diagram.js +39 -0
  45. package/src/spec/blocks/git-conflict.js +106 -0
  46. package/src/spec/blocks/image.js +32 -0
  47. package/src/spec/blocks/index.js +33 -0
  48. package/src/spec/blocks/markdown.js +13 -0
  49. package/src/spec/blocks/pdf.js +38 -0
  50. package/src/spec/blocks/table.js +122 -0
  51. package/src/spec/blocks/video.js +68 -0
  52. package/src/spec/blocks/widgets.js +98 -0
  53. package/src/spec/constants.js +65 -0
  54. package/src/spec/index.js +5 -0
  55. package/src/spec/normalize.js +285 -0
  56. package/src/spec/ready.js +106 -0
  57. package/src/spec/schema.js +182 -0
  58. package/src/spec/sources.js +83 -0
  59. package/src/store.js +1 -1
  60. package/src/ui/annotate/api.js +149 -0
  61. package/src/ui/annotate/badges.js +77 -0
  62. package/src/ui/annotate/chrome.js +158 -0
  63. package/src/ui/annotate/core.js +134 -0
  64. package/src/ui/annotate/highlights.js +129 -0
  65. package/src/ui/annotate/mutations.js +127 -0
  66. package/src/ui/annotate/popover.js +206 -0
  67. package/src/ui/annotate/summary.js +67 -0
  68. package/src/ui/app/annotations.js +88 -0
  69. package/src/ui/app/autosave.js +44 -0
  70. package/src/ui/app/core.js +74 -0
  71. package/src/ui/app/drafts.js +201 -0
  72. package/src/ui/app/heartbeat.js +150 -0
  73. package/src/ui/app/iframe-bridge.js +64 -0
  74. package/src/ui/app/persistence.js +117 -0
  75. package/src/ui/app/prefilled.js +21 -0
  76. package/src/ui/app/presence.js +38 -0
  77. package/src/ui/app/question-color.js +67 -0
  78. package/src/ui/app/questions.js +360 -0
  79. package/src/ui/app/render.js +135 -0
  80. package/src/ui/app/share.js +108 -0
  81. package/src/ui/app/submit.js +109 -0
  82. package/src/ui/app/theme.js +63 -0
  83. package/src/ui/blocks/api.js +1 -0
  84. package/src/ui/blocks/chart.js +222 -0
  85. package/src/ui/blocks/code.js +138 -0
  86. package/src/ui/blocks/compare.js +82 -0
  87. package/src/ui/blocks/core.js +74 -0
  88. package/src/ui/blocks/diff.js +361 -0
  89. package/src/ui/blocks/dispatch.js +111 -0
  90. package/src/ui/blocks/file-links.js +180 -0
  91. package/src/ui/blocks/git-conflict.js +151 -0
  92. package/src/ui/blocks/graphviz.js +57 -0
  93. package/src/ui/blocks/html.js +45 -0
  94. package/src/ui/blocks/image.js +371 -0
  95. package/src/ui/blocks/kpi.js +26 -0
  96. package/src/ui/blocks/markdown.js +223 -0
  97. package/src/ui/blocks/mermaid.js +242 -0
  98. package/src/ui/blocks/palette.js +59 -0
  99. package/src/ui/blocks/pdf.js +21 -0
  100. package/src/ui/blocks/plantuml.js +152 -0
  101. package/src/ui/blocks/table.js +155 -0
  102. package/src/ui/blocks/typography.js +25 -0
  103. package/src/ui/blocks/vendor.js +43 -0
  104. package/src/ui/blocks/video.js +43 -0
  105. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  106. package/src/ui/blocks/viewer.js +324 -0
  107. package/src/ui/kit.js +1 -0
  108. package/src/ui/manifest.js +140 -0
  109. package/types/index.d.ts +1 -1
  110. package/types/spec/blocks/a2ui.d.ts +4 -0
  111. package/types/spec/blocks/chart.d.ts +4 -0
  112. package/types/spec/blocks/code.d.ts +10 -0
  113. package/types/spec/blocks/diagram.d.ts +15 -0
  114. package/types/spec/blocks/git-conflict.d.ts +7 -0
  115. package/types/spec/blocks/image.d.ts +5 -0
  116. package/types/spec/blocks/index.d.ts +30 -0
  117. package/types/spec/blocks/markdown.d.ts +5 -0
  118. package/types/spec/blocks/pdf.d.ts +4 -0
  119. package/types/spec/blocks/table.d.ts +9 -0
  120. package/types/spec/blocks/video.d.ts +4 -0
  121. package/types/spec/blocks/widgets.d.ts +21 -0
  122. package/types/spec/constants.d.ts +67 -0
  123. package/types/spec/index.d.ts +4 -0
  124. package/types/spec/normalize.d.ts +17 -0
  125. package/types/spec/ready.d.ts +1 -0
  126. package/types/{spec.d.ts → spec/schema.d.ts} +0 -20
  127. package/types/spec/sources.d.ts +14 -0
  128. package/types/ui/manifest.d.ts +62 -0
  129. package/src/cli.js +0 -1767
  130. package/src/mcp-ui/board.js +0 -1162
  131. package/src/spec.js +0 -1224
  132. package/src/ui/annotate.js +0 -1055
  133. package/src/ui/app.js +0 -1643
  134. package/src/ui/blocks.js +0 -3260
package/src/cli.js DELETED
@@ -1,1767 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import os from 'node:os';
4
- import { spawn, spawnSync } from 'node:child_process';
5
- import { fileURLToPath } from 'node:url';
6
- import { CliError, sleep, pollFor } from './util.js';
7
- import { assertSpecReady, normalizeSpec, questionFromInline, SPEC_SCHEMA } from './spec.js';
8
- import {
9
- createBoard,
10
- loadBoard,
11
- saveBoard,
12
- deleteBoard,
13
- listBoards,
14
- listRunning,
15
- loadRunning,
16
- removeRunning,
17
- isAlive,
18
- saveResultFile,
19
- controlUrl,
20
- HOME,
21
- } from './store.js';
22
- import { runBoard } from './server.js';
23
- import { runMcp, runMcpHttp, mcpConfig } from './mcp.js';
24
- import { openUrl } from './open.js';
25
- import { linkSetting, loadConfig, parseLinkValue, saveConfig, serializeLink } from './link.js';
26
-
27
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
28
- const PKG_ROOT = path.join(__dirname, '..');
29
- const BIN = path.join(PKG_ROOT, 'bin', 'rly.js');
30
- const PKG_JSON = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8'));
31
- const VERSION = PKG_JSON.version;
32
- const PKG_NAME = PKG_JSON.name; // e.g. "@khanglvm/relay" — the global package to upgrade
33
- const DEFAULT_BOARD_TIMEOUT_SEC = 86400;
34
- const DEFAULT_WAIT_TIMEOUT_SEC = 86400;
35
-
36
- const VALUED_FLAGS = new Set([
37
- 'file', 'html', 'html-file', 'title', 'intro', 'timeout', 'port',
38
- 'submit-label', 'height', 'limit', 'target', 'id', 'replies',
39
- 'on-result', 'notify-cmd', 'idle-grace', 'scope', 'range',
40
- 'host', 'token', 'allow-origin', 'role', 'public-url', 'link',
41
- ]);
42
-
43
- function camel(key) {
44
- return key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
45
- }
46
-
47
- export function parseArgs(argv) {
48
- const args = { _: [], q: [] };
49
- for (let i = 0; i < argv.length; i++) {
50
- const t = argv[i];
51
- if (t === '-q' || t === '--question') {
52
- const v = argv[++i];
53
- if (v === undefined) throw new CliError(`${t} needs a value.`);
54
- args.q.push(v);
55
- } else if (t === '-') {
56
- args.stdin = true;
57
- } else if (t.startsWith('--')) {
58
- let key = t.slice(2);
59
- let val = true;
60
- const eq = key.indexOf('=');
61
- if (eq >= 0) {
62
- val = key.slice(eq + 1);
63
- key = key.slice(0, eq);
64
- } else if (VALUED_FLAGS.has(key)) {
65
- val = argv[++i];
66
- if (val === undefined) throw new CliError(`--${key} needs a value.`);
67
- }
68
- if (key === 'no-open') {
69
- args.open = false;
70
- } else {
71
- args[camel(key)] = val;
72
- }
73
- } else {
74
- args._.push(t);
75
- }
76
- }
77
- return args;
78
- }
79
-
80
- function printJson(obj) {
81
- process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
82
- }
83
-
84
- // Print a terminal result. A board with many annotations produces a large JSON
85
- // payload, and an agent's shell harness commonly truncates long stdout — so the
86
- // agent silently misses annotations past the cut. We write the FULL result to a
87
- // sidecar file and surface its path FIRST (`resultFile`), so even a truncated
88
- // stdout shows where the complete payload is; the agent reads that file with its
89
- // file tool. Falls back to a plain print if the sidecar can't be written.
90
- function printResult(result) {
91
- const resultFile = result && result.boardId ? saveResultFile(result.boardId, result) : null;
92
- printJson(resultFile ? { resultFile, ...result } : result);
93
- }
94
-
95
- // Push-wake for `rly wait --notify-cmd`: run the agent's local shell command
96
- // once a TERMINAL result lands. Result JSON goes to the command's stdin;
97
- // RLY_BOARD_ID / RLY_STATUS / RLY_URL are exported. Same shape as the server's
98
- // --on-result hook. Failures are swallowed; a 30s kill timer caps a hung cmd.
99
- function runNotifyCmd(cmd, result) {
100
- if (typeof cmd !== 'string' || !cmd.trim()) return;
101
- try {
102
- const child = spawn('/bin/sh', ['-c', cmd], {
103
- env: {
104
- ...process.env,
105
- RLY_BOARD_ID: result.boardId || '',
106
- RLY_STATUS: result.status || '',
107
- RLY_URL: result.url || '',
108
- },
109
- stdio: ['pipe', 'ignore', 'ignore'],
110
- });
111
- child.on('error', () => {});
112
- try {
113
- child.stdin.write(JSON.stringify(result));
114
- child.stdin.end();
115
- } catch {
116
- // best effort
117
- }
118
- const killTimer = setTimeout(() => {
119
- try {
120
- child.kill('SIGKILL');
121
- } catch {
122
- // already gone
123
- }
124
- }, 30000);
125
- killTimer.unref();
126
- child.on('close', () => clearTimeout(killTimer));
127
- child.unref();
128
- } catch {
129
- // swallow — push-wake is best effort
130
- }
131
- }
132
-
133
- function exitCodeFor(status) {
134
- return { submitted: 0, acknowledged: 0, open: 0, timeout: 2, cancelled: 3 }[status] ?? 1;
135
- }
136
-
137
- function parseJson(text, where) {
138
- try {
139
- return JSON.parse(text);
140
- } catch (err) {
141
- throw new CliError(`invalid JSON in ${where}: ${err.message}`);
142
- }
143
- }
144
-
145
- function readStdin() {
146
- return new Promise((resolve, reject) => {
147
- let data = '';
148
- process.stdin.setEncoding('utf8');
149
- process.stdin.on('data', (c) => (data += c));
150
- process.stdin.on('end', () => resolve(data));
151
- process.stdin.on('error', reject);
152
- });
153
- }
154
-
155
- function mustLoad(id) {
156
- if (!id) throw new CliError('missing <board-id>. See `rly history` for saved boards.');
157
- const record = loadBoard(id);
158
- if (!record) throw new CliError(`board "${id}" not found. See \`rly history\`.`, 5);
159
- return record;
160
- }
161
-
162
- async function resolveSpecInput(args, mode) {
163
- let raw = {};
164
- if (args.file) {
165
- raw =
166
- args.file === '-'
167
- ? parseJson(await readStdin(), 'stdin')
168
- : parseJson(readFileOrThrow(args.file), args.file);
169
- } else if (args.stdin) {
170
- raw = parseJson(await readStdin(), 'stdin');
171
- }
172
- if (args.title) raw.title = args.title;
173
- if (args.intro) raw.intro = args.intro;
174
- if (typeof args.html === 'string') raw.html = args.html;
175
- if (args.htmlFile) raw.htmlFile = args.htmlFile;
176
- if (args.height) raw.htmlHeight = args.height;
177
- if (args.submitLabel) raw.submitLabel = args.submitLabel;
178
- if (args.displayOnly === true) raw.responseRequired = false;
179
- if (args.q.length) {
180
- raw.questions = [...(raw.questions || []), ...args.q.map((s, i) => questionFromInline(s, i))];
181
- }
182
- // If the user supplied a spec (file/stdin) let normalizeSpec report what's
183
- // wrong with it precisely; the generic usage hint is only for a bare call.
184
- const suppliedSpec = Boolean(args.file || args.stdin);
185
- const hasContent = (raw.questions && raw.questions.length) || raw.html || raw.htmlFile;
186
- if (!suppliedSpec && !hasContent) {
187
- throw new CliError(
188
- mode === 'show'
189
- ? 'show needs --html-file <file>, --html "<markup>", or --file <spec.json>. Run `rly agent` for examples.'
190
- : 'ask needs a spec: --file <spec.json>, --file - (stdin), or -q "label::type::opt1,opt2". Run `rly agent` for examples.'
191
- );
192
- }
193
- return raw;
194
- }
195
-
196
- function readFileOrThrow(p) {
197
- try {
198
- return fs.readFileSync(path.resolve(p), 'utf8');
199
- } catch {
200
- throw new CliError(`cannot read file "${p}".`);
201
- }
202
- }
203
-
204
- async function runOrDetach(record, args) {
205
- await assertSpecReady(record.spec);
206
- const timeoutSec = args.timeout !== undefined ? Math.max(0, Number.parseInt(args.timeout, 10) || 0) : DEFAULT_BOARD_TIMEOUT_SEC;
207
- const port = args.port !== undefined ? Number.parseInt(args.port, 10) || 0 : 0;
208
- const open = args.open !== false;
209
- const link = linkSetting({ args, config: loadConfig(HOME) });
210
-
211
- // Push-wake: persist the agent's --on-result command on the record so BOTH
212
- // the inline runBoard path and the detached __serve path pick it up (the
213
- // detached server reads record.onResult from disk). Runtime concern only —
214
- // not part of the spec.
215
- if (typeof args.onResult === 'string' && args.onResult.trim()) {
216
- record.onResult = args.onResult;
217
- saveBoard(record);
218
- }
219
-
220
- if (args.detach) {
221
- const child = spawn(
222
- process.execPath,
223
- [
224
- BIN, '__serve',
225
- '--id', record.id,
226
- '--port', String(port),
227
- '--timeout', String(timeoutSec),
228
- ...(open ? [] : ['--no-open']),
229
- '--link', serializeLink(link),
230
- ],
231
- { detached: true, stdio: 'ignore' }
232
- );
233
- child.unref();
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);
238
- printJson({
239
- status: 'open',
240
- boardId: record.id,
241
- url: info.url,
242
- port: info.port,
243
- hint: record.spec.responseRequired === false
244
- ? 'display-only board opened; no response will be collected'
245
- : `block for the answers with: rly wait ${record.id}`,
246
- });
247
- return 0;
248
- }
249
-
250
- const { done } = await runBoard({ id: record.id, port, open, timeoutSec, link });
251
- const result = await done;
252
- printResult(result);
253
- return exitCodeFor(result.status);
254
- }
255
-
256
- async function cmdAsk(args, mode) {
257
- const raw = await resolveSpecInput(args, mode);
258
- const spec = normalizeSpec(raw);
259
- await assertSpecReady(spec);
260
- const record = createBoard(spec);
261
- return runOrDetach(record, spec.responseRequired === false ? { ...args, detach: true } : args);
262
- }
263
-
264
- // `rly diff [git args…]` — run `git diff` for the user and open the result as a
265
- // diff-block board in one step (sugar like `rly view`). Everything that isn't a
266
- // recognized rly flag is forwarded to git verbatim, so `rly diff --staged`,
267
- // `rly diff HEAD~1`, `rly diff main -- src/` all work. rly flags: --detach,
268
- // --no-open, --split (side-by-side), --title.
269
- async function cmdDiff(rest) {
270
- const RLY_FLAGS = new Set(['--detach', '--no-open', '--split', '--devlink', '--no-devlink']);
271
- const gitArgs = [];
272
- const rlyArgv = [];
273
- for (let i = 0; i < rest.length; i++) {
274
- const t = rest[i];
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; }
277
- if (RLY_FLAGS.has(t)) { rlyArgv.push(t); continue; }
278
- gitArgs.push(t);
279
- }
280
- const args = parseArgs(rlyArgv);
281
- const res = spawnSync('git', ['--no-pager', 'diff', ...gitArgs], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
282
- if (res.error) throw new CliError(`could not run git: ${res.error.message}. Is git installed and is this a repo?`);
283
- if (res.status !== 0 && res.stderr) throw new CliError(`git diff failed: ${res.stderr.trim()}`, res.status || 1);
284
- const diff = res.stdout || '';
285
- if (!diff.trim()) {
286
- printJson({ status: 'no-diff', hint: `git diff${gitArgs.length ? ' ' + gitArgs.join(' ') : ''} produced no output — nothing to show` });
287
- return 0;
288
- }
289
- const title = args.title || ('git diff' + (gitArgs.length ? ' ' + gitArgs.join(' ') : ''));
290
- const spec = normalizeSpec({ title, blocks: [{ type: 'diff', diff, view: args.split ? 'split' : 'unified' }] });
291
- await assertSpecReady(spec);
292
- const record = createBoard(spec);
293
- return runOrDetach(record, args);
294
- }
295
-
296
- function runGit(args, message) {
297
- const res = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
298
- if (res.error) throw new CliError(`could not run git: ${res.error.message}. Is git installed and is this a repo?`);
299
- if (res.status !== 0) {
300
- const detail = (res.stderr || res.stdout || '').trim();
301
- throw new CliError(`${message}: ${detail || `git ${args.join(' ')} exited ${res.status}`}`, res.status || 1);
302
- }
303
- return res.stdout || '';
304
- }
305
-
306
- function gitConflictPaths(explicitPaths) {
307
- if (explicitPaths.length) return explicitPaths;
308
- const out = runGit(['diff', '--name-only', '--diff-filter=U'], 'git conflict detection failed');
309
- return out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
310
- }
311
-
312
- function gitCommitRows(range, limit) {
313
- const n = Math.max(1, Math.min(200, Number.parseInt(limit, 10) || 20));
314
- const args = ['log', `-n${n}`, '--date=short', '--pretty=format:%H%x09%h%x09%ad%x09%an%x09%s'];
315
- if (range) args.push(range);
316
- return runGit(args, 'git log failed')
317
- .split(/\r?\n/)
318
- .filter(Boolean)
319
- .map((line) => {
320
- const [sha, short, date, author, ...subjectParts] = line.split('\t');
321
- const subject = subjectParts.join('\t');
322
- return { sha, short, date, author, subject };
323
- })
324
- .filter((r) => r.sha && r.short);
325
- }
326
-
327
- function gitCommitDiff(commit) {
328
- return runGit([
329
- '--no-pager',
330
- 'show',
331
- '--format=',
332
- '--patch',
333
- '--find-renames',
334
- '--find-copies',
335
- '--no-ext-diff',
336
- commit,
337
- ], `git show ${commit} failed`).trimEnd();
338
- }
339
-
340
- async function cmdGit(rest) {
341
- const args = parseArgs(rest);
342
- const modes = new Set(['pick', 'cherry-pick', 'cherrypick', 'conflict', 'conflicts', 'resolve']);
343
- let mode = 'pick';
344
- if (args._[0] && modes.has(args._[0])) mode = args._.shift();
345
- if (mode === 'cherrypick') mode = 'cherry-pick';
346
- if (mode === 'conflicts' || mode === 'resolve') mode = 'conflict';
347
-
348
- const blocks = [];
349
- const questions = [];
350
- let reviewDiffCount = 0;
351
-
352
- if (mode === 'pick' || mode === 'cherry-pick') {
353
- const range = args.range || args._[0] || '';
354
- const commits = gitCommitRows(range, args.limit);
355
- if (!commits.length) throw new CliError(`git log${range ? ` ${range}` : ''} produced no commits to show.`);
356
- const withCode = args.code === true || args.patch === true || args.diff === true;
357
- blocks.push({
358
- type: 'table',
359
- columns: ['short', 'date', 'author', 'subject'],
360
- rows: commits.map((c) => ({ short: c.short, date: c.date, author: c.author, subject: c.subject })),
361
- sortable: true,
362
- filterable: true,
363
- exportable: true,
364
- });
365
- const options = commits.map((c) => ({
366
- value: c.sha,
367
- label: `${c.short} ${c.subject}`,
368
- description: `${c.date} · ${c.author}`,
369
- }));
370
- questions.push({
371
- id: 'commit_actions',
372
- type: 'checklist',
373
- label: mode === 'cherry-pick' ? 'Choose cherry-pick actions' : 'Choose commit actions',
374
- description: 'Set only the commits you want the agent to act on.',
375
- options,
376
- statuses: mode === 'cherry-pick'
377
- ? [{ value: 'cherry-pick', label: 'Cherry-pick', tone: 'ok' }, { value: 'skip', label: 'Skip', tone: 'muted' }, { value: 'hold', label: 'Hold', tone: 'warn' }]
378
- : [{ value: 'pick', label: 'Pick', tone: 'ok' }, { value: 'cherry-pick', label: 'Cherry-pick', tone: 'warn' }, { value: 'drop', label: 'Drop', tone: 'bad' }],
379
- });
380
- if (options.length > 1) {
381
- questions.push({
382
- id: 'commit_order',
383
- type: 'rank',
384
- label: mode === 'cherry-pick' ? 'Cherry-pick order' : 'Preferred commit order',
385
- description: 'Drag or move commits into the order the agent should apply them.',
386
- options,
387
- });
388
- }
389
- if (withCode) {
390
- for (const c of commits) {
391
- const diff = gitCommitDiff(c.sha);
392
- if (!diff.trim()) continue;
393
- blocks.push({
394
- type: 'diff',
395
- title: `${c.short} ${c.subject}`,
396
- filename: `${c.short} ${c.subject}`,
397
- commit: c.sha,
398
- reviewKind: mode,
399
- review: true,
400
- view: 'split',
401
- diff,
402
- });
403
- reviewDiffCount++;
404
- }
405
- }
406
- }
407
-
408
- const paths = mode === 'conflict' ? gitConflictPaths(args._) : gitConflictPaths([]);
409
- for (const p of paths) {
410
- let text = '';
411
- try { text = fs.readFileSync(path.resolve(p), 'utf8'); } catch { /* normalizeSpec will report unreadable explicit files below */ }
412
- if (!text || /<<<<<<<[\s\S]*=======[\s\S]*>>>>>>>/.test(text)) {
413
- blocks.push({ type: 'git-conflict', path: p, filename: p });
414
- }
415
- }
416
-
417
- if (mode === 'conflict' && !blocks.some((b) => b.type === 'git-conflict')) {
418
- throw new CliError(args._.length
419
- ? 'no conflict markers found in the provided file(s).'
420
- : 'no unmerged git files with conflict markers were detected.');
421
- }
422
-
423
- const conflictCount = blocks.filter((b) => b.type === 'git-conflict').length;
424
- const title = args.title || (mode === 'conflict'
425
- ? `Resolve ${conflictCount} git conflict${conflictCount === 1 ? '' : 's'}`
426
- : mode === 'cherry-pick' ? 'Cherry-pick commits' : 'Pick commits');
427
- const intro = args.intro || (conflictCount
428
- ? 'Resolve each conflict on the board. The submitted result includes result.blockEdits with per-hunk choices and a full resolved file preview for every conflict block.'
429
- : reviewDiffCount
430
- ? 'Review commit code hunks on the board. Apply, skip, or hold each hunk; submit returns commit actions plus diff-review hunk choices as JSON.'
431
- : 'Pick commit actions and order on the board. Submit returns the selected actions and rank order as JSON.');
432
- const spec = normalizeSpec({ title, intro, blocks, questions, submitLabel: 'Submit git choices' });
433
- await assertSpecReady(spec);
434
- const record = createBoard(spec);
435
- return runOrDetach(record, args);
436
- }
437
-
438
- // `rly view <file.md> [more.md …]` — quick read-only board that renders files
439
- // with purpose-built blocks (markdown, data tables, PDF). With 2+ files a small
440
- // filename heading separates them. Sugar over `rly show`.
441
- async function cmdView(args) {
442
- const files = args._;
443
- if (!files.length) throw new CliError('usage: rly view <file.md|.csv|.json|.pdf> [more …] [--title T] [--detach]');
444
- const multi = files.length > 1;
445
- const DATA_EXT = new Set(['csv', 'tsv', 'json']);
446
- const blocks = [];
447
- for (const f of files) {
448
- if (multi) blocks.push({ type: 'markdown', md: `## ${path.basename(f)}` });
449
- const ext = path.extname(f).slice(1).toLowerCase();
450
- if (DATA_EXT.has(ext)) blocks.push({ type: 'table', rowsFile: f, sortable: true, filterable: true, exportable: true });
451
- else if (ext === 'pdf') blocks.push({ type: 'pdf', src: f, title: path.basename(f) });
452
- else blocks.push({ type: 'markdown', mdFile: f });
453
- }
454
- const raw = { blocks };
455
- raw.title = args.title || (multi ? `${files.length} files` : path.basename(files[0]));
456
- raw.submitLabel = args.submitLabel || 'Done';
457
- const spec = normalizeSpec(raw); // reads + validates each file, clear error if unreadable
458
- await assertSpecReady(spec);
459
- const record = createBoard(spec);
460
- return runOrDetach(record, args);
461
- }
462
-
463
- // Seeds the draft from the last result (as runBoard would on reopen) and
464
- // appends agent replies to the matching annotations, so an agent can ANSWER
465
- // the user's element comments and re-open the board as a conversation.
466
- // Persists the record with the result archived so runBoard doesn't re-seed.
467
- function seedAgentReplies(record, replies) {
468
- if (!Array.isArray(replies)) throw new CliError('--replies file must be a JSON array of {annotationId, text}.', 4);
469
- // Mirror runBoard's reopen draft-seeding from the prior result.
470
- if (record.result) {
471
- if (record.result.answers) {
472
- record.draft = {
473
- answers: record.result.answers,
474
- comment: record.result.comment || '',
475
- notes: record.result.notes || {},
476
- annotations: record.result.annotations || [],
477
- updatedAt: new Date().toISOString(),
478
- };
479
- }
480
- record.pastResults = [...(record.pastResults || []), record.result].slice(-10);
481
- record.result = null;
482
- }
483
- const annotations = (record.draft && Array.isArray(record.draft.annotations)) ? record.draft.annotations : [];
484
- const validIds = annotations.map((a) => a && a.id).filter(Boolean);
485
- const now = new Date().toISOString();
486
- replies.forEach((r, i) => {
487
- if (r === null || typeof r !== 'object' || Array.isArray(r)) {
488
- throw new CliError(`--replies[${i}]: must be an object {annotationId, text}.`, 4);
489
- }
490
- const annotationId = typeof r.annotationId === 'string' ? r.annotationId : '';
491
- const text = typeof r.text === 'string' ? r.text : '';
492
- if (!annotationId) throw new CliError(`--replies[${i}]: missing "annotationId".`, 4);
493
- if (!text.trim()) throw new CliError(`--replies[${i}]: missing "text".`, 4);
494
- const ann = annotations.find((a) => a && a.id === annotationId);
495
- if (!ann) {
496
- throw new CliError(
497
- `--replies[${i}]: unknown annotationId "${annotationId}". Valid ids: ${validIds.length ? validIds.join(', ') : '(none)'}.`,
498
- 4
499
- );
500
- }
501
- if (!Array.isArray(ann.replies)) ann.replies = [];
502
- ann.replies.push({ author: 'agent', text, createdAt: now });
503
- });
504
- if (!record.draft) record.draft = { answers: {}, comment: '', notes: {}, annotations, updatedAt: now };
505
- else record.draft.annotations = annotations;
506
- saveBoard(record);
507
- }
508
-
509
- async function cmdReopen(args) {
510
- const record = mustLoad(args._[0]);
511
- if (args.replies !== undefined) {
512
- const replies = parseJson(readFileOrThrow(args.replies), args.replies);
513
- seedAgentReplies(record, replies);
514
- }
515
- const running = loadRunning(record.id);
516
- if (running && isAlive(running.pid)) {
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' });
519
- return 0;
520
- }
521
- // Reuse the board's last port (unless the user forced one) so a tab still open
522
- // from a previous run reconnects on its own instead of being stranded on a
523
- // dead port. runBoard falls back to a random port if it's been taken.
524
- return runOrDetach(record, { ...args, port: args.port ?? record.lastPort });
525
- }
526
-
527
- // Rescue a board whose browser tab is still open but disconnected (its server
528
- // died / the machine slept). Re-serves the SAME board on the SAME port it last
529
- // used, so the open tab's relative /api/* fetches reconnect on their own — the
530
- // page's recovery loop lifts its "connection lost" block and re-flushes the
531
- // draft (incl. anything the user mirrored to localStorage during the outage)
532
- // with zero action from the user. Defaults to NOT opening a new browser tab
533
- // (the point is the existing one); pass --open to also open a fresh tab.
534
- async function cmdRescue(args) {
535
- const record = mustLoad(args._[0]);
536
- const running = loadRunning(record.id);
537
- if (running && isAlive(running.pid)) {
538
- if (args.open && !running.link) openUrl(running.url);
539
- printJson({
540
- status: 'open',
541
- boardId: record.id,
542
- url: running.url,
543
- port: running.port,
544
- note: 'already running — the open tab should be connected; reload it if not',
545
- });
546
- return 0;
547
- }
548
- if (!record.lastPort) {
549
- throw new CliError(
550
- `board "${record.id}" has no known port to reuse (never served in this version). Use \`rly reopen ${record.id}\` instead.`,
551
- 5
552
- );
553
- }
554
- // Force the original port so the disconnected tab can reconnect; default to
555
- // not opening a second tab. seedAgentReplies parity with reopen if provided.
556
- if (args.replies !== undefined) {
557
- const replies = parseJson(readFileOrThrow(args.replies), args.replies);
558
- seedAgentReplies(record, replies);
559
- }
560
- return runOrDetach(record, { ...args, port: record.lastPort, open: args.open === true });
561
- }
562
-
563
- async function cmdReuse(args) {
564
- const src = mustLoad(args._[0]);
565
- if (args.dump) {
566
- console.log(JSON.stringify(src.spec, null, 2));
567
- return 0;
568
- }
569
- const record = createBoard(src.spec);
570
- return runOrDetach(record, args);
571
- }
572
-
573
- // Live-mutates a running board: rebuild the spec (full replace via --file, or
574
- // patch the current spec via --title/--intro/-q), then POST it (already
575
- // normalized) to the board's /api/update with the per-board mutation token.
576
- async function cmdUpdate(args) {
577
- const id = args._[0];
578
- if (!id) throw new CliError('usage: rly update <board-id> (--file new-spec.json | --title T | --intro I | -q "...")');
579
- const record = loadBoard(id);
580
- if (!record) throw new CliError(`board "${id}" not found. See \`rly history\`.`, 5);
581
- const running = loadRunning(id);
582
- if (!running || !isAlive(running.pid)) {
583
- throw new CliError(`board "${id}" is not running — \`rly reopen ${id}\` to serve it, then update.`, 5);
584
- }
585
-
586
- let spec;
587
- if (args.file) {
588
- const raw =
589
- args.file === '-'
590
- ? parseJson(await readStdin(), 'stdin')
591
- : parseJson(readFileOrThrow(args.file), args.file);
592
- spec = normalizeSpec(raw);
593
- } else if (args.title || args.intro || args.q.length) {
594
- // Patch the CURRENT spec, then re-normalize so it's a clean normalized spec.
595
- const raw = { ...record.spec };
596
- if (args.title) raw.title = args.title;
597
- if (args.intro) raw.intro = args.intro;
598
- if (args.q.length) {
599
- raw.questions = [...(raw.questions || []), ...args.q.map((s, i) => questionFromInline(s, i))];
600
- }
601
- spec = normalizeSpec(raw);
602
- } else {
603
- throw new CliError('update needs --file <spec.json>, --title, --intro, or -q "...".', 4);
604
- }
605
- await assertSpecReady(spec);
606
-
607
- let res;
608
- try {
609
- res = await fetch(new URL('/api/update', controlUrl(running)), {
610
- method: 'POST',
611
- headers: { 'content-type': 'application/json', 'x-relay-token': running.token || '' },
612
- body: JSON.stringify({ spec }),
613
- });
614
- } catch (err) {
615
- throw new CliError(`could not reach board "${id}" at ${running.url}: ${String((err && err.message) || err)}`, 5);
616
- }
617
- if (res.status === 403) throw new CliError(`board "${id}" rejected the update token (stale running file?).`, 5);
618
- if (!res.ok) {
619
- let detail = '';
620
- try {
621
- detail = (await res.json()).error || '';
622
- } catch {
623
- // non-JSON body
624
- }
625
- throw new CliError(`board "${id}" rejected the update${detail ? `: ${detail}` : ''}.`, 4);
626
- }
627
- const body = await res.json();
628
- printJson({ status: 'updated', boardId: id, rev: body.rev, url: running.url });
629
- return 0;
630
- }
631
-
632
- // Best-effort fetch of /api/presence for a running board. Returns the parsed
633
- // presence object, or null on any failure / timeout (500ms cap via
634
- // AbortController). Never throws.
635
- async function fetchPresence(url) {
636
- if (!url) return null;
637
- const controller = new AbortController();
638
- const timer = setTimeout(() => controller.abort(), 500);
639
- try {
640
- const res = await fetch(new URL('/api/presence', url), { signal: controller.signal });
641
- if (!res.ok) return null;
642
- return await res.json();
643
- } catch {
644
- return null;
645
- } finally {
646
- clearTimeout(timer);
647
- }
648
- }
649
-
650
- async function cmdWait(args) {
651
- const id = args._[0];
652
- if (!id) throw new CliError('usage: rly wait <board-id> [--timeout <sec>] [--while-active] [--idle-grace <sec>] [--notify-cmd <cmd>]');
653
- const timeoutSec = args.timeout !== undefined ? Math.max(0, Number.parseInt(args.timeout, 10) || 0) : DEFAULT_WAIT_TIMEOUT_SEC;
654
- const whileActive = args.whileActive === true;
655
- const idleGrace = args.idleGrace !== undefined ? Math.max(0, Number.parseInt(args.idleGrace, 10) || 0) : 180;
656
- const notifyCmd = typeof args.notifyCmd === 'string' && args.notifyCmd.trim() ? args.notifyCmd : null;
657
- let deadline = timeoutSec === 0 ? Number.POSITIVE_INFINITY : Date.now() + timeoutSec * 1000;
658
- mustLoad(id);
659
-
660
- // Push-wake: run the agent's --notify-cmd after a TERMINAL result, then print.
661
- const finishResult = (result) => {
662
- if (notifyCmd) runNotifyCmd(notifyCmd, result);
663
- printResult(result);
664
- return exitCodeFor(result.status);
665
- };
666
-
667
- while (Date.now() < deadline) {
668
- const record = mustLoad(id);
669
- if (record.result && record.result.finishedAt) {
670
- return finishResult(record.result);
671
- }
672
- const running = loadRunning(id);
673
- if (!running || !isAlive(running.pid)) {
674
- await sleep(700); // the result write may be racing the process exit
675
- const again = loadBoard(id);
676
- if (again?.result?.finishedAt) {
677
- return finishResult(again.result);
678
- }
679
- printResult({
680
- status: 'lost',
681
- boardId: id,
682
- draft: again?.draft ?? null,
683
- error: 'board server exited without writing a result',
684
- });
685
- return 5;
686
- }
687
- if (Date.now() >= deadline) break;
688
- await sleep(400);
689
- }
690
-
691
- // Deadline hit while the board is still OPEN. Fetch presence (cheaply).
692
- const running = loadRunning(id);
693
- const presence = running && isAlive(running.pid) ? await fetchPresence(controlUrl(running)) : null;
694
-
695
- // --while-active: if the user is present + recently active, EXTEND and keep
696
- // waiting (repeat indefinitely while they stay active).
697
- if (
698
- whileActive &&
699
- presence &&
700
- presence.seen &&
701
- (presence.visible || presence.focused) &&
702
- presence.secondsSinceActivity < idleGrace
703
- ) {
704
- deadline = Date.now() + Math.min(idleGrace, 120) * 1000;
705
- return cmdWaitLoop(id, deadline, { whileActive, idleGrace, notifyCmd });
706
- }
707
-
708
- const out = {
709
- status: 'wait-timeout',
710
- boardId: id,
711
- hint: `board is still open — run \`rly wait ${id}\` again, or \`rly result ${id}\` to peek at the live draft`,
712
- };
713
- if (presence) out.presence = presence;
714
- printJson(out);
715
- return 2;
716
- }
717
-
718
- // Continuation loop for `rly wait --while-active` after a deadline extension.
719
- // Identical waiting logic to cmdWait's main loop, then re-evaluates presence;
720
- // extends again while the user stays active, otherwise emits wait-timeout.
721
- async function cmdWaitLoop(id, deadline, opts) {
722
- const { whileActive, idleGrace, notifyCmd } = opts;
723
- const finishResult = (result) => {
724
- if (notifyCmd) runNotifyCmd(notifyCmd, result);
725
- printResult(result);
726
- return exitCodeFor(result.status);
727
- };
728
- while (Date.now() < deadline) {
729
- const record = mustLoad(id);
730
- if (record.result && record.result.finishedAt) {
731
- return finishResult(record.result);
732
- }
733
- const running = loadRunning(id);
734
- if (!running || !isAlive(running.pid)) {
735
- await sleep(700);
736
- const again = loadBoard(id);
737
- if (again?.result?.finishedAt) {
738
- return finishResult(again.result);
739
- }
740
- printResult({
741
- status: 'lost',
742
- boardId: id,
743
- draft: again?.draft ?? null,
744
- error: 'board server exited without writing a result',
745
- });
746
- return 5;
747
- }
748
- if (Date.now() >= deadline) break;
749
- await sleep(400);
750
- }
751
- const running = loadRunning(id);
752
- const presence = running && isAlive(running.pid) ? await fetchPresence(controlUrl(running)) : null;
753
- if (
754
- whileActive &&
755
- presence &&
756
- presence.seen &&
757
- (presence.visible || presence.focused) &&
758
- presence.secondsSinceActivity < idleGrace
759
- ) {
760
- const next = Date.now() + Math.min(idleGrace, 120) * 1000;
761
- return cmdWaitLoop(id, next, opts);
762
- }
763
- const out = {
764
- status: 'wait-timeout',
765
- boardId: id,
766
- hint: `board is still open — run \`rly wait ${id}\` again, or \`rly result ${id}\` to peek at the live draft`,
767
- };
768
- if (presence) out.presence = presence;
769
- printJson(out);
770
- return 2;
771
- }
772
-
773
- async function cmdResult(args) {
774
- const record = mustLoad(args._[0]);
775
- const sideReviews = {
776
- referenceOnly: true,
777
- note: 'Side reviews are reference only. Wait for the board owner (or owner-authorized collaborator) to submit the final answer.',
778
- submissions: Array.isArray(record.sideReviews) ? record.sideReviews : [],
779
- drafts: record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {},
780
- };
781
- if (record.result && record.result.finishedAt) {
782
- printResult({ ...record.result, sideReviews });
783
- return exitCodeFor(record.result.status);
784
- }
785
- const running = loadRunning(record.id);
786
- if (running && isAlive(running.pid)) {
787
- // While open, expose the real-time autosaved draft so agents can peek, plus
788
- // best-effort presence (whether the user is still viewing/focused/active).
789
- const out = { status: 'open', boardId: record.id, url: running.url, draft: record.draft ?? null, sideReviews };
790
- const presence = await fetchPresence(controlUrl(running));
791
- if (presence) out.presence = presence;
792
- printResult(out); // draft can hold many annotations — sidecar it too
793
- return 0;
794
- }
795
- printResult({ status: 'lost', boardId: record.id, draft: record.draft ?? null, sideReviews });
796
- return 5;
797
- }
798
-
799
- async function cmdShare(args) {
800
- const record = mustLoad(args._[0]);
801
- const running = loadRunning(record.id);
802
- if (!running || !isAlive(running.pid)) {
803
- throw new CliError(`board "${record.id}" is not running. Use \`rly reopen ${record.id} --detach\` first.`, 5);
804
- }
805
- let role = args.all ? 'all' : args.role;
806
- if (role === 'readonly' || role === 'read-only') role = 'read';
807
- if (role !== undefined && !['collab', 'review', 'read', 'all'].includes(role)) {
808
- throw new CliError('--role must be collab, review, or read.', 4);
809
- }
810
- const shareUrl = new URL('/api/share', controlUrl(running));
811
- const headers = { 'content-type': 'application/json', 'x-relay-token': running.token || '' };
812
- let res;
813
- try {
814
- if (args.revoke) {
815
- res = await fetch(shareUrl, {
816
- method: 'DELETE',
817
- headers,
818
- body: JSON.stringify({ role: role || 'all' }),
819
- });
820
- } else if (role && role !== 'all') {
821
- res = await fetch(shareUrl, {
822
- method: 'POST',
823
- headers,
824
- body: JSON.stringify({ role }),
825
- });
826
- } else {
827
- res = await fetch(shareUrl, { method: 'GET', headers });
828
- }
829
- } catch (err) {
830
- throw new CliError(`could not reach board "${record.id}" at ${running.url}: ${String((err && err.message) || err)}`, 5);
831
- }
832
- const body = await res.json().catch(() => null);
833
- if (!res.ok) {
834
- throw new CliError((body && body.error) || `share request failed with HTTP ${res.status}`, res.status === 400 ? 4 : 5);
835
- }
836
- printJson({ status: args.revoke ? 'revoked' : role && role !== 'all' ? 'active' : 'shares', boardId: record.id, ...body });
837
- return 0;
838
- }
839
-
840
- function cmdList(args) {
841
- const running = listRunning();
842
- if (args.json) {
843
- printJson(running);
844
- return 0;
845
- }
846
- if (!running.length) {
847
- console.log('No boards running.');
848
- return 0;
849
- }
850
- for (const r of running) {
851
- console.log(`${r.id} ${r.url} pid ${r.pid} "${r.title}" since ${r.startedAt}`);
852
- }
853
- return 0;
854
- }
855
-
856
- function cmdOpen(args) {
857
- let id = args._[0];
858
- const running = listRunning();
859
- if (!id) {
860
- if (running.length === 1) id = running[0].id;
861
- else if (running.length === 0) throw new CliError('no boards running. Use `rly reopen <id>` to serve a saved one.', 5);
862
- else throw new CliError(`multiple boards running — pick one: ${running.map((r) => r.id).join(', ')}`);
863
- }
864
- const info = running.find((r) => r.id === id);
865
- if (!info) throw new CliError(`board "${id}" is not running. Use \`rly reopen ${id}\` to serve it again (with saved answers).`, 5);
866
- if (!info.link) openUrl(info.url);
867
- printJson({ status: 'open', boardId: id, url: info.url });
868
- return 0;
869
- }
870
-
871
- async function cmdStop(args) {
872
- let targets;
873
- if (args.all) {
874
- targets = listRunning();
875
- if (!targets.length) {
876
- printJson({ stopped: [] });
877
- return 0;
878
- }
879
- } else {
880
- const id = args._[0];
881
- if (!id) throw new CliError('usage: rly stop <board-id> | rly stop --all');
882
- const info = loadRunning(id);
883
- if (!info || !isAlive(info.pid)) {
884
- removeRunning(id);
885
- throw new CliError(`board "${id}" is not running.`, 5);
886
- }
887
- targets = [info];
888
- }
889
- for (const t of targets) {
890
- try {
891
- process.kill(t.pid, 'SIGTERM');
892
- } catch {
893
- // already gone
894
- }
895
- }
896
- for (const t of targets) {
897
- await pollFor(() => (loadRunning(t.id) ? null : true), 5000);
898
- }
899
- printJson({
900
- stopped: targets.map((t) => {
901
- const record = loadBoard(t.id);
902
- return { boardId: t.id, status: record?.result?.status ?? 'unknown', draft: record?.draft ?? null };
903
- }),
904
- });
905
- return 0;
906
- }
907
-
908
- function cmdHistory(args) {
909
- const limit = args.limit !== undefined ? Number.parseInt(args.limit, 10) || 15 : 15;
910
- const records = listBoards(limit);
911
- const runningIds = new Set(listRunning().map((r) => r.id));
912
- if (args.json) {
913
- printJson(
914
- records.map((r) => ({
915
- id: r.id,
916
- createdAt: r.createdAt,
917
- title: r.title,
918
- status: runningIds.has(r.id) ? 'open' : r.result?.status ?? 'unfinished',
919
- questions: r.spec.questions.length,
920
- blocks: (r.spec.blocks || []).length,
921
- hasDraft: Boolean(r.draft),
922
- answers: r.result?.answers ?? null,
923
- }))
924
- );
925
- return 0;
926
- }
927
- if (!records.length) {
928
- console.log(`No saved boards yet (storage: ${HOME}).`);
929
- return 0;
930
- }
931
- for (const r of records) {
932
- const status = runningIds.has(r.id) ? 'open' : r.result?.status ?? 'unfinished';
933
- const nBlocks = (r.spec.blocks || []).length;
934
- console.log(`${r.id} ${r.createdAt} [${status}] "${r.title}" ${r.spec.questions.length}q${nBlocks ? `+${nBlocks}b` : ''}`);
935
- }
936
- console.log(`\nReuse: \`rly reuse <id>\` · spec: \`rly spec <id>\` · reopen w/ answers: \`rly reopen <id>\` · delete: \`rly rm <id>\``);
937
- return 0;
938
- }
939
-
940
- function cmdSpec(args) {
941
- const record = mustLoad(args._[0]);
942
- console.log(JSON.stringify(record.spec, null, 2));
943
- return 0;
944
- }
945
-
946
- function cmdRm(args) {
947
- const runningIds = new Set(listRunning().map((r) => r.id));
948
- if (args.all) {
949
- let removed = 0;
950
- for (const r of listBoards(0)) {
951
- if (runningIds.has(r.id)) continue;
952
- if (deleteBoard(r.id)) removed++;
953
- }
954
- printJson({ removed, skippedRunning: runningIds.size });
955
- return 0;
956
- }
957
- const id = args._[0];
958
- if (!id) throw new CliError('usage: rly rm <board-id> | rly rm --all');
959
- if (runningIds.has(id)) throw new CliError(`board "${id}" is running — \`rly stop ${id}\` first.`);
960
- if (!deleteBoard(id)) throw new CliError(`board "${id}" not found.`, 5);
961
- printJson({ removed: id });
962
- return 0;
963
- }
964
-
965
- const SKILL_SRC = path.join(PKG_ROOT, 'skills', 'relay');
966
-
967
- const KNOWN_SKILL_DIRS = () => ({
968
- claude: path.join(os.homedir(), '.claude', 'skills', 'relay'),
969
- codex: path.join(os.homedir(), '.codex', 'skills', 'relay'),
970
- // The cross-agent skills dir (npx-skills ecosystem). Some Codex/agent
971
- // setups load skills from here INSTEAD of ~/.codex/skills.
972
- agents: path.join(os.homedir(), '.agents', 'skills', 'relay'),
973
- });
974
-
975
- // Pre-rename skill dirs (quest-board). `skill install` removes these so a
976
- // stale copy doesn't shadow the renamed one.
977
- const LEGACY_SKILL_DIRS = () => [
978
- path.join(os.homedir(), '.claude', 'skills', 'quest-board'),
979
- path.join(os.homedir(), '.codex', 'skills', 'quest-board'),
980
- ];
981
-
982
- // One-time stderr nudge so agents that only have the CLI discover the skill.
983
- function firstRunHint() {
984
- try {
985
- const marker = path.join(HOME, '.hinted');
986
- if (fs.existsSync(marker)) return;
987
- fs.mkdirSync(HOME, { recursive: true });
988
- fs.writeFileSync(marker, new Date().toISOString());
989
- const installed = Object.values(KNOWN_SKILL_DIRS()).some((p) => fs.existsSync(path.join(p, 'SKILL.md')));
990
- if (!installed) {
991
- process.stderr.write(
992
- 'tip (AI agents): rly bundles a universal skill — install it with `rly skill install`; full guide: `rly agent`\n'
993
- );
994
- }
995
- } catch {
996
- // never let the hint break a real command
997
- }
998
- }
999
-
1000
- // Installed skill copies are snapshots — warn when they lag the CLI.
1001
- function skillFreshnessWarning() {
1002
- try {
1003
- for (const [agent, dir] of Object.entries(KNOWN_SKILL_DIRS())) {
1004
- if (!fs.existsSync(path.join(dir, 'SKILL.md'))) continue;
1005
- let installedVersion = null;
1006
- try {
1007
- installedVersion = fs.readFileSync(path.join(dir, '.rly-version'), 'utf8').trim();
1008
- } catch {
1009
- // pre-rename install without a version marker
1010
- }
1011
- if (installedVersion !== VERSION) {
1012
- process.stderr.write(
1013
- `note: the relay skill installed for ${agent} is from rly ${installedVersion ?? '<0.2.0'}, you run ${VERSION} — refresh with \`rly skill install\`\n`
1014
- );
1015
- }
1016
- }
1017
- } catch {
1018
- // best effort only
1019
- }
1020
- }
1021
-
1022
- function skillTargets(target) {
1023
- const known = KNOWN_SKILL_DIRS();
1024
- if (!target || target === true || target === 'auto') {
1025
- const found = Object.values(known).filter((p) => fs.existsSync(path.dirname(path.dirname(p))));
1026
- if (!found.length) {
1027
- throw new CliError('no agent dirs found (~/.claude, ~/.codex, or ~/.agents). Use --target claude|codex|agents|all|<dir>.');
1028
- }
1029
- return found;
1030
- }
1031
- if (target === 'both' || target === 'all') return Object.values(known);
1032
- if (known[target]) return [known[target]];
1033
- return [path.join(path.resolve(target), 'relay')];
1034
- }
1035
-
1036
- // Removes stale pre-rename quest-board skill dirs so the renamed skill is the
1037
- // only one an agent sees. Returns the dirs actually removed.
1038
- function removeLegacySkills() {
1039
- const removed = [];
1040
- for (const dir of LEGACY_SKILL_DIRS()) {
1041
- try {
1042
- if (fs.existsSync(dir)) {
1043
- fs.rmSync(dir, { recursive: true, force: true });
1044
- removed.push(dir);
1045
- }
1046
- } catch {
1047
- // best effort — a leftover dir we couldn't remove shouldn't fail install
1048
- }
1049
- }
1050
- return removed;
1051
- }
1052
-
1053
- // Stamps the current CLI version into every installed skill dir's .rly-version.
1054
- // `rly skill install` writes this itself, but an `npx skills add` refresh does
1055
- // not — so after any refresh we re-stamp the dirs that now have a SKILL.md,
1056
- // keeping skillFreshnessWarning() from nagging about a just-refreshed skill.
1057
- function stampSkillVersion() {
1058
- const stamped = [];
1059
- for (const dir of Object.values(KNOWN_SKILL_DIRS())) {
1060
- try {
1061
- if (fs.existsSync(path.join(dir, 'SKILL.md'))) {
1062
- fs.writeFileSync(path.join(dir, '.rly-version'), VERSION);
1063
- stamped.push(dir);
1064
- }
1065
- } catch {
1066
- // best effort — a marker we couldn't write just re-triggers the nudge
1067
- }
1068
- }
1069
- return stamped;
1070
- }
1071
-
1072
- // Short instruction block for an agent's main instruction file (CLAUDE.md,
1073
- // AGENTS.md, …). A skill is only a tier-1 hint that agents can ignore; these
1074
- // rules, appended to the instructions the agent always reads, enforce usage.
1075
- // Printed to stdout so `rly skill rules >> CLAUDE.md` is the whole install.
1076
- const SKILL_RULES = `## relay — visual boards and structured feedback
1077
-
1078
- - Use Relay for files, visuals, plans, diffs, and multiple related questions.
1079
- Keep brief answers and progress updates in chat; follow existing user authorization.
1080
- - Show without feedback: \`rly show --file spec.json --display-only\` (no waiter).
1081
- Collect input: \`rly ask --file spec.json --detach\`, then keep
1082
- \`rly wait <boardId> --timeout 1800 --while-active --idle-grace 300\` in the
1083
- foreground. If it times out, read \`rly result <boardId>\` before continuing.
1084
- - Use the most specific block: table/chart/kpi for data, image/compare for visuals,
1085
- code/diff for source, mermaid for flows, markdown for prose, html for custom UI.
1086
- \`rly view\`, \`rly diff\`, and \`rly git\` are shortcuts; visual options use \`options[].blocks\`.
1087
- - Browser file links such as \`[source](/absolute/app.js:98)\` open supported files
1088
- in a modal and highlight source lines. Unsupported files offer Open in app.
1089
- For inline MCP or shared reviewers, embed file content as blocks instead.
1090
- - Reconnect existing boards by ID with \`rly rescue\` / \`rly reopen\`; update
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.
1097
- - Read answers, notes, comment, annotations, and blockEdits together. Use the
1098
- returned resultFile when stdout is truncated; a timeout is not an answer.
1099
- - Full skill: \`rly skill path\`; fields: \`rly schema\`; advanced recipes and
1100
- sharing permissions: \`rly agent\`. Load details only when needed.`;
1101
-
1102
- function cmdSkill(rest) {
1103
- const sub = rest[0];
1104
- if (sub === 'rules') {
1105
- console.log(SKILL_RULES);
1106
- return 0;
1107
- }
1108
- if (sub === 'path') {
1109
- console.log(SKILL_SRC);
1110
- process.stderr.write('(bundled skill source — copy into your agent with `rly skill install`)\n');
1111
- return 0;
1112
- }
1113
- if (sub === 'install') {
1114
- const args = parseArgs(rest.slice(1));
1115
- const targets = skillTargets(args.target);
1116
- const installed = [];
1117
- for (const t of targets) {
1118
- fs.mkdirSync(path.dirname(t), { recursive: true });
1119
- // Clear whatever is already there first. cpSync refuses to overwrite a
1120
- // non-directory (a symlink or file at the target — e.g. a skill dir the
1121
- // user symlinked elsewhere) with a directory, so a plain re-install would
1122
- // crash. rmSync on a symlink removes the link itself, not its target.
1123
- fs.rmSync(t, { recursive: true, force: true });
1124
- fs.cpSync(SKILL_SRC, t, { recursive: true });
1125
- fs.writeFileSync(path.join(t, '.rly-version'), VERSION);
1126
- installed.push(t);
1127
- }
1128
- const removedLegacy = removeLegacySkills();
1129
- printJson({ installed, removedLegacy, note: 'most agents pick new skills up immediately; if yours does not, re-list skills or restart the session' });
1130
- return 0;
1131
- }
1132
- console.log(`relay ships a universal agent skill (Claude Code, Codex, and any SKILL.md-aware agent).
1133
-
1134
- bundled at: ${SKILL_SRC}
1135
- install it: rly skill install # auto-detects ~/.claude, ~/.codex, ~/.agents
1136
- rly skill install --target claude|codex|both|<dir>
1137
- from repo: npx skills add khanglvm/relay --skill relay --all
1138
- enforce it: rly skill rules # short always-read rules — paste into the file your
1139
- # agent reads (CLAUDE.md, AGENTS.md, .cursor/rules, …);
1140
- # a skill alone is an ignorable hint
1141
-
1142
- The skill teaches your agent the board spec format (questions + rich blocks +
1143
- annotations), the blocking vs --detach patterns, and visualization sizing.
1144
- Full guide: \`rly agent\`.`);
1145
- return 0;
1146
- }
1147
-
1148
- // ===========================================================================
1149
- // `rly install` — inject relay's always-read rules into ANY agent's
1150
- // instruction file, cross-platform. `rly skill install` (above) handles the
1151
- // full SKILL.md for skill-aware agents; this covers the long tail (Cursor,
1152
- // Copilot, Kiro, Windsurf, Cline, Gemini, generic AGENTS.md, …) that read a
1153
- // rules/instructions/steering/context markdown file instead.
1154
- // ===========================================================================
1155
-
1156
- const RELAY_BEGIN = '<!-- relay:begin (managed by `rly install` — your edits outside these markers are kept) -->';
1157
- const RELAY_END = '<!-- relay:end -->';
1158
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1159
-
1160
- // Resolve OS-specific base dirs from an injectable env/home/platform so the
1161
- // path logic is unit-testable for win32 / linux / darwin without running there.
1162
- function platformDirs({ platform, home, env }) {
1163
- const xdg = env.XDG_CONFIG_HOME || path.join(home, '.config');
1164
- const localApp = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
1165
- // Copilot-in-JetBrains global instructions dir.
1166
- const jetbrainsCopilot = platform === 'win32'
1167
- ? path.join(localApp, 'github-copilot', 'intellij')
1168
- : path.join(xdg, 'github-copilot', 'intellij');
1169
- return { xdg, jetbrainsCopilot, documents: path.join(home, 'Documents') };
1170
- }
1171
-
1172
- // The relay instruction registry. Each agent declares how to install relay's
1173
- // rules at `global` (user, machine-wide) and/or `project` (cwd) scope, in what
1174
- // `style`, and a `detect` dir whose existence means "you use this agent"
1175
- // (drives `--all`). Styles:
1176
- // 'shared' — upsert a marked block into a possibly-shared file (CLAUDE.md,
1177
- // AGENTS.md, copilot-instructions.md, …); your other content is
1178
- // preserved, only relay's block is rewritten.
1179
- // 'dedicated' — relay owns the whole file (.kiro/steering, .windsurf/rules,
1180
- // .clinerules, …); safe to overwrite.
1181
- // 'mdc' — dedicated, with Cursor `.mdc` YAML frontmatter.
1182
- export function agentRegistry({ platform = process.platform, home = os.homedir(), cwd = process.cwd(), env = process.env } = {}) {
1183
- const d = platformDirs({ platform, home, env });
1184
- const j = path.join;
1185
- return [
1186
- { id: 'claude', label: 'Claude Code',
1187
- detect: j(home, '.claude'),
1188
- global: { file: j(home, '.claude', 'CLAUDE.md'), style: 'shared' },
1189
- project: { file: j(cwd, 'CLAUDE.md'), style: 'shared' },
1190
- note: 'full skill: `rly skill install`' },
1191
- { id: 'codex', label: 'OpenAI Codex',
1192
- detect: j(home, '.codex'),
1193
- global: { file: j(home, '.codex', 'AGENTS.md'), style: 'shared' },
1194
- project: { file: j(cwd, 'AGENTS.md'), style: 'shared' } },
1195
- { id: 'agents', label: 'AGENTS.md standard (Amp, Jules, Cline, …)',
1196
- detect: j(home, '.agents'),
1197
- global: { file: j(home, '.agents', 'AGENTS.md'), style: 'shared' },
1198
- project: { file: j(cwd, 'AGENTS.md'), style: 'shared' } },
1199
- { id: 'cursor', label: 'Cursor',
1200
- detect: j(home, '.cursor'),
1201
- global: null, // user rules are set in Cursor Settings UI (not file-based)
1202
- project: { file: j(cwd, '.cursor', 'rules', 'relay.mdc'), style: 'mdc' },
1203
- note: 'global "User Rules" are set in Settings UI, not a file' },
1204
- { id: 'copilot', label: 'GitHub Copilot (VS Code / Visual Studio / JetBrains)',
1205
- detect: path.dirname(d.jetbrainsCopilot), // …/github-copilot
1206
- global: { file: j(d.jetbrainsCopilot, 'global-copilot-instructions.md'), style: 'shared' },
1207
- project: { file: j(cwd, '.github', 'copilot-instructions.md'), style: 'shared' },
1208
- note: 'global file applies in JetBrains IDEs; project file applies everywhere' },
1209
- { id: 'kiro', label: 'Kiro',
1210
- detect: j(home, '.kiro'),
1211
- global: { file: j(home, '.kiro', 'steering', 'relay.md'), style: 'dedicated' },
1212
- project: { file: j(cwd, '.kiro', 'steering', 'relay.md'), style: 'dedicated' } },
1213
- { id: 'windsurf', label: 'Windsurf',
1214
- detect: j(home, '.codeium'),
1215
- global: { file: j(home, '.codeium', 'windsurf', 'memories', 'global_rules.md'), style: 'shared' },
1216
- project: { file: j(cwd, '.windsurf', 'rules', 'relay.md'), style: 'dedicated' } },
1217
- { id: 'cline', label: 'Cline',
1218
- detect: j(d.documents, 'Cline'),
1219
- global: { file: j(d.documents, 'Cline', 'Rules', 'relay.md'), style: 'dedicated' },
1220
- project: { file: j(cwd, '.clinerules', 'relay.md'), style: 'dedicated' } },
1221
- { id: 'gemini', label: 'Gemini CLI',
1222
- detect: j(home, '.gemini'),
1223
- global: { file: j(home, '.gemini', 'GEMINI.md'), style: 'shared' },
1224
- project: { file: j(cwd, 'GEMINI.md'), style: 'shared' } },
1225
- { id: 'opencode', label: 'OpenCode',
1226
- detect: j(d.xdg, 'opencode'),
1227
- global: { file: j(d.xdg, 'opencode', 'AGENTS.md'), style: 'shared' },
1228
- project: { file: j(cwd, 'AGENTS.md'), style: 'shared' } },
1229
- { id: 'droid', label: 'Droid (Factory)',
1230
- detect: j(home, '.factory'),
1231
- global: { file: j(home, '.factory', 'AGENTS.md'), style: 'shared' },
1232
- project: { file: j(cwd, 'AGENTS.md'), style: 'shared' } },
1233
- ];
1234
- }
1235
-
1236
- // Render the relay rules in the style the target file expects.
1237
- function renderInstruction(style) {
1238
- if (style === 'mdc') {
1239
- return `---\ndescription: relay — collect decisions & show rich visuals in the browser, not the terminal\nalwaysApply: true\n---\n\n${SKILL_RULES}\n`;
1240
- }
1241
- return `${SKILL_RULES}\n`; // dedicated file — relay owns it
1242
- }
1243
-
1244
- // Upsert relay's marked block into a (possibly shared / pre-existing) file,
1245
- // leaving everything outside the markers untouched. Returns 'added'|'updated'.
1246
- function upsertBlock(file, body) {
1247
- let existing = '';
1248
- try { existing = fs.readFileSync(file, 'utf8'); } catch { /* new file */ }
1249
- const wrapped = `${RELAY_BEGIN}\n${body}\n${RELAY_END}`;
1250
- const re = new RegExp(escapeRegExp(RELAY_BEGIN) + '[\\s\\S]*?' + escapeRegExp(RELAY_END));
1251
- const had = re.test(existing);
1252
- const next = had
1253
- ? existing.replace(re, wrapped)
1254
- : (existing.trim() ? existing.replace(/\s*$/, '') + '\n\n' + wrapped + '\n' : wrapped + '\n');
1255
- fs.mkdirSync(path.dirname(file), { recursive: true });
1256
- fs.writeFileSync(file, next);
1257
- return had ? 'updated' : 'added';
1258
- }
1259
-
1260
- function writeInstruction(target) {
1261
- if (target.style === 'shared') return upsertBlock(target.file, SKILL_RULES);
1262
- const existed = fs.existsSync(target.file);
1263
- fs.mkdirSync(path.dirname(target.file), { recursive: true });
1264
- fs.writeFileSync(target.file, renderInstruction(target.style));
1265
- return existed ? 'updated' : 'added';
1266
- }
1267
-
1268
- function cmdInstall(args) {
1269
- const reg = agentRegistry();
1270
- const byId = Object.fromEntries(reg.map((a) => [a.id, a]));
1271
- const scope = args.scope === 'project' ? 'project' : args.scope === 'global' ? 'global' : null;
1272
-
1273
- // Pick the target for an agent: explicit --scope wins; else prefer global
1274
- // (machine-wide), falling back to project when the agent has no global file.
1275
- const pick = (a) => {
1276
- if (scope === 'project') return a.project ? { scope: 'project', t: a.project } : null;
1277
- if (scope === 'global') return a.global ? { scope: 'global', t: a.global } : null;
1278
- if (a.global) return { scope: 'global', t: a.global };
1279
- if (a.project) return { scope: 'project', t: a.project };
1280
- return null;
1281
- };
1282
-
1283
- const wantAll = args.all === true || String(args.target || '').toLowerCase() === 'all';
1284
-
1285
- // No target → show the matrix for THIS platform.
1286
- if (!wantAll && (args.list === true || !args.target)) {
1287
- printJson({
1288
- platform: process.platform,
1289
- agents: reg.map((a) => ({
1290
- agent: a.id, label: a.label,
1291
- global: a.global ? a.global.file : null,
1292
- project: a.project ? a.project.file : null,
1293
- note: a.note,
1294
- })),
1295
- usage: 'rly install --target <agent>[,<agent>] [--scope global|project] [--print] | rly install --all',
1296
- });
1297
- return 0;
1298
- }
1299
-
1300
- // Resolve the set of {agent, scope, target} to act on.
1301
- let chosen;
1302
- if (wantAll) {
1303
- chosen = reg
1304
- .filter((a) => { try { return fs.existsSync(a.detect); } catch { return false; } })
1305
- .map((a) => ({ a, ...(pick(a) || {}) }))
1306
- .filter((x) => x.t);
1307
- if (!chosen.length) {
1308
- throw new CliError('no known agents detected on this machine (no ~/.claude, ~/.codex, ~/.cursor, ~/.kiro, …). Use --target <agent>.', 4);
1309
- }
1310
- } else {
1311
- const ids = String(args.target).split(',').map((s) => s.trim()).filter(Boolean);
1312
- chosen = [];
1313
- for (const id of ids) {
1314
- const a = byId[id];
1315
- if (!a) throw new CliError(`unknown agent "${id}". Run \`rly install --list\` to see supported agents.`, 4);
1316
- const p = pick(a);
1317
- if (!p) throw new CliError(`${a.label} has no ${scope || 'installable'} instruction file${a.note ? ` — ${a.note}` : ''}. Try \`--scope project\`.`, 4);
1318
- chosen.push({ a, ...p });
1319
- }
1320
- }
1321
-
1322
- // --print: emit content + resolved path for manual copy/paste; no writes.
1323
- if (args.print === true) {
1324
- for (const { a, t } of chosen) {
1325
- const content = t.style === 'shared' ? `${RELAY_BEGIN}\n${SKILL_RULES}\n${RELAY_END}` : renderInstruction(t.style);
1326
- process.stdout.write(`# ${a.label}\n# → ${t.file}\n\n${content}\n\n`);
1327
- }
1328
- return 0;
1329
- }
1330
-
1331
- const installed = chosen.map(({ a, scope: sc, t }) => ({
1332
- agent: a.id, scope: sc, file: t.file, action: writeInstruction(t),
1333
- }));
1334
- printJson({ installed, note: 'reload/re-open your agent (or re-list its rules) if it does not pick this up immediately' });
1335
- return 0;
1336
- }
1337
-
1338
- function cmdA2ui() {
1339
- console.log(fs.readFileSync(path.join(PKG_ROOT, 'docs', 'A2UI.md'), 'utf8'));
1340
- return 0;
1341
- }
1342
-
1343
- function cmdAgent() {
1344
- console.log(fs.readFileSync(path.join(PKG_ROOT, 'docs', 'AGENT.md'), 'utf8'));
1345
- return 0;
1346
- }
1347
-
1348
- // `rly upgrade` — install the latest CLI globally AND refresh the skill (via the
1349
- // npx-skills package manager, falling back to the bundled copy) in one shot.
1350
- // (`update` is taken by the live-mutate command, so this is
1351
- // `upgrade` / `self-update`.) Running boards are surfaced and handled: a global
1352
- // reinstall overwrites relay's files, but live detached servers snapshot their
1353
- // UI at first request and serve from memory, so they keep working on their own
1354
- // version. Flags: --stop (stop running boards first), --force (upgrade while
1355
- // they keep running), --cli-only / --skill-only (scope).
1356
- async function cmdUpgrade(args) {
1357
- const force = args.force === true;
1358
- const doStop = args.stop === true;
1359
- const wantCli = args.skillOnly !== true;
1360
- const wantSkill = args.cliOnly !== true;
1361
-
1362
- const running = listRunning();
1363
-
1364
- // --dry-run: report the plan (incl. how running boards would be handled)
1365
- // without installing anything or stopping anything.
1366
- if (args.dryRun === true) {
1367
- printJson({
1368
- dryRun: true,
1369
- wouldRun: [wantCli && `npm install -g ${PKG_NAME}@latest`, wantSkill && 'npx skills add khanglvm/relay --skill relay --all'].filter(Boolean),
1370
- runningBoards: running.map((r) => r.id),
1371
- runningHandling: running.length
1372
- ? doStop
1373
- ? 'stop them first'
1374
- : force
1375
- ? 'leave them running (snapshotted)'
1376
- : 'BLOCKED — pass --stop or --force'
1377
- : 'none running',
1378
- });
1379
- return 0;
1380
- }
1381
-
1382
- if (running.length) {
1383
- const ids = running.map((r) => r.id).join(', ');
1384
- if (doStop) {
1385
- process.stderr.write(`Stopping ${running.length} running board(s) before upgrading: ${ids}\n`);
1386
- for (const r of running) {
1387
- try { process.kill(r.pid, 'SIGTERM'); } catch { /* already gone */ }
1388
- }
1389
- for (const r of running) await pollFor(() => (loadRunning(r.id) ? null : true), 5000);
1390
- } else if (!force) {
1391
- // Default: don't silently overwrite under live boards — explain + let the
1392
- // user choose. The boards themselves are safe; this is about clarity.
1393
- process.stderr.write(
1394
- `${running.length} board(s) still running: ${ids}\n` +
1395
- 'They keep serving their current version safely (each snapshots its UI in memory),\n' +
1396
- 'and stay readable via `rly result <id>` / `rly wait <id>`. Pick one:\n' +
1397
- ' • rly stop --all then re-run `rly upgrade` (cleanest)\n' +
1398
- ' • rly upgrade --stop stop them as part of this upgrade\n' +
1399
- ' • rly upgrade --force upgrade now; leave them running on their snapshot\n'
1400
- );
1401
- printJson({ upgraded: false, reason: 'running-boards', running: running.map((r) => r.id) });
1402
- return 0;
1403
- } else {
1404
- process.stderr.write(`--force: leaving ${running.length} board(s) running on their snapshotted version: ${ids}\n`);
1405
- }
1406
- }
1407
-
1408
- const did = {};
1409
-
1410
- if (wantCli) {
1411
- process.stderr.write(`\nUpgrading ${PKG_NAME} → latest (npm install -g ${PKG_NAME}@latest)\n`);
1412
- // shell:true so Windows resolves `npm` → `npm.cmd` (same reason the skill /
1413
- // version spawns below use it); the package name has no shell metacharacters.
1414
- const r = spawnSync('npm', ['install', '-g', `${PKG_NAME}@latest`], { stdio: 'inherit', shell: true });
1415
- if (r.error || r.status !== 0) {
1416
- throw new CliError(
1417
- `npm install failed${r.error ? ` (${r.error.message})` : ` (exit ${r.status})`}. ` +
1418
- `Update manually: npm install -g ${PKG_NAME}@latest`,
1419
- 1
1420
- );
1421
- }
1422
- did.cli = `${PKG_NAME}@latest`;
1423
- }
1424
-
1425
- if (wantSkill) {
1426
- // Refresh the skill through the npx-skills package manager — the same channel
1427
- // the skill is normally managed by (skills-lock.json, ~/.agents, ~/.claude, …)
1428
- // — so the global install stays in sync and pulls the freshest skill for
1429
- // khanglvm/relay. `npx -y` so the one-off download needs no prompt.
1430
- process.stderr.write('\nRefreshing the relay skill (npx skills add khanglvm/relay --skill relay --all)\n');
1431
- let r = spawnSync('npx', ['-y', 'skills', 'add', 'khanglvm/relay', '--skill', 'relay', '--all'], { stdio: 'inherit', shell: true });
1432
- let how = 'npx-skills';
1433
- if (r.error || r.status !== 0) {
1434
- // Fallback: install the skill bundled with the CLI we just upgraded. Works
1435
- // offline / when the skills CLI is unreachable, and matches this version.
1436
- process.stderr.write('\nnpx skills unavailable — falling back to the bundled skill (rly skill install)\n');
1437
- r = spawnSync('rly', ['skill', 'install'], { stdio: 'inherit', shell: true });
1438
- how = 'bundled';
1439
- }
1440
- if (r.error || r.status !== 0) {
1441
- process.stderr.write(
1442
- `Skill refresh did not complete${r.error ? ` (${r.error.message})` : ` (exit ${r.status})`} — ` +
1443
- 'run `npx skills add khanglvm/relay --skill relay --all` (or `rly skill install`) yourself.\n'
1444
- );
1445
- } else {
1446
- // Keep the freshness marker accurate however the skill landed, so the next
1447
- // `rly` run doesn't nag that the just-refreshed skill is stale.
1448
- stampSkillVersion();
1449
- did.skill = how;
1450
- }
1451
- }
1452
-
1453
- // Report the now-current global version (best-effort).
1454
- let nowVersion = null;
1455
- try {
1456
- const v = spawnSync('rly', ['--version'], { encoding: 'utf8', shell: true });
1457
- if (v.status === 0 && v.stdout) nowVersion = String(v.stdout).trim();
1458
- } catch {
1459
- // best effort
1460
- }
1461
-
1462
- printJson({
1463
- upgraded: true,
1464
- ...did,
1465
- version: nowVersion,
1466
- note: 'most agents pick the new skill up immediately; if not, re-list skills or restart the session',
1467
- });
1468
- return 0;
1469
- }
1470
-
1471
- // `rly mcp` — run relay as an MCP App server, or print/write the host config.
1472
- // rly mcp serve over stdio (what a local desktop host launches)
1473
- // rly mcp --http [--port N] serve over Streamable HTTP (web/mobile/remote hosts)
1474
- // rly mcp config [--print] show setup for Claude / Codex / generic hosts
1475
- // rly mcp install --target claude|codex write it into that host's config
1476
- async function cmdMcp(rest) {
1477
- const sub = rest[0];
1478
- if (sub === 'config' || sub === 'setup' || sub === 'install' || sub === 'add') {
1479
- return cmdMcpConfig(parseArgs(rest.slice(1)), sub);
1480
- }
1481
- const args = parseArgs(rest);
1482
- if (args.http) {
1483
- // Port precedence: --port flag, then PaaS-injected $PORT / $RLY_MCP_PORT,
1484
- // then the default. PaaS hosts (Render, Railway, Fly, mcpdeploy, …) set $PORT.
1485
- const envPort = process.env.PORT || process.env.RLY_MCP_PORT;
1486
- return runMcpHttp({
1487
- port: args.port ? Number(args.port) : (envPort ? Number(envPort) : undefined),
1488
- host: typeof args.host === 'string' ? args.host : (process.env.RLY_MCP_HOST || '127.0.0.1'),
1489
- token: typeof args.token === 'string' ? args.token : (process.env.RLY_MCP_TOKEN || ''),
1490
- allowOrigin: typeof args.allowOrigin === 'string' ? args.allowOrigin : (process.env.RLY_MCP_ALLOW_ORIGIN || ''),
1491
- });
1492
- }
1493
- // Default: be the stdio server. main() never resolves this, so the CLI's
1494
- // post-run exit timer never arms — the server lives until stdin closes.
1495
- return runMcp();
1496
- }
1497
-
1498
- // Resolve Claude Desktop's config path for this platform.
1499
- function claudeDesktopConfigPath() {
1500
- const home = os.homedir();
1501
- if (process.platform === 'darwin') return path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
1502
- if (process.platform === 'win32') return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json');
1503
- return path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), 'Claude', 'claude_desktop_config.json');
1504
- }
1505
-
1506
- function cmdMcpConfig(args, sub) {
1507
- const cfg = mcpConfig({ command: 'rly' });
1508
- const target = String(args.target || '').toLowerCase();
1509
- const wantInstall = (sub === 'install' || sub === 'add') && args.print !== true;
1510
-
1511
- // --print, or `config`/`setup` with no writable target: show every option.
1512
- if (!wantInstall || !target) {
1513
- const claudePath = claudeDesktopConfigPath();
1514
- const codexPath = path.join(os.homedir(), '.codex', 'config.toml');
1515
- printJson({
1516
- note: 'Register relay as an MCP App server, then call relay_ask / relay_show from inside the host.',
1517
- claudeCode: 'claude mcp add relay -- rly mcp',
1518
- claudeDesktop: { file: claudePath, add: cfg.json },
1519
- codex: { file: codexPath, add: cfg.toml },
1520
- generic: { add: cfg.json },
1521
- webMobile: cfg.http,
1522
- install: 'rly mcp install --target claude | rly mcp install --target codex',
1523
- });
1524
- return 0;
1525
- }
1526
-
1527
- if (target === 'claude' || target === 'claude-desktop') {
1528
- const file = claudeDesktopConfigPath();
1529
- /** @type {Record<string, any>} */
1530
- let existing = {};
1531
- try { existing = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { existing = {}; }
1532
- if (existing === null || typeof existing !== 'object' || Array.isArray(existing)) existing = {};
1533
- existing.mcpServers = existing.mcpServers && typeof existing.mcpServers === 'object' ? existing.mcpServers : {};
1534
- existing.mcpServers.relay = { command: cfg.command, args: cfg.args };
1535
- fs.mkdirSync(path.dirname(file), { recursive: true });
1536
- fs.writeFileSync(file, JSON.stringify(existing, null, 2) + '\n');
1537
- printJson({ installed: 'claude-desktop', file, server: 'relay', note: 'restart Claude Desktop to load it' });
1538
- return 0;
1539
- }
1540
- if (target === 'codex') {
1541
- const file = path.join(os.homedir(), '.codex', 'config.toml');
1542
- let body = '';
1543
- try { body = fs.readFileSync(file, 'utf8'); } catch { body = ''; }
1544
- if (/\[mcp_servers\.relay\]/.test(body)) {
1545
- printJson({ installed: 'codex', file, server: 'relay', note: 'already present — left as-is' });
1546
- return 0;
1547
- }
1548
- fs.mkdirSync(path.dirname(file), { recursive: true });
1549
- const sep = body && !body.endsWith('\n') ? '\n\n' : body ? '\n' : '';
1550
- fs.writeFileSync(file, body + sep + cfg.toml);
1551
- printJson({ installed: 'codex', file, server: 'relay', note: 'restart Codex to load it' });
1552
- return 0;
1553
- }
1554
- throw new CliError(`unknown --target "${target}". Use claude or codex (or \`rly mcp config\` to print all).`, 4);
1555
- }
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
-
1576
- async function cmdServeInternal(args) {
1577
- const id = args.id;
1578
- if (!id) throw new CliError('__serve: missing --id');
1579
- const { done } = await runBoard({
1580
- id,
1581
- port: args.port !== undefined ? Number.parseInt(args.port, 10) || 0 : 0,
1582
- open: args.open !== false,
1583
- timeoutSec: args.timeout !== undefined ? Math.max(0, Number.parseInt(args.timeout, 10) || 0) : DEFAULT_BOARD_TIMEOUT_SEC,
1584
- quiet: true,
1585
- // Detached board: timeout hands back to the agent but keeps the same
1586
- // URL/port serving until Submit or explicit stop.
1587
- keepAliveOnTimeout: true,
1588
- link: args.link !== undefined ? parseLinkValue(args.link, '--link') : { mode: 'off' },
1589
- });
1590
- await done;
1591
- return 0;
1592
- }
1593
-
1594
- function printHelp() {
1595
- console.log(`rly ${VERSION} — relay: browser question boards, rich blocks & annotations for AI agents
1596
-
1597
- USAGE
1598
- rly ask --file spec.json create board, open browser, BLOCK until submit, print answers JSON
1599
- rly ask --file - < spec.json spec from stdin
1600
- rly ask -q "Deploy?::yesno" -q "!Env::single::dev,staging,prod"
1601
- quick inline questions ("!" = required, label::type::options)
1602
- rly ask ... --detach no blocking: prints {boardId,url} now; collect via \`rly wait <id>\`
1603
- rly ask ... --on-result "<cmd>" push-wake: run <cmd> when the board finishes (result JSON on stdin)
1604
- rly show --html-file viz.html visualization board (submit button = acknowledge)
1605
- rly show --file spec.json --display-only
1606
- present without comments/acknowledgement; returns immediately
1607
- rly view <file.md> [more.md …] quick read-only board rendering markdown file(s) (no lib)
1608
- (.csv/.tsv/.json render as a filterable, sortable table;
1609
- .pdf streams in an inline PDF viewer)
1610
- rly diff [git args…] run git diff and show it in a diff board (--split, --detach,
1611
- --title; other args pass to git: rly diff --staged | HEAD~1 | -- path)
1612
- rly git pick [range] board for choosing pick/cherry-pick/drop actions plus commit order
1613
- rly git cherry-pick [range] board for choosing commits and cherry-pick order
1614
- add --code for split code view with per-hunk Apply/Skip/Hold
1615
- rly git conflict [files…] board for resolving conflict-marker files; with no files, auto-detects
1616
- unmerged git files and returns resolved content in result.blockEdits
1617
- rly wait <id> [--timeout 86400] block up to one day until the board finishes (0 = no deadline)
1618
- --while-active [--idle-grace 180]: keep waiting past the deadline
1619
- while the user is still viewing/focused & recently active
1620
- --notify-cmd "<cmd>": run <cmd> on a terminal result (JSON on stdin)
1621
- NB: also writes the FULL result to "resultFile" (first field) —
1622
- read that file if your shell truncates stdout; never pipe to head/tail
1623
- rly result <id> result/status now (includes live autosaved draft + presence while open)
1624
- rly share <id> list active same-Wi-Fi share links for a running board
1625
- rly share <id> --role review reviewer: answer/comment/submit a reference-only side review
1626
- rly share <id> --role collab collaborator: edit/comment/final-submit as owner-authorized
1627
- rly share <id> --role read activate a read-only viewer link
1628
- rly share <id> --role review --revoke
1629
- revoke one share role; use --revoke --all to disable all roles
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)
1636
- rly list [--json] running boards
1637
- rly open [id] re-open the browser tab of a running board
1638
- rly reopen <id> [--replies f.json] serve a saved board again, prefilled with saved answers
1639
- (--replies [{annotationId,text}] = agent answers to element comments)
1640
- rly rescue <id> [--open] re-serve a board on its ORIGINAL port so a still-open but
1641
- disconnected browser tab auto-reconnects & re-saves (no new tab
1642
- unless --open). Use when a tab shows "connection lost".
1643
- rly reuse <id> [--dump] re-run a past board as a new board (--dump prints its spec)
1644
- rly update <id> --file spec.json live-mutate a RUNNING board (or --title/--intro/-q); page reloads
1645
- rly stop <id> | --all stop running board(s) (status: cancelled, draft preserved)
1646
- rly history [--limit n] [--json] saved boards
1647
- rly spec <id> print a saved board's spec JSON (edit, then ask --file again)
1648
- rly rm <id> | --all delete saved board(s)
1649
- rly schema JSON Schema of the board spec
1650
- rly agent FULL GUIDE for AI agents (spec format, blocks, sizing, patterns)
1651
- rly a2ui A2UI widget blocks: Express grammar, components, examples
1652
- rly skill [install|rules|path] bundled universal agent skill (Claude Code, Codex, …)
1653
- \`rly skill rules >> CLAUDE.md\` adds always-read usage rules
1654
- rly install --target <agent> inject relay's rules into an agent's instruction file
1655
- claude codex cursor copilot kiro windsurf cline gemini opencode droid agents
1656
- --scope global|project · --print (copy/paste) · --all · --list (no flags)
1657
- rly upgrade install the latest CLI globally + refresh the skill in one step
1658
- --stop/--force handle running boards · --dry-run · --cli-only/--skill-only
1659
- rly mcp run relay as an MCP App server (stdio) — boards render INLINE in
1660
- a local desktop host (Claude Desktop, Codex) instead of a browser tab
1661
- rly mcp --http [--port N] serve over Streamable HTTP for web/mobile/remote hosts
1662
- [--host H --token SECRET --allow-origin ORIGIN]
1663
- rly mcp config | install --target print host setup, or write it (claude | codex)
1664
-
1665
- COMMON FLAGS
1666
- --title <s> --intro <s> --html-file <f> --height <px> --submit-label <s>
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)
1669
-
1670
- EXIT CODES 0 submitted/acknowledged · 2 timeout · 3 cancelled · 4 usage · 5 not found
1671
-
1672
- NOTES detached boards keep serving after timeout until Submit or stop;
1673
- answers & annotations autosave in real time (drafts survive timeout/cancel);
1674
- submitting auto-closes the tab and unblocks the CLI.
1675
-
1676
- AI AGENTS run \`rly agent\` for the complete machine-oriented guide.
1677
- a universal skill is bundled — install with \`rly skill install\`
1678
- (or from the repo: npx skills add khanglvm/relay --skill relay --all)`);
1679
- return 0;
1680
- }
1681
-
1682
- export async function main(argv) {
1683
- const [cmd, ...rest] = argv;
1684
- if (cmd !== '__serve') firstRunHint();
1685
- if (cmd === undefined || cmd === 'help' || cmd === '--help' || cmd === '-h' || cmd === 'agent' || cmd === 'skill') {
1686
- skillFreshnessWarning();
1687
- }
1688
- try {
1689
- switch (cmd) {
1690
- case undefined:
1691
- case 'help':
1692
- case '--help':
1693
- case '-h':
1694
- return printHelp();
1695
- case 'version':
1696
- case '--version':
1697
- case '-v':
1698
- console.log(VERSION);
1699
- return 0;
1700
- case 'ask':
1701
- return await cmdAsk(parseArgs(rest), 'ask');
1702
- case 'show':
1703
- return await cmdAsk(parseArgs(rest), 'show');
1704
- case 'view':
1705
- return await cmdView(parseArgs(rest));
1706
- case 'diff':
1707
- return await cmdDiff(rest);
1708
- case 'git':
1709
- return await cmdGit(rest);
1710
- case 'reopen':
1711
- return await cmdReopen(parseArgs(rest));
1712
- case 'rescue':
1713
- return await cmdRescue(parseArgs(rest));
1714
- case 'reuse':
1715
- return await cmdReuse(parseArgs(rest));
1716
- case 'update':
1717
- return await cmdUpdate(parseArgs(rest));
1718
- case 'wait':
1719
- return await cmdWait(parseArgs(rest));
1720
- case 'result':
1721
- return await cmdResult(parseArgs(rest));
1722
- case 'share':
1723
- return await cmdShare(parseArgs(rest));
1724
- case 'config':
1725
- return cmdConfig(parseArgs(rest));
1726
- case 'list':
1727
- return cmdList(parseArgs(rest));
1728
- case 'open':
1729
- return cmdOpen(parseArgs(rest));
1730
- case 'stop':
1731
- return await cmdStop(parseArgs(rest));
1732
- case 'history':
1733
- return cmdHistory(parseArgs(rest));
1734
- case 'spec':
1735
- return cmdSpec(parseArgs(rest));
1736
- case 'rm':
1737
- return cmdRm(parseArgs(rest));
1738
- case 'skill':
1739
- return cmdSkill(rest);
1740
- case 'install':
1741
- return cmdInstall(parseArgs(rest));
1742
- case 'upgrade':
1743
- case 'self-update':
1744
- return await cmdUpgrade(parseArgs(rest));
1745
- case 'agent':
1746
- return cmdAgent();
1747
- case 'a2ui':
1748
- return cmdA2ui();
1749
- case 'schema':
1750
- console.log(JSON.stringify(SPEC_SCHEMA, null, 2));
1751
- return 0;
1752
- case 'mcp':
1753
- return await cmdMcp(rest);
1754
- case '__serve':
1755
- return await cmdServeInternal(parseArgs(rest));
1756
- default:
1757
- throw new CliError(`unknown command "${cmd}". Run \`rly help\`.`);
1758
- }
1759
- } catch (err) {
1760
- if (err instanceof CliError) {
1761
- process.stderr.write(`rly: ${err.message}\n`);
1762
- if (err.code === 4) process.stderr.write('run `rly agent` for the agent-oriented guide\n');
1763
- return err.code;
1764
- }
1765
- throw err;
1766
- }
1767
- }