@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/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
+ }
@@ -0,0 +1,91 @@
1
+ // The rly help text.
2
+ import { VERSION } from './context.js';
3
+
4
+ export function printHelp() {
5
+ console.log(`rly ${VERSION} — relay: browser question boards, rich blocks & annotations for AI agents
6
+
7
+ USAGE
8
+ rly ask --file spec.json create board, open browser, BLOCK until submit, print answers JSON
9
+ rly ask --file - < spec.json spec from stdin
10
+ rly ask -q "Deploy?::yesno" -q "!Env::single::dev,staging,prod"
11
+ quick inline questions ("!" = required, label::type::options)
12
+ rly ask ... --detach no blocking: prints {boardId,url} now; collect via \`rly wait <id>\`
13
+ rly ask ... --on-result "<cmd>" push-wake: run <cmd> when the board finishes (result JSON on stdin)
14
+ rly show --html-file viz.html visualization board (submit button = acknowledge)
15
+ rly show --file spec.json --display-only
16
+ present without comments/acknowledgement; returns immediately
17
+ rly view <file.md> [more.md …] quick read-only board rendering markdown file(s) (no lib)
18
+ (.csv/.tsv/.json render as a filterable, sortable table;
19
+ .pdf streams in an inline PDF viewer)
20
+ rly diff [git args…] run git diff and show it in a diff board (--split, --detach,
21
+ --title; other args pass to git: rly diff --staged | HEAD~1 | -- path)
22
+ rly git pick [range] board for choosing pick/cherry-pick/drop actions plus commit order
23
+ rly git cherry-pick [range] board for choosing commits and cherry-pick order
24
+ add --code for split code view with per-hunk Apply/Skip/Hold
25
+ rly git conflict [files…] board for resolving conflict-marker files; with no files, auto-detects
26
+ unmerged git files and returns resolved content in result.blockEdits
27
+ rly wait <id> [--timeout 86400] block up to one day until the board finishes (0 = no deadline)
28
+ --while-active [--idle-grace 180]: keep waiting past the deadline
29
+ while the user is still viewing/focused & recently active
30
+ --notify-cmd "<cmd>": run <cmd> on a terminal result (JSON on stdin)
31
+ NB: also writes the FULL result to "resultFile" (first field) —
32
+ read that file if your shell truncates stdout; never pipe to head/tail
33
+ rly result <id> result/status now (includes live autosaved draft + presence while open)
34
+ rly share <id> list active same-Wi-Fi share links for a running board
35
+ rly share <id> --role review reviewer: answer/comment/submit a reference-only side review
36
+ rly share <id> --role collab collaborator: edit/comment/final-submit as owner-authorized
37
+ rly share <id> --role read activate a read-only viewer link
38
+ rly share <id> --role review --revoke
39
+ revoke one share role; use --revoke --all to disable all roles
40
+ active links survive same-port reopen/rescue until revoked
41
+ rly ask ... --link-command <cmd> serve the board at the https URL a link-provider command prints
42
+ for its port ({port} in <cmd>, else appended); no local browser opens
43
+ rly ask ... --devlink same, through the optional devlink command
44
+ rly ask ... --public-url <url> same, through your own proxy or tunnel: https://relay.example.com:{port}
45
+ rly config link <off|auto|devlink|url|command:CMD>
46
+ save that choice for every board (auto = devlink when installed)
47
+ rly list [--json] running boards
48
+ rly open [id] re-open the browser tab of a running board
49
+ rly reopen <id> [--replies f.json] serve a saved board again, prefilled with saved answers
50
+ (--replies [{annotationId,text}] = agent answers to element comments)
51
+ rly rescue <id> [--open] re-serve a board on its ORIGINAL port so a still-open but
52
+ disconnected browser tab auto-reconnects & re-saves (no new tab
53
+ unless --open). Use when a tab shows "connection lost".
54
+ rly reuse <id> [--dump] re-run a past board as a new board (--dump prints its spec)
55
+ rly update <id> --file spec.json live-mutate a RUNNING board (or --title/--intro/-q); page reloads
56
+ rly stop <id> | --all stop running board(s) (status: cancelled, draft preserved)
57
+ rly history [--limit n] [--json] saved boards
58
+ rly spec <id> print a saved board's spec JSON (edit, then ask --file again)
59
+ rly rm <id> | --all delete saved board(s)
60
+ rly schema JSON Schema of the board spec
61
+ rly agent FULL GUIDE for AI agents (spec format, blocks, sizing, patterns)
62
+ rly a2ui A2UI widget blocks: Express grammar, components, examples
63
+ rly skill [install|rules|path] bundled universal agent skill (Claude Code, Codex, …)
64
+ \`rly skill rules >> CLAUDE.md\` adds always-read usage rules
65
+ rly install --target <agent> inject relay's rules into an agent's instruction file
66
+ claude codex cursor copilot kiro windsurf cline gemini opencode droid agents
67
+ --scope global|project · --print (copy/paste) · --all · --list (no flags)
68
+ rly upgrade install the latest CLI globally + refresh the skill in one step
69
+ --stop/--force handle running boards · --dry-run · --cli-only/--skill-only
70
+ rly mcp run relay as an MCP App server (stdio) — boards render INLINE in
71
+ a local desktop host (Claude Desktop, Codex) instead of a browser tab
72
+ rly mcp --http [--port N] serve over Streamable HTTP for web/mobile/remote hosts
73
+ [--host H --token SECRET --allow-origin ORIGIN]
74
+ rly mcp config | install --target print host setup, or write it (claude | codex)
75
+
76
+ COMMON FLAGS
77
+ --title <s> --intro <s> --html-file <f> --height <px> --submit-label <s>
78
+ --timeout <sec> (default 86400; 0 = none) --port <n> --no-open --detach --display-only
79
+ --devlink | --no-devlink | --public-url <url> where the board link points (see rly config link)
80
+
81
+ EXIT CODES 0 submitted/acknowledged · 2 timeout · 3 cancelled · 4 usage · 5 not found
82
+
83
+ NOTES detached boards keep serving after timeout until Submit or stop;
84
+ answers & annotations autosave in real time (drafts survive timeout/cancel);
85
+ submitting auto-closes the tab and unblocks the CLI.
86
+
87
+ AI AGENTS run \`rly agent\` for the complete machine-oriented guide.
88
+ a universal skill is bundled — install with \`rly skill install\`
89
+ (or from the repo: npx skills add khanglvm/relay --skill relay --all)`);
90
+ return 0;
91
+ }
@@ -0,0 +1,103 @@
1
+ // The rly command router.
2
+ import { SPEC_SCHEMA } from '../spec/index.js';
3
+ import { CliError } from '../util.js';
4
+ import { cmdSkill, firstRunHint, skillFreshnessWarning } from './skill.js';
5
+ import { printHelp } from './help.js';
6
+ import { VERSION } from './context.js';
7
+ import { cmdAsk } from './ask.js';
8
+ import { parseArgs } from './args.js';
9
+ import { cmdHistory, cmdList, cmdOpen, cmdReopen, cmdRescue, cmdReuse, cmdRm, cmdSpec, cmdStop, cmdUpdate, cmdView } from './boards.js';
10
+ import { cmdDiff, cmdGit } from './git.js';
11
+ import { cmdResult, cmdWait } from './wait.js';
12
+ import { cmdShare } from './share.js';
13
+ import { cmdA2ui, cmdAgent, cmdConfig, cmdServeInternal } from './config.js';
14
+ import { cmdInstall } from './install.js';
15
+ import { cmdUpgrade } from './upgrade.js';
16
+ import { cmdMcp } from './mcp.js';
17
+
18
+ export async function main(argv) {
19
+ const [cmd, ...rest] = argv;
20
+ if (cmd !== '__serve') firstRunHint();
21
+ if (cmd === undefined || cmd === 'help' || cmd === '--help' || cmd === '-h' || cmd === 'agent' || cmd === 'skill') {
22
+ skillFreshnessWarning();
23
+ }
24
+ try {
25
+ switch (cmd) {
26
+ case undefined:
27
+ case 'help':
28
+ case '--help':
29
+ case '-h':
30
+ return printHelp();
31
+ case 'version':
32
+ case '--version':
33
+ case '-v':
34
+ console.log(VERSION);
35
+ return 0;
36
+ case 'ask':
37
+ return await cmdAsk(parseArgs(rest), 'ask');
38
+ case 'show':
39
+ return await cmdAsk(parseArgs(rest), 'show');
40
+ case 'view':
41
+ return await cmdView(parseArgs(rest));
42
+ case 'diff':
43
+ return await cmdDiff(rest);
44
+ case 'git':
45
+ return await cmdGit(rest);
46
+ case 'reopen':
47
+ return await cmdReopen(parseArgs(rest));
48
+ case 'rescue':
49
+ return await cmdRescue(parseArgs(rest));
50
+ case 'reuse':
51
+ return await cmdReuse(parseArgs(rest));
52
+ case 'update':
53
+ return await cmdUpdate(parseArgs(rest));
54
+ case 'wait':
55
+ return await cmdWait(parseArgs(rest));
56
+ case 'result':
57
+ return await cmdResult(parseArgs(rest));
58
+ case 'share':
59
+ return await cmdShare(parseArgs(rest));
60
+ case 'config':
61
+ return cmdConfig(parseArgs(rest));
62
+ case 'list':
63
+ return cmdList(parseArgs(rest));
64
+ case 'open':
65
+ return cmdOpen(parseArgs(rest));
66
+ case 'stop':
67
+ return await cmdStop(parseArgs(rest));
68
+ case 'history':
69
+ return cmdHistory(parseArgs(rest));
70
+ case 'spec':
71
+ return cmdSpec(parseArgs(rest));
72
+ case 'rm':
73
+ return cmdRm(parseArgs(rest));
74
+ case 'skill':
75
+ return cmdSkill(rest);
76
+ case 'install':
77
+ return cmdInstall(parseArgs(rest));
78
+ case 'upgrade':
79
+ case 'self-update':
80
+ return await cmdUpgrade(parseArgs(rest));
81
+ case 'agent':
82
+ return cmdAgent();
83
+ case 'a2ui':
84
+ return cmdA2ui();
85
+ case 'schema':
86
+ console.log(JSON.stringify(SPEC_SCHEMA, null, 2));
87
+ return 0;
88
+ case 'mcp':
89
+ return await cmdMcp(rest);
90
+ case '__serve':
91
+ return await cmdServeInternal(parseArgs(rest));
92
+ default:
93
+ throw new CliError(`unknown command "${cmd}". Run \`rly help\`.`);
94
+ }
95
+ } catch (err) {
96
+ if (err instanceof CliError) {
97
+ process.stderr.write(`rly: ${err.message}\n`);
98
+ if (err.code === 4) process.stderr.write('run `rly agent` for the agent-oriented guide\n');
99
+ return err.code;
100
+ }
101
+ throw err;
102
+ }
103
+ }
@@ -0,0 +1,197 @@
1
+ // rly install: write the Relay instructions into each agent's rules file.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { CliError } from '../util.js';
6
+ import { SKILL_RULES } from './skill.js';
7
+ import { printJson } from './io.js';
8
+
9
+ // ===========================================================================
10
+ // `rly install` — inject relay's always-read rules into ANY agent's
11
+ // instruction file, cross-platform. `rly skill install` (above) handles the
12
+ // full SKILL.md for skill-aware agents; this covers the long tail (Cursor,
13
+ // Copilot, Kiro, Windsurf, Cline, Gemini, generic AGENTS.md, …) that read a
14
+ // rules/instructions/steering/context markdown file instead.
15
+ // ===========================================================================
16
+
17
+ const RELAY_BEGIN = '<!-- relay:begin (managed by `rly install` — your edits outside these markers are kept) -->';
18
+ const RELAY_END = '<!-- relay:end -->';
19
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
20
+
21
+ // Resolve OS-specific base dirs from an injectable env/home/platform so the
22
+ // path logic is unit-testable for win32 / linux / darwin without running there.
23
+ function platformDirs({ platform, home, env }) {
24
+ const xdg = env.XDG_CONFIG_HOME || path.join(home, '.config');
25
+ const localApp = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
26
+ // Copilot-in-JetBrains global instructions dir.
27
+ const jetbrainsCopilot = platform === 'win32'
28
+ ? path.join(localApp, 'github-copilot', 'intellij')
29
+ : path.join(xdg, 'github-copilot', 'intellij');
30
+ return { xdg, jetbrainsCopilot, documents: path.join(home, 'Documents') };
31
+ }
32
+
33
+ // The relay instruction registry. Each agent declares how to install relay's
34
+ // rules at `global` (user, machine-wide) and/or `project` (cwd) scope, in what
35
+ // `style`, and a `detect` dir whose existence means "you use this agent"
36
+ // (drives `--all`). Styles:
37
+ // 'shared' — upsert a marked block into a possibly-shared file (CLAUDE.md,
38
+ // AGENTS.md, copilot-instructions.md, …); your other content is
39
+ // preserved, only relay's block is rewritten.
40
+ // 'dedicated' — relay owns the whole file (.kiro/steering, .windsurf/rules,
41
+ // .clinerules, …); safe to overwrite.
42
+ // 'mdc' — dedicated, with Cursor `.mdc` YAML frontmatter.
43
+ export function agentRegistry({ platform = process.platform, home = os.homedir(), cwd = process.cwd(), env = process.env } = {}) {
44
+ const d = platformDirs({ platform, home, env });
45
+ const j = path.join;
46
+ return [
47
+ { id: 'claude', label: 'Claude Code',
48
+ detect: j(home, '.claude'),
49
+ global: { file: j(home, '.claude', 'CLAUDE.md'), style: 'shared' },
50
+ project: { file: j(cwd, 'CLAUDE.md'), style: 'shared' },
51
+ note: 'full skill: `rly skill install`' },
52
+ { id: 'codex', label: 'OpenAI Codex',
53
+ detect: j(home, '.codex'),
54
+ global: { file: j(home, '.codex', 'AGENTS.md'), style: 'shared' },
55
+ project: { file: j(cwd, 'AGENTS.md'), style: 'shared' } },
56
+ { id: 'agents', label: 'AGENTS.md standard (Amp, Jules, Cline, …)',
57
+ detect: j(home, '.agents'),
58
+ global: { file: j(home, '.agents', 'AGENTS.md'), style: 'shared' },
59
+ project: { file: j(cwd, 'AGENTS.md'), style: 'shared' } },
60
+ { id: 'cursor', label: 'Cursor',
61
+ detect: j(home, '.cursor'),
62
+ global: null, // user rules are set in Cursor Settings UI (not file-based)
63
+ project: { file: j(cwd, '.cursor', 'rules', 'relay.mdc'), style: 'mdc' },
64
+ note: 'global "User Rules" are set in Settings UI, not a file' },
65
+ { id: 'copilot', label: 'GitHub Copilot (VS Code / Visual Studio / JetBrains)',
66
+ detect: path.dirname(d.jetbrainsCopilot), // …/github-copilot
67
+ global: { file: j(d.jetbrainsCopilot, 'global-copilot-instructions.md'), style: 'shared' },
68
+ project: { file: j(cwd, '.github', 'copilot-instructions.md'), style: 'shared' },
69
+ note: 'global file applies in JetBrains IDEs; project file applies everywhere' },
70
+ { id: 'kiro', label: 'Kiro',
71
+ detect: j(home, '.kiro'),
72
+ global: { file: j(home, '.kiro', 'steering', 'relay.md'), style: 'dedicated' },
73
+ project: { file: j(cwd, '.kiro', 'steering', 'relay.md'), style: 'dedicated' } },
74
+ { id: 'windsurf', label: 'Windsurf',
75
+ detect: j(home, '.codeium'),
76
+ global: { file: j(home, '.codeium', 'windsurf', 'memories', 'global_rules.md'), style: 'shared' },
77
+ project: { file: j(cwd, '.windsurf', 'rules', 'relay.md'), style: 'dedicated' } },
78
+ { id: 'cline', label: 'Cline',
79
+ detect: j(d.documents, 'Cline'),
80
+ global: { file: j(d.documents, 'Cline', 'Rules', 'relay.md'), style: 'dedicated' },
81
+ project: { file: j(cwd, '.clinerules', 'relay.md'), style: 'dedicated' } },
82
+ { id: 'gemini', label: 'Gemini CLI',
83
+ detect: j(home, '.gemini'),
84
+ global: { file: j(home, '.gemini', 'GEMINI.md'), style: 'shared' },
85
+ project: { file: j(cwd, 'GEMINI.md'), style: 'shared' } },
86
+ { id: 'opencode', label: 'OpenCode',
87
+ detect: j(d.xdg, 'opencode'),
88
+ global: { file: j(d.xdg, 'opencode', 'AGENTS.md'), style: 'shared' },
89
+ project: { file: j(cwd, 'AGENTS.md'), style: 'shared' } },
90
+ { id: 'droid', label: 'Droid (Factory)',
91
+ detect: j(home, '.factory'),
92
+ global: { file: j(home, '.factory', 'AGENTS.md'), style: 'shared' },
93
+ project: { file: j(cwd, 'AGENTS.md'), style: 'shared' } },
94
+ ];
95
+ }
96
+
97
+ // Render the relay rules in the style the target file expects.
98
+ function renderInstruction(style) {
99
+ if (style === 'mdc') {
100
+ return `---\ndescription: relay — collect decisions & show rich visuals in the browser, not the terminal\nalwaysApply: true\n---\n\n${SKILL_RULES}\n`;
101
+ }
102
+ return `${SKILL_RULES}\n`; // dedicated file — relay owns it
103
+ }
104
+
105
+ // Upsert relay's marked block into a (possibly shared / pre-existing) file,
106
+ // leaving everything outside the markers untouched. Returns 'added'|'updated'.
107
+ function upsertBlock(file, body) {
108
+ let existing = '';
109
+ try { existing = fs.readFileSync(file, 'utf8'); } catch { /* new file */ }
110
+ const wrapped = `${RELAY_BEGIN}\n${body}\n${RELAY_END}`;
111
+ const re = new RegExp(escapeRegExp(RELAY_BEGIN) + '[\\s\\S]*?' + escapeRegExp(RELAY_END));
112
+ const had = re.test(existing);
113
+ const next = had
114
+ ? existing.replace(re, wrapped)
115
+ : (existing.trim() ? existing.replace(/\s*$/, '') + '\n\n' + wrapped + '\n' : wrapped + '\n');
116
+ fs.mkdirSync(path.dirname(file), { recursive: true });
117
+ fs.writeFileSync(file, next);
118
+ return had ? 'updated' : 'added';
119
+ }
120
+
121
+ function writeInstruction(target) {
122
+ if (target.style === 'shared') return upsertBlock(target.file, SKILL_RULES);
123
+ const existed = fs.existsSync(target.file);
124
+ fs.mkdirSync(path.dirname(target.file), { recursive: true });
125
+ fs.writeFileSync(target.file, renderInstruction(target.style));
126
+ return existed ? 'updated' : 'added';
127
+ }
128
+
129
+ export function cmdInstall(args) {
130
+ const reg = agentRegistry();
131
+ const byId = Object.fromEntries(reg.map((a) => [a.id, a]));
132
+ const scope = args.scope === 'project' ? 'project' : args.scope === 'global' ? 'global' : null;
133
+
134
+ // Pick the target for an agent: explicit --scope wins; else prefer global
135
+ // (machine-wide), falling back to project when the agent has no global file.
136
+ const pick = (a) => {
137
+ if (scope === 'project') return a.project ? { scope: 'project', t: a.project } : null;
138
+ if (scope === 'global') return a.global ? { scope: 'global', t: a.global } : null;
139
+ if (a.global) return { scope: 'global', t: a.global };
140
+ if (a.project) return { scope: 'project', t: a.project };
141
+ return null;
142
+ };
143
+
144
+ const wantAll = args.all === true || String(args.target || '').toLowerCase() === 'all';
145
+
146
+ // No target → show the matrix for THIS platform.
147
+ if (!wantAll && (args.list === true || !args.target)) {
148
+ printJson({
149
+ platform: process.platform,
150
+ agents: reg.map((a) => ({
151
+ agent: a.id, label: a.label,
152
+ global: a.global ? a.global.file : null,
153
+ project: a.project ? a.project.file : null,
154
+ note: a.note,
155
+ })),
156
+ usage: 'rly install --target <agent>[,<agent>] [--scope global|project] [--print] | rly install --all',
157
+ });
158
+ return 0;
159
+ }
160
+
161
+ // Resolve the set of {agent, scope, target} to act on.
162
+ let chosen;
163
+ if (wantAll) {
164
+ chosen = reg
165
+ .filter((a) => { try { return fs.existsSync(a.detect); } catch { return false; } })
166
+ .map((a) => ({ a, ...(pick(a) || {}) }))
167
+ .filter((x) => x.t);
168
+ if (!chosen.length) {
169
+ throw new CliError('no known agents detected on this machine (no ~/.claude, ~/.codex, ~/.cursor, ~/.kiro, …). Use --target <agent>.', 4);
170
+ }
171
+ } else {
172
+ const ids = String(args.target).split(',').map((s) => s.trim()).filter(Boolean);
173
+ chosen = [];
174
+ for (const id of ids) {
175
+ const a = byId[id];
176
+ if (!a) throw new CliError(`unknown agent "${id}". Run \`rly install --list\` to see supported agents.`, 4);
177
+ const p = pick(a);
178
+ if (!p) throw new CliError(`${a.label} has no ${scope || 'installable'} instruction file${a.note ? ` — ${a.note}` : ''}. Try \`--scope project\`.`, 4);
179
+ chosen.push({ a, ...p });
180
+ }
181
+ }
182
+
183
+ // --print: emit content + resolved path for manual copy/paste; no writes.
184
+ if (args.print === true) {
185
+ for (const { a, t } of chosen) {
186
+ const content = t.style === 'shared' ? `${RELAY_BEGIN}\n${SKILL_RULES}\n${RELAY_END}` : renderInstruction(t.style);
187
+ process.stdout.write(`# ${a.label}\n# → ${t.file}\n\n${content}\n\n`);
188
+ }
189
+ return 0;
190
+ }
191
+
192
+ const installed = chosen.map(({ a, scope: sc, t }) => ({
193
+ agent: a.id, scope: sc, file: t.file, action: writeInstruction(t),
194
+ }));
195
+ printJson({ installed, note: 'reload/re-open your agent (or re-list its rules) if it does not pick this up immediately' });
196
+ return 0;
197
+ }