@khanglvm/relay 0.21.0 → 0.22.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 (89) hide show
  1. package/docs/AGENT.md +14 -2
  2. package/package.json +6 -1
  3. package/schema/spec.v1.json +55 -3
  4. package/skills/relay/SKILL.md +2 -1
  5. package/src/a2ui/board-catalog.json +1004 -0
  6. package/src/a2ui/board-constants.js +35 -0
  7. package/src/a2ui/board.js +5 -0
  8. package/src/a2ui/from-a2ui.js +71 -0
  9. package/src/a2ui/negotiate.js +38 -0
  10. package/src/a2ui/to-a2ui.js +147 -0
  11. package/src/cli/args.js +4 -2
  12. package/src/cli/ask.js +4 -3
  13. package/src/cli/boards.js +10 -7
  14. package/src/cli/git.js +5 -3
  15. package/src/cli/help.js +3 -1
  16. package/src/cli/io.js +21 -0
  17. package/src/cli/mcp.js +31 -2
  18. package/src/file-access.js +117 -0
  19. package/src/file-preview.js +1 -1
  20. package/src/mcp/boards.js +30 -7
  21. package/src/mcp/constants.js +3 -1
  22. package/src/mcp/schemas.js +5 -2
  23. package/src/mcp/serve.js +4 -4
  24. package/src/mcp/server.js +2 -1
  25. package/src/mcp/store.js +2 -2
  26. package/src/mcp/token.js +33 -8
  27. package/src/mcp/tools.js +16 -7
  28. package/src/mcp-ui/board/normalize.js +12 -0
  29. package/src/mcp-ui/board/render.js +2 -1
  30. package/src/mcp-ui/board/state.js +3 -0
  31. package/src/server/board.js +30 -22
  32. package/src/server/files.js +10 -0
  33. package/src/server/http.js +19 -0
  34. package/src/server/page.js +4 -0
  35. package/src/spec/blocks/a2ui.js +1 -1
  36. package/src/spec/blocks/chart.js +1 -1
  37. package/src/spec/blocks/code.js +4 -4
  38. package/src/spec/blocks/diagram.js +3 -3
  39. package/src/spec/blocks/git-conflict.js +2 -2
  40. package/src/spec/blocks/image.js +6 -5
  41. package/src/spec/blocks/markdown.js +2 -2
  42. package/src/spec/blocks/pdf.js +4 -10
  43. package/src/spec/blocks/table.js +5 -4
  44. package/src/spec/blocks/video.js +4 -10
  45. package/src/spec/blocks/widgets.js +6 -6
  46. package/src/spec/constants.js +13 -1
  47. package/src/spec/index.js +1 -0
  48. package/src/spec/lookup.js +1 -0
  49. package/src/spec/normalize.js +20 -10
  50. package/src/spec/pick.js +104 -0
  51. package/src/spec/schema.js +26 -3
  52. package/src/spec/sources.js +19 -24
  53. package/src/store.js +6 -1
  54. package/src/ui/app/drafts.js +3 -0
  55. package/src/ui/app/render.js +1 -0
  56. package/src/ui/app/submit.js +1 -1
  57. package/src/ui/manifest.js +2 -1
  58. package/src/ui/pick.css +32 -0
  59. package/src/ui/pick.js +246 -0
  60. package/types/a2ui/board-constants.d.ts +24 -0
  61. package/types/a2ui/from-a2ui.d.ts +16 -0
  62. package/types/a2ui/negotiate.d.ts +17 -0
  63. package/types/a2ui/to-a2ui.d.ts +12 -0
  64. package/types/file-access.d.ts +62 -0
  65. package/types/mcp/boards.d.ts +13 -2
  66. package/types/mcp/schemas.d.ts +5 -2
  67. package/types/mcp/serve.d.ts +5 -2
  68. package/types/mcp/store.d.ts +6 -3
  69. package/types/mcp/token.d.ts +5 -1
  70. package/types/mcp/tools.d.ts +2 -0
  71. package/types/spec/blocks/a2ui.d.ts +1 -1
  72. package/types/spec/blocks/chart.d.ts +1 -1
  73. package/types/spec/blocks/code.d.ts +2 -2
  74. package/types/spec/blocks/diagram.d.ts +3 -3
  75. package/types/spec/blocks/git-conflict.d.ts +1 -1
  76. package/types/spec/blocks/image.d.ts +2 -2
  77. package/types/spec/blocks/markdown.d.ts +1 -1
  78. package/types/spec/blocks/pdf.d.ts +1 -1
  79. package/types/spec/blocks/table.d.ts +1 -1
  80. package/types/spec/blocks/video.d.ts +1 -1
  81. package/types/spec/blocks/widgets.d.ts +4 -4
  82. package/types/spec/constants.d.ts +9 -0
  83. package/types/spec/index.d.ts +1 -0
  84. package/types/spec/lookup.d.ts +2 -1
  85. package/types/spec/normalize.d.ts +7 -1
  86. package/types/spec/pick.d.ts +25 -0
  87. package/types/spec/schema.d.ts +48 -0
  88. package/types/spec/sources.d.ts +5 -4
  89. package/types/store.d.ts +8 -1
@@ -0,0 +1,35 @@
1
+ // Names the A2UI board surface and its negotiation share, in one place. The MIME
2
+ // strings and the action tool name come from a2ui.org's "A2UI over MCP" guide, which
3
+ // the package source does not confirm and one secondary source spells differently,
4
+ // so both MIME spellings are accepted and nothing else in Relay repeats them.
5
+
6
+ /** Relay's own id for the board catalog; a renderer lists it in `supportedCatalogIds`. */
7
+ export const BOARD_CATALOG_ID = 'https://github.com/khanglvm/relay/a2ui/catalog/board/v1';
8
+ export const A2UI_PROTOCOL_VERSION = '1.0';
9
+
10
+ /** The MIME a surface is sent as, then the other spelling a host may declare it under. */
11
+ export const A2UI_MIME = 'application/a2ui+json';
12
+ export const A2UI_MIMES = [A2UI_MIME, 'application/json+a2ui'];
13
+
14
+ /** The tool a host calls with a renderer event. */
15
+ export const A2UI_ACTION_TOOL = 'a2ui_action';
16
+ export const ACTION_SUBMIT = 'relay.submit';
17
+ export const ACTION_DRAFT = 'relay.draft';
18
+
19
+ /** Where the person's input lives in the surface's data model. */
20
+ export const DATA_ROOT = {
21
+ answers: 'answers',
22
+ notes: 'notes',
23
+ comment: 'comment',
24
+ annotations: 'annotations',
25
+ blockEdits: 'blockEdits',
26
+ };
27
+
28
+ /** Ids that would reach Object.prototype if used as a data-model key. */
29
+ export const UNSAFE_KEYS = ['__proto__', 'constructor', 'prototype'];
30
+
31
+ /** Escapes one data-model path segment (RFC 6901). */
32
+ export const pointerSegment = (key) => String(key).replace(/~/g, '~0').replace(/\//g, '~1');
33
+
34
+ /** The data-model pointer for one entry under a root: `/answers/q1`. */
35
+ export const dataPath = (root, key) => `/${DATA_ROOT[root]}/${pointerSegment(key)}`;
@@ -0,0 +1,5 @@
1
+ // The public board-catalog entry (@khanglvm/relay/a2ui-board): a Relay board as A2UI messages and back.
2
+ export { A2UI_MIME, A2UI_MIMES, BOARD_CATALOG_ID } from './board-constants.js';
3
+ export { declaresBoardCatalog, wantsA2ui } from './negotiate.js';
4
+ export { fromA2ui } from './from-a2ui.js';
5
+ export { toA2ui } from './to-a2ui.js';
@@ -0,0 +1,71 @@
1
+ // fromA2ui: the data model a renderer sends back, as the payload a board submit takes.
2
+ // It applies the same "was this answered" rules the web board does, so both surfaces
3
+ // produce one result for one set of answers. It is pure: the caller stores the result.
4
+ import { cleanPick } from '../spec/pick.js';
5
+ import { DATA_ROOT } from './board-constants.js';
6
+
7
+ const NOTE_MAX = 20000;
8
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
9
+ const own = (obj, key) => (isObject(obj) && Object.hasOwn(obj, key) ? obj[key] : undefined);
10
+ const text = (v) => (typeof v === 'string' ? v.trim() : '');
11
+
12
+ /** The value to submit for one answer, or undefined while the question counts as unanswered. */
13
+ export function answeredValue(q, raw) {
14
+ switch (q.type) {
15
+ case 'single': return typeof raw === 'string' && raw ? raw : undefined;
16
+ case 'multi': {
17
+ const picked = Array.isArray(raw) ? raw.filter((v) => typeof v === 'string' && v) : [];
18
+ return picked.length ? picked : undefined;
19
+ }
20
+ case 'yesno': return raw === 'yes' || raw === 'no' ? raw : undefined;
21
+ case 'scale': return typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined;
22
+ case 'rank': return Array.isArray(raw) && raw.length ? [...raw] : undefined;
23
+ case 'checklist': return isObject(raw) && Object.keys(raw).length ? { ...raw } : undefined;
24
+ case 'allocate': {
25
+ const sum = isObject(raw) ? Object.values(raw).reduce((a, n) => a + (Number(n) || 0), 0) : 0;
26
+ return sum > 0 ? { ...raw } : undefined;
27
+ }
28
+ case 'pick': return cleanPick(q, raw);
29
+ default: return text(raw) || undefined;
30
+ }
31
+ }
32
+
33
+ /** Block comments (`/annotations/<blockId>`: text) as the annotation records a result carries. */
34
+ function blockAnnotations(spec, raw, now) {
35
+ const owner = new Map();
36
+ for (const q of spec.questions) for (const b of q.blocks || []) owner.set(b.id, q.id);
37
+ const known = new Set([...owner.keys(), ...(spec.blocks || []).map((b) => b.id)]);
38
+ return Object.keys(isObject(raw) ? raw : {})
39
+ .filter((blockId) => known.has(blockId) && text(raw[blockId]))
40
+ .map((blockId) => ({
41
+ id: `a2ui-${blockId}`, questionId: owner.get(blockId) ?? null, blockId,
42
+ target: { kind: 'block' }, text: text(raw[blockId]).slice(0, 5000), createdAt: now,
43
+ }));
44
+ }
45
+
46
+ /**
47
+ * @param {Record<string, any>} dataModel the surface's data model: /answers, /notes, /comment, /annotations, /blockEdits
48
+ * @param {Record<string, any>} spec the normalized spec the surface was made from
49
+ * @returns {{ answers: Record<string, unknown>, comment: string, notes: Record<string, string>, annotations: object[], blockEdits: Record<string, unknown> }}
50
+ */
51
+ export function fromA2ui(dataModel, spec, { now = new Date().toISOString() } = {}) {
52
+ const model = isObject(dataModel) ? dataModel : {};
53
+ const rawAnswers = model[DATA_ROOT.answers];
54
+ const rawNotes = model[DATA_ROOT.notes];
55
+ const answers = {};
56
+ const notes = {};
57
+ for (const q of spec.questions) {
58
+ const value = answeredValue(q, own(rawAnswers, q.id));
59
+ if (value !== undefined) answers[q.id] = value;
60
+ const note = text(own(rawNotes, q.id));
61
+ if (note) notes[q.id] = note.slice(0, NOTE_MAX);
62
+ }
63
+ const edits = model[DATA_ROOT.blockEdits];
64
+ return {
65
+ answers,
66
+ comment: text(model[DATA_ROOT.comment]).slice(0, NOTE_MAX),
67
+ notes,
68
+ annotations: blockAnnotations(spec, model[DATA_ROOT.annotations], now),
69
+ blockEdits: isObject(edits) ? edits : {},
70
+ };
71
+ }
@@ -0,0 +1,38 @@
1
+ // Decides whether a caller can draw the board catalog, from what it declared.
2
+ import { A2UI_MIMES, A2UI_PROTOCOL_VERSION, BOARD_CATALOG_ID } from './board-constants.js';
3
+
4
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
5
+
6
+ /** The a2ui declaration inside client capabilities: top-level, or under `extensions` or `experimental`. */
7
+ function declared(capabilities) {
8
+ if (!isObject(capabilities)) return undefined;
9
+ const nested = (key) => (isObject(capabilities[key]) ? capabilities[key].a2ui : undefined);
10
+ return capabilities.a2ui ?? nested('extensions') ?? nested('experimental');
11
+ }
12
+
13
+ /** True when the client declared the board catalog when it connected. */
14
+ export const capabilitiesDeclareBoardCatalog = (capabilities) => declaresBoardCatalog(declared(capabilities));
15
+
16
+ /**
17
+ * True when a declaration lists the board catalog for protocol 1.0:
18
+ * `{"1.0": {supportedCatalogIds: [...]}}`. A declaration that names the MIME
19
+ * types it accepts must include one Relay sends.
20
+ */
21
+ export function declaresBoardCatalog(declaration) {
22
+ if (!isObject(declaration)) return false;
23
+ const version = declaration[A2UI_PROTOCOL_VERSION];
24
+ if (!isObject(version) || !Array.isArray(version.supportedCatalogIds)) return false;
25
+ if (!version.supportedCatalogIds.includes(BOARD_CATALOG_ID)) return false;
26
+ const mimes = declaration.mimeTypes ?? version.mimeTypes;
27
+ return !Array.isArray(mimes) || mimes.some((m) => A2UI_MIMES.includes(m));
28
+ }
29
+
30
+ /**
31
+ * Whether a call should get A2UI messages: the call's own `_meta.a2ui` decides first,
32
+ * then the capabilities the client declared when it connected.
33
+ * @param {{ capabilities?: any, meta?: any }} caller
34
+ */
35
+ export function wantsA2ui({ capabilities, meta }) {
36
+ if (isObject(meta) && 'a2ui' in meta) return declaresBoardCatalog(meta.a2ui);
37
+ return capabilitiesDeclareBoardCatalog(capabilities);
38
+ }
@@ -0,0 +1,147 @@
1
+ // toA2ui: a normalized board spec as the A2UI v1.0 messages that draw it on the board catalog
2
+ // (board-catalog.json). It is pure: the host renders, and answers come back through fromA2ui.
3
+ import { CliError } from '../util.js';
4
+ import {
5
+ A2UI_PROTOCOL_VERSION, ACTION_SUBMIT, BOARD_CATALOG_ID, DATA_ROOT, dataPath, UNSAFE_KEYS,
6
+ } from './board-constants.js';
7
+
8
+ const COMPONENT_OF = {
9
+ markdown: 'Markdown', chart: 'Chart', table: 'Table', code: 'Code', diff: 'Diff', mermaid: 'Mermaid',
10
+ graphviz: 'Graphviz', plantuml: 'Plantuml', image: 'Image', compare: 'Compare', html: 'Html',
11
+ palette: 'Palette', kpi: 'Kpi', typography: 'Typography', video: 'Video', pdf: 'Pdf',
12
+ 'git-conflict': 'GitConflict', a2ui: 'Widget',
13
+ };
14
+
15
+ const FALLBACK_CHARS = 2000;
16
+ const clip = (s, max = FALLBACK_CHARS) => (typeof s === 'string' && s.length > max ? `${s.slice(0, max)}…` : String(s ?? ''));
17
+
18
+ /** The plain text a renderer shows for a block it cannot draw. */
19
+ export function fallbackText(block) {
20
+ switch (block.type) {
21
+ case 'markdown': return clip(block.md);
22
+ case 'chart': return clip(`Chart${block.title ? `: ${block.title}` : ''}${block.kind ? ` (${block.kind})` : ''}${Array.isArray(block.labels) ? `. ${block.labels.join(', ')}` : ''}`);
23
+ case 'table': return clip(`Table with ${Array.isArray(block.rows) ? block.rows.length : 0} rows. Columns: ${(block.columns || []).map((c) => (typeof c === 'string' ? c : c.label ?? c.key)).join(', ')}`);
24
+ case 'code': case 'mermaid': case 'plantuml': return clip(block.code);
25
+ case 'graphviz': return clip(block.dot);
26
+ case 'diff': return clip(block.diff);
27
+ case 'image': return clip(block.alt || block.src);
28
+ case 'compare': return clip(`${block.beforeLabel || 'Before'} and ${block.afterLabel || 'After'}`);
29
+ case 'html': return 'Custom page. Open the full board to see it.';
30
+ case 'video': return clip(block.title || `${block.provider} video ${block.videoId}`);
31
+ case 'pdf': return clip(block.title || block.src);
32
+ case 'kpi': return clip((block.items || []).map((i) => `${i.label}: ${i.value}`).join('; '));
33
+ case 'git-conflict': return clip(block.filename || 'A file with merge conflicts');
34
+ case 'a2ui': return clip(block.title || 'Widget');
35
+ default: return clip(block.title || block.type);
36
+ }
37
+ }
38
+
39
+ /** Maps block and question ids to unique component ids that fit the A2UI id rules. */
40
+ function idMaker() {
41
+ const used = new Set(['root', 'comment', 'submit']);
42
+ return (prefix, raw) => {
43
+ // A2UI component ids are UAX #31 identifiers: letters, digits and underscores.
44
+ const base = `${prefix}_${String(raw).replace(/[^A-Za-z0-9_]/g, '_')}`.slice(0, 60);
45
+ let id = base;
46
+ for (let n = 2; used.has(id); n++) id = `${base}_${n}`;
47
+ used.add(id);
48
+ return id;
49
+ };
50
+ }
51
+
52
+ function blockComponent(block, id, extra = {}) {
53
+ const { id: _id, type, a2uiSurface, components, dataModel, express, ...fields } = block;
54
+ const out = { id, component: COMPONENT_OF[type], ...fields, text: fallbackText(block), ...extra };
55
+ if (type === 'a2ui') {
56
+ out.widgetComponents = components ?? [];
57
+ if (dataModel) out.widgetData = dataModel;
58
+ }
59
+ if (!out.title && type !== 'markdown') out.title = block.title ?? block.filename ?? block.type;
60
+ return out;
61
+ }
62
+
63
+ function questionComponent(q, id, childIds) {
64
+ const { id: questionId, type, label, blocks, html, htmlFile, htmlHeight, note, ...rest } = q;
65
+ return {
66
+ id, component: 'Question', questionId, questionType: type, label, ...rest,
67
+ hasNote: note === true,
68
+ text: clip(label),
69
+ value: { '@path': dataPath('answers', questionId) },
70
+ note: { '@path': dataPath('notes', questionId) },
71
+ ...(childIds.length ? { children: childIds } : {}),
72
+ };
73
+ }
74
+
75
+ /** Questions are keyed in the data model by their ids, so the ones that could reach the prototype are refused. */
76
+ function assertSafeIds(spec) {
77
+ const bad = spec.questions.find((q) => UNSAFE_KEYS.includes(q.id));
78
+ if (bad) throw new CliError(`question id "${bad.id}" cannot be sent as A2UI; use another id.`);
79
+ }
80
+
81
+ /** The data model a surface starts with: defaults, then the saved draft. */
82
+ function initialData(spec, draft) {
83
+ const answers = new Map();
84
+ for (const q of spec.questions) if (q.default !== undefined) answers.set(q.id, q.default);
85
+ const saved = draft && typeof draft === 'object' ? draft : {};
86
+ if (saved.answers && typeof saved.answers === 'object') for (const [k, v] of Object.entries(saved.answers)) answers.set(k, v);
87
+ const pick = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.entries(v)) : {});
88
+ return {
89
+ [DATA_ROOT.answers]: Object.fromEntries(answers),
90
+ [DATA_ROOT.notes]: pick(saved.notes),
91
+ [DATA_ROOT.comment]: typeof saved.comment === 'string' ? saved.comment : '',
92
+ [DATA_ROOT.annotations]: {},
93
+ [DATA_ROOT.blockEdits]: pick(saved.blockEdits),
94
+ };
95
+ }
96
+
97
+ /**
98
+ * The three messages that make up a board's surface: createSurface, updateComponents, updateDataModel.
99
+ * @param {Record<string, any>} spec a normalized spec
100
+ * @param {{ surfaceId?: string, draft?: Record<string, any> | null }} [options]
101
+ * @returns {Array<Record<string, any>>}
102
+ */
103
+ export function toA2ui(spec, { surfaceId = 'relay-board', draft = null } = {}) {
104
+ assertSafeIds(spec);
105
+ const nextId = idMaker();
106
+ const components = [];
107
+ const children = [];
108
+ const addBlock = (block, extra) => {
109
+ const id = nextId('b', block.id);
110
+ components.push(blockComponent(block, id, extra));
111
+ return id;
112
+ };
113
+ for (const block of spec.blocks || []) children.push(addBlock(block));
114
+ for (const q of spec.questions) {
115
+ const own = [];
116
+ for (const block of q.blocks || []) own.push(addBlock(block));
117
+ for (const option of q.options || []) {
118
+ for (const block of option.blocks || []) own.push(addBlock(block, { optionValue: option.value }));
119
+ }
120
+ const id = nextId('q', q.id);
121
+ components.push(questionComponent({ ...q, options: (q.options || []).map(({ blocks, ...o }) => o) }, id, own));
122
+ children.push(id);
123
+ }
124
+ const display = spec.responseRequired === false;
125
+ if (!display) {
126
+ if (spec.note) {
127
+ components.push({ id: 'comment', component: 'Comment', label: 'Anything else?', value: { '@path': `/${DATA_ROOT.comment}` } });
128
+ children.push('comment');
129
+ }
130
+ components.push({
131
+ id: 'submit', component: 'Submit', label: spec.submitLabel || 'Submit',
132
+ action: { event: { name: ACTION_SUBMIT, context: {} } },
133
+ });
134
+ children.push('submit');
135
+ }
136
+ components.unshift({
137
+ id: 'root', component: 'Board', title: spec.title, text: clip(spec.intro || spec.title),
138
+ ...(spec.intro ? { intro: spec.intro } : {}), children,
139
+ responseRequired: !display, allowPartial: spec.allowPartial !== false,
140
+ });
141
+ const v = A2UI_PROTOCOL_VERSION;
142
+ return [
143
+ { version: v, createSurface: { surfaceId, catalogId: BOARD_CATALOG_ID, sendDataModel: !display } },
144
+ { version: v, updateComponents: { surfaceId, components } },
145
+ { version: v, updateDataModel: { surfaceId, value: initialData(spec, draft) } },
146
+ ];
147
+ }
package/src/cli/args.js CHANGED
@@ -5,7 +5,7 @@ const VALUED_FLAGS = new Set([
5
5
  'file', 'html', 'html-file', 'title', 'intro', 'timeout', 'port',
6
6
  'submit-label', 'height', 'limit', 'target', 'id', 'replies',
7
7
  'on-result', 'notify-cmd', 'idle-grace', 'scope', 'range',
8
- 'host', 'token', 'allow-origin', 'role', 'public-url', 'link', 'link-command',
8
+ 'host', 'token', 'token-file', 'root', 'allow-origin', 'role', 'public-url', 'link', 'link-command',
9
9
  ]);
10
10
 
11
11
  function camel(key) {
@@ -13,7 +13,7 @@ function camel(key) {
13
13
  }
14
14
 
15
15
  export function parseArgs(argv) {
16
- const args = { _: [], q: [] };
16
+ const args = { _: [], q: [], root: [] };
17
17
  for (let i = 0; i < argv.length; i++) {
18
18
  const t = argv[i];
19
19
  if (t === '-q' || t === '--question') {
@@ -35,6 +35,8 @@ export function parseArgs(argv) {
35
35
  }
36
36
  if (key === 'no-open') {
37
37
  args.open = false;
38
+ } else if (key === 'root') {
39
+ args.root.push(val);
38
40
  } else {
39
41
  args[camel(key)] = val;
40
42
  }
package/src/cli/ask.js CHANGED
@@ -1,12 +1,13 @@
1
1
  // rly ask: build a board from a spec and serve it.
2
2
  import { assertSpecReady, normalizeSpec } from '../spec/index.js';
3
3
  import { createBoard } from '../store.js';
4
- import { resolveSpecInput, runOrDetach } from './io.js';
4
+ import { cliFileRoots, resolveSpecInput, runOrDetach } from './io.js';
5
5
 
6
6
  export async function cmdAsk(args, mode) {
7
7
  const raw = await resolveSpecInput(args, mode);
8
- const spec = normalizeSpec(raw);
8
+ const fileRoots = cliFileRoots(args);
9
+ const spec = normalizeSpec(raw, { fileRoots });
9
10
  await assertSpecReady(spec);
10
- const record = createBoard(spec);
11
+ const record = createBoard(spec, { fileRoots });
11
12
  return runOrDetach(record, spec.responseRequired === false ? { ...args, detach: true } : args);
12
13
  }
package/src/cli/boards.js CHANGED
@@ -4,7 +4,7 @@ import { openUrl } from '../open.js';
4
4
  import { assertSpecReady, normalizeSpec, questionFromInline } from '../spec/index.js';
5
5
  import { HOME, controlUrl, createBoard, deleteBoard, isAlive, listBoards, listRunning, loadBoard, loadRunning, removeRunning, saveBoard } from '../store.js';
6
6
  import { CliError, pollFor } from '../util.js';
7
- import { mustLoad, parseJson, printJson, readFileOrThrow, readStdin, runOrDetach } from './io.js';
7
+ import { cliFileRoots, mustLoad, parseJson, printJson, readFileOrThrow, readStdin, runOrDetach } from './io.js';
8
8
 
9
9
  // `rly view <file.md> [more.md …]` — quick read-only board that renders files
10
10
  // with purpose-built blocks (markdown, data tables, PDF). With 2+ files a small
@@ -25,9 +25,11 @@ export async function cmdView(args) {
25
25
  const raw = { blocks };
26
26
  raw.title = args.title || (multi ? `${files.length} files` : path.basename(files[0]));
27
27
  raw.submitLabel = args.submitLabel || 'Done';
28
- const spec = normalizeSpec(raw); // reads + validates each file, clear error if unreadable
28
+ // The files were named on the command line, so their folders are allowed.
29
+ const fileRoots = cliFileRoots(args, files.map((f) => path.dirname(f)));
30
+ const spec = normalizeSpec(raw, { fileRoots }); // reads + validates each file, clear error if unreadable
29
31
  await assertSpecReady(spec);
30
- const record = createBoard(spec);
32
+ const record = createBoard(spec, { fileRoots });
31
33
  return runOrDetach(record, args);
32
34
  }
33
35
 
@@ -137,7 +139,7 @@ export async function cmdReuse(args) {
137
139
  console.log(JSON.stringify(src.spec, null, 2));
138
140
  return 0;
139
141
  }
140
- const record = createBoard(src.spec);
142
+ const record = createBoard(src.spec, { fileRoots: src.fileRoots });
141
143
  return runOrDetach(record, args);
142
144
  }
143
145
 
@@ -154,13 +156,14 @@ export async function cmdUpdate(args) {
154
156
  throw new CliError(`board "${id}" is not running — \`rly reopen ${id}\` to serve it, then update.`, 5);
155
157
  }
156
158
 
159
+ const fileRoots = [...new Set([...(record.fileRoots ?? [record.cwd]), ...cliFileRoots(args)])];
157
160
  let spec;
158
161
  if (args.file) {
159
162
  const raw =
160
163
  args.file === '-'
161
164
  ? parseJson(await readStdin(), 'stdin')
162
165
  : parseJson(readFileOrThrow(args.file), args.file);
163
- spec = normalizeSpec(raw);
166
+ spec = normalizeSpec(raw, { fileRoots });
164
167
  } else if (args.title || args.intro || args.q.length) {
165
168
  // Patch the CURRENT spec, then re-normalize so it's a clean normalized spec.
166
169
  const raw = { ...record.spec };
@@ -169,7 +172,7 @@ export async function cmdUpdate(args) {
169
172
  if (args.q.length) {
170
173
  raw.questions = [...(raw.questions || []), ...args.q.map((s, i) => questionFromInline(s, i))];
171
174
  }
172
- spec = normalizeSpec(raw);
175
+ spec = normalizeSpec(raw, { fileRoots });
173
176
  } else {
174
177
  throw new CliError('update needs --file <spec.json>, --title, --intro, or -q "...".', 4);
175
178
  }
@@ -180,7 +183,7 @@ export async function cmdUpdate(args) {
180
183
  res = await fetch(new URL('/api/update', controlUrl(running)), {
181
184
  method: 'POST',
182
185
  headers: { 'content-type': 'application/json', 'x-relay-token': running.token || '' },
183
- body: JSON.stringify({ spec }),
186
+ body: JSON.stringify({ spec, fileRoots }),
184
187
  });
185
188
  } catch (err) {
186
189
  throw new CliError(`could not reach board "${id}" at ${running.url}: ${String((err && err.message) || err)}`, 5);
package/src/cli/git.js CHANGED
@@ -6,7 +6,7 @@ import { assertSpecReady, normalizeSpec } from '../spec/index.js';
6
6
  import { createBoard } from '../store.js';
7
7
  import { CliError } from '../util.js';
8
8
  import { parseArgs } from './args.js';
9
- import { printJson, runOrDetach } from './io.js';
9
+ import { cliFileRoots, printJson, runOrDetach } from './io.js';
10
10
 
11
11
  // `rly diff [git args…]` — run `git diff` for the user and open the result as a
12
12
  // diff-block board in one step (sugar like `rly view`). Everything that isn't a
@@ -176,8 +176,10 @@ export async function cmdGit(rest) {
176
176
  : reviewDiffCount
177
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
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' });
179
+ // Conflict files named on the command line are the person's own choice.
180
+ const fileRoots = cliFileRoots(args, args._.map((p) => path.dirname(p)));
181
+ const spec = normalizeSpec({ title, intro, blocks, questions, submitLabel: 'Submit git choices' }, { fileRoots });
180
182
  await assertSpecReady(spec);
181
- const record = createBoard(spec);
183
+ const record = createBoard(spec, { fileRoots });
182
184
  return runOrDetach(record, args);
183
185
  }
package/src/cli/help.js CHANGED
@@ -70,7 +70,9 @@ USAGE
70
70
  rly mcp run relay as an MCP App server (stdio) — boards render INLINE in
71
71
  a local desktop host (Claude Desktop, Codex) instead of a browser tab
72
72
  rly mcp --http [--port N] serve over Streamable HTTP for web/mobile/remote hosts
73
- [--host H --token SECRET --allow-origin ORIGIN]
73
+ [--host H --token-file PATH --allow-origin ORIGIN]
74
+ [--root PATH ...] folders a spec may read local files from (none by default over HTTP; also $RLY_FILE_ROOTS)
75
+ (token: --token-file, $RLY_MCP_TOKEN, or --token, which shows in the process list)
74
76
  rly mcp config | install --target print host setup, or write it (claude | codex)
75
77
 
76
78
  COMMON FLAGS
package/src/cli/io.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { spawn } from 'node:child_process';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
+ import { envFileRoots, expandHome } from '../file-access.js';
5
6
  import { linkSetting, loadConfig, serializeLink } from '../link.js';
6
7
  import { runBoard } from '../server/index.js';
7
8
  import { assertSpecReady, questionFromInline } from '../spec/index.js';
@@ -9,6 +10,26 @@ import { HOME, loadBoard, loadRunning, saveBoard, saveResultFile } from '../stor
9
10
  import { CliError, pollFor } from '../util.js';
10
11
  import { BIN, DEFAULT_BOARD_TIMEOUT_SEC } from './context.js';
11
12
 
13
+ /**
14
+ * The directories a CLI-built spec may read local files from: where the person
15
+ * ran the command, the spec file's directory, the `--html-file` directory, every
16
+ * `--root`, `$RLY_FILE_ROOTS`, and `extra` for paths the command itself was given.
17
+ * @param {Record<string, any>} args parsed flags
18
+ * @param {string[]} [extra]
19
+ * @returns {string[]} absolute paths
20
+ */
21
+ export function cliFileRoots(args, extra = []) {
22
+ const given = [
23
+ process.cwd(),
24
+ args.file && args.file !== '-' ? path.dirname(args.file) : '',
25
+ typeof args.htmlFile === 'string' ? path.dirname(args.htmlFile) : '',
26
+ ...(Array.isArray(args.root) ? args.root : []),
27
+ ...envFileRoots(),
28
+ ...extra,
29
+ ];
30
+ return given.filter(Boolean).map((p) => path.resolve(expandHome(p)));
31
+ }
32
+
12
33
  export function printJson(obj) {
13
34
  process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
14
35
  }
package/src/cli/mcp.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
+ import { envFileRoots, expandHome } from '../file-access.js';
5
6
  import { mcpConfig } from '../mcp/config.js';
6
7
  import { CliError } from '../util.js';
7
8
  import { parseArgs } from './args.js';
@@ -24,16 +25,44 @@ export async function cmdMcp(rest) {
24
25
  const envPort = process.env.PORT || process.env.RLY_MCP_PORT;
25
26
  const { runMcpHttp } = await import('../mcp/serve.js');
26
27
  return runMcpHttp({
28
+ fileRoots: mcpFileRoots(args, []),
27
29
  port: args.port ? Number(args.port) : (envPort ? Number(envPort) : undefined),
28
30
  host: typeof args.host === 'string' ? args.host : (process.env.RLY_MCP_HOST || '127.0.0.1'),
29
- token: typeof args.token === 'string' ? args.token : (process.env.RLY_MCP_TOKEN || ''),
31
+ token: resolveToken(args),
30
32
  allowOrigin: typeof args.allowOrigin === 'string' ? args.allowOrigin : (process.env.RLY_MCP_ALLOW_ORIGIN || ''),
31
33
  });
32
34
  }
33
35
  // Default: be the stdio server. main() never resolves this, so the CLI's
34
36
  // post-run exit timer never arms — the server lives until stdin closes.
35
37
  const { runMcp } = await import('../mcp/serve.js');
36
- return runMcp();
38
+ return runMcp({ fileRoots: mcpFileRoots(args, [process.cwd()]) });
39
+ }
40
+
41
+ /**
42
+ * Where a spec may read local files. A local stdio host gets the working
43
+ * directory; an HTTP server gets nothing unless the operator passes `--root` or
44
+ * `$RLY_FILE_ROOTS`, because its clients are remote.
45
+ */
46
+ function mcpFileRoots(args, defaults) {
47
+ return [...defaults, ...args.root, ...envFileRoots()].map((p) => path.resolve(expandHome(p)));
48
+ }
49
+
50
+ /**
51
+ * The bearer token for --http. `--token` shows up in `ps`, so prefer `--token-file PATH`
52
+ * or $RLY_MCP_TOKEN; the flag keeps working. A file that cannot be read is an error,
53
+ * never an open endpoint.
54
+ */
55
+ function resolveToken(args) {
56
+ if (typeof args.tokenFile === 'string') {
57
+ try {
58
+ const token = fs.readFileSync(args.tokenFile, 'utf8').trim();
59
+ if (token) return token;
60
+ } catch (e) {
61
+ throw new CliError(`cannot read --token-file ${args.tokenFile}: ${e.message}`);
62
+ }
63
+ throw new CliError(`--token-file ${args.tokenFile} is empty`);
64
+ }
65
+ return typeof args.token === 'string' ? args.token : (process.env.RLY_MCP_TOKEN || '');
37
66
  }
38
67
 
39
68
  // Resolve Claude Desktop's config path for this platform.
@@ -0,0 +1,117 @@
1
+ // The one place a spec's local-file reads are allowed or refused. Specs are
2
+ // untrusted (an MCP client over HTTP writes them), so every path they name is
3
+ // resolved through realpath and must land inside a configured root.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { CliError } from './util.js';
8
+
9
+ /**
10
+ * @typedef {object} FileAccess
11
+ * @property {string} cwd Directory that relative spec paths resolve against.
12
+ * @property {string[]} roots Real paths a spec may read from; a root may be a single file.
13
+ */
14
+
15
+ /** Env var with extra roots, separated by the platform's path delimiter (":" on macOS and Linux). */
16
+ export const FILE_ROOTS_ENV = 'RLY_FILE_ROOTS';
17
+
18
+ const FIX_HINT = 'pass --root PATH (or set RLY_FILE_ROOTS), or fileRoots in registerRelay, to allow it';
19
+
20
+ /** Expands a leading `~` to the home directory. */
21
+ export function expandHome(p) {
22
+ if (p === '~') return os.homedir();
23
+ if (/^~[\\/]/.test(p)) return path.join(os.homedir(), p.slice(2));
24
+ return p;
25
+ }
26
+
27
+ /**
28
+ * Real path of `p`, or of its nearest existing ancestor plus the rest when `p`
29
+ * does not exist. A missing path under an allowed root can then be told apart
30
+ * from one outside every root without touching the outside path.
31
+ */
32
+ function realpathOrAncestor(p) {
33
+ const rest = [];
34
+ let cur = p;
35
+ for (;;) {
36
+ try {
37
+ return path.join(fs.realpathSync.native(cur), ...rest);
38
+ } catch (err) {
39
+ const parent = path.dirname(cur);
40
+ if (parent === cur || (err && err.code !== 'ENOENT' && err.code !== 'ENOTDIR')) return p;
41
+ rest.unshift(path.basename(cur));
42
+ cur = parent;
43
+ }
44
+ }
45
+ }
46
+
47
+ /** Real paths of the roots that exist; a root that does not exist grants nothing. */
48
+ export function realRoots(list, cwd) {
49
+ const out = [];
50
+ for (const raw of list) {
51
+ if (typeof raw !== 'string' || !raw.trim()) continue;
52
+ try {
53
+ out.push(fs.realpathSync.native(path.resolve(cwd, expandHome(raw.trim()))));
54
+ } catch { /* a root that is not there yet grants nothing */ }
55
+ }
56
+ return [...new Set(out)];
57
+ }
58
+
59
+ /** Roots named by `RLY_FILE_ROOTS`. */
60
+ export function envFileRoots(env = process.env) {
61
+ return String(env[FILE_ROOTS_ENV] || '').split(path.delimiter).filter(Boolean);
62
+ }
63
+
64
+ /**
65
+ * @param {{ cwd?: string, roots?: string[] }} [options] `roots` of `[]` means no local file may be read.
66
+ * @returns {FileAccess}
67
+ */
68
+ export function createFileAccess({ cwd = process.cwd(), roots = [cwd] } = {}) {
69
+ return { cwd, roots: realRoots(roots, cwd) };
70
+ }
71
+
72
+ /** True when `target` is a root or lies under one. Both are real paths. */
73
+ export function isInsideRoots(target, roots) {
74
+ return roots.some((root) => {
75
+ const rel = path.relative(root, target);
76
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
77
+ });
78
+ }
79
+
80
+ /**
81
+ * Resolves a path a spec names and says whether it may be read.
82
+ * @param {FileAccess} access
83
+ * @param {unknown} raw the path as written; `~` and relative paths are expanded
84
+ * @param {{ allowDirectory?: boolean }} [options] directories are refused unless a caller opens them in an app
85
+ * @returns {{ ok: boolean, file?: string, stat?: fs.Stats, reason?: 'invalid' | 'outside' | 'missing' | 'not-file', resolved?: string }} `file` and `stat` when ok; otherwise `reason` and the real path it was refused at
86
+ */
87
+ export function checkReadable(access, raw, { allowDirectory = false } = {}) {
88
+ const text = typeof raw === 'string' ? raw.trim() : '';
89
+ if (!text || text.includes('\0')) return { ok: false, reason: 'invalid', resolved: text };
90
+ const resolved = path.resolve(access.cwd, expandHome(text));
91
+ const real = realpathOrAncestor(resolved);
92
+ if (!isInsideRoots(real, access.roots)) return { ok: false, reason: 'outside', resolved: real };
93
+ let stat;
94
+ try { stat = fs.statSync(real); } catch { return { ok: false, reason: 'missing', resolved: real }; }
95
+ if (!stat.isFile() && !(allowDirectory && stat.isDirectory())) return { ok: false, reason: 'not-file', resolved: real };
96
+ return { ok: true, file: real, stat };
97
+ }
98
+
99
+ /**
100
+ * The real path of a file a spec names, or a CliError worded for the agent.
101
+ * @param {FileAccess} access
102
+ * @param {unknown} raw
103
+ * @param {string} where which block, e.g. `board.blocks[0]`
104
+ * @param {string} field which field, e.g. `codeFile`
105
+ * @returns {{ file: string, stat: fs.Stats }}
106
+ */
107
+ export function resolveReadable(access, raw, where, field) {
108
+ const checked = checkReadable(access, raw);
109
+ if (checked.ok) return { file: /** @type {string} */ (checked.file), stat: /** @type {fs.Stats} */ (checked.stat) };
110
+ const given = typeof raw === 'string' ? raw : String(raw);
111
+ const prefix = `${where}: ${field}: `;
112
+ if (checked.reason === 'outside') {
113
+ throw new CliError(`${prefix}path outside allowed roots (\"${given}\" resolves to ${checked.resolved}); ${FIX_HINT}.`);
114
+ }
115
+ if (checked.reason === 'not-file') throw new CliError(`${prefix}\"${given}\" is not a regular file (resolved: ${checked.resolved}).`);
116
+ throw new CliError(`${prefix}cannot read \"${given}\" (resolved: ${checked.resolved})`);
117
+ }