@khanglvm/relay 0.18.0 → 0.20.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.
Files changed (138) hide show
  1. package/bin/rly.js +1 -1
  2. package/package.json +39 -4
  3. package/schema/spec.v1.json +1368 -0
  4. package/src/a2ui/compile.js +2 -0
  5. package/src/cli/args.js +46 -0
  6. package/src/cli/ask.js +12 -0
  7. package/src/cli/boards.js +326 -0
  8. package/src/cli/config.js +56 -0
  9. package/src/cli/context.js +13 -0
  10. package/src/cli/git.js +183 -0
  11. package/src/cli/help.js +90 -0
  12. package/src/cli/index.js +103 -0
  13. package/src/cli/install.js +197 -0
  14. package/src/cli/io.js +186 -0
  15. package/src/cli/mcp.js +94 -0
  16. package/src/cli/share.js +45 -0
  17. package/src/cli/skill.js +192 -0
  18. package/src/cli/upgrade.js +130 -0
  19. package/src/cli/wait.js +172 -0
  20. package/src/file-preview.js +1 -1
  21. package/src/index.js +104 -0
  22. package/src/link.js +1 -0
  23. package/src/mcp-ui/board/block-ctx.js +43 -0
  24. package/src/mcp-ui/board/bridge.js +165 -0
  25. package/src/mcp-ui/board/controls.js +310 -0
  26. package/src/mcp-ui/board/core.js +20 -0
  27. package/src/mcp-ui/board/lifecycle.js +118 -0
  28. package/src/mcp-ui/board/normalize.js +95 -0
  29. package/src/mcp-ui/board/render.js +200 -0
  30. package/src/mcp-ui/board/state.js +106 -0
  31. package/src/mcp-ui/board/vendors.js +86 -0
  32. package/src/mcp.js +15 -21
  33. package/src/{server.js → server/board.js} +17 -781
  34. package/src/server/files.js +141 -0
  35. package/src/server/http.js +114 -0
  36. package/src/server/index.js +2 -0
  37. package/src/server/page.js +183 -0
  38. package/src/server/paths.js +7 -0
  39. package/src/server/result.js +58 -0
  40. package/src/server/reviews.js +41 -0
  41. package/src/server/sanitize.js +231 -0
  42. package/src/spec/blocks/a2ui.js +25 -0
  43. package/src/spec/blocks/chart.js +49 -0
  44. package/src/spec/blocks/code.js +38 -0
  45. package/src/spec/blocks/diagram.js +39 -0
  46. package/src/spec/blocks/git-conflict.js +106 -0
  47. package/src/spec/blocks/image.js +32 -0
  48. package/src/spec/blocks/index.js +33 -0
  49. package/src/spec/blocks/markdown.js +13 -0
  50. package/src/spec/blocks/pdf.js +38 -0
  51. package/src/spec/blocks/table.js +122 -0
  52. package/src/spec/blocks/video.js +68 -0
  53. package/src/spec/blocks/widgets.js +98 -0
  54. package/src/spec/constants.js +65 -0
  55. package/src/spec/index.js +5 -0
  56. package/src/spec/normalize.js +285 -0
  57. package/src/spec/ready.js +106 -0
  58. package/src/spec/schema.js +182 -0
  59. package/src/spec/sources.js +83 -0
  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/a2ui/compile.d.ts +40 -0
  110. package/types/index.d.ts +181 -0
  111. package/types/mcp.d.ts +31 -0
  112. package/types/spec/blocks/a2ui.d.ts +4 -0
  113. package/types/spec/blocks/chart.d.ts +4 -0
  114. package/types/spec/blocks/code.d.ts +10 -0
  115. package/types/spec/blocks/diagram.d.ts +15 -0
  116. package/types/spec/blocks/git-conflict.d.ts +7 -0
  117. package/types/spec/blocks/image.d.ts +5 -0
  118. package/types/spec/blocks/index.d.ts +30 -0
  119. package/types/spec/blocks/markdown.d.ts +5 -0
  120. package/types/spec/blocks/pdf.d.ts +4 -0
  121. package/types/spec/blocks/table.d.ts +9 -0
  122. package/types/spec/blocks/video.d.ts +4 -0
  123. package/types/spec/blocks/widgets.d.ts +21 -0
  124. package/types/spec/constants.d.ts +67 -0
  125. package/types/spec/index.d.ts +4 -0
  126. package/types/spec/normalize.d.ts +17 -0
  127. package/types/spec/ready.d.ts +1 -0
  128. package/types/spec/schema.d.ts +1171 -0
  129. package/types/spec/sources.d.ts +14 -0
  130. package/types/store.d.ts +29 -0
  131. package/types/ui/manifest.d.ts +62 -0
  132. package/types/util.d.ts +6 -0
  133. package/src/cli.js +0 -1766
  134. package/src/mcp-ui/board.js +0 -1162
  135. package/src/spec.js +0 -1222
  136. package/src/ui/annotate.js +0 -1055
  137. package/src/ui/app.js +0 -1643
  138. package/src/ui/blocks.js +0 -3260
@@ -210,6 +210,8 @@ function assertTree(byId, where) {
210
210
  /**
211
211
  * Validates a flat surface against Relay's catalog and returns it as plain data.
212
212
  * Throws a CliError worded for the agent that wrote it.
213
+ * @param {{ components: any, dataModel?: any }} surface
214
+ * @param {string} [where]
213
215
  */
214
216
  export function validateSurface({ components, dataModel }, where = 'a2ui') {
215
217
  const catalog = loadCatalog().components;
@@ -0,0 +1,46 @@
1
+ // Command-line argument parsing.
2
+ import { CliError } from '../util.js';
3
+
4
+ const VALUED_FLAGS = new Set([
5
+ 'file', 'html', 'html-file', 'title', 'intro', 'timeout', 'port',
6
+ 'submit-label', 'height', 'limit', 'target', 'id', 'replies',
7
+ 'on-result', 'notify-cmd', 'idle-grace', 'scope', 'range',
8
+ 'host', 'token', 'allow-origin', 'role', 'public-url', 'link',
9
+ ]);
10
+
11
+ function camel(key) {
12
+ return key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
13
+ }
14
+
15
+ export function parseArgs(argv) {
16
+ const args = { _: [], q: [] };
17
+ for (let i = 0; i < argv.length; i++) {
18
+ const t = argv[i];
19
+ if (t === '-q' || t === '--question') {
20
+ const v = argv[++i];
21
+ if (v === undefined) throw new CliError(`${t} needs a value.`);
22
+ args.q.push(v);
23
+ } else if (t === '-') {
24
+ args.stdin = true;
25
+ } else if (t.startsWith('--')) {
26
+ let key = t.slice(2);
27
+ let val = true;
28
+ const eq = key.indexOf('=');
29
+ if (eq >= 0) {
30
+ val = key.slice(eq + 1);
31
+ key = key.slice(0, eq);
32
+ } else if (VALUED_FLAGS.has(key)) {
33
+ val = argv[++i];
34
+ if (val === undefined) throw new CliError(`--${key} needs a value.`);
35
+ }
36
+ if (key === 'no-open') {
37
+ args.open = false;
38
+ } else {
39
+ args[camel(key)] = val;
40
+ }
41
+ } else {
42
+ args._.push(t);
43
+ }
44
+ }
45
+ return args;
46
+ }
package/src/cli/ask.js ADDED
@@ -0,0 +1,12 @@
1
+ // rly ask: build a board from a spec and serve it.
2
+ import { assertSpecReady, normalizeSpec } from '../spec/index.js';
3
+ import { createBoard } from '../store.js';
4
+ import { resolveSpecInput, runOrDetach } from './io.js';
5
+
6
+ export async function cmdAsk(args, mode) {
7
+ const raw = await resolveSpecInput(args, mode);
8
+ const spec = normalizeSpec(raw);
9
+ await assertSpecReady(spec);
10
+ const record = createBoard(spec);
11
+ return runOrDetach(record, spec.responseRequired === false ? { ...args, detach: true } : args);
12
+ }
@@ -0,0 +1,326 @@
1
+ // Commands that act on an existing board: view, reopen, rescue, reuse, update, list, open, stop, history, spec and rm.
2
+ import path from 'node:path';
3
+ import { openUrl } from '../open.js';
4
+ import { assertSpecReady, normalizeSpec, questionFromInline } from '../spec/index.js';
5
+ import { HOME, controlUrl, createBoard, deleteBoard, isAlive, listBoards, listRunning, loadBoard, loadRunning, removeRunning, saveBoard } from '../store.js';
6
+ import { CliError, pollFor } from '../util.js';
7
+ import { mustLoad, parseJson, printJson, readFileOrThrow, readStdin, runOrDetach } from './io.js';
8
+
9
+ // `rly view <file.md> [more.md …]` — quick read-only board that renders files
10
+ // with purpose-built blocks (markdown, data tables, PDF). With 2+ files a small
11
+ // filename heading separates them. Sugar over `rly show`.
12
+ export async function cmdView(args) {
13
+ const files = args._;
14
+ if (!files.length) throw new CliError('usage: rly view <file.md|.csv|.json|.pdf> [more …] [--title T] [--detach]');
15
+ const multi = files.length > 1;
16
+ const DATA_EXT = new Set(['csv', 'tsv', 'json']);
17
+ const blocks = [];
18
+ for (const f of files) {
19
+ if (multi) blocks.push({ type: 'markdown', md: `## ${path.basename(f)}` });
20
+ const ext = path.extname(f).slice(1).toLowerCase();
21
+ if (DATA_EXT.has(ext)) blocks.push({ type: 'table', rowsFile: f, sortable: true, filterable: true, exportable: true });
22
+ else if (ext === 'pdf') blocks.push({ type: 'pdf', src: f, title: path.basename(f) });
23
+ else blocks.push({ type: 'markdown', mdFile: f });
24
+ }
25
+ const raw = { blocks };
26
+ raw.title = args.title || (multi ? `${files.length} files` : path.basename(files[0]));
27
+ raw.submitLabel = args.submitLabel || 'Done';
28
+ const spec = normalizeSpec(raw); // reads + validates each file, clear error if unreadable
29
+ await assertSpecReady(spec);
30
+ const record = createBoard(spec);
31
+ return runOrDetach(record, args);
32
+ }
33
+
34
+ // Seeds the draft from the last result (as runBoard would on reopen) and
35
+ // appends agent replies to the matching annotations, so an agent can ANSWER
36
+ // the user's element comments and re-open the board as a conversation.
37
+ // Persists the record with the result archived so runBoard doesn't re-seed.
38
+ function seedAgentReplies(record, replies) {
39
+ if (!Array.isArray(replies)) throw new CliError('--replies file must be a JSON array of {annotationId, text}.', 4);
40
+ // Mirror runBoard's reopen draft-seeding from the prior result.
41
+ if (record.result) {
42
+ if (record.result.answers) {
43
+ record.draft = {
44
+ answers: record.result.answers,
45
+ comment: record.result.comment || '',
46
+ notes: record.result.notes || {},
47
+ annotations: record.result.annotations || [],
48
+ updatedAt: new Date().toISOString(),
49
+ };
50
+ }
51
+ record.pastResults = [...(record.pastResults || []), record.result].slice(-10);
52
+ record.result = null;
53
+ }
54
+ const annotations = (record.draft && Array.isArray(record.draft.annotations)) ? record.draft.annotations : [];
55
+ const validIds = annotations.map((a) => a && a.id).filter(Boolean);
56
+ const now = new Date().toISOString();
57
+ replies.forEach((r, i) => {
58
+ if (r === null || typeof r !== 'object' || Array.isArray(r)) {
59
+ throw new CliError(`--replies[${i}]: must be an object {annotationId, text}.`, 4);
60
+ }
61
+ const annotationId = typeof r.annotationId === 'string' ? r.annotationId : '';
62
+ const text = typeof r.text === 'string' ? r.text : '';
63
+ if (!annotationId) throw new CliError(`--replies[${i}]: missing "annotationId".`, 4);
64
+ if (!text.trim()) throw new CliError(`--replies[${i}]: missing "text".`, 4);
65
+ const ann = annotations.find((a) => a && a.id === annotationId);
66
+ if (!ann) {
67
+ throw new CliError(
68
+ `--replies[${i}]: unknown annotationId "${annotationId}". Valid ids: ${validIds.length ? validIds.join(', ') : '(none)'}.`,
69
+ 4
70
+ );
71
+ }
72
+ if (!Array.isArray(ann.replies)) ann.replies = [];
73
+ ann.replies.push({ author: 'agent', text, createdAt: now });
74
+ });
75
+ if (!record.draft) record.draft = { answers: {}, comment: '', notes: {}, annotations, updatedAt: now };
76
+ else record.draft.annotations = annotations;
77
+ saveBoard(record);
78
+ }
79
+
80
+ export async function cmdReopen(args) {
81
+ const record = mustLoad(args._[0]);
82
+ if (args.replies !== undefined) {
83
+ const replies = parseJson(readFileOrThrow(args.replies), args.replies);
84
+ seedAgentReplies(record, replies);
85
+ }
86
+ const running = loadRunning(record.id);
87
+ if (running && isAlive(running.pid)) {
88
+ if (!running.link) openUrl(running.url);
89
+ printJson({ status: 'open', boardId: record.id, url: running.url, note: running.link ? 'already running' : 'already running — browser re-opened' });
90
+ return 0;
91
+ }
92
+ // Reuse the board's last port (unless the user forced one) so a tab still open
93
+ // from a previous run reconnects on its own instead of being stranded on a
94
+ // dead port. runBoard falls back to a random port if it's been taken.
95
+ return runOrDetach(record, { ...args, port: args.port ?? record.lastPort });
96
+ }
97
+
98
+ // Rescue a board whose browser tab is still open but disconnected (its server
99
+ // died / the machine slept). Re-serves the SAME board on the SAME port it last
100
+ // used, so the open tab's relative /api/* fetches reconnect on their own — the
101
+ // page's recovery loop lifts its "connection lost" block and re-flushes the
102
+ // draft (incl. anything the user mirrored to localStorage during the outage)
103
+ // with zero action from the user. Defaults to NOT opening a new browser tab
104
+ // (the point is the existing one); pass --open to also open a fresh tab.
105
+ export async function cmdRescue(args) {
106
+ const record = mustLoad(args._[0]);
107
+ const running = loadRunning(record.id);
108
+ if (running && isAlive(running.pid)) {
109
+ if (args.open && !running.link) openUrl(running.url);
110
+ printJson({
111
+ status: 'open',
112
+ boardId: record.id,
113
+ url: running.url,
114
+ port: running.port,
115
+ note: 'already running — the open tab should be connected; reload it if not',
116
+ });
117
+ return 0;
118
+ }
119
+ if (!record.lastPort) {
120
+ throw new CliError(
121
+ `board "${record.id}" has no known port to reuse (never served in this version). Use \`rly reopen ${record.id}\` instead.`,
122
+ 5
123
+ );
124
+ }
125
+ // Force the original port so the disconnected tab can reconnect; default to
126
+ // not opening a second tab. seedAgentReplies parity with reopen if provided.
127
+ if (args.replies !== undefined) {
128
+ const replies = parseJson(readFileOrThrow(args.replies), args.replies);
129
+ seedAgentReplies(record, replies);
130
+ }
131
+ return runOrDetach(record, { ...args, port: record.lastPort, open: args.open === true });
132
+ }
133
+
134
+ export async function cmdReuse(args) {
135
+ const src = mustLoad(args._[0]);
136
+ if (args.dump) {
137
+ console.log(JSON.stringify(src.spec, null, 2));
138
+ return 0;
139
+ }
140
+ const record = createBoard(src.spec);
141
+ return runOrDetach(record, args);
142
+ }
143
+
144
+ // Live-mutates a running board: rebuild the spec (full replace via --file, or
145
+ // patch the current spec via --title/--intro/-q), then POST it (already
146
+ // normalized) to the board's /api/update with the per-board mutation token.
147
+ export async function cmdUpdate(args) {
148
+ const id = args._[0];
149
+ if (!id) throw new CliError('usage: rly update <board-id> (--file new-spec.json | --title T | --intro I | -q "...")');
150
+ const record = loadBoard(id);
151
+ if (!record) throw new CliError(`board "${id}" not found. See \`rly history\`.`, 5);
152
+ const running = loadRunning(id);
153
+ if (!running || !isAlive(running.pid)) {
154
+ throw new CliError(`board "${id}" is not running — \`rly reopen ${id}\` to serve it, then update.`, 5);
155
+ }
156
+
157
+ let spec;
158
+ if (args.file) {
159
+ const raw =
160
+ args.file === '-'
161
+ ? parseJson(await readStdin(), 'stdin')
162
+ : parseJson(readFileOrThrow(args.file), args.file);
163
+ spec = normalizeSpec(raw);
164
+ } else if (args.title || args.intro || args.q.length) {
165
+ // Patch the CURRENT spec, then re-normalize so it's a clean normalized spec.
166
+ const raw = { ...record.spec };
167
+ if (args.title) raw.title = args.title;
168
+ if (args.intro) raw.intro = args.intro;
169
+ if (args.q.length) {
170
+ raw.questions = [...(raw.questions || []), ...args.q.map((s, i) => questionFromInline(s, i))];
171
+ }
172
+ spec = normalizeSpec(raw);
173
+ } else {
174
+ throw new CliError('update needs --file <spec.json>, --title, --intro, or -q "...".', 4);
175
+ }
176
+ await assertSpecReady(spec);
177
+
178
+ let res;
179
+ try {
180
+ res = await fetch(new URL('/api/update', controlUrl(running)), {
181
+ method: 'POST',
182
+ headers: { 'content-type': 'application/json', 'x-relay-token': running.token || '' },
183
+ body: JSON.stringify({ spec }),
184
+ });
185
+ } catch (err) {
186
+ throw new CliError(`could not reach board "${id}" at ${running.url}: ${String((err && err.message) || err)}`, 5);
187
+ }
188
+ if (res.status === 403) throw new CliError(`board "${id}" rejected the update token (stale running file?).`, 5);
189
+ if (!res.ok) {
190
+ let detail = '';
191
+ try {
192
+ detail = (await res.json()).error || '';
193
+ } catch {
194
+ // non-JSON body
195
+ }
196
+ throw new CliError(`board "${id}" rejected the update${detail ? `: ${detail}` : ''}.`, 4);
197
+ }
198
+ const body = await res.json();
199
+ printJson({ status: 'updated', boardId: id, rev: body.rev, url: running.url });
200
+ return 0;
201
+ }
202
+
203
+ export function cmdList(args) {
204
+ const running = listRunning();
205
+ if (args.json) {
206
+ printJson(running);
207
+ return 0;
208
+ }
209
+ if (!running.length) {
210
+ console.log('No boards running.');
211
+ return 0;
212
+ }
213
+ for (const r of running) {
214
+ console.log(`${r.id} ${r.url} pid ${r.pid} "${r.title}" since ${r.startedAt}`);
215
+ }
216
+ return 0;
217
+ }
218
+
219
+ export function cmdOpen(args) {
220
+ let id = args._[0];
221
+ const running = listRunning();
222
+ if (!id) {
223
+ if (running.length === 1) id = running[0].id;
224
+ else if (running.length === 0) throw new CliError('no boards running. Use `rly reopen <id>` to serve a saved one.', 5);
225
+ else throw new CliError(`multiple boards running — pick one: ${running.map((r) => r.id).join(', ')}`);
226
+ }
227
+ const info = running.find((r) => r.id === id);
228
+ if (!info) throw new CliError(`board "${id}" is not running. Use \`rly reopen ${id}\` to serve it again (with saved answers).`, 5);
229
+ if (!info.link) openUrl(info.url);
230
+ printJson({ status: 'open', boardId: id, url: info.url });
231
+ return 0;
232
+ }
233
+
234
+ export async function cmdStop(args) {
235
+ let targets;
236
+ if (args.all) {
237
+ targets = listRunning();
238
+ if (!targets.length) {
239
+ printJson({ stopped: [] });
240
+ return 0;
241
+ }
242
+ } else {
243
+ const id = args._[0];
244
+ if (!id) throw new CliError('usage: rly stop <board-id> | rly stop --all');
245
+ const info = loadRunning(id);
246
+ if (!info || !isAlive(info.pid)) {
247
+ removeRunning(id);
248
+ throw new CliError(`board "${id}" is not running.`, 5);
249
+ }
250
+ targets = [info];
251
+ }
252
+ for (const t of targets) {
253
+ try {
254
+ process.kill(t.pid, 'SIGTERM');
255
+ } catch {
256
+ // already gone
257
+ }
258
+ }
259
+ for (const t of targets) {
260
+ await pollFor(() => (loadRunning(t.id) ? null : true), 5000);
261
+ }
262
+ printJson({
263
+ stopped: targets.map((t) => {
264
+ const record = loadBoard(t.id);
265
+ return { boardId: t.id, status: record?.result?.status ?? 'unknown', draft: record?.draft ?? null };
266
+ }),
267
+ });
268
+ return 0;
269
+ }
270
+
271
+ export function cmdHistory(args) {
272
+ const limit = args.limit !== undefined ? Number.parseInt(args.limit, 10) || 15 : 15;
273
+ const records = listBoards(limit);
274
+ const runningIds = new Set(listRunning().map((r) => r.id));
275
+ if (args.json) {
276
+ printJson(
277
+ records.map((r) => ({
278
+ id: r.id,
279
+ createdAt: r.createdAt,
280
+ title: r.title,
281
+ status: runningIds.has(r.id) ? 'open' : r.result?.status ?? 'unfinished',
282
+ questions: r.spec.questions.length,
283
+ blocks: (r.spec.blocks || []).length,
284
+ hasDraft: Boolean(r.draft),
285
+ answers: r.result?.answers ?? null,
286
+ }))
287
+ );
288
+ return 0;
289
+ }
290
+ if (!records.length) {
291
+ console.log(`No saved boards yet (storage: ${HOME}).`);
292
+ return 0;
293
+ }
294
+ for (const r of records) {
295
+ const status = runningIds.has(r.id) ? 'open' : r.result?.status ?? 'unfinished';
296
+ const nBlocks = (r.spec.blocks || []).length;
297
+ console.log(`${r.id} ${r.createdAt} [${status}] "${r.title}" ${r.spec.questions.length}q${nBlocks ? `+${nBlocks}b` : ''}`);
298
+ }
299
+ console.log(`\nReuse: \`rly reuse <id>\` · spec: \`rly spec <id>\` · reopen w/ answers: \`rly reopen <id>\` · delete: \`rly rm <id>\``);
300
+ return 0;
301
+ }
302
+
303
+ export function cmdSpec(args) {
304
+ const record = mustLoad(args._[0]);
305
+ console.log(JSON.stringify(record.spec, null, 2));
306
+ return 0;
307
+ }
308
+
309
+ export function cmdRm(args) {
310
+ const runningIds = new Set(listRunning().map((r) => r.id));
311
+ if (args.all) {
312
+ let removed = 0;
313
+ for (const r of listBoards(0)) {
314
+ if (runningIds.has(r.id)) continue;
315
+ if (deleteBoard(r.id)) removed++;
316
+ }
317
+ printJson({ removed, skippedRunning: runningIds.size });
318
+ return 0;
319
+ }
320
+ const id = args._[0];
321
+ if (!id) throw new CliError('usage: rly rm <board-id> | rly rm --all');
322
+ if (runningIds.has(id)) throw new CliError(`board "${id}" is running — \`rly stop ${id}\` first.`);
323
+ if (!deleteBoard(id)) throw new CliError(`board "${id}" not found.`, 5);
324
+ printJson({ removed: id });
325
+ return 0;
326
+ }
@@ -0,0 +1,56 @@
1
+ // Small commands: config, a2ui, agent and the internal detached server.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { loadConfig, parseLinkValue, saveConfig, serializeLink } from '../link.js';
5
+ import { runBoard } from '../server/index.js';
6
+ import { HOME } from '../store.js';
7
+ import { CliError } from '../util.js';
8
+ import { DEFAULT_BOARD_TIMEOUT_SEC, PKG_ROOT } from './context.js';
9
+ import { printJson } from './io.js';
10
+
11
+ export function cmdA2ui() {
12
+ console.log(fs.readFileSync(path.join(PKG_ROOT, 'docs', 'A2UI.md'), 'utf8'));
13
+ return 0;
14
+ }
15
+
16
+ export function cmdAgent() {
17
+ console.log(fs.readFileSync(path.join(PKG_ROOT, 'docs', 'AGENT.md'), 'utf8'));
18
+ return 0;
19
+ }
20
+
21
+ // `rly config [link [off|auto|devlink|<url>]]` — the saved link default, so
22
+ // every board prints a cross-device URL without a flag.
23
+ export function cmdConfig(args) {
24
+ const [key, value] = args._;
25
+ if (key === undefined) {
26
+ printJson(loadConfig(HOME));
27
+ return 0;
28
+ }
29
+ if (key !== 'link') throw new CliError(`unknown config key "${key}". Use: link.`, 4);
30
+ if (value === undefined) {
31
+ printJson({ link: loadConfig(HOME).link ?? 'off' });
32
+ return 0;
33
+ }
34
+ const setting = parseLinkValue(value, 'link');
35
+ const next = saveConfig(HOME, { link: setting.mode === 'off' ? null : serializeLink(setting) });
36
+ printJson({ status: 'saved', link: next.link ?? 'off' });
37
+ return 0;
38
+ }
39
+
40
+ export async function cmdServeInternal(args) {
41
+ const id = args.id;
42
+ if (!id) throw new CliError('__serve: missing --id');
43
+ const { done } = await runBoard({
44
+ id,
45
+ port: args.port !== undefined ? Number.parseInt(args.port, 10) || 0 : 0,
46
+ open: args.open !== false,
47
+ timeoutSec: args.timeout !== undefined ? Math.max(0, Number.parseInt(args.timeout, 10) || 0) : DEFAULT_BOARD_TIMEOUT_SEC,
48
+ quiet: true,
49
+ // Detached board: timeout hands back to the agent but keeps the same
50
+ // URL/port serving until Submit or explicit stop.
51
+ keepAliveOnTimeout: true,
52
+ link: args.link !== undefined ? parseLinkValue(args.link, '--link') : { mode: 'off' },
53
+ });
54
+ await done;
55
+ return 0;
56
+ }
@@ -0,0 +1,13 @@
1
+ // Package facts the commands share: version, bin path and default timeouts.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
+ export const PKG_ROOT = path.join(__dirname, '..', '..');
8
+ export const BIN = path.join(PKG_ROOT, 'bin', 'rly.js');
9
+ const PKG_JSON = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8'));
10
+ export const VERSION = PKG_JSON.version;
11
+ export const PKG_NAME = PKG_JSON.name; // e.g. "@khanglvm/relay" — the global package to upgrade
12
+ export const DEFAULT_BOARD_TIMEOUT_SEC = 86400;
13
+ export const DEFAULT_WAIT_TIMEOUT_SEC = 86400;
package/src/cli/git.js ADDED
@@ -0,0 +1,183 @@
1
+ // rly diff and rly git: boards built from git changes, commits and conflicts.
2
+ import { spawnSync } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { assertSpecReady, normalizeSpec } from '../spec/index.js';
6
+ import { createBoard } from '../store.js';
7
+ import { CliError } from '../util.js';
8
+ import { parseArgs } from './args.js';
9
+ import { printJson, runOrDetach } from './io.js';
10
+
11
+ // `rly diff [git args…]` — run `git diff` for the user and open the result as a
12
+ // diff-block board in one step (sugar like `rly view`). Everything that isn't a
13
+ // recognized rly flag is forwarded to git verbatim, so `rly diff --staged`,
14
+ // `rly diff HEAD~1`, `rly diff main -- src/` all work. rly flags: --detach,
15
+ // --no-open, --split (side-by-side), --title.
16
+ export async function cmdDiff(rest) {
17
+ const RLY_FLAGS = new Set(['--detach', '--no-open', '--split', '--devlink', '--no-devlink']);
18
+ const gitArgs = [];
19
+ const rlyArgv = [];
20
+ for (let i = 0; i < rest.length; i++) {
21
+ const t = rest[i];
22
+ if (t === '--title' || t === '--public-url') { rlyArgv.push(t, rest[++i]); continue; }
23
+ if (t.startsWith('--title=') || t.startsWith('--public-url=')) { rlyArgv.push(t); continue; }
24
+ if (RLY_FLAGS.has(t)) { rlyArgv.push(t); continue; }
25
+ gitArgs.push(t);
26
+ }
27
+ const args = parseArgs(rlyArgv);
28
+ const res = spawnSync('git', ['--no-pager', 'diff', ...gitArgs], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
29
+ if (res.error) throw new CliError(`could not run git: ${res.error.message}. Is git installed and is this a repo?`);
30
+ if (res.status !== 0 && res.stderr) throw new CliError(`git diff failed: ${res.stderr.trim()}`, res.status || 1);
31
+ const diff = res.stdout || '';
32
+ if (!diff.trim()) {
33
+ printJson({ status: 'no-diff', hint: `git diff${gitArgs.length ? ' ' + gitArgs.join(' ') : ''} produced no output — nothing to show` });
34
+ return 0;
35
+ }
36
+ const title = args.title || ('git diff' + (gitArgs.length ? ' ' + gitArgs.join(' ') : ''));
37
+ const spec = normalizeSpec({ title, blocks: [{ type: 'diff', diff, view: args.split ? 'split' : 'unified' }] });
38
+ await assertSpecReady(spec);
39
+ const record = createBoard(spec);
40
+ return runOrDetach(record, args);
41
+ }
42
+
43
+ function runGit(args, message) {
44
+ const res = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
45
+ if (res.error) throw new CliError(`could not run git: ${res.error.message}. Is git installed and is this a repo?`);
46
+ if (res.status !== 0) {
47
+ const detail = (res.stderr || res.stdout || '').trim();
48
+ throw new CliError(`${message}: ${detail || `git ${args.join(' ')} exited ${res.status}`}`, res.status || 1);
49
+ }
50
+ return res.stdout || '';
51
+ }
52
+
53
+ function gitConflictPaths(explicitPaths) {
54
+ if (explicitPaths.length) return explicitPaths;
55
+ const out = runGit(['diff', '--name-only', '--diff-filter=U'], 'git conflict detection failed');
56
+ return out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
57
+ }
58
+
59
+ function gitCommitRows(range, limit) {
60
+ const n = Math.max(1, Math.min(200, Number.parseInt(limit, 10) || 20));
61
+ const args = ['log', `-n${n}`, '--date=short', '--pretty=format:%H%x09%h%x09%ad%x09%an%x09%s'];
62
+ if (range) args.push(range);
63
+ return runGit(args, 'git log failed')
64
+ .split(/\r?\n/)
65
+ .filter(Boolean)
66
+ .map((line) => {
67
+ const [sha, short, date, author, ...subjectParts] = line.split('\t');
68
+ const subject = subjectParts.join('\t');
69
+ return { sha, short, date, author, subject };
70
+ })
71
+ .filter((r) => r.sha && r.short);
72
+ }
73
+
74
+ function gitCommitDiff(commit) {
75
+ return runGit([
76
+ '--no-pager',
77
+ 'show',
78
+ '--format=',
79
+ '--patch',
80
+ '--find-renames',
81
+ '--find-copies',
82
+ '--no-ext-diff',
83
+ commit,
84
+ ], `git show ${commit} failed`).trimEnd();
85
+ }
86
+
87
+ export async function cmdGit(rest) {
88
+ const args = parseArgs(rest);
89
+ const modes = new Set(['pick', 'cherry-pick', 'cherrypick', 'conflict', 'conflicts', 'resolve']);
90
+ let mode = 'pick';
91
+ if (args._[0] && modes.has(args._[0])) mode = args._.shift();
92
+ if (mode === 'cherrypick') mode = 'cherry-pick';
93
+ if (mode === 'conflicts' || mode === 'resolve') mode = 'conflict';
94
+
95
+ const blocks = [];
96
+ const questions = [];
97
+ let reviewDiffCount = 0;
98
+
99
+ if (mode === 'pick' || mode === 'cherry-pick') {
100
+ const range = args.range || args._[0] || '';
101
+ const commits = gitCommitRows(range, args.limit);
102
+ if (!commits.length) throw new CliError(`git log${range ? ` ${range}` : ''} produced no commits to show.`);
103
+ const withCode = args.code === true || args.patch === true || args.diff === true;
104
+ blocks.push({
105
+ type: 'table',
106
+ columns: ['short', 'date', 'author', 'subject'],
107
+ rows: commits.map((c) => ({ short: c.short, date: c.date, author: c.author, subject: c.subject })),
108
+ sortable: true,
109
+ filterable: true,
110
+ exportable: true,
111
+ });
112
+ const options = commits.map((c) => ({
113
+ value: c.sha,
114
+ label: `${c.short} ${c.subject}`,
115
+ description: `${c.date} · ${c.author}`,
116
+ }));
117
+ questions.push({
118
+ id: 'commit_actions',
119
+ type: 'checklist',
120
+ label: mode === 'cherry-pick' ? 'Choose cherry-pick actions' : 'Choose commit actions',
121
+ description: 'Set only the commits you want the agent to act on.',
122
+ options,
123
+ statuses: mode === 'cherry-pick'
124
+ ? [{ value: 'cherry-pick', label: 'Cherry-pick', tone: 'ok' }, { value: 'skip', label: 'Skip', tone: 'muted' }, { value: 'hold', label: 'Hold', tone: 'warn' }]
125
+ : [{ value: 'pick', label: 'Pick', tone: 'ok' }, { value: 'cherry-pick', label: 'Cherry-pick', tone: 'warn' }, { value: 'drop', label: 'Drop', tone: 'bad' }],
126
+ });
127
+ if (options.length > 1) {
128
+ questions.push({
129
+ id: 'commit_order',
130
+ type: 'rank',
131
+ label: mode === 'cherry-pick' ? 'Cherry-pick order' : 'Preferred commit order',
132
+ description: 'Drag or move commits into the order the agent should apply them.',
133
+ options,
134
+ });
135
+ }
136
+ if (withCode) {
137
+ for (const c of commits) {
138
+ const diff = gitCommitDiff(c.sha);
139
+ if (!diff.trim()) continue;
140
+ blocks.push({
141
+ type: 'diff',
142
+ title: `${c.short} ${c.subject}`,
143
+ filename: `${c.short} ${c.subject}`,
144
+ commit: c.sha,
145
+ reviewKind: mode,
146
+ review: true,
147
+ view: 'split',
148
+ diff,
149
+ });
150
+ reviewDiffCount++;
151
+ }
152
+ }
153
+ }
154
+
155
+ const paths = mode === 'conflict' ? gitConflictPaths(args._) : gitConflictPaths([]);
156
+ for (const p of paths) {
157
+ let text = '';
158
+ try { text = fs.readFileSync(path.resolve(p), 'utf8'); } catch { /* normalizeSpec will report unreadable explicit files below */ }
159
+ if (!text || /<<<<<<<[\s\S]*=======[\s\S]*>>>>>>>/.test(text)) {
160
+ blocks.push({ type: 'git-conflict', path: p, filename: p });
161
+ }
162
+ }
163
+
164
+ if (mode === 'conflict' && !blocks.some((b) => b.type === 'git-conflict')) {
165
+ throw new CliError(args._.length
166
+ ? 'no conflict markers found in the provided file(s).'
167
+ : 'no unmerged git files with conflict markers were detected.');
168
+ }
169
+
170
+ const conflictCount = blocks.filter((b) => b.type === 'git-conflict').length;
171
+ const title = args.title || (mode === 'conflict'
172
+ ? `Resolve ${conflictCount} git conflict${conflictCount === 1 ? '' : 's'}`
173
+ : mode === 'cherry-pick' ? 'Cherry-pick commits' : 'Pick commits');
174
+ const intro = args.intro || (conflictCount
175
+ ? '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.'
176
+ : reviewDiffCount
177
+ ? 'Review commit code hunks on the board. Apply, skip, or hold each hunk; submit returns commit actions plus diff-review hunk choices as JSON.'
178
+ : 'Pick commit actions and order on the board. Submit returns the selected actions and rank order as JSON.');
179
+ const spec = normalizeSpec({ title, intro, blocks, questions, submitLabel: 'Submit git choices' });
180
+ await assertSpecReady(spec);
181
+ const record = createBoard(spec);
182
+ return runOrDetach(record, args);
183
+ }