@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
@@ -0,0 +1,90 @@
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 ... --devlink serve the board on a private cross-device URL through the optional
42
+ devlink command (https over Tailscale); no local browser opens
43
+ rly ask ... --public-url <url> same, through your own proxy or tunnel: https://relay.example.com:{port}
44
+ rly config link <off|auto|devlink|url>
45
+ save that choice for every board (auto = devlink when installed)
46
+ rly list [--json] running boards
47
+ rly open [id] re-open the browser tab of a running board
48
+ rly reopen <id> [--replies f.json] serve a saved board again, prefilled with saved answers
49
+ (--replies [{annotationId,text}] = agent answers to element comments)
50
+ rly rescue <id> [--open] re-serve a board on its ORIGINAL port so a still-open but
51
+ disconnected browser tab auto-reconnects & re-saves (no new tab
52
+ unless --open). Use when a tab shows "connection lost".
53
+ rly reuse <id> [--dump] re-run a past board as a new board (--dump prints its spec)
54
+ rly update <id> --file spec.json live-mutate a RUNNING board (or --title/--intro/-q); page reloads
55
+ rly stop <id> | --all stop running board(s) (status: cancelled, draft preserved)
56
+ rly history [--limit n] [--json] saved boards
57
+ rly spec <id> print a saved board's spec JSON (edit, then ask --file again)
58
+ rly rm <id> | --all delete saved board(s)
59
+ rly schema JSON Schema of the board spec
60
+ rly agent FULL GUIDE for AI agents (spec format, blocks, sizing, patterns)
61
+ rly a2ui A2UI widget blocks: Express grammar, components, examples
62
+ rly skill [install|rules|path] bundled universal agent skill (Claude Code, Codex, …)
63
+ \`rly skill rules >> CLAUDE.md\` adds always-read usage rules
64
+ rly install --target <agent> inject relay's rules into an agent's instruction file
65
+ claude codex cursor copilot kiro windsurf cline gemini opencode droid agents
66
+ --scope global|project · --print (copy/paste) · --all · --list (no flags)
67
+ rly upgrade install the latest CLI globally + refresh the skill in one step
68
+ --stop/--force handle running boards · --dry-run · --cli-only/--skill-only
69
+ rly mcp run relay as an MCP App server (stdio) — boards render INLINE in
70
+ a local desktop host (Claude Desktop, Codex) instead of a browser tab
71
+ rly mcp --http [--port N] serve over Streamable HTTP for web/mobile/remote hosts
72
+ [--host H --token SECRET --allow-origin ORIGIN]
73
+ rly mcp config | install --target print host setup, or write it (claude | codex)
74
+
75
+ COMMON FLAGS
76
+ --title <s> --intro <s> --html-file <f> --height <px> --submit-label <s>
77
+ --timeout <sec> (default 86400; 0 = none) --port <n> --no-open --detach --display-only
78
+ --devlink | --no-devlink | --public-url <url> where the board link points (see rly config link)
79
+
80
+ EXIT CODES 0 submitted/acknowledged · 2 timeout · 3 cancelled · 4 usage · 5 not found
81
+
82
+ NOTES detached boards keep serving after timeout until Submit or stop;
83
+ answers & annotations autosave in real time (drafts survive timeout/cancel);
84
+ submitting auto-closes the tab and unblocks the CLI.
85
+
86
+ AI AGENTS run \`rly agent\` for the complete machine-oriented guide.
87
+ a universal skill is bundled — install with \`rly skill install\`
88
+ (or from the repo: npx skills add khanglvm/relay --skill relay --all)`);
89
+ return 0;
90
+ }
@@ -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
+ }
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 devlink 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
+ }