@khanglvm/relay 0.19.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 (131) hide show
  1. package/bin/rly.js +1 -1
  2. package/package.json +4 -4
  3. package/src/cli/args.js +46 -0
  4. package/src/cli/ask.js +12 -0
  5. package/src/cli/boards.js +326 -0
  6. package/src/cli/config.js +56 -0
  7. package/src/cli/context.js +13 -0
  8. package/src/cli/git.js +183 -0
  9. package/src/cli/help.js +90 -0
  10. package/src/cli/index.js +103 -0
  11. package/src/cli/install.js +197 -0
  12. package/src/cli/io.js +186 -0
  13. package/src/cli/mcp.js +94 -0
  14. package/src/cli/share.js +45 -0
  15. package/src/cli/skill.js +192 -0
  16. package/src/cli/upgrade.js +130 -0
  17. package/src/cli/wait.js +172 -0
  18. package/src/file-preview.js +1 -1
  19. package/src/index.js +1 -1
  20. package/src/mcp-ui/board/block-ctx.js +43 -0
  21. package/src/mcp-ui/board/bridge.js +165 -0
  22. package/src/mcp-ui/board/controls.js +310 -0
  23. package/src/mcp-ui/board/core.js +20 -0
  24. package/src/mcp-ui/board/lifecycle.js +118 -0
  25. package/src/mcp-ui/board/normalize.js +95 -0
  26. package/src/mcp-ui/board/render.js +200 -0
  27. package/src/mcp-ui/board/state.js +106 -0
  28. package/src/mcp-ui/board/vendors.js +86 -0
  29. package/src/mcp.js +12 -18
  30. package/src/{server.js → server/board.js} +15 -778
  31. package/src/server/files.js +141 -0
  32. package/src/server/http.js +114 -0
  33. package/src/server/index.js +2 -0
  34. package/src/server/page.js +183 -0
  35. package/src/server/paths.js +7 -0
  36. package/src/server/result.js +58 -0
  37. package/src/server/reviews.js +41 -0
  38. package/src/server/sanitize.js +231 -0
  39. package/src/spec/blocks/a2ui.js +25 -0
  40. package/src/spec/blocks/chart.js +49 -0
  41. package/src/spec/blocks/code.js +38 -0
  42. package/src/spec/blocks/diagram.js +39 -0
  43. package/src/spec/blocks/git-conflict.js +106 -0
  44. package/src/spec/blocks/image.js +32 -0
  45. package/src/spec/blocks/index.js +33 -0
  46. package/src/spec/blocks/markdown.js +13 -0
  47. package/src/spec/blocks/pdf.js +38 -0
  48. package/src/spec/blocks/table.js +122 -0
  49. package/src/spec/blocks/video.js +68 -0
  50. package/src/spec/blocks/widgets.js +98 -0
  51. package/src/spec/constants.js +65 -0
  52. package/src/spec/index.js +5 -0
  53. package/src/spec/normalize.js +285 -0
  54. package/src/spec/ready.js +106 -0
  55. package/src/spec/schema.js +182 -0
  56. package/src/spec/sources.js +83 -0
  57. package/src/ui/annotate/api.js +149 -0
  58. package/src/ui/annotate/badges.js +77 -0
  59. package/src/ui/annotate/chrome.js +158 -0
  60. package/src/ui/annotate/core.js +134 -0
  61. package/src/ui/annotate/highlights.js +129 -0
  62. package/src/ui/annotate/mutations.js +127 -0
  63. package/src/ui/annotate/popover.js +206 -0
  64. package/src/ui/annotate/summary.js +67 -0
  65. package/src/ui/app/annotations.js +88 -0
  66. package/src/ui/app/autosave.js +44 -0
  67. package/src/ui/app/core.js +74 -0
  68. package/src/ui/app/drafts.js +201 -0
  69. package/src/ui/app/heartbeat.js +150 -0
  70. package/src/ui/app/iframe-bridge.js +64 -0
  71. package/src/ui/app/persistence.js +117 -0
  72. package/src/ui/app/prefilled.js +21 -0
  73. package/src/ui/app/presence.js +38 -0
  74. package/src/ui/app/question-color.js +67 -0
  75. package/src/ui/app/questions.js +360 -0
  76. package/src/ui/app/render.js +135 -0
  77. package/src/ui/app/share.js +108 -0
  78. package/src/ui/app/submit.js +109 -0
  79. package/src/ui/app/theme.js +63 -0
  80. package/src/ui/blocks/api.js +1 -0
  81. package/src/ui/blocks/chart.js +222 -0
  82. package/src/ui/blocks/code.js +138 -0
  83. package/src/ui/blocks/compare.js +82 -0
  84. package/src/ui/blocks/core.js +74 -0
  85. package/src/ui/blocks/diff.js +361 -0
  86. package/src/ui/blocks/dispatch.js +111 -0
  87. package/src/ui/blocks/file-links.js +180 -0
  88. package/src/ui/blocks/git-conflict.js +151 -0
  89. package/src/ui/blocks/graphviz.js +57 -0
  90. package/src/ui/blocks/html.js +45 -0
  91. package/src/ui/blocks/image.js +371 -0
  92. package/src/ui/blocks/kpi.js +26 -0
  93. package/src/ui/blocks/markdown.js +223 -0
  94. package/src/ui/blocks/mermaid.js +242 -0
  95. package/src/ui/blocks/palette.js +59 -0
  96. package/src/ui/blocks/pdf.js +21 -0
  97. package/src/ui/blocks/plantuml.js +152 -0
  98. package/src/ui/blocks/table.js +155 -0
  99. package/src/ui/blocks/typography.js +25 -0
  100. package/src/ui/blocks/vendor.js +43 -0
  101. package/src/ui/blocks/video.js +43 -0
  102. package/src/ui/blocks/viewer-fullscreen.js +146 -0
  103. package/src/ui/blocks/viewer.js +324 -0
  104. package/src/ui/kit.js +1 -0
  105. package/src/ui/manifest.js +140 -0
  106. package/types/index.d.ts +1 -1
  107. package/types/spec/blocks/a2ui.d.ts +4 -0
  108. package/types/spec/blocks/chart.d.ts +4 -0
  109. package/types/spec/blocks/code.d.ts +10 -0
  110. package/types/spec/blocks/diagram.d.ts +15 -0
  111. package/types/spec/blocks/git-conflict.d.ts +7 -0
  112. package/types/spec/blocks/image.d.ts +5 -0
  113. package/types/spec/blocks/index.d.ts +30 -0
  114. package/types/spec/blocks/markdown.d.ts +5 -0
  115. package/types/spec/blocks/pdf.d.ts +4 -0
  116. package/types/spec/blocks/table.d.ts +9 -0
  117. package/types/spec/blocks/video.d.ts +4 -0
  118. package/types/spec/blocks/widgets.d.ts +21 -0
  119. package/types/spec/constants.d.ts +67 -0
  120. package/types/spec/index.d.ts +4 -0
  121. package/types/spec/normalize.d.ts +17 -0
  122. package/types/spec/ready.d.ts +1 -0
  123. package/types/{spec.d.ts → spec/schema.d.ts} +0 -20
  124. package/types/spec/sources.d.ts +14 -0
  125. package/types/ui/manifest.d.ts +62 -0
  126. package/src/cli.js +0 -1767
  127. package/src/mcp-ui/board.js +0 -1162
  128. package/src/spec.js +0 -1224
  129. package/src/ui/annotate.js +0 -1055
  130. package/src/ui/app.js +0 -1643
  131. package/src/ui/blocks.js +0 -3260
@@ -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
+ }
@@ -0,0 +1,172 @@
1
+ // rly wait and rly result: block for a board's answer, or read it.
2
+ import { controlUrl, isAlive, loadBoard, loadRunning } from '../store.js';
3
+ import { CliError, sleep } from '../util.js';
4
+ import { DEFAULT_WAIT_TIMEOUT_SEC } from './context.js';
5
+ import { exitCodeFor, mustLoad, printJson, printResult, runNotifyCmd } from './io.js';
6
+
7
+ // Best-effort fetch of /api/presence for a running board. Returns the parsed
8
+ // presence object, or null on any failure / timeout (500ms cap via
9
+ // AbortController). Never throws.
10
+ async function fetchPresence(url) {
11
+ if (!url) return null;
12
+ const controller = new AbortController();
13
+ const timer = setTimeout(() => controller.abort(), 500);
14
+ try {
15
+ const res = await fetch(new URL('/api/presence', url), { signal: controller.signal });
16
+ if (!res.ok) return null;
17
+ return await res.json();
18
+ } catch {
19
+ return null;
20
+ } finally {
21
+ clearTimeout(timer);
22
+ }
23
+ }
24
+
25
+ export async function cmdWait(args) {
26
+ const id = args._[0];
27
+ if (!id) throw new CliError('usage: rly wait <board-id> [--timeout <sec>] [--while-active] [--idle-grace <sec>] [--notify-cmd <cmd>]');
28
+ const timeoutSec = args.timeout !== undefined ? Math.max(0, Number.parseInt(args.timeout, 10) || 0) : DEFAULT_WAIT_TIMEOUT_SEC;
29
+ const whileActive = args.whileActive === true;
30
+ const idleGrace = args.idleGrace !== undefined ? Math.max(0, Number.parseInt(args.idleGrace, 10) || 0) : 180;
31
+ const notifyCmd = typeof args.notifyCmd === 'string' && args.notifyCmd.trim() ? args.notifyCmd : null;
32
+ let deadline = timeoutSec === 0 ? Number.POSITIVE_INFINITY : Date.now() + timeoutSec * 1000;
33
+ mustLoad(id);
34
+
35
+ // Push-wake: run the agent's --notify-cmd after a TERMINAL result, then print.
36
+ const finishResult = (result) => {
37
+ if (notifyCmd) runNotifyCmd(notifyCmd, result);
38
+ printResult(result);
39
+ return exitCodeFor(result.status);
40
+ };
41
+
42
+ while (Date.now() < deadline) {
43
+ const record = mustLoad(id);
44
+ if (record.result && record.result.finishedAt) {
45
+ return finishResult(record.result);
46
+ }
47
+ const running = loadRunning(id);
48
+ if (!running || !isAlive(running.pid)) {
49
+ await sleep(700); // the result write may be racing the process exit
50
+ const again = loadBoard(id);
51
+ if (again?.result?.finishedAt) {
52
+ return finishResult(again.result);
53
+ }
54
+ printResult({
55
+ status: 'lost',
56
+ boardId: id,
57
+ draft: again?.draft ?? null,
58
+ error: 'board server exited without writing a result',
59
+ });
60
+ return 5;
61
+ }
62
+ if (Date.now() >= deadline) break;
63
+ await sleep(400);
64
+ }
65
+
66
+ // Deadline hit while the board is still OPEN. Fetch presence (cheaply).
67
+ const running = loadRunning(id);
68
+ const presence = running && isAlive(running.pid) ? await fetchPresence(controlUrl(running)) : null;
69
+
70
+ // --while-active: if the user is present + recently active, EXTEND and keep
71
+ // waiting (repeat indefinitely while they stay active).
72
+ if (
73
+ whileActive &&
74
+ presence &&
75
+ presence.seen &&
76
+ (presence.visible || presence.focused) &&
77
+ presence.secondsSinceActivity < idleGrace
78
+ ) {
79
+ deadline = Date.now() + Math.min(idleGrace, 120) * 1000;
80
+ return cmdWaitLoop(id, deadline, { whileActive, idleGrace, notifyCmd });
81
+ }
82
+
83
+ const out = {
84
+ status: 'wait-timeout',
85
+ boardId: id,
86
+ hint: `board is still open — run \`rly wait ${id}\` again, or \`rly result ${id}\` to peek at the live draft`,
87
+ };
88
+ if (presence) out.presence = presence;
89
+ printJson(out);
90
+ return 2;
91
+ }
92
+
93
+ // Continuation loop for `rly wait --while-active` after a deadline extension.
94
+ // Identical waiting logic to cmdWait's main loop, then re-evaluates presence;
95
+ // extends again while the user stays active, otherwise emits wait-timeout.
96
+ async function cmdWaitLoop(id, deadline, opts) {
97
+ const { whileActive, idleGrace, notifyCmd } = opts;
98
+ const finishResult = (result) => {
99
+ if (notifyCmd) runNotifyCmd(notifyCmd, result);
100
+ printResult(result);
101
+ return exitCodeFor(result.status);
102
+ };
103
+ while (Date.now() < deadline) {
104
+ const record = mustLoad(id);
105
+ if (record.result && record.result.finishedAt) {
106
+ return finishResult(record.result);
107
+ }
108
+ const running = loadRunning(id);
109
+ if (!running || !isAlive(running.pid)) {
110
+ await sleep(700);
111
+ const again = loadBoard(id);
112
+ if (again?.result?.finishedAt) {
113
+ return finishResult(again.result);
114
+ }
115
+ printResult({
116
+ status: 'lost',
117
+ boardId: id,
118
+ draft: again?.draft ?? null,
119
+ error: 'board server exited without writing a result',
120
+ });
121
+ return 5;
122
+ }
123
+ if (Date.now() >= deadline) break;
124
+ await sleep(400);
125
+ }
126
+ const running = loadRunning(id);
127
+ const presence = running && isAlive(running.pid) ? await fetchPresence(controlUrl(running)) : null;
128
+ if (
129
+ whileActive &&
130
+ presence &&
131
+ presence.seen &&
132
+ (presence.visible || presence.focused) &&
133
+ presence.secondsSinceActivity < idleGrace
134
+ ) {
135
+ const next = Date.now() + Math.min(idleGrace, 120) * 1000;
136
+ return cmdWaitLoop(id, next, opts);
137
+ }
138
+ const out = {
139
+ status: 'wait-timeout',
140
+ boardId: id,
141
+ hint: `board is still open — run \`rly wait ${id}\` again, or \`rly result ${id}\` to peek at the live draft`,
142
+ };
143
+ if (presence) out.presence = presence;
144
+ printJson(out);
145
+ return 2;
146
+ }
147
+
148
+ export async function cmdResult(args) {
149
+ const record = mustLoad(args._[0]);
150
+ const sideReviews = {
151
+ referenceOnly: true,
152
+ note: 'Side reviews are reference only. Wait for the board owner (or owner-authorized collaborator) to submit the final answer.',
153
+ submissions: Array.isArray(record.sideReviews) ? record.sideReviews : [],
154
+ drafts: record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {},
155
+ };
156
+ if (record.result && record.result.finishedAt) {
157
+ printResult({ ...record.result, sideReviews });
158
+ return exitCodeFor(record.result.status);
159
+ }
160
+ const running = loadRunning(record.id);
161
+ if (running && isAlive(running.pid)) {
162
+ // While open, expose the real-time autosaved draft so agents can peek, plus
163
+ // best-effort presence (whether the user is still viewing/focused/active).
164
+ const out = { status: 'open', boardId: record.id, url: running.url, draft: record.draft ?? null, sideReviews };
165
+ const presence = await fetchPresence(controlUrl(running));
166
+ if (presence) out.presence = presence;
167
+ printResult(out); // draft can hold many annotations — sidecar it too
168
+ return 0;
169
+ }
170
+ printResult({ status: 'lost', boardId: record.id, draft: record.draft ?? null, sideReviews });
171
+ return 5;
172
+ }
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { normalizeSpec } from './spec.js';
3
+ import { normalizeSpec } from './spec/index.js';
4
4
 
5
5
  const TEXT_LIMIT = 1024 * 1024;
6
6
  const MEDIA = {
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Public library entry (`import ... from '@khanglvm/relay'`). It exposes the
2
2
  // spec checks and the board store without starting a server or a browser.
3
3
  import { compileExpress, validateSurface } from './a2ui/compile.js';
4
- import { normalizeSpec } from './spec.js';
4
+ import { normalizeSpec } from './spec/index.js';
5
5
  import { createBoard as storeBoard } from './store.js';
6
6
 
7
7
  /**
@@ -0,0 +1,43 @@
1
+ function blockCtx(questionId) {
2
+ return {
3
+ theme: effectiveTheme,
4
+ htmlSrc: (blockId) => htmlBlobSrc(blockId),
5
+ questionId: questionId == null ? null : questionId,
6
+ // No annotation during the streaming preview (it re-renders); on the final
7
+ // interactive render, wire the engine so blocks register their targets.
8
+ annotate: composing || (spec && spec.responseRequired === false) ? null : Annotate,
9
+ canComment: Boolean(spec && spec.responseRequired !== false),
10
+ saveArtifact: async ({ dataUrl, mime, width, height }) => {
11
+ const comma = typeof dataUrl === 'string' ? dataUrl.indexOf(',') : -1;
12
+ if (comma < 0) throw new Error('invalid image crop');
13
+ return { data: dataUrl.slice(comma + 1), mime: mime || 'image/png', width, height };
14
+ },
15
+ edits: state.blockEdits,
16
+ onBlockEdit: (blockId, codeOrNull) => {
17
+ if (codeOrNull === null || codeOrNull === undefined) delete state.blockEdits[blockId];
18
+ else state.blockEdits[blockId] = codeOrNull;
19
+ },
20
+ };
21
+ }
22
+ document.addEventListener('relay:block-edit', (e) => {
23
+ const d = e.detail || {};
24
+ if (!d.blockId) return;
25
+ if (d.value === null || d.value === undefined) delete state.blockEdits[d.blockId];
26
+ else state.blockEdits[d.blockId] = d.value;
27
+ });
28
+ function renderBlocks(container, blocks, questionId) {
29
+ if (!Array.isArray(blocks) || !blocks.length) return;
30
+ const target = el('div', { class: 'blocks' });
31
+ container.append(target);
32
+ if (!window.RelayBlocks) {
33
+ target.append(el('div', { class: 'blk' }, el('div', { class: 'blk-error' }, 'block failed to render')));
34
+ return;
35
+ }
36
+ Promise.resolve()
37
+ .then(() => window.RelayBlocks.render(target, blocks, blockCtx(questionId)))
38
+ .then(reportSize)
39
+ .catch(() => {
40
+ target.append(el('div', { class: 'blk' }, el('div', { class: 'blk-error' }, 'block failed to render')));
41
+ });
42
+ }
43
+