@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,95 @@
1
+ // ======================================================================
2
+ // client-side spec normalization (resilience)
3
+ // ----------------------------------------------------------------------
4
+ // The host normally hands us the SERVER-normalized spec via the tool result
5
+ // (structuredContent.spec) — options as {value,label}, blocks with ids, etc.
6
+ // If a host only forwards the raw tool input, this brings it close enough to
7
+ // render: it assigns ids and coerces option/column shapes. File-backed blocks
8
+ // (codeFile/htmlFile/local images) can't be resolved client-side and are left
9
+ // to the server path.
10
+ function clientNormalize(raw) {
11
+ if (!raw || typeof raw !== 'object') return null;
12
+ const spec = {
13
+ title: String(raw.title || 'Relay'),
14
+ intro: typeof raw.intro === 'string' ? raw.intro : '',
15
+ blocks: normBlocks(raw.blocks, ''),
16
+ allowPartial: raw.allowPartial !== false,
17
+ note: raw.note !== false,
18
+ autoClose: raw.autoClose !== false,
19
+ responseRequired: raw.responseRequired !== false,
20
+ questions: [],
21
+ submitLabel: typeof raw.submitLabel === 'string' ? raw.submitLabel : '',
22
+ };
23
+ const qs = Array.isArray(raw.questions) ? raw.questions : [];
24
+ qs.forEach((rq, i) => {
25
+ if (!rq || typeof rq !== 'object') return;
26
+ const id = String(rq.id || 'q' + (i + 1));
27
+ const type = String(rq.type || 'text');
28
+ const q = {
29
+ id, type,
30
+ label: String(rq.label || rq.question || rq.text || ''),
31
+ description: typeof rq.description === 'string' ? rq.description : '',
32
+ required: rq.required === true,
33
+ note: rq.note === undefined ? (type === 'single' || type === 'rank' || type === 'checklist' || type === 'allocate') : rq.note === true,
34
+ placeholder: typeof rq.placeholder === 'string' ? rq.placeholder : '',
35
+ blocks: normBlocks(rq.blocks, id + '-'),
36
+ };
37
+ if (type === 'single' || type === 'multi' || type === 'rank' || type === 'checklist' || type === 'allocate') {
38
+ const opts = Array.isArray(rq.options) ? rq.options : [];
39
+ q.options = opts.map((o, j) => {
40
+ if (typeof o === 'string' || typeof o === 'number') return { value: String(o), label: String(o) };
41
+ if (o && typeof o === 'object') {
42
+ const value = String(o.value != null ? o.value : o.label != null ? o.label : '');
43
+ const out = { value, label: String(o.label != null ? o.label : value) };
44
+ if (o.description) out.description = String(o.description);
45
+ const ob = normBlocks(o.blocks, id + '-o' + (j + 1) + '-');
46
+ if (ob.length) out.blocks = ob;
47
+ return out;
48
+ }
49
+ return { value: String(o), label: String(o) };
50
+ });
51
+ if (type === 'single' || type === 'multi') q.other = type === 'single' ? rq.other !== false : rq.other === true;
52
+ }
53
+ if (type === 'checklist') {
54
+ const rawSt = Array.isArray(rq.statuses) && rq.statuses.length ? rq.statuses
55
+ : [{ value: 'pass', label: 'Pass', tone: 'ok' }, { value: 'fail', label: 'Fail', tone: 'bad' }, { value: 'na', label: 'N/A', tone: 'muted' }];
56
+ q.statuses = rawSt.map((s) => typeof s === 'object' && s
57
+ ? { value: String(s.value != null ? s.value : s.label || ''), label: String(s.label != null ? s.label : s.value || ''), tone: s.tone ? String(s.tone) : undefined }
58
+ : { value: String(s), label: String(s) === 'na' ? 'N/A' : String(s) });
59
+ }
60
+ if (type === 'allocate') {
61
+ q.total = Number.isFinite(rq.total) && rq.total > 0 ? Math.floor(rq.total) : 100;
62
+ if (rq.unit !== undefined) q.unit = String(rq.unit);
63
+ }
64
+ if (type === 'scale') {
65
+ q.min = Number.isFinite(rq.min) ? rq.min : 1;
66
+ q.max = Number.isFinite(rq.max) ? rq.max : Math.max(5, q.min + 1);
67
+ q.minLabel = typeof rq.minLabel === 'string' ? rq.minLabel : '';
68
+ q.maxLabel = typeof rq.maxLabel === 'string' ? rq.maxLabel : '';
69
+ }
70
+ if (type === 'color' && Array.isArray(rq.presets)) {
71
+ q.presets = rq.presets.map((c) => String(c)).filter(Boolean);
72
+ }
73
+ if (type === 'color' && Array.isArray(rq.palette)) {
74
+ q.palette = rq.palette.map((p) => typeof p === 'object' && p
75
+ ? { value: String(p.value != null ? p.value : p.color || ''), label: String(p.label != null ? p.label : (p.name != null ? p.name : (p.value != null ? p.value : p.color || ''))) }
76
+ : { value: String(p), label: String(p) }).filter((p) => p.value);
77
+ }
78
+ if (rq.default !== undefined) q.default = rq.default;
79
+ spec.questions.push(q);
80
+ });
81
+ if (!spec.submitLabel) spec.submitLabel = spec.questions.length ? 'Submit' : 'Acknowledge';
82
+ return spec;
83
+ }
84
+ function normBlocks(blocks, prefix) {
85
+ if (!Array.isArray(blocks)) return [];
86
+ let n = 0;
87
+ const out = [];
88
+ for (const b of blocks) {
89
+ if (!b || typeof b !== 'object' || !b.type) continue;
90
+ out.push(b.id ? b : { ...b, id: prefix + 'b' + (++n) });
91
+ if (b.id) n++;
92
+ }
93
+ return out;
94
+ }
95
+
@@ -0,0 +1,200 @@
1
+ // ======================================================================
2
+ // render
3
+ // ======================================================================
4
+ function render() {
5
+ app.replaceChildren();
6
+ const annotateOn = !composing && Annotate;
7
+ const titleEl = el('h1', {}, spec.title);
8
+ app.append(el('header', { class: 'qb-header' }, titleEl));
9
+ if (annotateOn) Annotate.register(titleEl, { blockId: null, questionId: null, target: { kind: 'html-element', label: spec.title } });
10
+ if (spec.intro) {
11
+ const md = window.RelayBlocks && RelayBlocks.renderMarkdown;
12
+ const introEl = md
13
+ ? el('div', { class: 'intro blk-markdown' }, RelayBlocks.renderMarkdown(spec.intro))
14
+ : el('p', { class: 'intro' }, spec.intro);
15
+ app.append(introEl);
16
+ if (annotateOn) Annotate.enableTextSelection(introEl, { blockId: null, questionId: null });
17
+ }
18
+ renderBlocks(app, spec.blocks || [], null);
19
+
20
+ QS.forEach((q, idx) => {
21
+ const required = q.required || !spec.allowPartial;
22
+ const card = el('div', { class: 'card' },
23
+ el('div', { class: 'qnum' }, 'Q' + (idx + 1)),
24
+ el('p', { class: 'qlabel' }, q.label, required ? el('span', { class: 'req' }, ' *') : null),
25
+ q.description ? el('p', { class: 'qdesc' }, q.description) : null);
26
+ renderBlocks(card, q.blocks || [], q.id);
27
+ const control = el('div', { class: 'control' });
28
+ if (q.type === 'single') control.append(controlSingle(q));
29
+ else if (q.type === 'multi') control.append(controlMulti(q));
30
+ else if (q.type === 'yesno') control.append(segButtons(q, ['yes', 'no'], ['Yes', 'No']));
31
+ else if (q.type === 'scale') control.append(controlScale(q));
32
+ else if (q.type === 'color') control.append(controlColor(q));
33
+ else if (q.type === 'rank') control.append(controlRank(q));
34
+ else if (q.type === 'checklist') control.append(controlChecklist(q));
35
+ else if (q.type === 'allocate') control.append(controlAllocate(q));
36
+ else control.append(controlText(q, q.type === 'textarea'));
37
+ card.append(control);
38
+ if (q.note) {
39
+ const noteInput = el('textarea', { class: 'qnote', rows: 2, placeholder: 'optional note about this answer…' });
40
+ noteInput.value = typeof state.notes[q.id] === 'string' ? state.notes[q.id] : '';
41
+ noteInput.addEventListener('input', () => { state.notes[q.id] = noteInput.value; });
42
+ card.append(el('div', { class: 'qnotewrap' }, noteInput));
43
+ }
44
+ card.append(el('p', { class: 'errmsg' }, 'This question is required.'));
45
+ cards[q.id] = card;
46
+ app.append(card);
47
+ });
48
+
49
+ if (spec.note && spec.responseRequired !== false) {
50
+ const note = el('textarea', { placeholder: 'optional note back to the agent…' });
51
+ note.value = state.comment || '';
52
+ note.addEventListener('input', () => { state.comment = note.value; });
53
+ app.append(el('div', { class: 'card' },
54
+ el('p', { class: 'qlabel' }, 'Anything else?'),
55
+ el('p', { class: 'qdesc' }, 'Free-text note returned to the agent along with your answers.'),
56
+ el('div', { class: 'control' }, note)));
57
+ }
58
+
59
+ if (composing) {
60
+ // still streaming in — show a live "composing" note, no submit yet
61
+ app.append(el('div', { class: 'submitbar' }, el('span', { class: 'mcp-composing' }, 'Composing this board…')));
62
+ reportSize();
63
+ return;
64
+ }
65
+ if (spec.responseRequired === false) {
66
+ app.append(el('div', { class: 'submitbar display-only' },
67
+ el('span', { class: 'hint' }, 'Display only · no response requested')));
68
+ reportSize();
69
+ return;
70
+ }
71
+ const submitBtn = el('button', { class: 'submit', type: 'button' }, spec.submitLabel);
72
+ const saveEl = el('span', { class: 'savestate' }, '');
73
+ const hint = el('span', { class: 'hint' }, QS.length && spec.allowPartial ? 'Unanswered questions are returned as skipped.' : '');
74
+ submitBtn.addEventListener('click', () => onSubmit(submitBtn, saveEl));
75
+ app.append(el('div', { class: 'submitbar' }, submitBtn, hint, saveEl));
76
+ reportSize();
77
+ }
78
+
79
+ function validate() {
80
+ let firstBad = null;
81
+ for (const q of QS) {
82
+ const required = q.required || !spec.allowPartial;
83
+ const bad = required && getValue(q) === undefined;
84
+ cards[q.id].classList.toggle('error', bad);
85
+ if (bad && !firstBad) firstBad = cards[q.id];
86
+ }
87
+ if (firstBad) firstBad.scrollIntoView({ behavior: 'smooth', block: 'center' });
88
+ return !firstBad;
89
+ }
90
+
91
+ // A human-readable transcript of the submission — so the agent reads the
92
+ // answers even on a host that doesn't surface structuredContent.
93
+ function summarize(data) {
94
+ const lines = [];
95
+ lines.push('The user submitted the relay board "' + spec.title + '".');
96
+ if (QS.length) {
97
+ lines.push('', 'Answers:');
98
+ for (const q of QS) {
99
+ const v = data.answers[q.id];
100
+ let shown;
101
+ if (v === undefined) shown = '(skipped)';
102
+ else if (Array.isArray(v)) shown = v.join(', ');
103
+ else shown = String(v);
104
+ lines.push('- ' + q.label + ' [' + q.id + ']: ' + shown);
105
+ if (data.notes[q.id]) lines.push(' note: ' + data.notes[q.id]);
106
+ }
107
+ }
108
+ if (data.comment) lines.push('', 'Comment: ' + data.comment);
109
+ if (data.annotations && data.annotations.length) {
110
+ lines.push('', 'Inline comments (' + data.annotations.length + '):');
111
+ for (const a of data.annotations) {
112
+ const where = (a.target && (a.target.label || a.target.text || a.target.kind)) || a.blockId || 'element';
113
+ const crop = a.target && a.target.crop;
114
+ const cropNote = crop && crop.path ? ' · crop: ' + crop.path : crop && crop.data ? ' · image crop attached' : '';
115
+ lines.push('- [' + where + ']: ' + a.text + cropNote);
116
+ }
117
+ }
118
+ if (data.blockEdits) lines.push('', 'Edited diagrams: ' + Object.keys(data.blockEdits).join(', '));
119
+ return lines.join('\n');
120
+ }
121
+
122
+ async function onSubmit(submitBtn, saveEl) {
123
+ if (submitted) return;
124
+ if (!validate()) return;
125
+ submitBtn.disabled = true;
126
+ submitBtn.textContent = 'Submitting…';
127
+ const data = payload();
128
+ const structured = {
129
+ boardId: BOOT.boardId || null,
130
+ status: QS.length ? 'submitted' : 'acknowledged',
131
+ answers: data.answers,
132
+ skipped: data.skipped,
133
+ notes: data.notes,
134
+ comment: data.comment,
135
+ blockEdits: data.blockEdits,
136
+ annotations: data.annotations,
137
+ };
138
+ const text = summarize(data);
139
+ const messageContent = [{ type: 'text', text }];
140
+ for (const a of data.annotations || []) {
141
+ const crop = a && a.target && a.target.crop;
142
+ if (!crop || typeof crop.data !== 'string' || !crop.data) continue;
143
+ messageContent.push({ type: 'image', data: crop.data, mimeType: crop.mime || 'image/png' });
144
+ }
145
+ let messageDelivered = false;
146
+ let contextDelivered = false;
147
+ try {
148
+ // A completed relay form is a user reply, not passive context. Some hosts
149
+ // ACK `ui/update-model-context` without starting a new model turn, so send
150
+ // the transcript as a user message first to wake the agent reliably.
151
+ await request('ui/message', { role: 'user', content: messageContent });
152
+ messageDelivered = true;
153
+ } catch {
154
+ // Older hosts may not advertise image content or may implement the early
155
+ // single-content draft. Preserve the text wake path before giving up.
156
+ try {
157
+ await request('ui/message', { role: 'user', content: [{ type: 'text', text }] });
158
+ messageDelivered = true;
159
+ } catch {
160
+ try {
161
+ await request('ui/message', { role: 'user', content: { type: 'text', text } });
162
+ messageDelivered = true;
163
+ } catch { /* app-initiated messages unavailable */ }
164
+ }
165
+ }
166
+ try {
167
+ // Keep the structured payload available to hosts that attach app context.
168
+ // This is best-effort because context updates are intentionally silent.
169
+ await request('ui/update-model-context', { content: messageContent, structuredContent: structured });
170
+ contextDelivered = true;
171
+ } catch {
172
+ try {
173
+ await request('ui/update-model-context', { content: [{ type: 'text', text }], structuredContent: structured });
174
+ contextDelivered = true;
175
+ } catch { /* ui/message may still have delivered the result */ }
176
+ }
177
+ submitted = true;
178
+ showDone(messageDelivered, contextDelivered);
179
+ }
180
+
181
+ function showDone(messageDelivered, contextDelivered) {
182
+ // Collapse: leave fullscreen, drop the whole form for a one-line confirmation
183
+ // so the host shrinks the iframe to a small footprint in the transcript.
184
+ if (Annotate) { try { Annotate.teardown(); } catch { /* nothing to tear down */ } }
185
+ document.documentElement.classList.remove('mcp-fullscreen');
186
+ app.replaceChildren(el('div', { class: 'mcp-done' },
187
+ el('span', { class: 'mark' }, '✓'),
188
+ el('span', { class: 'lead' }, QS.length ? 'Submitted' : 'Acknowledged'),
189
+ el('span', { class: 'sub' }, messageDelivered
190
+ ? '· sent back to the agent'
191
+ : contextDelivered
192
+ ? '· saved; send the agent a message to continue'
193
+ : '· tell the agent you’ve responded')));
194
+ // Report the small height immediately, then again next frame / after layout
195
+ // settles — beats hosts that only grow on debounced size events.
196
+ reportSizeNow();
197
+ if (typeof requestAnimationFrame === 'function') requestAnimationFrame(reportSizeNow);
198
+ setTimeout(reportSizeNow, 150);
199
+ }
200
+
@@ -0,0 +1,106 @@
1
+ // ======================================================================
2
+ // board state + answer controls (ported from the browser board)
3
+ // ======================================================================
4
+ let spec = null;
5
+ let QS = [];
6
+ const state = { answers: {}, other: {}, notes: {}, comment: '', blockEdits: {}, annotations: [] };
7
+ // Element-level comments: the SAME self-contained annotate engine the browser
8
+ // board uses (no server — it reports the thread list via onChange). Charts,
9
+ // diagram nodes, table cells, images and text selections become commentable;
10
+ // the comments ride back in the submission alongside answers.
11
+ const Annotate = (window.RelayAnnotate && typeof window.RelayAnnotate.init === 'function') ? window.RelayAnnotate : null;
12
+ let submitted = false;
13
+ const cards = {};
14
+ const app = document.getElementById('app');
15
+
16
+ // ---------- display mode (host-driven) ----------
17
+ // GUI hosts (Claude, Codex) render their OWN full-screen control, so relay
18
+ // adds no redundant button. We still declare fullscreen support in
19
+ // ui/initialize and react to the host's mode change: in fullscreen the iframe
20
+ // fills the window, so we center the content to a readable column.
21
+ let displayMode = 'inline';
22
+ function applyDisplayMode() {
23
+ document.documentElement.classList.toggle('mcp-fullscreen', displayMode === 'fullscreen');
24
+ reportSize();
25
+ }
26
+
27
+ function seedDefaults() {
28
+ for (const q of QS) if (q.default !== undefined) state.answers[q.id] = q.default;
29
+ // Rank questions carry a full, valid permutation so an untouched rank still
30
+ // submits a meaningful order (mirrors the browser board's seedRankOrder).
31
+ for (const q of QS) {
32
+ if (q.type !== 'rank') continue;
33
+ const opts = (q.options || []).map((o) => o.value);
34
+ const prior = Array.isArray(state.answers[q.id]) ? state.answers[q.id] : [];
35
+ const order = prior.filter((v, i) => opts.includes(v) && prior.indexOf(v) === i);
36
+ for (const v of opts) if (!order.includes(v)) order.push(v);
37
+ state.answers[q.id] = order;
38
+ }
39
+ for (const q of QS) if (q.type === 'allocate') state.answers[q.id] = seedAllocate(q, state.answers[q.id]);
40
+ for (const q of QS) if (q.type === 'checklist') state.answers[q.id] = seedChecklist(q, state.answers[q.id]);
41
+ }
42
+ function seedAllocate(q, prior) {
43
+ const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
44
+ const out = {};
45
+ for (const o of q.options || []) out[o.value] = Math.max(0, Number(m[o.value]) || 0);
46
+ return out;
47
+ }
48
+ function seedChecklist(q, prior) {
49
+ const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
50
+ const optVals = new Set((q.options || []).map((o) => o.value));
51
+ const stVals = new Set((q.statuses || []).map((s) => s.value));
52
+ const out = {};
53
+ for (const k of Object.keys(m)) if (optVals.has(k) && stVals.has(m[k])) out[k] = m[k];
54
+ return out;
55
+ }
56
+
57
+ function getValue(q) {
58
+ const v = state.answers[q.id];
59
+ const oth = state.other[q.id];
60
+ switch (q.type) {
61
+ case 'single': {
62
+ if (oth && oth.on) { const t = (oth.text || '').trim(); return t || undefined; }
63
+ return typeof v === 'string' && v ? v : undefined;
64
+ }
65
+ case 'multi': {
66
+ const arr = Array.isArray(v) ? [...v] : [];
67
+ if (oth && oth.on) { const t = (oth.text || '').trim(); if (t) arr.push(t); }
68
+ return arr.length ? arr : undefined;
69
+ }
70
+ case 'yesno':
71
+ return v === 'yes' || v === 'no' ? v : undefined;
72
+ case 'scale':
73
+ return typeof v === 'number' ? v : undefined;
74
+ case 'rank':
75
+ return Array.isArray(v) && v.length ? [...v] : undefined;
76
+ case 'checklist': {
77
+ const m = v && typeof v === 'object' && !Array.isArray(v) ? v : {};
78
+ return Object.keys(m).length ? { ...m } : undefined;
79
+ }
80
+ case 'allocate': {
81
+ const m = v && typeof v === 'object' && !Array.isArray(v) ? v : {};
82
+ const sum = Object.values(m).reduce((a, n) => a + (Number(n) || 0), 0);
83
+ return sum > 0 ? { ...m } : undefined;
84
+ }
85
+ default: {
86
+ const t = typeof v === 'string' ? v.trim() : '';
87
+ return t || undefined;
88
+ }
89
+ }
90
+ }
91
+
92
+ function payload() {
93
+ const answers = {};
94
+ const notes = {};
95
+ for (const q of QS) {
96
+ const v = getValue(q);
97
+ if (v !== undefined) answers[q.id] = v;
98
+ const n = typeof state.notes[q.id] === 'string' ? state.notes[q.id].trim() : '';
99
+ if (n) notes[q.id] = n;
100
+ }
101
+ const skipped = QS.filter((q) => !(q.id in answers)).map((q) => q.id);
102
+ const blockEdits = Object.keys(state.blockEdits).length ? state.blockEdits : null;
103
+ const annotations = Array.isArray(state.annotations) && state.annotations.length ? state.annotations : null;
104
+ return { answers, skipped, comment: (state.comment || '').trim(), notes, blockEdits, annotations };
105
+ }
106
+
@@ -0,0 +1,86 @@
1
+ // ======================================================================
2
+ // vendored libraries pulled through the host bridge (resources/read)
3
+ // ----------------------------------------------------------------------
4
+ // blocks.js lazy-loads Chart.js / Mermaid / Viz.js via <script src="/vendor/…">
5
+ // and short-circuits when the global already exists. There's no server here,
6
+ // so we fetch the vendor source over the bridge and define the global up
7
+ // front; blocks.js then never reaches for the (absent) /vendor route.
8
+ const NEED = { chart: ['chart.umd.js', 'Chart'], mermaid: ['mermaid.min.js', 'mermaid'], graphviz: ['viz-standalone.js', 'Viz'] };
9
+ function blockTypesIn(spec) {
10
+ const types = new Set();
11
+ const scan = (blocks) => {
12
+ for (const b of Array.isArray(blocks) ? blocks : []) {
13
+ if (b && b.type) types.add(b.type);
14
+ if (b && Array.isArray(b.blocks)) scan(b.blocks);
15
+ }
16
+ };
17
+ scan(spec.blocks);
18
+ for (const q of spec.questions || []) {
19
+ scan(q.blocks);
20
+ for (const o of Array.isArray(q.options) ? q.options : []) if (o) scan(o.blocks);
21
+ }
22
+ return types;
23
+ }
24
+ async function ensureVendor(file, globalName) {
25
+ if (window[globalName]) return true;
26
+ try {
27
+ const res = await request('resources/read', { uri: 'ui://relay/vendor/' + file });
28
+ const c = res && Array.isArray(res.contents) ? res.contents[0] : null;
29
+ const code = c && (c.text || (c.blob ? atob(c.blob) : ''));
30
+ if (!code) return false;
31
+ const s = document.createElement('script');
32
+ s.textContent = code;
33
+ document.head.appendChild(s);
34
+ return Boolean(window[globalName]);
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+ async function preloadVendors(spec) {
40
+ const types = blockTypesIn(spec);
41
+ const jobs = [];
42
+ if (types.has('chart')) jobs.push(ensureVendor(...NEED.chart));
43
+ if (types.has('mermaid')) jobs.push(ensureVendor(...NEED.mermaid));
44
+ if (types.has('graphviz')) jobs.push(ensureVendor(...NEED.graphviz));
45
+ if (jobs.length) await Promise.allSettled(jobs);
46
+ }
47
+
48
+ // html blocks: the browser board serves each in its own iframe from
49
+ // /html/b/<id>. Here we wrap the body into a self-contained document and hand
50
+ // blocks.js a blob: URL for the iframe src (same sandbox, no server needed).
51
+ const htmlBodies = new Map();
52
+ function indexHtmlBlocks(spec) {
53
+ const add = (blocks) => {
54
+ for (const b of Array.isArray(blocks) ? blocks : []) {
55
+ if (b && b.type === 'html' && typeof b.html === 'string') htmlBodies.set(b.id, b.html);
56
+ }
57
+ };
58
+ add(spec.blocks);
59
+ for (const q of spec.questions || []) {
60
+ add(q.blocks);
61
+ for (const o of Array.isArray(q.options) ? q.options : []) if (o) add(o.blocks);
62
+ }
63
+ }
64
+ function htmlBlobSrc(blockId) {
65
+ const body = htmlBodies.get(blockId) || '';
66
+ const dark = effectiveTheme() === 'dark';
67
+ let doc;
68
+ if (/<html[\s>]/i.test(body)) {
69
+ doc = body;
70
+ } else {
71
+ const bg = dark ? '#282624' : '#ffffff';
72
+ const fg = dark ? '#edeae4' : '#1c1b19';
73
+ doc =
74
+ '<!doctype html><html><head><meta charset="utf-8">' +
75
+ '<meta name="viewport" content="width=device-width, initial-scale=1">' +
76
+ '<style>:root{color-scheme:' + (dark ? 'dark' : 'light') + '}' +
77
+ 'body{margin:12px;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;' +
78
+ 'background:' + bg + ';color:' + fg + '}</style></head><body>' + body + '</body></html>';
79
+ }
80
+ try {
81
+ return URL.createObjectURL(new Blob([doc], { type: 'text/html' }));
82
+ } catch {
83
+ return 'data:text/html;charset=utf-8,' + encodeURIComponent(doc);
84
+ }
85
+ }
86
+
package/src/mcp.js CHANGED
@@ -1,3 +1,4 @@
1
+ // code-craft: allow-size one MCP server: tool schemas, the stdio loop and the App resource share one request handler.
1
2
  // mcp.js — relay as an MCP App (SEP-1865, extension "io.modelcontextprotocol/ui").
2
3
  //
3
4
  // `rly mcp` starts an MCP server over stdio with no npm runtime dependencies.
@@ -20,12 +21,11 @@ import path from 'node:path';
20
21
  import http from 'node:http';
21
22
  import crypto from 'node:crypto';
22
23
  import { fileURLToPath } from 'node:url';
23
- import { assertSpecReady, normalizeSpec, SPEC_SCHEMA } from './spec.js';
24
+ import { assertSpecReady, normalizeSpec, SPEC_SCHEMA } from './spec/index.js';
24
25
  import { CliError } from './util.js';
26
+ import { fillPage, SRC_DIR } from './ui/manifest.js';
25
27
 
26
28
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
27
- const UI_DIR = path.join(__dirname, 'ui');
28
- const MCP_UI_DIR = path.join(__dirname, 'mcp-ui');
29
29
  const PKG_ROOT = path.join(__dirname, '..');
30
30
  const VENDOR_DIR = path.join(PKG_ROOT, 'vendor');
31
31
  const PKG = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8'));
@@ -43,12 +43,11 @@ const escapeHtml = (s) =>
43
43
 
44
44
  // ---------- UI asset assembly (cached for the process lifetime) ----------
45
45
  const _cache = new Map();
46
- function readAsset(dir, name) {
47
- const key = dir + '\0' + name;
48
- if (_cache.has(key)) return _cache.get(key);
46
+ function readAsset(file) {
47
+ if (_cache.has(file)) return _cache.get(file);
49
48
  let content = '';
50
- try { content = fs.readFileSync(path.join(dir, name), 'utf8'); } catch { content = ''; }
51
- _cache.set(key, content);
49
+ try { content = fs.readFileSync(path.join(SRC_DIR, file), 'utf8'); } catch { content = ''; }
50
+ _cache.set(file, content);
52
51
  return content;
53
52
  }
54
53
 
@@ -57,17 +56,12 @@ function readAsset(dir, name) {
57
56
  // /api routes exist in the sandbox; vendors load over the bridge on demand).
58
57
  function buildBoardPage() {
59
58
  if (_cache.has('__page__')) return _cache.get('__page__');
60
- const html = readAsset(MCP_UI_DIR, 'index.html');
61
59
  const boot = { version: PKG.version, boardId: 'mcp-' + Date.now().toString(36) };
62
- const page = html
63
- .split('__TITLE__').join('Relay')
64
- .split('/*__CSS__*/').join(readAsset(UI_DIR, 'style.css'))
65
- .split('/*__BLOCKS_CSS__*/').join(readAsset(UI_DIR, 'blocks.css') + '\n' + readAsset(UI_DIR, 'a2ui.css'))
66
- .split('/*__ANNOTATE_CSS__*/').join(readAsset(UI_DIR, 'annotate.css'))
67
- .split('/*__BLOCKS_JS__*/').join(readAsset(UI_DIR, 'a2ui-state.js') + '\n' + readAsset(UI_DIR, 'a2ui.js') + '\n' + readAsset(UI_DIR, 'blocks.js'))
68
- .split('/*__ANNOTATE_JS__*/').join(readAsset(UI_DIR, 'annotate.js'))
69
- .split('/*__BOARD_JS__*/').join(readAsset(MCP_UI_DIR, 'board.js'))
70
- .split('__BOOT_JSON__').join(JSON.stringify(boot).replace(/</g, '\\u003c'));
60
+ const page = fillPage(
61
+ readAsset('mcp-ui/index.html'),
62
+ { title: 'Relay', bootJson: JSON.stringify(boot).replace(/</g, '\\u003c'), entry: 'board' },
63
+ readAsset,
64
+ );
71
65
  _cache.set('__page__', page);
72
66
  return page;
73
67
  }
@@ -174,7 +168,7 @@ async function buildResult(method, params, clientProtocol) {
174
168
  case 'tools/call':
175
169
  return callTool(params);
176
170
  default: {
177
- const err = new Error('method not found: ' + method);
171
+ const err = /** @type {Error & { code?: number }} */ (new Error('method not found: ' + method));
178
172
  err.code = -32601;
179
173
  throw err;
180
174
  }
@@ -189,10 +183,10 @@ function readResource(params) {
189
183
  if (typeof uri === 'string' && uri.startsWith(VENDOR_PREFIX)) {
190
184
  const name = uri.slice(VENDOR_PREFIX.length);
191
185
  const text = vendorText(name);
192
- if (text == null) { const e = new Error('vendor not found: ' + name); e.code = -32002; throw e; }
186
+ if (text == null) { const e = /** @type {Error & { code?: number }} */ (new Error('vendor not found: ' + name)); e.code = -32002; throw e; }
193
187
  return { contents: [{ uri, mimeType: 'application/javascript', text }] };
194
188
  }
195
- const e = new Error('resource not found: ' + uri);
189
+ const e = /** @type {Error & { code?: number }} */ (new Error('resource not found: ' + uri));
196
190
  e.code = -32002;
197
191
  throw e;
198
192
  }