@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/io.js ADDED
@@ -0,0 +1,186 @@
1
+ // What every command needs: output, spec input, loading a board and detaching a server.
2
+ import { spawn } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { linkSetting, loadConfig, serializeLink } from '../link.js';
6
+ import { runBoard } from '../server/index.js';
7
+ import { assertSpecReady, questionFromInline } from '../spec/index.js';
8
+ import { HOME, loadBoard, loadRunning, saveBoard, saveResultFile } from '../store.js';
9
+ import { CliError, pollFor } from '../util.js';
10
+ import { BIN, DEFAULT_BOARD_TIMEOUT_SEC } from './context.js';
11
+
12
+ export function printJson(obj) {
13
+ process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
14
+ }
15
+
16
+ // Print a terminal result. A board with many annotations produces a large JSON
17
+ // payload, and an agent's shell harness commonly truncates long stdout — so the
18
+ // agent silently misses annotations past the cut. We write the FULL result to a
19
+ // sidecar file and surface its path FIRST (`resultFile`), so even a truncated
20
+ // stdout shows where the complete payload is; the agent reads that file with its
21
+ // file tool. Falls back to a plain print if the sidecar can't be written.
22
+ export function printResult(result) {
23
+ const resultFile = result && result.boardId ? saveResultFile(result.boardId, result) : null;
24
+ printJson(resultFile ? { resultFile, ...result } : result);
25
+ }
26
+
27
+ // Push-wake for `rly wait --notify-cmd`: run the agent's local shell command
28
+ // once a TERMINAL result lands. Result JSON goes to the command's stdin;
29
+ // RLY_BOARD_ID / RLY_STATUS / RLY_URL are exported. Same shape as the server's
30
+ // --on-result hook. Failures are swallowed; a 30s kill timer caps a hung cmd.
31
+ export function runNotifyCmd(cmd, result) {
32
+ if (typeof cmd !== 'string' || !cmd.trim()) return;
33
+ try {
34
+ const child = spawn('/bin/sh', ['-c', cmd], {
35
+ env: {
36
+ ...process.env,
37
+ RLY_BOARD_ID: result.boardId || '',
38
+ RLY_STATUS: result.status || '',
39
+ RLY_URL: result.url || '',
40
+ },
41
+ stdio: ['pipe', 'ignore', 'ignore'],
42
+ });
43
+ child.on('error', () => {});
44
+ try {
45
+ child.stdin.write(JSON.stringify(result));
46
+ child.stdin.end();
47
+ } catch {
48
+ // best effort
49
+ }
50
+ const killTimer = setTimeout(() => {
51
+ try {
52
+ child.kill('SIGKILL');
53
+ } catch {
54
+ // already gone
55
+ }
56
+ }, 30000);
57
+ killTimer.unref();
58
+ child.on('close', () => clearTimeout(killTimer));
59
+ child.unref();
60
+ } catch {
61
+ // swallow — push-wake is best effort
62
+ }
63
+ }
64
+
65
+ export function exitCodeFor(status) {
66
+ return { submitted: 0, acknowledged: 0, open: 0, timeout: 2, cancelled: 3 }[status] ?? 1;
67
+ }
68
+
69
+ export function parseJson(text, where) {
70
+ try {
71
+ return JSON.parse(text);
72
+ } catch (err) {
73
+ throw new CliError(`invalid JSON in ${where}: ${err.message}`);
74
+ }
75
+ }
76
+
77
+ export function readStdin() {
78
+ return new Promise((resolve, reject) => {
79
+ let data = '';
80
+ process.stdin.setEncoding('utf8');
81
+ process.stdin.on('data', (c) => (data += c));
82
+ process.stdin.on('end', () => resolve(data));
83
+ process.stdin.on('error', reject);
84
+ });
85
+ }
86
+
87
+ export function mustLoad(id) {
88
+ if (!id) throw new CliError('missing <board-id>. See `rly history` for saved boards.');
89
+ const record = loadBoard(id);
90
+ if (!record) throw new CliError(`board "${id}" not found. See \`rly history\`.`, 5);
91
+ return record;
92
+ }
93
+
94
+ export async function resolveSpecInput(args, mode) {
95
+ let raw = {};
96
+ if (args.file) {
97
+ raw =
98
+ args.file === '-'
99
+ ? parseJson(await readStdin(), 'stdin')
100
+ : parseJson(readFileOrThrow(args.file), args.file);
101
+ } else if (args.stdin) {
102
+ raw = parseJson(await readStdin(), 'stdin');
103
+ }
104
+ if (args.title) raw.title = args.title;
105
+ if (args.intro) raw.intro = args.intro;
106
+ if (typeof args.html === 'string') raw.html = args.html;
107
+ if (args.htmlFile) raw.htmlFile = args.htmlFile;
108
+ if (args.height) raw.htmlHeight = args.height;
109
+ if (args.submitLabel) raw.submitLabel = args.submitLabel;
110
+ if (args.displayOnly === true) raw.responseRequired = false;
111
+ if (args.q.length) {
112
+ raw.questions = [...(raw.questions || []), ...args.q.map((s, i) => questionFromInline(s, i))];
113
+ }
114
+ // If the user supplied a spec (file/stdin) let normalizeSpec report what's
115
+ // wrong with it precisely; the generic usage hint is only for a bare call.
116
+ const suppliedSpec = Boolean(args.file || args.stdin);
117
+ const hasContent = (raw.questions && raw.questions.length) || raw.html || raw.htmlFile;
118
+ if (!suppliedSpec && !hasContent) {
119
+ throw new CliError(
120
+ mode === 'show'
121
+ ? 'show needs --html-file <file>, --html "<markup>", or --file <spec.json>. Run `rly agent` for examples.'
122
+ : 'ask needs a spec: --file <spec.json>, --file - (stdin), or -q "label::type::opt1,opt2". Run `rly agent` for examples.'
123
+ );
124
+ }
125
+ return raw;
126
+ }
127
+
128
+ export function readFileOrThrow(p) {
129
+ try {
130
+ return fs.readFileSync(path.resolve(p), 'utf8');
131
+ } catch {
132
+ throw new CliError(`cannot read file "${p}".`);
133
+ }
134
+ }
135
+
136
+ export async function runOrDetach(record, args) {
137
+ await assertSpecReady(record.spec);
138
+ const timeoutSec = args.timeout !== undefined ? Math.max(0, Number.parseInt(args.timeout, 10) || 0) : DEFAULT_BOARD_TIMEOUT_SEC;
139
+ const port = args.port !== undefined ? Number.parseInt(args.port, 10) || 0 : 0;
140
+ const open = args.open !== false;
141
+ const link = linkSetting({ args, config: loadConfig(HOME) });
142
+
143
+ // Push-wake: persist the agent's --on-result command on the record so BOTH
144
+ // the inline runBoard path and the detached __serve path pick it up (the
145
+ // detached server reads record.onResult from disk). Runtime concern only —
146
+ // not part of the spec.
147
+ if (typeof args.onResult === 'string' && args.onResult.trim()) {
148
+ record.onResult = args.onResult;
149
+ saveBoard(record);
150
+ }
151
+
152
+ if (args.detach) {
153
+ const child = spawn(
154
+ process.execPath,
155
+ [
156
+ BIN, '__serve',
157
+ '--id', record.id,
158
+ '--port', String(port),
159
+ '--timeout', String(timeoutSec),
160
+ ...(open ? [] : ['--no-open']),
161
+ '--link', serializeLink(link),
162
+ ],
163
+ { detached: true, stdio: 'ignore' }
164
+ );
165
+ child.unref();
166
+ // A link setting adds a link-provider round trip before the board is announced.
167
+ const startSec = link.mode === 'off' ? 8 : 40;
168
+ const info = await pollFor(() => loadRunning(record.id), startSec * 1000);
169
+ if (!info) throw new CliError(`board ${record.id} failed to start (no server after ${startSec}s).`, 1);
170
+ printJson({
171
+ status: 'open',
172
+ boardId: record.id,
173
+ url: info.url,
174
+ port: info.port,
175
+ hint: record.spec.responseRequired === false
176
+ ? 'display-only board opened; no response will be collected'
177
+ : `block for the answers with: rly wait ${record.id}`,
178
+ });
179
+ return 0;
180
+ }
181
+
182
+ const { done } = await runBoard({ id: record.id, port, open, timeoutSec, link });
183
+ const result = await done;
184
+ printResult(result);
185
+ return exitCodeFor(result.status);
186
+ }
package/src/cli/mcp.js ADDED
@@ -0,0 +1,94 @@
1
+ // rly mcp: run the MCP server, or print and write its client config.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { mcpConfig, runMcp, runMcpHttp } from '../mcp.js';
6
+ import { CliError } from '../util.js';
7
+ import { parseArgs } from './args.js';
8
+ import { printJson } from './io.js';
9
+
10
+ // `rly mcp` — run relay as an MCP App server, or print/write the host config.
11
+ // rly mcp serve over stdio (what a local desktop host launches)
12
+ // rly mcp --http [--port N] serve over Streamable HTTP (web/mobile/remote hosts)
13
+ // rly mcp config [--print] show setup for Claude / Codex / generic hosts
14
+ // rly mcp install --target claude|codex write it into that host's config
15
+ export async function cmdMcp(rest) {
16
+ const sub = rest[0];
17
+ if (sub === 'config' || sub === 'setup' || sub === 'install' || sub === 'add') {
18
+ return cmdMcpConfig(parseArgs(rest.slice(1)), sub);
19
+ }
20
+ const args = parseArgs(rest);
21
+ if (args.http) {
22
+ // Port precedence: --port flag, then PaaS-injected $PORT / $RLY_MCP_PORT,
23
+ // then the default. PaaS hosts (Render, Railway, Fly, mcpdeploy, …) set $PORT.
24
+ const envPort = process.env.PORT || process.env.RLY_MCP_PORT;
25
+ return runMcpHttp({
26
+ port: args.port ? Number(args.port) : (envPort ? Number(envPort) : undefined),
27
+ host: typeof args.host === 'string' ? args.host : (process.env.RLY_MCP_HOST || '127.0.0.1'),
28
+ token: typeof args.token === 'string' ? args.token : (process.env.RLY_MCP_TOKEN || ''),
29
+ allowOrigin: typeof args.allowOrigin === 'string' ? args.allowOrigin : (process.env.RLY_MCP_ALLOW_ORIGIN || ''),
30
+ });
31
+ }
32
+ // Default: be the stdio server. main() never resolves this, so the CLI's
33
+ // post-run exit timer never arms — the server lives until stdin closes.
34
+ return runMcp();
35
+ }
36
+
37
+ // Resolve Claude Desktop's config path for this platform.
38
+ function claudeDesktopConfigPath() {
39
+ const home = os.homedir();
40
+ if (process.platform === 'darwin') return path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
41
+ if (process.platform === 'win32') return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json');
42
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), 'Claude', 'claude_desktop_config.json');
43
+ }
44
+
45
+ function cmdMcpConfig(args, sub) {
46
+ const cfg = mcpConfig({ command: 'rly' });
47
+ const target = String(args.target || '').toLowerCase();
48
+ const wantInstall = (sub === 'install' || sub === 'add') && args.print !== true;
49
+
50
+ // --print, or `config`/`setup` with no writable target: show every option.
51
+ if (!wantInstall || !target) {
52
+ const claudePath = claudeDesktopConfigPath();
53
+ const codexPath = path.join(os.homedir(), '.codex', 'config.toml');
54
+ printJson({
55
+ note: 'Register relay as an MCP App server, then call relay_ask / relay_show from inside the host.',
56
+ claudeCode: 'claude mcp add relay -- rly mcp',
57
+ claudeDesktop: { file: claudePath, add: cfg.json },
58
+ codex: { file: codexPath, add: cfg.toml },
59
+ generic: { add: cfg.json },
60
+ webMobile: cfg.http,
61
+ install: 'rly mcp install --target claude | rly mcp install --target codex',
62
+ });
63
+ return 0;
64
+ }
65
+
66
+ if (target === 'claude' || target === 'claude-desktop') {
67
+ const file = claudeDesktopConfigPath();
68
+ /** @type {Record<string, any>} */
69
+ let existing = {};
70
+ try { existing = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { existing = {}; }
71
+ if (existing === null || typeof existing !== 'object' || Array.isArray(existing)) existing = {};
72
+ existing.mcpServers = existing.mcpServers && typeof existing.mcpServers === 'object' ? existing.mcpServers : {};
73
+ existing.mcpServers.relay = { command: cfg.command, args: cfg.args };
74
+ fs.mkdirSync(path.dirname(file), { recursive: true });
75
+ fs.writeFileSync(file, JSON.stringify(existing, null, 2) + '\n');
76
+ printJson({ installed: 'claude-desktop', file, server: 'relay', note: 'restart Claude Desktop to load it' });
77
+ return 0;
78
+ }
79
+ if (target === 'codex') {
80
+ const file = path.join(os.homedir(), '.codex', 'config.toml');
81
+ let body = '';
82
+ try { body = fs.readFileSync(file, 'utf8'); } catch { body = ''; }
83
+ if (/\[mcp_servers\.relay\]/.test(body)) {
84
+ printJson({ installed: 'codex', file, server: 'relay', note: 'already present — left as-is' });
85
+ return 0;
86
+ }
87
+ fs.mkdirSync(path.dirname(file), { recursive: true });
88
+ const sep = body && !body.endsWith('\n') ? '\n\n' : body ? '\n' : '';
89
+ fs.writeFileSync(file, body + sep + cfg.toml);
90
+ printJson({ installed: 'codex', file, server: 'relay', note: 'restart Codex to load it' });
91
+ return 0;
92
+ }
93
+ throw new CliError(`unknown --target "${target}". Use claude or codex (or \`rly mcp config\` to print all).`, 4);
94
+ }
@@ -0,0 +1,45 @@
1
+ // rly share: turn the share links of a running board on or off.
2
+ import { controlUrl, isAlive, loadRunning } from '../store.js';
3
+ import { CliError } from '../util.js';
4
+ import { mustLoad, printJson } from './io.js';
5
+
6
+ export async function cmdShare(args) {
7
+ const record = mustLoad(args._[0]);
8
+ const running = loadRunning(record.id);
9
+ if (!running || !isAlive(running.pid)) {
10
+ throw new CliError(`board "${record.id}" is not running. Use \`rly reopen ${record.id} --detach\` first.`, 5);
11
+ }
12
+ let role = args.all ? 'all' : args.role;
13
+ if (role === 'readonly' || role === 'read-only') role = 'read';
14
+ if (role !== undefined && !['collab', 'review', 'read', 'all'].includes(role)) {
15
+ throw new CliError('--role must be collab, review, or read.', 4);
16
+ }
17
+ const shareUrl = new URL('/api/share', controlUrl(running));
18
+ const headers = { 'content-type': 'application/json', 'x-relay-token': running.token || '' };
19
+ let res;
20
+ try {
21
+ if (args.revoke) {
22
+ res = await fetch(shareUrl, {
23
+ method: 'DELETE',
24
+ headers,
25
+ body: JSON.stringify({ role: role || 'all' }),
26
+ });
27
+ } else if (role && role !== 'all') {
28
+ res = await fetch(shareUrl, {
29
+ method: 'POST',
30
+ headers,
31
+ body: JSON.stringify({ role }),
32
+ });
33
+ } else {
34
+ res = await fetch(shareUrl, { method: 'GET', headers });
35
+ }
36
+ } catch (err) {
37
+ throw new CliError(`could not reach board "${record.id}" at ${running.url}: ${String((err && err.message) || err)}`, 5);
38
+ }
39
+ const body = await res.json().catch(() => null);
40
+ if (!res.ok) {
41
+ throw new CliError((body && body.error) || `share request failed with HTTP ${res.status}`, res.status === 400 ? 4 : 5);
42
+ }
43
+ printJson({ status: args.revoke ? 'revoked' : role && role !== 'all' ? 'active' : 'shares', boardId: record.id, ...body });
44
+ return 0;
45
+ }
@@ -0,0 +1,192 @@
1
+ // rly skill: install the bundled agent skill and warn when it is stale.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { HOME } from '../store.js';
6
+ import { CliError } from '../util.js';
7
+ import { PKG_ROOT, VERSION } from './context.js';
8
+ import { parseArgs } from './args.js';
9
+ import { printJson } from './io.js';
10
+
11
+ const SKILL_SRC = path.join(PKG_ROOT, 'skills', 'relay');
12
+
13
+ const KNOWN_SKILL_DIRS = () => ({
14
+ claude: path.join(os.homedir(), '.claude', 'skills', 'relay'),
15
+ codex: path.join(os.homedir(), '.codex', 'skills', 'relay'),
16
+ // The cross-agent skills dir (npx-skills ecosystem). Some Codex/agent
17
+ // setups load skills from here INSTEAD of ~/.codex/skills.
18
+ agents: path.join(os.homedir(), '.agents', 'skills', 'relay'),
19
+ });
20
+
21
+ // Pre-rename skill dirs (quest-board). `skill install` removes these so a
22
+ // stale copy doesn't shadow the renamed one.
23
+ const LEGACY_SKILL_DIRS = () => [
24
+ path.join(os.homedir(), '.claude', 'skills', 'quest-board'),
25
+ path.join(os.homedir(), '.codex', 'skills', 'quest-board'),
26
+ ];
27
+
28
+ // One-time stderr nudge so agents that only have the CLI discover the skill.
29
+ export function firstRunHint() {
30
+ try {
31
+ const marker = path.join(HOME, '.hinted');
32
+ if (fs.existsSync(marker)) return;
33
+ fs.mkdirSync(HOME, { recursive: true });
34
+ fs.writeFileSync(marker, new Date().toISOString());
35
+ const installed = Object.values(KNOWN_SKILL_DIRS()).some((p) => fs.existsSync(path.join(p, 'SKILL.md')));
36
+ if (!installed) {
37
+ process.stderr.write(
38
+ 'tip (AI agents): rly bundles a universal skill — install it with `rly skill install`; full guide: `rly agent`\n'
39
+ );
40
+ }
41
+ } catch {
42
+ // never let the hint break a real command
43
+ }
44
+ }
45
+
46
+ // Installed skill copies are snapshots — warn when they lag the CLI.
47
+ export function skillFreshnessWarning() {
48
+ try {
49
+ for (const [agent, dir] of Object.entries(KNOWN_SKILL_DIRS())) {
50
+ if (!fs.existsSync(path.join(dir, 'SKILL.md'))) continue;
51
+ let installedVersion = null;
52
+ try {
53
+ installedVersion = fs.readFileSync(path.join(dir, '.rly-version'), 'utf8').trim();
54
+ } catch {
55
+ // pre-rename install without a version marker
56
+ }
57
+ if (installedVersion !== VERSION) {
58
+ process.stderr.write(
59
+ `note: the relay skill installed for ${agent} is from rly ${installedVersion ?? '<0.2.0'}, you run ${VERSION} — refresh with \`rly skill install\`\n`
60
+ );
61
+ }
62
+ }
63
+ } catch {
64
+ // best effort only
65
+ }
66
+ }
67
+
68
+ function skillTargets(target) {
69
+ const known = KNOWN_SKILL_DIRS();
70
+ if (!target || target === true || target === 'auto') {
71
+ const found = Object.values(known).filter((p) => fs.existsSync(path.dirname(path.dirname(p))));
72
+ if (!found.length) {
73
+ throw new CliError('no agent dirs found (~/.claude, ~/.codex, or ~/.agents). Use --target claude|codex|agents|all|<dir>.');
74
+ }
75
+ return found;
76
+ }
77
+ if (target === 'both' || target === 'all') return Object.values(known);
78
+ if (known[target]) return [known[target]];
79
+ return [path.join(path.resolve(target), 'relay')];
80
+ }
81
+
82
+ // Removes stale pre-rename quest-board skill dirs so the renamed skill is the
83
+ // only one an agent sees. Returns the dirs actually removed.
84
+ function removeLegacySkills() {
85
+ const removed = [];
86
+ for (const dir of LEGACY_SKILL_DIRS()) {
87
+ try {
88
+ if (fs.existsSync(dir)) {
89
+ fs.rmSync(dir, { recursive: true, force: true });
90
+ removed.push(dir);
91
+ }
92
+ } catch {
93
+ // best effort — a leftover dir we couldn't remove shouldn't fail install
94
+ }
95
+ }
96
+ return removed;
97
+ }
98
+
99
+ // Stamps the current CLI version into every installed skill dir's .rly-version.
100
+ // `rly skill install` writes this itself, but an `npx skills add` refresh does
101
+ // not — so after any refresh we re-stamp the dirs that now have a SKILL.md,
102
+ // keeping skillFreshnessWarning() from nagging about a just-refreshed skill.
103
+ export function stampSkillVersion() {
104
+ const stamped = [];
105
+ for (const dir of Object.values(KNOWN_SKILL_DIRS())) {
106
+ try {
107
+ if (fs.existsSync(path.join(dir, 'SKILL.md'))) {
108
+ fs.writeFileSync(path.join(dir, '.rly-version'), VERSION);
109
+ stamped.push(dir);
110
+ }
111
+ } catch {
112
+ // best effort — a marker we couldn't write just re-triggers the nudge
113
+ }
114
+ }
115
+ return stamped;
116
+ }
117
+
118
+ // Short instruction block for an agent's main instruction file (CLAUDE.md,
119
+ // AGENTS.md, …). A skill is only a tier-1 hint that agents can ignore; these
120
+ // rules, appended to the instructions the agent always reads, enforce usage.
121
+ // Printed to stdout so `rly skill rules >> CLAUDE.md` is the whole install.
122
+ export const SKILL_RULES = `## relay — visual boards and structured feedback
123
+
124
+ - Use Relay for files, visuals, plans, diffs, and multiple related questions.
125
+ Keep brief answers and progress updates in chat; follow existing user authorization.
126
+ - Show without feedback: \`rly show --file spec.json --display-only\` (no waiter).
127
+ Collect input: \`rly ask --file spec.json --detach\`, then keep
128
+ \`rly wait <boardId> --timeout 1800 --while-active --idle-grace 300\` in the
129
+ foreground. If it times out, read \`rly result <boardId>\` before continuing.
130
+ - Use the most specific block: table/chart/kpi for data, image/compare for visuals,
131
+ code/diff for source, mermaid for flows, markdown for prose, html for custom UI.
132
+ \`rly view\`, \`rly diff\`, and \`rly git\` are shortcuts; visual options use \`options[].blocks\`.
133
+ - Browser file links such as \`[source](/absolute/app.js:98)\` open supported files
134
+ in a modal and highlight source lines. Unsupported files offer Open in app.
135
+ For inline MCP or shared reviewers, embed file content as blocks instead.
136
+ - Reconnect existing boards by ID with \`rly rescue\` / \`rly reopen\`; update
137
+ content with \`rly update\`. Preserve the original port and saved input.
138
+ - On a setup with \`devlink\`, add \`--devlink\` (or run \`rly config link devlink\` once)
139
+ so the board opens on a private URL that phones and other Macs can reach.
140
+ Share that printed URL, never a localhost one.
141
+ - Small live widgets (status lists, numbers, buttons) are \`a2ui\` blocks; the
142
+ grammar is in \`rly a2ui\`. Questions you depend on stay normal questions.
143
+ - Read answers, notes, comment, annotations, and blockEdits together. Use the
144
+ returned resultFile when stdout is truncated; a timeout is not an answer.
145
+ - Full skill: \`rly skill path\`; fields: \`rly schema\`; advanced recipes and
146
+ sharing permissions: \`rly agent\`. Load details only when needed.`;
147
+
148
+ export function cmdSkill(rest) {
149
+ const sub = rest[0];
150
+ if (sub === 'rules') {
151
+ console.log(SKILL_RULES);
152
+ return 0;
153
+ }
154
+ if (sub === 'path') {
155
+ console.log(SKILL_SRC);
156
+ process.stderr.write('(bundled skill source — copy into your agent with `rly skill install`)\n');
157
+ return 0;
158
+ }
159
+ if (sub === 'install') {
160
+ const args = parseArgs(rest.slice(1));
161
+ const targets = skillTargets(args.target);
162
+ const installed = [];
163
+ for (const t of targets) {
164
+ fs.mkdirSync(path.dirname(t), { recursive: true });
165
+ // Clear whatever is already there first. cpSync refuses to overwrite a
166
+ // non-directory (a symlink or file at the target — e.g. a skill dir the
167
+ // user symlinked elsewhere) with a directory, so a plain re-install would
168
+ // crash. rmSync on a symlink removes the link itself, not its target.
169
+ fs.rmSync(t, { recursive: true, force: true });
170
+ fs.cpSync(SKILL_SRC, t, { recursive: true });
171
+ fs.writeFileSync(path.join(t, '.rly-version'), VERSION);
172
+ installed.push(t);
173
+ }
174
+ const removedLegacy = removeLegacySkills();
175
+ printJson({ installed, removedLegacy, note: 'most agents pick new skills up immediately; if yours does not, re-list skills or restart the session' });
176
+ return 0;
177
+ }
178
+ console.log(`relay ships a universal agent skill (Claude Code, Codex, and any SKILL.md-aware agent).
179
+
180
+ bundled at: ${SKILL_SRC}
181
+ install it: rly skill install # auto-detects ~/.claude, ~/.codex, ~/.agents
182
+ rly skill install --target claude|codex|both|<dir>
183
+ from repo: npx skills add khanglvm/relay --skill relay --all
184
+ enforce it: rly skill rules # short always-read rules — paste into the file your
185
+ # agent reads (CLAUDE.md, AGENTS.md, .cursor/rules, …);
186
+ # a skill alone is an ignorable hint
187
+
188
+ The skill teaches your agent the board spec format (questions + rich blocks +
189
+ annotations), the blocking vs --detach patterns, and visualization sizing.
190
+ Full guide: \`rly agent\`.`);
191
+ return 0;
192
+ }
@@ -0,0 +1,130 @@
1
+ // rly upgrade: update the global package and refresh what depends on it.
2
+ import { spawnSync } from 'node:child_process';
3
+ import { listRunning, loadRunning } from '../store.js';
4
+ import { CliError, pollFor } from '../util.js';
5
+ import { printJson } from './io.js';
6
+ import { PKG_NAME } from './context.js';
7
+ import { stampSkillVersion } from './skill.js';
8
+
9
+ // `rly upgrade` — install the latest CLI globally AND refresh the skill (via the
10
+ // npx-skills package manager, falling back to the bundled copy) in one shot.
11
+ // (`update` is taken by the live-mutate command, so this is
12
+ // `upgrade` / `self-update`.) Running boards are surfaced and handled: a global
13
+ // reinstall overwrites relay's files, but live detached servers snapshot their
14
+ // UI at first request and serve from memory, so they keep working on their own
15
+ // version. Flags: --stop (stop running boards first), --force (upgrade while
16
+ // they keep running), --cli-only / --skill-only (scope).
17
+ export async function cmdUpgrade(args) {
18
+ const force = args.force === true;
19
+ const doStop = args.stop === true;
20
+ const wantCli = args.skillOnly !== true;
21
+ const wantSkill = args.cliOnly !== true;
22
+
23
+ const running = listRunning();
24
+
25
+ // --dry-run: report the plan (incl. how running boards would be handled)
26
+ // without installing anything or stopping anything.
27
+ if (args.dryRun === true) {
28
+ printJson({
29
+ dryRun: true,
30
+ wouldRun: [wantCli && `npm install -g ${PKG_NAME}@latest`, wantSkill && 'npx skills add khanglvm/relay --skill relay --all'].filter(Boolean),
31
+ runningBoards: running.map((r) => r.id),
32
+ runningHandling: running.length
33
+ ? doStop
34
+ ? 'stop them first'
35
+ : force
36
+ ? 'leave them running (snapshotted)'
37
+ : 'BLOCKED — pass --stop or --force'
38
+ : 'none running',
39
+ });
40
+ return 0;
41
+ }
42
+
43
+ if (running.length) {
44
+ const ids = running.map((r) => r.id).join(', ');
45
+ if (doStop) {
46
+ process.stderr.write(`Stopping ${running.length} running board(s) before upgrading: ${ids}\n`);
47
+ for (const r of running) {
48
+ try { process.kill(r.pid, 'SIGTERM'); } catch { /* already gone */ }
49
+ }
50
+ for (const r of running) await pollFor(() => (loadRunning(r.id) ? null : true), 5000);
51
+ } else if (!force) {
52
+ // Default: don't silently overwrite under live boards — explain + let the
53
+ // user choose. The boards themselves are safe; this is about clarity.
54
+ process.stderr.write(
55
+ `${running.length} board(s) still running: ${ids}\n` +
56
+ 'They keep serving their current version safely (each snapshots its UI in memory),\n' +
57
+ 'and stay readable via `rly result <id>` / `rly wait <id>`. Pick one:\n' +
58
+ ' • rly stop --all then re-run `rly upgrade` (cleanest)\n' +
59
+ ' • rly upgrade --stop stop them as part of this upgrade\n' +
60
+ ' • rly upgrade --force upgrade now; leave them running on their snapshot\n'
61
+ );
62
+ printJson({ upgraded: false, reason: 'running-boards', running: running.map((r) => r.id) });
63
+ return 0;
64
+ } else {
65
+ process.stderr.write(`--force: leaving ${running.length} board(s) running on their snapshotted version: ${ids}\n`);
66
+ }
67
+ }
68
+
69
+ const did = {};
70
+
71
+ if (wantCli) {
72
+ process.stderr.write(`\nUpgrading ${PKG_NAME} → latest (npm install -g ${PKG_NAME}@latest)\n`);
73
+ // shell:true so Windows resolves `npm` → `npm.cmd` (same reason the skill /
74
+ // version spawns below use it); the package name has no shell metacharacters.
75
+ const r = spawnSync('npm', ['install', '-g', `${PKG_NAME}@latest`], { stdio: 'inherit', shell: true });
76
+ if (r.error || r.status !== 0) {
77
+ throw new CliError(
78
+ `npm install failed${r.error ? ` (${r.error.message})` : ` (exit ${r.status})`}. ` +
79
+ `Update manually: npm install -g ${PKG_NAME}@latest`,
80
+ 1
81
+ );
82
+ }
83
+ did.cli = `${PKG_NAME}@latest`;
84
+ }
85
+
86
+ if (wantSkill) {
87
+ // Refresh the skill through the npx-skills package manager — the same channel
88
+ // the skill is normally managed by (skills-lock.json, ~/.agents, ~/.claude, …)
89
+ // — so the global install stays in sync and pulls the freshest skill for
90
+ // khanglvm/relay. `npx -y` so the one-off download needs no prompt.
91
+ process.stderr.write('\nRefreshing the relay skill (npx skills add khanglvm/relay --skill relay --all)\n');
92
+ let r = spawnSync('npx', ['-y', 'skills', 'add', 'khanglvm/relay', '--skill', 'relay', '--all'], { stdio: 'inherit', shell: true });
93
+ let how = 'npx-skills';
94
+ if (r.error || r.status !== 0) {
95
+ // Fallback: install the skill bundled with the CLI we just upgraded. Works
96
+ // offline / when the skills CLI is unreachable, and matches this version.
97
+ process.stderr.write('\nnpx skills unavailable — falling back to the bundled skill (rly skill install)\n');
98
+ r = spawnSync('rly', ['skill', 'install'], { stdio: 'inherit', shell: true });
99
+ how = 'bundled';
100
+ }
101
+ if (r.error || r.status !== 0) {
102
+ process.stderr.write(
103
+ `Skill refresh did not complete${r.error ? ` (${r.error.message})` : ` (exit ${r.status})`} — ` +
104
+ 'run `npx skills add khanglvm/relay --skill relay --all` (or `rly skill install`) yourself.\n'
105
+ );
106
+ } else {
107
+ // Keep the freshness marker accurate however the skill landed, so the next
108
+ // `rly` run doesn't nag that the just-refreshed skill is stale.
109
+ stampSkillVersion();
110
+ did.skill = how;
111
+ }
112
+ }
113
+
114
+ // Report the now-current global version (best-effort).
115
+ let nowVersion = null;
116
+ try {
117
+ const v = spawnSync('rly', ['--version'], { encoding: 'utf8', shell: true });
118
+ if (v.status === 0 && v.stdout) nowVersion = String(v.stdout).trim();
119
+ } catch {
120
+ // best effort
121
+ }
122
+
123
+ printJson({
124
+ upgraded: true,
125
+ ...did,
126
+ version: nowVersion,
127
+ note: 'most agents pick the new skill up immediately; if not, re-list skills or restart the session',
128
+ });
129
+ return 0;
130
+ }