@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
@@ -53,7 +53,7 @@ export function filePreview(target, stat, reference) {
53
53
  let kind = /^(md|markdown|mdown)$/.test(ext) ? 'markdown' : /^(html|htm)$/.test(ext) ? 'html' : 'code';
54
54
  if (!reference.line && /^(csv|tsv)$/.test(ext)) {
55
55
  try {
56
- const block = normalizeSpec({ blocks: [{ type: 'table', rowsFile: target, sortable: true, filterable: true }] }).blocks[0];
56
+ const block = normalizeSpec({ blocks: [{ type: 'table', rowsFile: target, sortable: true, filterable: true }] }, { fileRoots: [target] }).blocks[0];
57
57
  return { ...base, kind: 'table', block, text, lang };
58
58
  } catch { /* malformed tables remain readable as source */ }
59
59
  }
package/src/mcp/boards.js CHANGED
@@ -1,8 +1,10 @@
1
1
  // What each relay tool does to a board, apart from MCP framing: build, view, draft, submit, read.
2
- import { assertSpecReady, normalizeSpec } from '../spec/index.js';
2
+ import { assertSpecReady, cleanAnswers, normalizeSpec } from '../spec/index.js';
3
3
  import { CliError } from '../util.js';
4
4
  import { saveBoardArtifact } from '../store.js';
5
+ import { ACTION_DRAFT, ACTION_SUBMIT } from '../a2ui/board-constants.js';
5
6
  import { assertSafeJson } from '../a2ui/compile.js';
7
+ import { fromA2ui } from '../a2ui/from-a2ui.js';
6
8
  import { findBlock, sanitizeAnnotations, sanitizeBlockEdits } from '../server/sanitize.js';
7
9
  import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, artifactBytesMatch } from '../server/result.js';
8
10
  import { RESULT_BUDGET_BYTES } from './constants.js';
@@ -25,15 +27,16 @@ export const modeOf = (spec) => (spec.responseRequired === false ? 'show' : 'ask
25
27
  * CliError so the tool can answer with an isError result the model can fix.
26
28
  * @param {import('./store.js').RelayStore} store
27
29
  * @param {Record<string, any>} args
28
- * @param {{ displayOnly?: boolean }} [options]
30
+ * @param {{ displayOnly?: boolean, fileRoots?: string[] }} [options] `fileRoots` are the only places a spec may read local files from; none by default
29
31
  */
30
32
  export async function createMcpBoard(store, args, options = {}) {
33
+ const fileRoots = options.fileRoots ?? [];
31
34
  const raw = { ...args };
32
35
  const hasQuestions = Array.isArray(raw.questions) && raw.questions.length > 0;
33
36
  if (options.displayOnly || (!hasQuestions && raw.responseRequired === undefined)) raw.responseRequired = false;
34
- const spec = normalizeSpec(raw);
37
+ const spec = normalizeSpec(raw, { fileRoots });
35
38
  await assertSpecReady(spec);
36
- const record = await store.create(spec);
39
+ const record = await store.create(spec, { fileRoots });
37
40
  return { record, spec, mode: modeOf(spec) };
38
41
  }
39
42
 
@@ -73,11 +76,11 @@ export function specError(err) {
73
76
  }
74
77
 
75
78
  /** Saves the person's answers so far, so relay_result can show them before the final submit. */
76
- export async function saveDraft(store, id, draft) {
79
+ export async function saveDraft(store, id, draft, spec) {
77
80
  const d = asObject(draft);
78
81
  return store.update(id, {
79
82
  draft: {
80
- answers: asObject(d.answers),
83
+ answers: spec ? cleanAnswers(spec, asObject(d.answers)) : asObject(d.answers),
81
84
  comment: limit(d.comment, MAX_TEXT),
82
85
  notes: asObject(d.notes),
83
86
  annotations: sanitizeAnnotations(d.annotations, id),
@@ -119,7 +122,7 @@ export async function submitBoard(store, record, body) {
119
122
  if (record.spec.responseRequired === false) return { ok: false, error: 'this board is display-only' };
120
123
  if (record.result) return { ok: false, error: 'this board was already submitted' };
121
124
  const b = asObject(body);
122
- const answers = asObject(b.answers);
125
+ const answers = cleanAnswers(record.spec, asObject(b.answers));
123
126
  const status = record.spec.questions.length ? 'submitted' : 'acknowledged';
124
127
  const result = {
125
128
  status,
@@ -157,6 +160,26 @@ export async function recordEvent(store, record, event) {
157
160
  return { ok: true, entry };
158
161
  }
159
162
 
163
+ /**
164
+ * A renderer event from an A2UI surface. `relay.submit` and `relay.draft` carry the surface's
165
+ * data model and store it as a submit or a draft; any other name is a widget button click.
166
+ * @returns {Promise<{ ok: boolean, status?: string, error?: string }>}
167
+ */
168
+ export async function handleSurfaceAction(store, record, args) {
169
+ const action = asObject(args.action);
170
+ const name = typeof action.name === 'string' ? action.name : args.name;
171
+ if (name !== ACTION_SUBMIT && name !== ACTION_DRAFT) {
172
+ const blockId = args.blockId;
173
+ return recordEvent(store, record, { blockId, name, context: args.context ?? action.context });
174
+ }
175
+ const dataModel = args.dataModel ?? asObject(action.context).dataModel ?? action.dataModel;
176
+ if (!dataModel || typeof dataModel !== 'object') return { ok: false, error: 'the event carries no data model' };
177
+ const payload = fromA2ui(dataModel, record.spec);
178
+ if (name === ACTION_SUBMIT) return submitBoard(store, record, payload);
179
+ await saveDraft(store, record.id, payload, record.spec);
180
+ return { ok: true };
181
+ }
182
+
160
183
  /** What relay_result reports for a board right now. */
161
184
  export function resultOf(record) {
162
185
  const r = record.result;
@@ -1,4 +1,6 @@
1
1
  // Names and limits shared by the MCP server modules and the board page.
2
+ import { A2UI_ACTION_TOOL } from '../a2ui/board-constants.js';
3
+
2
4
  export const UI_EXT = 'io.modelcontextprotocol/ui';
3
5
  export const UI_MIME = 'text/html;profile=mcp-app';
4
6
  export const BOARD_URI = 'ui://relay/board';
@@ -25,7 +27,7 @@ export const TOOL = {
25
27
  draft: 'relay_draft',
26
28
  submit: 'relay_submit',
27
29
  asset: 'relay_asset',
28
- a2uiAction: 'a2ui_action',
30
+ a2uiAction: A2UI_ACTION_TOOL,
29
31
  ask: 'relay_ask',
30
32
  show: 'relay_show',
31
33
  };
@@ -22,12 +22,15 @@ export const aliasInput = z.looseObject({});
22
22
  export const viewInput = z.object({ boardId, token });
23
23
  export const draftInput = z.object({ boardId, token, draft: loose });
24
24
  export const submitInput = z.object({ boardId, token, payload: loose });
25
+ /** A widget button click (`blockId`, `name`, `context`), or a renderer event (`action`, plus the surface's `dataModel`). */
25
26
  export const actionInput = z.object({
26
27
  boardId,
27
28
  token,
28
- blockId: z.string(),
29
- name: z.string(),
29
+ blockId: z.string().optional(),
30
+ name: z.string().optional(),
30
31
  context: loose.optional(),
32
+ action: loose.optional(),
33
+ dataModel: loose.optional(),
31
34
  });
32
35
  export const assetInput = z.object({ name: z.string(), index: z.number().int().min(0).default(0) });
33
36
 
package/src/mcp/serve.js CHANGED
@@ -7,11 +7,11 @@ import { loadServerKey } from './token.js';
7
7
  const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
8
8
 
9
9
  /** Serves MCP over this process's stdin and stdout until the host closes stdin. */
10
- export async function runMcp() {
10
+ export async function runMcp({ fileRoots = [] } = {}) {
11
11
  const { serveStdio } = await import('@modelcontextprotocol/server/stdio');
12
12
  const { createRelayServer } = await import('./server.js');
13
13
  const tokenKey = loadServerKey();
14
- const handle = serveStdio(() => createRelayServer({ tokenKey }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
14
+ const handle = serveStdio(() => createRelayServer({ tokenKey, fileRoots }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
15
15
  // Resolves only once the host disconnects, so the CLI's exit timer never fires.
16
16
  return new Promise((resolve) => {
17
17
  const finish = () => handle.close().finally(() => resolve(0));
@@ -90,12 +90,12 @@ const bearerOk = (header = '', token) => /^bearer /i.test(header) && safeEqual(h
90
90
  * Serves MCP over Streamable HTTP. Localhost by default; a bearer token and an
91
91
  * allowed Origin are the controls for anything wider.
92
92
  */
93
- export async function runMcpHttp({ port = DEFAULT_HTTP_PORT, host = '127.0.0.1', token = '', allowOrigin = '' } = {}) {
93
+ export async function runMcpHttp({ port = DEFAULT_HTTP_PORT, host = '127.0.0.1', token = '', allowOrigin = '', fileRoots = [] } = {}) {
94
94
  const { createMcpHandler } = await import('@modelcontextprotocol/server');
95
95
  const { toNodeHandler } = await import('@modelcontextprotocol/node');
96
96
  const { createRelayServer } = await import('./server.js');
97
97
  const tokenKey = loadServerKey();
98
- const handler = createMcpHandler(() => createRelayServer({ tokenKey }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
98
+ const handler = createMcpHandler(() => createRelayServer({ tokenKey, fileRoots }), { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
99
99
  const serve = toNodeHandler(handler, { onerror: (e) => process.stderr.write(`relay mcp: ${e.message}\n`) });
100
100
 
101
101
  const server = http.createServer(requestListener({ serve, token, allowOrigin, endpoint: `http://${host === '0.0.0.0' ? 'localhost' : host}:${port}${HTTP_PATH}` }));
package/src/mcp/server.js CHANGED
@@ -1,12 +1,13 @@
1
1
  // Builds an McpServer with the relay tools registered.
2
2
  import { McpServer } from '@modelcontextprotocol/server';
3
+ import { capabilitiesDeclareBoardCatalog } from '../a2ui/negotiate.js';
3
4
  import { UI_EXT, UI_MIME } from './constants.js';
4
5
  import { PKG } from './page.js';
5
6
  import { registerRelay } from './tools.js';
6
7
 
7
8
  const INSTRUCTIONS = 'Relay shows boards inline. Call relay_board with a spec; the person answers in the board, then read it with relay_result. relay_help gives exact field shapes.';
8
9
 
9
- const clientRendersBoards = (capabilities) => Boolean(capabilities?.extensions?.[UI_EXT]);
10
+ const clientRendersBoards = (capabilities) => Boolean(capabilities?.extensions?.[UI_EXT]) || capabilitiesDeclareBoardCatalog(capabilities);
10
11
 
11
12
  /** @param {Parameters<typeof registerRelay>[1]} [options] */
12
13
  export function createRelayServer(options = {}) {
package/src/mcp/store.js CHANGED
@@ -12,7 +12,7 @@ import { createBoard, loadBoard, saveBoard, saveResultFile } from '../store.js';
12
12
 
13
13
  /**
14
14
  * @typedef {object} RelayStore
15
- * @property {(spec: any) => BoardRecord | Promise<BoardRecord>} create
15
+ * @property {(spec: any, options?: { fileRoots?: string[] }) => BoardRecord | Promise<BoardRecord>} create
16
16
  * @property {(id: string) => BoardRecord | null | Promise<BoardRecord | null>} get
17
17
  * @property {(id: string, patch: Partial<BoardRecord>) => BoardRecord | null | Promise<BoardRecord | null>} update
18
18
  */
@@ -21,7 +21,7 @@ import { createBoard, loadBoard, saveBoard, saveResultFile } from '../store.js';
21
21
  export function fileStore() {
22
22
  const get = (id) => (/^b-[a-z0-9]+$/i.test(String(id)) ? loadBoard(id) : null);
23
23
  return {
24
- create: (spec) => createBoard(spec),
24
+ create: (spec, options) => createBoard(spec, options),
25
25
  get,
26
26
  update(id, patch) {
27
27
  const record = get(id);
package/src/mcp/token.js CHANGED
@@ -6,18 +6,43 @@ import { HOME } from '../store.js';
6
6
 
7
7
  const KEY_FILE = path.join(HOME, 'mcp-key');
8
8
 
9
- /** The server's HMAC key: a random value kept in the relay home, created on first use. */
10
- export function loadServerKey(file = KEY_FILE) {
9
+ const readKey = (file) => {
11
10
  try {
12
- const existing = fs.readFileSync(file, 'utf8').trim();
13
- if (existing) return existing;
11
+ return fs.readFileSync(file, 'utf8').trim();
14
12
  } catch {
15
- // first run: create it below
13
+ return '';
16
14
  }
17
- const key = crypto.randomBytes(32).toString('hex');
15
+ };
16
+
17
+ /**
18
+ * The server's HMAC key: a random value kept in the relay home, created on first use.
19
+ * Two servers starting together both try to create it; the exclusive create lets one
20
+ * win and the other read what the winner wrote, so they never hold different keys.
21
+ */
22
+ export function loadServerKey(file = KEY_FILE) {
23
+ const existing = readKey(file);
24
+ if (existing) return existing;
18
25
  fs.mkdirSync(path.dirname(file), { recursive: true });
19
- fs.writeFileSync(file, key + '\n', { mode: 0o600 });
20
- return key;
26
+ const key = crypto.randomBytes(32).toString('hex');
27
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
28
+ fs.writeFileSync(tmp, `${key}\n`, { mode: 0o600 });
29
+ try {
30
+ // link() fails when the key already exists and never exposes a half-written file.
31
+ fs.linkSync(tmp, file);
32
+ return key;
33
+ } catch (e) {
34
+ if (e.code === 'EEXIST') return readKey(file) || key;
35
+ // A filesystem without hard links: fall back to an exclusive create.
36
+ try {
37
+ fs.writeFileSync(file, `${key}\n`, { mode: 0o600, flag: 'wx' });
38
+ return key;
39
+ } catch (again) {
40
+ if (again.code !== 'EEXIST') throw again;
41
+ return readKey(file) || key;
42
+ }
43
+ } finally {
44
+ fs.rmSync(tmp, { force: true });
45
+ }
21
46
  }
22
47
 
23
48
  export const boardToken = (key, boardId) => crypto.createHmac('sha256', key).update(String(boardId)).digest('hex');
package/src/mcp/tools.js CHANGED
@@ -2,11 +2,14 @@
2
2
  import { registerAppResource, registerAppTool } from '@modelcontextprotocol/ext-apps/server';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
+ import { A2UI_MIME, BOARD_CATALOG_ID } from '../a2ui/board-constants.js';
6
+ import { wantsA2ui } from '../a2ui/negotiate.js';
7
+ import { toA2ui } from '../a2ui/to-a2ui.js';
5
8
  import { renderAgentTopic, topicIndex } from '../cli/agent-topics.js';
6
9
  import { lookupSchema } from '../spec/index.js';
7
10
  import { sleep } from '../util.js';
8
11
  import {
9
- boardResult, createMcpBoard, errorResult, isFinal, recordEvent, resultOf, saveDraft, specError, submitBoard,
12
+ boardResult, createMcpBoard, errorResult, handleSurfaceAction, isFinal, resultOf, saveDraft, specError, submitBoard,
10
13
  } from './boards.js';
11
14
  import { BOARD_URI, MAX_WAIT_SECONDS, TOOL, UI_MIME, VENDOR_URI_PREFIX } from './constants.js';
12
15
  import { BOARD_RESOURCE_META, boardPage, DOCS_DIR, vendorChunk, vendorText, VENDOR_FILES } from './page.js';
@@ -33,6 +36,7 @@ const json = (value, structured) => ({ content: [{ type: 'text', text: JSON.stri
33
36
  * @param {any} server an McpServer
34
37
  * @param {object} [options]
35
38
  * @param {import('./store.js').RelayStore} [options.store] where boards live; defaults to the relay home on disk
39
+ * @param {string[]} [options.fileRoots] folders a spec may read local files from (`codeFile`, images, `rowsFile`...); none by default, so a remote client cannot read the server's disk
36
40
  * @param {string | Buffer} [options.tokenKey] the secret behind board tokens; defaults to a key file in the relay home
37
41
  * @param {(name: string) => string} [options.assetUrl] URL of a vendor file, for hosts that can fetch it
38
42
  * @param {(boardId: string) => string} [options.linkUrl] a URL where a person can open the board outside the host
@@ -67,13 +71,13 @@ function registerBoardTools({ server, options, store, key }) {
67
71
  const openBoard = (displayOnly) => async (args) => {
68
72
  let made;
69
73
  try {
70
- made = await createMcpBoard(store, args, { displayOnly });
74
+ made = await createMcpBoard(store, args, { displayOnly, fileRoots: options.fileRoots });
71
75
  } catch (err) {
72
76
  return specError(err);
73
77
  }
74
78
  const result = boardResult(made.record, made.spec, made.mode);
75
79
  if (options.linkUrl) result.structuredContent = { .../** @type {object} */ (result.structuredContent), url: options.linkUrl(made.record.id) };
76
- result._meta = { ...appMeta(['model', 'app']), relay: { token: boardToken(key, made.record.id) } };
80
+ result._meta = { ...appMeta(['model', 'app']), relay: { token: boardToken(key, made.record.id) }, 'relay/a2ui': { catalogIds: [BOARD_CATALOG_ID] } };
77
81
  return result;
78
82
  };
79
83
  registerAppTool(server, TOOL.board, { title: 'Relay board', description: BOARD_DESCRIPTION, inputSchema: boardInput, _meta: modelMeta }, openBoard(false));
@@ -131,18 +135,23 @@ function registerAppTools({ server, options, store, key }) {
131
135
  return act(record, args);
132
136
  });
133
137
 
134
- appTool(TOOL.view, { description: 'The board spec, for the board iframe.', inputSchema: viewInput }, async (args) => {
138
+ appTool(TOOL.view, { description: 'The board, for the board iframe; for a host that declared the board catalog, A2UI messages.', inputSchema: viewInput }, async (args, ctx) => {
135
139
  const { record, error } = await guard(args);
136
140
  if (error) return error;
141
+ const caller = { capabilities: server.server.getClientCapabilities(), meta: ctx?.mcpReq?._meta };
142
+ if (wantsA2ui(caller)) {
143
+ const messages = toA2ui(record.spec, { surfaceId: `relay-${record.id}`, draft: record.draft });
144
+ return { content: [{ type: 'resource', resource: { uri: `a2ui://relay/board/${record.id}`, mimeType: A2UI_MIME, text: JSON.stringify(messages) } }] };
145
+ }
137
146
  const vendorUrls = options.assetUrl ? Object.fromEntries(VENDOR_FILES.map((f) => [f, options.assetUrl(f)])) : undefined;
138
147
  return json({ boardId: record.id }, { boardId: record.id, spec: record.spec, draft: record.draft ?? null, finished: Boolean(record.result), vendorUrls });
139
148
  });
140
149
  appTool(TOOL.draft, { description: 'Saves the answers so far.', inputSchema: draftInput }, onOpenBoard(async (record, args) => {
141
- await saveDraft(store, record.id, args.draft);
150
+ await saveDraft(store, record.id, args.draft, record.spec);
142
151
  return text('saved');
143
152
  }));
144
- appTool(TOOL.a2uiAction, { description: 'Records a button click from an a2ui block.', inputSchema: actionInput }, onOpenBoard(async (record, args) => {
145
- const outcome = await recordEvent(store, record, args);
153
+ appTool(TOOL.a2uiAction, { description: 'A renderer event: a button click from an a2ui block, or relay.submit and relay.draft from an A2UI board surface.', inputSchema: actionInput }, onOpenBoard(async (record, args) => {
154
+ const outcome = await handleSurfaceAction(store, record, args);
146
155
  return outcome.ok ? text('recorded') : errorResult(`relay: ${outcome.error}`);
147
156
  }));
148
157
  appTool(TOOL.submit, { description: 'Stores the final answers.', inputSchema: submitInput }, (args) => oneAtATime(args.boardId, async () => {
@@ -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
  }
@@ -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;
@@ -6,15 +6,16 @@ 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';
17
- import { buildOpenAllowlist, resolveLocalPath, streamFile } from './files.js';
17
+ import { checkReadable } from '../file-access.js';
18
+ import { buildOpenAllowlist, recordFileAccess, resolveLocalPath, streamFile } from './files.js';
18
19
 
19
20
  // Serves one board on 127.0.0.1 and resolves `done` when it finishes
20
21
  // (submitted / acknowledged / timeout / cancelled). The result is also
@@ -267,6 +268,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
267
268
  return sendJson(res, 400, { error: err && err.message ? err.message : String(err) });
268
269
  }
269
270
  record.spec = next;
271
+ if (Array.isArray(body.fileRoots)) record.fileRoots = body.fileRoots.filter((r) => typeof r === 'string');
270
272
  rev++;
271
273
  saveBoard(record);
272
274
  sendJson(res, 200, { ok: true, rev });
@@ -289,10 +291,12 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
289
291
  // Embedded image bytes (image blocks authored from local files).
290
292
  const blockId = decodeURIComponent(pathname.slice('/img/b/'.length));
291
293
  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'));
294
+ if (!sendDataImage(res, block?.src)) return sendJson(res, 404, { error: `no embedded image block "${blockId}"` });
295
+ } else if (req.method === 'GET' && pathname.startsWith('/img/p/')) {
296
+ // Embedded tile image bytes (pick questions authored from local files).
297
+ const [questionId, itemId] = pathname.slice('/img/p/'.length).split('/').map(decodeURIComponent);
298
+ const tile = record.spec.questions.find((q) => q.id === questionId && q.type === 'pick')?.items.find((t) => t.id === itemId);
299
+ if (!sendDataImage(res, tile?.image)) return sendJson(res, 404, { error: `no embedded tile image "${questionId}/${itemId}"` });
296
300
  } else if (req.method === 'POST' && pathname === '/api/artifact') {
297
301
  if (record.spec.responseRequired === false) return sendJson(res, 409, { error: 'display-only boards do not collect feedback' });
298
302
  if (!sameOrigin(req, actualPort, [advertisedHost], [publicLink?.origin])) return sendJson(res, 403, { error: 'cross-origin artifact upload rejected' });
@@ -324,13 +328,17 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
324
328
  const blockId = decodeURIComponent(pathname.slice('/video/b/'.length));
325
329
  const block = findBlock(record.spec, blockId, 'video');
326
330
  if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local video block "${blockId}"` });
327
- streamFile(req, res, block.file, block.mime || 'application/octet-stream');
331
+ const video = checkReadable(recordFileAccess(record), block.file);
332
+ if (!video.ok) return sendJson(res, 404, { error: `no local video block "${blockId}"` });
333
+ streamFile(req, res, video.file, block.mime || 'application/octet-stream');
328
334
  } else if ((req.method === 'GET' || req.method === 'HEAD') && pathname.startsWith('/pdf/b/')) {
329
335
  // Local PDF bytes, Range-streamed for the browser's built-in PDF viewer.
330
336
  const blockId = decodeURIComponent(pathname.slice('/pdf/b/'.length));
331
337
  const block = findBlock(record.spec, blockId, 'pdf');
332
338
  if (!block || typeof block.file !== 'string') return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
333
- streamFile(req, res, block.file, block.mime || 'application/pdf');
339
+ const pdf = checkReadable(recordFileAccess(record), block.file);
340
+ if (!pdf.ok) return sendJson(res, 404, { error: `no local pdf block "${blockId}"` });
341
+ streamFile(req, res, pdf.file, block.mime || 'application/pdf');
334
342
  } else if (req.method === 'GET' && pathname === '/html/board') {
335
343
  // Legacy alias → the board's first html block.
336
344
  const block = firstBoardHtml(record.spec);
@@ -366,24 +374,23 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
366
374
  if (!buildOpenAllowlist(record.spec, baseCwd).has(target)) {
367
375
  return sendJson(res, 403, { error: 'this path is not referenced on the board' });
368
376
  }
369
- let stat = null;
370
- try {
371
- stat = fs.statSync(target);
372
- } catch {
373
- stat = null;
377
+ const checked = checkReadable(recordFileAccess(record), target, { allowDirectory: true });
378
+ if (!checked.ok) {
379
+ if (checked.reason === 'missing') return sendJson(res, 404, { error: 'file not found', path: target });
380
+ return sendJson(res, 403, { error: checked.reason === 'outside' ? 'this path is outside the board\'s file roots' : 'this path is not a file or folder' });
374
381
  }
375
- if (!stat) return sendJson(res, 404, { error: 'file not found', path: target });
382
+ const { file: real, stat } = checked;
376
383
  if (pathname === '/api/file-preview') {
377
- return sendJson(res, 200, { ok: true, ...filePreview(target, stat, splitFileReference(raw)) });
384
+ return sendJson(res, 200, { ok: true, ...filePreview(real, stat, splitFileReference(raw)) });
378
385
  }
379
386
  if (pathname === '/api/file-content') {
380
- const media = mediaType(target);
387
+ const media = mediaType(real);
381
388
  if (!stat.isFile() || !media) return sendJson(res, 415, { error: 'this file type cannot be streamed' });
382
389
  res.setHeader('X-Content-Type-Options', 'nosniff');
383
390
  res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
384
- return streamFile(req, res, target, media[1]);
391
+ return streamFile(req, res, real, media[1]);
385
392
  }
386
- if (!openUrl(target)) return sendJson(res, 500, { error: 'could not open the file' });
393
+ if (!openUrl(real)) return sendJson(res, 500, { error: 'could not open the file' });
387
394
  sendJson(res, 200, { ok: true, path: target, name: path.basename(target) });
388
395
  } else if (req.method === 'POST' && pathname === '/api/draft') {
389
396
  if (record.spec.responseRequired === false) return sendJson(res, 409, { error: 'display-only boards do not collect feedback' });
@@ -393,11 +400,12 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
393
400
  return sendJson(res, 403, { error: 'this share is read only' });
394
401
  }
395
402
  const body = JSON.parse((await readBody(req)) || '{}');
403
+ const draftAnswers = cleanAnswers(record.spec, body.answers && typeof body.answers === 'object' ? body.answers : {});
396
404
  if (access.role === 'review') {
397
405
  record.reviewDrafts = record.reviewDrafts && typeof record.reviewDrafts === 'object' ? record.reviewDrafts : {};
398
406
  const priorRev = Number(record.reviewDrafts[access.reviewSessionId]?.draftRev) || 0;
399
407
  record.reviewDrafts[access.reviewSessionId] = {
400
- answers: body.answers && typeof body.answers === 'object' ? body.answers : {},
408
+ answers: draftAnswers,
401
409
  comment: typeof body.comment === 'string' ? body.comment : '',
402
410
  notes: body.notes && typeof body.notes === 'object' ? body.notes : {},
403
411
  annotations: sanitizeAnnotations(body.annotations, record.id),
@@ -408,7 +416,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
408
416
  pruneReviewDrafts(record);
409
417
  } else {
410
418
  record.draft = {
411
- answers: body.answers && typeof body.answers === 'object' ? body.answers : {},
419
+ answers: draftAnswers,
412
420
  comment: typeof body.comment === 'string' ? body.comment : '',
413
421
  notes: body.notes && typeof body.notes === 'object' ? body.notes : {},
414
422
  annotations: sanitizeAnnotations(body.annotations, record.id),
@@ -429,7 +437,7 @@ export async function runBoard({ id, port = 0, open = true, timeoutSec = 86400,
429
437
  if (!access.canSubmit) return sendJson(res, 403, { error: 'this share is read only' });
430
438
  if (status !== 'open') return sendJson(res, 409, { error: 'board already finished' });
431
439
  const body = JSON.parse((await readBody(req)) || '{}');
432
- const answers = body.answers && typeof body.answers === 'object' ? body.answers : {};
440
+ const answers = cleanAnswers(record.spec, body.answers && typeof body.answers === 'object' ? body.answers : {});
433
441
  const skipped = record.spec.questions.filter((q) => !(q.id in answers)).map((q) => q.id);
434
442
  if (access.role === 'review') {
435
443
  const review = {
@@ -3,6 +3,7 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { createFileAccess } from '../file-access.js';
6
7
  import { splitFileReference } from '../file-preview.js';
7
8
  import { sendJson } from './http.js';
8
9
 
@@ -35,6 +36,15 @@ function looksLikeLocalPath(s) {
35
36
  return false;
36
37
  }
37
38
 
39
+ /**
40
+ * The file roots a stored board was created under. Boards saved before roots
41
+ * existed fall back to their authoring directory.
42
+ */
43
+ export function recordFileAccess(record) {
44
+ const cwd = record.cwd || process.cwd();
45
+ return createFileAccess({ cwd, roots: Array.isArray(record.fileRoots) ? record.fileRoots : [cwd] });
46
+ }
47
+
38
48
  // Expands ~ / file:// and resolves a (possibly relative) path to an absolute,
39
49
  // normalized one against the board's authoring cwd. null on a malformed URL.
40
50
  export function resolveLocalPath(raw, baseCwd) {
@@ -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
@@ -5,7 +5,7 @@ import { asStr, clampInt } from '../sources.js';
5
5
  import { BLOCK_HEIGHT } from '../constants.js';
6
6
 
7
7
  // Normalizes one a2ui block. `id` is the already-assigned block id.
8
- export function normalizeA2uiBlock(rawBlock, id, cwd, where, hasHeight) {
8
+ export function normalizeA2uiBlock(rawBlock, id, files, where, hasHeight) {
9
9
  // A live A2UI v1.0 widget: Express text (compiled in assertSpecReady) or
10
10
  // ready JSON components, checked against Relay's catalog either way.
11
11
  const hasExpress = rawBlock.express !== undefined && rawBlock.express !== null;
@@ -7,7 +7,7 @@ import { BLOCK_HEIGHT, CHART_KINDS, CHART_KIND_FIELDS, CHART_SERIES_FIELDS } fro
7
7
  const firstDefined = (raw, names) => raw[names.find((n) => raw[n] !== undefined)];
8
8
 
9
9
  // Normalizes one chart block. `id` is the already-assigned block id.
10
- export function normalizeChartBlock(raw, id, cwd, where, hasHeight) {
10
+ export function normalizeChartBlock(raw, id, files, where, hasHeight) {
11
11
  const rawBlock = { ...raw, kind: firstDefined(raw, CHART_KIND_FIELDS), series: firstDefined(raw, CHART_SERIES_FIELDS) };
12
12
  const hasConfig = rawBlock.config && typeof rawBlock.config === 'object' && !Array.isArray(rawBlock.config);
13
13
  const hasShorthand =
@@ -5,8 +5,8 @@ import { asStr, clampInt, readTextSource } from '../sources.js';
5
5
  import { BLOCK_HEIGHT } from '../constants.js';
6
6
 
7
7
  // Normalizes one code block. `id` is the already-assigned block id.
8
- export function normalizeCodeBlock(rawBlock, id, cwd, where, hasHeight) {
9
- const code = readTextSource(rawBlock, 'code', 'codeFile', cwd, where);
8
+ export function normalizeCodeBlock(rawBlock, id, files, where, hasHeight) {
9
+ const code = readTextSource(rawBlock, 'code', 'codeFile', files, where);
10
10
  if (!code) throw new CliError(`${where}: code block needs a "code" string or a readable "codeFile".`);
11
11
  const block = { id, type: 'code', code };
12
12
  if (rawBlock.lang !== undefined) block.lang = asStr(rawBlock.lang);
@@ -21,8 +21,8 @@ export function normalizeCodeBlock(rawBlock, id, cwd, where, hasHeight) {
21
21
  }
22
22
 
23
23
  // Normalizes one diff block. `id` is the already-assigned block id.
24
- export function normalizeDiffBlock(rawBlock, id, cwd, where, hasHeight) {
25
- const diff = readTextSource(rawBlock, 'diff', 'diffFile', cwd, where);
24
+ export function normalizeDiffBlock(rawBlock, id, files, where, hasHeight) {
25
+ const diff = readTextSource(rawBlock, 'diff', 'diffFile', files, where);
26
26
  if (!diff.trim()) throw new CliError(`${where}: diff block needs a non-empty "diff" string (unified diff) or a readable "diffFile".`);
27
27
  const block = { id, type: 'diff', diff };
28
28
  if (rawBlock.lang !== undefined) block.lang = asStr(rawBlock.lang);