@khanglvm/relay 0.20.3 → 0.22.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 (73) hide show
  1. package/README.md +1 -1
  2. package/docs/AGENT.md +35 -62
  3. package/docs/SETUP.md +3 -2
  4. package/package.json +17 -5
  5. package/schema/spec.v1.json +55 -3
  6. package/skills/relay/SKILL.md +5 -2
  7. package/src/a2ui/board-catalog.json +1004 -0
  8. package/src/a2ui/board-constants.js +35 -0
  9. package/src/a2ui/board.js +5 -0
  10. package/src/a2ui/from-a2ui.js +71 -0
  11. package/src/a2ui/negotiate.js +38 -0
  12. package/src/a2ui/to-a2ui.js +147 -0
  13. package/src/cli/args.js +1 -1
  14. package/src/cli/help.js +2 -1
  15. package/src/cli/mcp.js +23 -3
  16. package/src/mcp/boards.js +195 -0
  17. package/src/mcp/config.js +20 -0
  18. package/src/mcp/constants.js +33 -0
  19. package/src/mcp/index.js +5 -0
  20. package/src/mcp/page.js +59 -0
  21. package/src/mcp/schemas.js +45 -0
  22. package/src/mcp/serve.js +116 -0
  23. package/src/mcp/server.js +24 -0
  24. package/src/mcp/store.js +35 -0
  25. package/src/mcp/token.js +56 -0
  26. package/src/mcp/tools.js +179 -0
  27. package/src/mcp-ui/board/block-ctx.js +22 -0
  28. package/src/mcp-ui/board/bridge.js +12 -2
  29. package/src/mcp-ui/board/core.js +2 -0
  30. package/src/mcp-ui/board/lifecycle.js +47 -9
  31. package/src/mcp-ui/board/normalize.js +12 -0
  32. package/src/mcp-ui/board/render.js +38 -45
  33. package/src/mcp-ui/board/state.js +3 -0
  34. package/src/mcp-ui/board/vendors.js +56 -11
  35. package/src/server/board.js +12 -9
  36. package/src/server/http.js +19 -0
  37. package/src/server/page.js +4 -0
  38. package/src/spec/constants.js +13 -1
  39. package/src/spec/index.js +1 -0
  40. package/src/spec/lookup.js +1 -0
  41. package/src/spec/normalize.js +3 -0
  42. package/src/spec/pick.js +104 -0
  43. package/src/spec/schema.js +26 -3
  44. package/src/ui/app/drafts.js +3 -0
  45. package/src/ui/app/render.js +1 -0
  46. package/src/ui/app/submit.js +1 -1
  47. package/src/ui/manifest.js +3 -2
  48. package/src/ui/pick.css +32 -0
  49. package/src/ui/pick.js +246 -0
  50. package/types/a2ui/board-constants.d.ts +24 -0
  51. package/types/a2ui/from-a2ui.d.ts +16 -0
  52. package/types/a2ui/negotiate.d.ts +17 -0
  53. package/types/a2ui/to-a2ui.d.ts +12 -0
  54. package/types/cli/agent-topics.d.ts +46 -0
  55. package/types/mcp/boards.d.ts +178 -0
  56. package/types/{mcp.d.ts → mcp/config.d.ts} +1 -8
  57. package/types/mcp/constants.d.ts +21 -0
  58. package/types/mcp/index.d.ts +4 -0
  59. package/types/mcp/page.d.ts +27 -0
  60. package/types/mcp/schemas.d.ts +49 -0
  61. package/types/mcp/serve.d.ts +16 -0
  62. package/types/mcp/server.d.ts +4 -0
  63. package/types/mcp/store.d.ts +52 -0
  64. package/types/mcp/token.d.ts +9 -0
  65. package/types/mcp/tools.d.ts +17 -0
  66. package/types/server/result.d.ts +10 -0
  67. package/types/server/sanitize.d.ts +6 -0
  68. package/types/spec/constants.d.ts +9 -0
  69. package/types/spec/index.d.ts +1 -0
  70. package/types/spec/lookup.d.ts +2 -1
  71. package/types/spec/pick.d.ts +25 -0
  72. package/types/spec/schema.d.ts +48 -0
  73. package/src/mcp.js +0 -483
@@ -54,21 +54,59 @@
54
54
  previewTimer = setTimeout(() => { previewTimer = null; if (!booted && !submitted) render(); }, 120);
55
55
  }
56
56
 
57
- // The spec can arrive as the tool RESULT (preferred — server-normalized) or,
58
- // on a leaner host, as the tool INPUT (raw). Prefer the result: when raw input
59
- // lands first, hold briefly for a result before falling back to the input.
57
+ // The tool result carries only the board id and token. The spec comes from
58
+ // relay_view, already normalized by the server. A host that will not run app
59
+ // tool calls still gets a board: the raw tool input is the fallback, held for
60
+ // a moment so the server's version wins when both arrive.
61
+ let rawInput = null;
60
62
  let rawInputTimer = null;
61
- onNotify('ui/notifications/tool-result', (p) => {
63
+ const DRAFT_EVERY_MS = 4000;
64
+ let lastDraft = '';
65
+
66
+ function startDraftSync() {
67
+ setInterval(() => {
68
+ if (!booted || submitted || !BOARD.token || spec.responseRequired === false) return;
69
+ const body = JSON.stringify(payload());
70
+ if (body === lastDraft) return;
71
+ lastDraft = body;
72
+ callServerTool('relay_draft', { boardId: BOARD.id, token: BOARD.token, draft: JSON.parse(body) }).catch(() => {});
73
+ }, DRAFT_EVERY_MS);
74
+ }
75
+
76
+ async function bootFromServer(result) {
77
+ const sc = result && result.structuredContent;
78
+ const token = result && result._meta && result._meta.relay && result._meta.relay.token;
79
+ if (!sc || !sc.boardId || !token) return false;
80
+ BOARD.id = sc.boardId;
81
+ BOARD.token = token;
82
+ try {
83
+ const view = await callServerTool('relay_view', { boardId: BOARD.id, token: BOARD.token });
84
+ if (!view.spec) return false;
85
+ vendorUrls = view.vendorUrls || null;
86
+ await boot(view.spec, true);
87
+ if (view.finished) {
88
+ submitted = true;
89
+ showDone(true, false);
90
+ return true;
91
+ }
92
+ startDraftSync();
93
+ return true;
94
+ } catch {
95
+ BOARD.token = null;
96
+ return false;
97
+ }
98
+ }
99
+
100
+ onNotify('ui/notifications/tool-result', async (p) => {
62
101
  if (rawInputTimer) { clearTimeout(rawInputTimer); rawInputTimer = null; }
63
- const sc = p && p.structuredContent;
64
- if (sc && sc.spec) return boot(sc.spec, true);
65
- // Some hosts may echo the spec at the top level of structuredContent.
66
- if (sc && Array.isArray(sc.questions)) return boot(sc, true);
102
+ if (booted) return;
103
+ if (!(await bootFromServer(p)) && rawInput) boot(rawInput, false);
67
104
  });
68
105
  onNotify('ui/notifications/tool-input', (p) => {
69
106
  const args = p && p.arguments;
70
107
  if (!args || typeof args !== 'object' || booted || rawInputTimer) return;
71
- rawInputTimer = setTimeout(() => { rawInputTimer = null; boot(args, false); }, 250);
108
+ rawInput = args;
109
+ rawInputTimer = setTimeout(() => { rawInputTimer = null; boot(args, false); }, 1500);
72
110
  });
73
111
  onNotify('ui/notifications/tool-input-partial', (p) => {
74
112
  const args = p && p.arguments;
@@ -61,6 +61,18 @@
61
61
  q.total = Number.isFinite(rq.total) && rq.total > 0 ? Math.floor(rq.total) : 100;
62
62
  if (rq.unit !== undefined) q.unit = String(rq.unit);
63
63
  }
64
+ if (type === 'pick') {
65
+ const tiles = Array.isArray(rq.items) ? rq.items : [];
66
+ q.items = tiles.map((t) => (t && typeof t === 'object'
67
+ ? { ...t, id: String(t.id != null ? t.id : t.title || ''), title: String(t.title != null ? t.title : t.id || '') }
68
+ : { id: String(t), title: String(t) }));
69
+ q.min = Number.isInteger(rq.min) && rq.min >= 0 ? Math.min(rq.min, q.items.length) : 0;
70
+ q.max = Number.isInteger(rq.max) && rq.max >= 1 ? Math.min(rq.max, q.items.length) : q.items.length;
71
+ q.itemNote = rq.itemNote !== false;
72
+ q.overall = rq.overall !== false;
73
+ q.note = false;
74
+ if (q.min > 0) q.required = true;
75
+ }
64
76
  if (type === 'scale') {
65
77
  q.min = Number.isFinite(rq.min) ? rq.min : 1;
66
78
  q.max = Number.isFinite(rq.max) ? rq.max : Math.max(5, q.min + 1);
@@ -33,6 +33,7 @@
33
33
  else if (q.type === 'rank') control.append(controlRank(q));
34
34
  else if (q.type === 'checklist') control.append(controlChecklist(q));
35
35
  else if (q.type === 'allocate') control.append(controlAllocate(q));
36
+ else if (q.type === 'pick') control.append(window.RelayPick.control(q, state, { onChange: () => clearErr(q.id) }));
36
37
  else control.append(controlText(q, q.type === 'textarea'));
37
38
  card.append(control);
38
39
  if (q.note) {
@@ -80,7 +81,7 @@
80
81
  let firstBad = null;
81
82
  for (const q of QS) {
82
83
  const required = q.required || !spec.allowPartial;
83
- const bad = required && getValue(q) === undefined;
84
+ const bad = required && (getValue(q) === undefined || (q.type === 'pick' && window.RelayPick.short(q, state.answers[q.id])));
84
85
  cards[q.id].classList.toggle('error', bad);
85
86
  if (bad && !firstBad) firstBad = cards[q.id];
86
87
  }
@@ -119,63 +120,55 @@
119
120
  return lines.join('\n');
120
121
  }
121
122
 
123
+ // The full answers go to the server, which keeps them for relay_result; the
124
+ // agent gets a one-line nudge. A host that refuses app tool calls gets the
125
+ // whole transcript as the message instead, so the answers still arrive.
122
126
  async function onSubmit(submitBtn, saveEl) {
123
127
  if (submitted) return;
124
128
  if (!validate()) return;
125
129
  submitBtn.disabled = true;
126
130
  submitBtn.textContent = 'Submitting…';
127
131
  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' });
132
+ const stored = BOARD.token ? await storeSubmission(data) : false;
133
+ const text = stored
134
+ ? 'Relay board ' + BOARD.id + ' submitted. Read it with relay_result {"boardId":"' + BOARD.id + '"}.'
135
+ : summarize(data);
136
+ const content = [{ type: 'text', text }];
137
+ if (!stored) {
138
+ for (const a of data.annotations || []) {
139
+ const crop = a && a.target && a.target.crop;
140
+ if (!crop || typeof crop.data !== 'string' || !crop.data) continue;
141
+ content.push({ type: 'image', data: crop.data, mimeType: crop.mime || 'image/png' });
142
+ }
144
143
  }
145
- let messageDelivered = false;
146
- let contextDelivered = false;
144
+ const messageDelivered = await sendUserMessage(content, text);
145
+ submitted = true;
146
+ showDone(messageDelivered, stored);
147
+ }
148
+
149
+ async function storeSubmission(data) {
147
150
  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;
151
+ await callServerTool('relay_submit', { boardId: BOARD.id, token: BOARD.token, payload: data });
152
+ return true;
153
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.
154
+ return false;
155
+ }
156
+ }
157
+
158
+ // A completed relay form is a user reply, so it goes as a user message to wake
159
+ // the agent. Older hosts reject image content or the content array; each retry
160
+ // keeps the text.
161
+ async function sendUserMessage(content, text) {
162
+ const attempts = [content, [{ type: 'text', text }], { type: 'text', text }];
163
+ for (const attempt of attempts) {
156
164
  try {
157
- await request('ui/message', { role: 'user', content: [{ type: 'text', text }] });
158
- messageDelivered = true;
165
+ await request('ui/message', { role: 'user', content: attempt });
166
+ return true;
159
167
  } catch {
160
- try {
161
- await request('ui/message', { role: 'user', content: { type: 'text', text } });
162
- messageDelivered = true;
163
- } catch { /* app-initiated messages unavailable */ }
168
+ // try a simpler shape
164
169
  }
165
170
  }
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);
171
+ return false;
179
172
  }
180
173
 
181
174
  function showDone(messageDelivered, contextDelivered) {
@@ -38,6 +38,7 @@
38
38
  }
39
39
  for (const q of QS) if (q.type === 'allocate') state.answers[q.id] = seedAllocate(q, state.answers[q.id]);
40
40
  for (const q of QS) if (q.type === 'checklist') state.answers[q.id] = seedChecklist(q, state.answers[q.id]);
41
+ for (const q of QS) if (q.type === 'pick') state.answers[q.id] = window.RelayPick.seed(q, state.answers[q.id]);
41
42
  }
42
43
  function seedAllocate(q, prior) {
43
44
  const m = prior && typeof prior === 'object' && !Array.isArray(prior) ? prior : {};
@@ -82,6 +83,8 @@
82
83
  const sum = Object.values(m).reduce((a, n) => a + (Number(n) || 0), 0);
83
84
  return sum > 0 ? { ...m } : undefined;
84
85
  }
86
+ case 'pick':
87
+ return window.RelayPick.value(q, v);
85
88
  default: {
86
89
  const t = typeof v === 'string' ? v.trim() : '';
87
90
  return t || undefined;
@@ -21,20 +21,65 @@
21
21
  }
22
22
  return types;
23
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;
24
+ function bytesOf(base64) {
25
+ const bin = atob(base64);
26
+ const out = new Uint8Array(bin.length);
27
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
28
+ return out;
29
+ }
30
+ // The preferred route: the host reads the vendor file as a ui:// resource.
31
+ async function vendorFromResource(file) {
32
+ const res = await request('resources/read', { uri: 'ui://relay/vendor/' + file });
33
+ const c = res && Array.isArray(res.contents) ? res.contents[0] : null;
34
+ return c ? (c.text || (c.blob ? new TextDecoder().decode(bytesOf(c.blob)) : '')) : '';
35
+ }
36
+ // For a host that refuses resources/read: the server hands the file over in
37
+ // chunks. The chunks are joined as bytes before decoding, so a UTF-8 character
38
+ // split across two chunks stays whole.
39
+ async function vendorFromTool(file) {
40
+ const parts = [];
41
+ let count = 1;
42
+ for (let i = 0; i < count; i++) {
43
+ const chunk = await callServerTool('relay_asset', { name: file, index: i }, 60000);
44
+ count = chunk.count;
45
+ parts.push(bytesOf(chunk.data));
46
+ }
47
+ const all = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
48
+ let at = 0;
49
+ for (const p of parts) { all.set(p, at); at += p.length; }
50
+ return new TextDecoder().decode(all);
51
+ }
52
+ // Where the server says a vendor file can also be fetched over HTTP, from relay_view.
53
+ let vendorUrls = null;
54
+ function vendorFromUrl(file) {
55
+ return new Promise((resolve, reject) => {
56
+ const url = vendorUrls && vendorUrls[file];
57
+ if (!url) return reject(new Error('no url'));
31
58
  const s = document.createElement('script');
32
- s.textContent = code;
59
+ s.src = url;
60
+ s.onload = () => resolve('');
61
+ s.onerror = () => reject(new Error('script failed'));
33
62
  document.head.appendChild(s);
34
- return Boolean(window[globalName]);
35
- } catch {
36
- return false;
63
+ });
64
+ }
65
+ async function ensureVendor(file, globalName) {
66
+ if (window[globalName]) return true;
67
+ for (const load of [vendorFromResource, vendorFromTool, vendorFromUrl]) {
68
+ try {
69
+ const code = await load(file);
70
+ if (!code) {
71
+ if (window[globalName]) return true;
72
+ continue;
73
+ }
74
+ const s = document.createElement('script');
75
+ s.textContent = code;
76
+ document.head.appendChild(s);
77
+ if (window[globalName]) return true;
78
+ } catch {
79
+ // try the next route
80
+ }
37
81
  }
82
+ return false;
38
83
  }
39
84
  async function preloadVendors(spec) {
40
85
  const types = blockTypesIn(spec);
@@ -6,11 +6,11 @@ import path from 'node:path';
6
6
  import { filePreview, mediaType, splitFileReference } from '../file-preview.js';
7
7
  import { resolveLink } from '../link.js';
8
8
  import { openUrl } from '../open.js';
9
- import { assertSpecReady } from '../spec/index.js';
9
+ import { assertSpecReady, cleanAnswers } from '../spec/index.js';
10
10
  import { loadBoard, removeRunning, saveBoard, saveBoardArtifact, savePref, saveRunning } from '../store.js';
11
11
  import { SHARE_STATE_VERSION, pruneReviewDrafts, reviewSessionCookie, reviewSessionId, sideReviewState } from './reviews.js';
12
12
  import { buildLockedPage, buildPage, shareHost } from './page.js';
13
- import { isDirectLocalRequest, readBody, sameOrigin, sendFromDir, sendHtml, sendJs, sendJson, wrapFragment } from './http.js';
13
+ import { isDirectLocalRequest, readBody, sameOrigin, sendDataImage, sendFromDir, sendHtml, sendJs, sendJson, wrapFragment } from './http.js';
14
14
  import { UI_DIR, VENDOR_DIR } from './paths.js';
15
15
  import { findBlock, findHtmlBlock, firstBoardHtml, firstQuestionHtml, sanitizeAnnotations, sanitizeBlockEdits } from './sanitize.js';
16
16
  import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, artifactBytesMatch, runOnResult } from './result.js';
@@ -289,10 +289,12 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
289
289
  // Embedded image bytes (image blocks authored from local files).
290
290
  const blockId = decodeURIComponent(pathname.slice('/img/b/'.length));
291
291
  const block = findBlock(record.spec, blockId, 'image');
292
- const m = block && typeof block.src === 'string' ? block.src.match(/^data:([^;,]+);base64,(.*)$/s) : null;
293
- if (!m) return sendJson(res, 404, { error: `no embedded image block "${blockId}"` });
294
- res.writeHead(200, { 'content-type': m[1], 'cache-control': 'no-store' });
295
- res.end(Buffer.from(m[2], 'base64'));
292
+ if (!sendDataImage(res, block?.src)) return sendJson(res, 404, { error: `no embedded image block "${blockId}"` });
293
+ } else if (req.method === 'GET' && pathname.startsWith('/img/p/')) {
294
+ // Embedded tile image bytes (pick questions authored from local files).
295
+ const [questionId, itemId] = pathname.slice('/img/p/'.length).split('/').map(decodeURIComponent);
296
+ const tile = record.spec.questions.find((q) => q.id === questionId && q.type === 'pick')?.items.find((t) => t.id === itemId);
297
+ if (!sendDataImage(res, tile?.image)) return sendJson(res, 404, { error: `no embedded tile image "${questionId}/${itemId}"` });
296
298
  } else if (req.method === 'POST' && pathname === '/api/artifact') {
297
299
  if (record.spec.responseRequired === false) return sendJson(res, 409, { error: 'display-only boards do not collect feedback' });
298
300
  if (!sameOrigin(req, actualPort, [advertisedHost], [publicLink?.origin])) return sendJson(res, 403, { error: 'cross-origin artifact upload rejected' });
@@ -393,11 +395,12 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
393
395
  return sendJson(res, 403, { error: 'this share is read only' });
394
396
  }
395
397
  const body = JSON.parse((await readBody(req)) || '{}');
398
+ const draftAnswers = cleanAnswers(record.spec, body.answers && typeof body.answers === 'object' ? body.answers : {});
396
399
  if (access.role === 'review') {
397
400
  record.reviewDrafts = record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {};
398
401
  const priorRev = Number(record.reviewDrafts[access.reviewSessionId]?.draftRev) || 0;
399
402
  record.reviewDrafts[access.reviewSessionId] = {
400
- answers: body.answers && typeof body.answers === 'object' ? body.answers : {},
403
+ answers: draftAnswers,
401
404
  comment: typeof body.comment === 'string' ? body.comment : '',
402
405
  notes: body.notes && typeof body.notes === 'object' ? body.notes : {},
403
406
  annotations: sanitizeAnnotations(body.annotations, record.id),
@@ -408,7 +411,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
408
411
  pruneReviewDrafts(record);
409
412
  } else {
410
413
  record.draft = {
411
- answers: body.answers && typeof body.answers === 'object' ? body.answers : {},
414
+ answers: draftAnswers,
412
415
  comment: typeof body.comment === 'string' ? body.comment : '',
413
416
  notes: body.notes && typeof body.notes === 'object' ? body.notes : {},
414
417
  annotations: sanitizeAnnotations(body.annotations, record.id),
@@ -429,7 +432,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
429
432
  if (!access.canSubmit) return sendJson(res, 403, { error: 'this share is read only' });
430
433
  if (status !== 'open') return sendJson(res, 409, { error: 'board already finished' });
431
434
  const body = JSON.parse((await readBody(req)) || '{}');
432
- const answers = body.answers && typeof body.answers === 'object' ? body.answers : {};
435
+ const answers = cleanAnswers(record.spec, body.answers && typeof body.answers === 'object' ? body.answers : {});
433
436
  const skipped = record.spec.questions.filter((q) => !(q.id in answers)).map((q) => q.id);
434
437
  if (access.role === 'review') {
435
438
  const review = {
@@ -42,6 +42,25 @@ export function sendHtml(res, body, headers = {}) {
42
42
  res.end(body);
43
43
  }
44
44
 
45
+ const DATA_IMAGE = /^data:(image\/[a-z0-9.+-]+);base64,(.*)$/is;
46
+
47
+ /**
48
+ * Serves the bytes of an agent-written `data:image/...;base64` URI. Security: the
49
+ * MIME is the agent's, so only image types pass, and the sandbox CSP keeps an SVG
50
+ * opened as its own page from running script on the board's origin.
51
+ * Returns false (nothing written) when the value is not such a URI.
52
+ */
53
+ export function sendDataImage(res, dataUri) {
54
+ const m = typeof dataUri === 'string' ? dataUri.match(DATA_IMAGE) : null;
55
+ if (!m) return false;
56
+ res.writeHead(200, {
57
+ 'content-type': m[1], 'cache-control': 'no-store',
58
+ 'x-content-type-options': 'nosniff', 'content-security-policy': "sandbox; default-src 'none'; style-src 'unsafe-inline'",
59
+ });
60
+ res.end(Buffer.from(m[2], 'base64'));
61
+ return true;
62
+ }
63
+
45
64
  export function sendJs(res, body) {
46
65
  res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
47
66
  res.end(body);
@@ -64,6 +64,10 @@ function clientBlock(b) {
64
64
  // level AND inside each option's blocks.
65
65
  function clientQuestion(q) {
66
66
  const out = { ...q, blocks: (q.blocks || []).map(clientBlock) };
67
+ // pick tiles: embedded image bytes are served at /img/p/<question>/<tile>, like image blocks.
68
+ if (Array.isArray(q.items)) {
69
+ out.items = q.items.map((t) => (typeof t.image === 'string' && t.image.startsWith('data:') ? { ...t, image: undefined, hasImage: true } : t));
70
+ }
67
71
  if (Array.isArray(q.options)) {
68
72
  out.options = q.options.map((o) =>
69
73
  o && Array.isArray(o.blocks) && o.blocks.length ? { ...o, blocks: o.blocks.map(clientBlock) } : o
@@ -1,6 +1,6 @@
1
1
  // Limits, allowed values and aliases that the spec readers share.
2
2
 
3
- export const TYPES = ['single', 'multi', 'yesno', 'text', 'textarea', 'scale', 'color', 'rank', 'checklist', 'allocate'];
3
+ export const TYPES = ['single', 'multi', 'yesno', 'text', 'textarea', 'scale', 'color', 'rank', 'checklist', 'allocate', 'pick'];
4
4
 
5
5
  export const ALIASES = {
6
6
  radio: 'single',
@@ -31,6 +31,9 @@ export const ALIASES = {
31
31
  budget: 'allocate',
32
32
  distribute: 'allocate',
33
33
  points: 'allocate',
34
+ tiles: 'pick',
35
+ gallery: 'pick',
36
+ shortlist: 'pick',
34
37
  };
35
38
 
36
39
  // Block type names agents reach for that mean one of ours. A chart kind used as
@@ -82,3 +85,12 @@ export const IMAGE_MIMES = {
82
85
  webp: 'image/webp', svg: 'image/svg+xml', avif: 'image/avif', bmp: 'image/bmp',
83
86
  };
84
87
  export const IMAGE_MAX_BYTES = 8 * 1024 * 1024;
88
+
89
+ // pick questions: media tiles the person chooses among. Local images are embedded
90
+ // as data URIs like image blocks, so the total is capped, not just each file.
91
+ export const PICK = {
92
+ maxItems: 60,
93
+ maxImageBytes: 24 * 1024 * 1024,
94
+ maxNoteChars: 2000,
95
+ maxOverallChars: 5000,
96
+ };
package/src/spec/index.js CHANGED
@@ -4,3 +4,4 @@ export { assertSpecReady } from './ready.js';
4
4
  export { normalizeSpec, questionFromInline } from './normalize.js';
5
5
  export { SPEC_SCHEMA } from './schema.js';
6
6
  export { lookupSchema } from './lookup.js';
7
+ export { cleanAnswers, cleanPick } from './pick.js';
@@ -46,6 +46,7 @@ export const QUESTION_FIELDS = {
46
46
  rank: ['options', 'default'],
47
47
  checklist: ['options', 'statuses', 'default'],
48
48
  allocate: ['options', 'total', 'unit', 'default'],
49
+ pick: ['items', 'min', 'max', 'itemNote', 'overall', 'default'],
49
50
  };
50
51
 
51
52
  function pick(props, names) {
@@ -4,6 +4,7 @@ import { CliError } from '../util.js';
4
4
  import { asStr, clampInt, readBlockHtml, readHtml } from './sources.js';
5
5
  import { ALIASES, BLOCK_ALIASES, BLOCK_HEIGHT, BLOCK_TYPES, CHART_KINDS, HTML_HEIGHT, TYPES } from './constants.js';
6
6
  import { BLOCK_NORMALIZERS } from './blocks/index.js';
7
+ import { normalizePick } from './pick.js';
7
8
 
8
9
  // Normalizes one block object. `id` is the already-assigned block id.
9
10
  // Returns the normalized block (with a guaranteed string `type` + `id`).
@@ -197,6 +198,8 @@ export function normalizeSpec(raw, { cwd = process.cwd() } = {}) {
197
198
  }
198
199
  }
199
200
 
201
+ if (type === 'pick') normalizePick(q, rq, where, cwd);
202
+
200
203
  if (type === 'checklist') {
201
204
  // Per-item status control. Default Pass / Fail / N/A; override with
202
205
  // "statuses" (strings or {value,label,tone?}). tone colors the chip.
@@ -0,0 +1,104 @@
1
+ // The `pick` question: media tiles the person chooses among. This file reads the
2
+ // tiles an agent wrote and cleans the answer a board sends back; drawing is
3
+ // src/ui/pick.js.
4
+ import { CliError } from '../util.js';
5
+ import { resolveImageSrc } from './blocks/image.js';
6
+ import { PICK } from './constants.js';
7
+ import { asStr, clampInt } from './sources.js';
8
+
9
+ const HTTP_URL = /^https?:\/\/\S+$/i;
10
+ const ID_MAX = 80;
11
+
12
+ function httpUrl(raw, where, field) {
13
+ const url = asStr(raw).trim();
14
+ if (!HTTP_URL.test(url)) throw new CliError(`${where}: "${field}" must be an http(s) URL${field === 'video' ? ' (a YouTube/Vimeo link or a media file URL; a local video file cannot be a tile)' : ''}.`);
15
+ return url;
16
+ }
17
+
18
+ function normalizeTile(raw, j, where, cwd) {
19
+ if (typeof raw === 'string' || typeof raw === 'number') return { id: String(raw), title: String(raw) };
20
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
21
+ throw new CliError(`${where}.items[${j}]: must be a string or {id, title, image?, video?, url?, caption?}.`);
22
+ }
23
+ const at = `${where}.items[${j}]`;
24
+ const id = asStr(raw.id ?? raw.value ?? raw.title ?? raw.label).trim();
25
+ if (!id) throw new CliError(`${at}: needs an "id" or a "title".`);
26
+ if (id.length > ID_MAX) throw new CliError(`${at}: id is longer than ${ID_MAX} characters.`);
27
+ const tile = { id, title: asStr(raw.title ?? raw.label).trim() || id };
28
+ const caption = asStr(raw.caption ?? raw.description).trim();
29
+ if (caption) tile.caption = caption;
30
+ const image = raw.image ?? raw.src ?? raw.img;
31
+ if (image !== undefined && image !== null && image !== '') tile.image = resolveImageSrc(image, cwd, at, '"image"');
32
+ if (raw.video !== undefined && raw.video !== null && raw.video !== '') tile.video = httpUrl(raw.video, at, 'video');
33
+ if (raw.url !== undefined && raw.url !== null && raw.url !== '') tile.url = httpUrl(raw.url, at, 'url');
34
+ return tile;
35
+ }
36
+
37
+ /**
38
+ * Adds the pick fields to a normalized question: `items`, `min`, `max`, `itemNote`, `overall`.
39
+ * The generic per-question note stays off: a pick carries its own notes.
40
+ * @param {Record<string, any>} q the question being built
41
+ * @param {Record<string, any>} rq what the agent wrote
42
+ */
43
+ export function normalizePick(q, rq, where, cwd) {
44
+ const rawItems = Array.isArray(rq.items) ? rq.items : Array.isArray(rq.options) ? rq.options : Array.isArray(rq.choices) ? rq.choices : [];
45
+ if (!rawItems.length) throw new CliError(`${where}: type "pick" needs "items", the tiles to choose among: [{id, title, image?, video?, url?, caption?}].`);
46
+ if (rawItems.length > PICK.maxItems) throw new CliError(`${where}: a pick takes at most ${PICK.maxItems} items.`);
47
+ q.items = rawItems.map((raw, j) => normalizeTile(raw, j, where, cwd));
48
+ const seen = new Set();
49
+ for (const tile of q.items) {
50
+ if (seen.has(tile.id)) throw new CliError(`${where}: duplicate item id "${tile.id}".`);
51
+ seen.add(tile.id);
52
+ }
53
+ const imageBytes = q.items.reduce((sum, t) => sum + (t.image ? t.image.length : 0), 0);
54
+ if (imageBytes > PICK.maxImageBytes) throw new CliError(`${where}: the embedded images add up to ${(imageBytes / 1024 / 1024).toFixed(0)}MB; the limit is ${PICK.maxImageBytes / 1024 / 1024}MB. Use https image URLs or smaller files.`);
55
+ const count = q.items.length;
56
+ q.min = clampInt(rq.min, 0, count, rq.required === true ? 1 : 0);
57
+ q.max = clampInt(rq.max, Math.max(1, q.min), count, count);
58
+ if (q.min > 0) q.required = true;
59
+ q.itemNote = rq.itemNote !== false;
60
+ q.overall = rq.overall !== false;
61
+ q.note = false;
62
+ delete q.placeholder;
63
+ }
64
+
65
+ const asObject = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
66
+ const limit = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
67
+
68
+ /**
69
+ * The answer to a pick question, cut down to what the question allows: known ids
70
+ * once each, at most `max` of them in the order picked, notes only when the tiles
71
+ * take them. Returns undefined when nothing is left, which reads as skipped.
72
+ * @returns {{ picks: Array<{ id: string, note?: string }>, overall?: string } | undefined}
73
+ */
74
+ export function cleanPick(q, value) {
75
+ const raw = asObject(value);
76
+ const known = new Set((q.items || []).map((t) => t.id));
77
+ const seen = new Set();
78
+ const picks = [];
79
+ for (const entry of Array.isArray(raw.picks) ? raw.picks : []) {
80
+ const id = typeof entry === 'string' ? entry : asObject(entry).id;
81
+ if (typeof id !== 'string' || !known.has(id) || seen.has(id) || picks.length >= q.max) continue;
82
+ seen.add(id);
83
+ const note = q.itemNote === false || typeof entry === 'string' ? '' : limit(entry.note, PICK.maxNoteChars);
84
+ picks.push(note ? { id, note } : { id });
85
+ }
86
+ const overall = q.overall === false ? '' : limit(raw.overall, PICK.maxOverallChars);
87
+ if (!picks.length && !overall) return undefined;
88
+ return overall ? { picks, overall } : { picks };
89
+ }
90
+
91
+ /**
92
+ * A copy of a board's answers in which every pick answer is cleaned. Other
93
+ * answers pass through as sent, which is how every board already treats them.
94
+ */
95
+ export function cleanAnswers(spec, answers) {
96
+ const out = { ...answers };
97
+ for (const q of spec.questions) {
98
+ if (q.type !== 'pick' || !(q.id in out)) continue;
99
+ const cleaned = cleanPick(q, out[q.id]);
100
+ if (cleaned) out[q.id] = cleaned;
101
+ else delete out[q.id];
102
+ }
103
+ return out;
104
+ }
@@ -123,7 +123,7 @@ export const SPEC_SCHEMA = {
123
123
  required: ['label'],
124
124
  properties: {
125
125
  id: { type: 'string', description: 'Answer key in the result JSON. Defaults to q1, q2, …' },
126
- type: { type: 'string', enum: ['single', 'multi', 'yesno', 'text', 'textarea', 'scale', 'color', 'rank', 'checklist', 'allocate'], default: 'text' },
126
+ type: { type: 'string', enum: ['single', 'multi', 'yesno', 'text', 'textarea', 'scale', 'color', 'rank', 'checklist', 'allocate', 'pick'], default: 'text' },
127
127
  label: { type: 'string' },
128
128
  description: { type: 'string' },
129
129
  required: { type: 'boolean', default: false },
@@ -145,12 +145,35 @@ export const SPEC_SCHEMA = {
145
145
  ],
146
146
  },
147
147
  },
148
+ items: {
149
+ type: 'array',
150
+ description: 'pick only: the tiles to choose among, 1 to 60. Strings, or {id, title, image?, video?, url?, caption?}. "image" is an https/data URL or a local file (embedded); "video" is an https YouTube/Vimeo link or media URL, shown as a link or a muted preview; "url" opens a page. The answer is {picks:[{id, note?}], overall?}: ids in the order picked, a note per tile, one overall note.',
151
+ items: {
152
+ anyOf: [
153
+ { type: 'string' },
154
+ {
155
+ type: 'object',
156
+ required: ['id'],
157
+ properties: {
158
+ id: { type: 'string', description: 'Answer key for this tile (default: its title).' },
159
+ title: { type: 'string' },
160
+ caption: { type: 'string' },
161
+ image: { type: 'string', description: 'https/data URL, or a local image file (embedded).' },
162
+ video: { type: 'string', description: 'https YouTube/Vimeo link or media file URL.' },
163
+ url: { type: 'string', description: 'https page the tile links to.' },
164
+ },
165
+ },
166
+ ],
167
+ },
168
+ },
169
+ itemNote: { type: 'boolean', default: true, description: 'pick only: a note field on each picked tile. Set false to hide it.' },
170
+ overall: { type: 'boolean', default: true, description: 'pick only: one overall note under the tiles. Set false to hide it.' },
148
171
  other: { type: 'boolean', description: 'Add a free-text "Other" option (a multi-line textarea); its text is returned verbatim as the value. Defaults ON for "single" (radio) questions so the user is never boxed in — set other:false to remove it; "multi" stays opt-in (other:true).' },
149
172
  note: { type: 'boolean', description: 'Small optional free-text field under the question (to qualify an answer). Returned separately as result.notes[questionId]. Defaults to true for the decision types — single, rank, checklist, allocate — so users can qualify their pick; false for other types. Set note:false to hide it, note:true to add it.' },
150
173
  placeholder: { type: 'string', description: 'For text/textarea.' },
151
174
  default: { description: 'Pre-selected value. Shape matches the answer shape for the type.' },
152
- min: { type: 'integer', default: 1, description: 'scale only' },
153
- max: { type: 'integer', default: 5, maximum: 10, description: 'scale only' },
175
+ min: { type: 'integer', default: 1, description: 'scale: lowest value. pick: fewest tiles to pick (default 0; 1 or more makes the question required).' },
176
+ max: { type: 'integer', default: 5, maximum: 10, description: 'scale: highest value, at most 10. pick: most tiles to pick (default: all of them; 1 makes it a single choice).' },
154
177
  minLabel: { type: 'string', description: 'scale only' },
155
178
  maxLabel: { type: 'string', description: 'scale only' },
156
179
  presets: { type: 'array', items: { type: 'string' }, description: 'color only: optional small preset swatches (CSS colors) shown beside the native picker for one-click selection. The answer is returned as a color string.' },
@@ -135,6 +135,7 @@
135
135
  for (const q of QS) if (q.type === 'rank') state.answers[q.id] = seedRankOrder(q, state.answers[q.id]);
136
136
  for (const q of QS) if (q.type === 'allocate') state.answers[q.id] = seedAllocate(q, state.answers[q.id]);
137
137
  for (const q of QS) if (q.type === 'checklist') state.answers[q.id] = seedChecklist(q, state.answers[q.id]);
138
+ for (const q of QS) if (q.type === 'pick') state.answers[q.id] = window.RelayPick.seed(q, state.answers[q.id]);
138
139
  // If the local mirror was newer than the server (or the server had nothing),
139
140
  // the in-memory state now holds input the server hasn't seen — flush it once
140
141
  // the rest of the app is wired (see the post-init flush near the heartbeat).
@@ -174,6 +175,8 @@
174
175
  const sum = Object.values(m).reduce((a, n) => a + (Number(n) || 0), 0);
175
176
  return sum > 0 ? { ...m } : undefined;
176
177
  }
178
+ case 'pick':
179
+ return window.RelayPick.value(q, v);
177
180
  default: {
178
181
  const t = typeof v === 'string' ? v.trim() : '';
179
182
  return t || undefined;