@khanglvm/relay 0.20.2 → 0.21.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.
- package/README.md +2 -2
- package/docs/AGENT.md +56 -83
- package/docs/SETUP.md +3 -2
- package/package.json +12 -5
- package/skills/relay/SKILL.md +45 -145
- package/src/cli/agent-topics.js +84 -0
- package/src/cli/config.js +26 -2
- package/src/cli/index.js +3 -5
- package/src/cli/mcp.js +4 -2
- package/src/cli/skill.js +21 -22
- package/src/mcp/boards.js +173 -0
- package/src/mcp/config.js +20 -0
- package/src/mcp/constants.js +31 -0
- package/src/mcp/index.js +5 -0
- package/src/mcp/page.js +59 -0
- package/src/mcp/schemas.js +42 -0
- package/src/mcp/serve.js +116 -0
- package/src/mcp/server.js +23 -0
- package/src/mcp/store.js +35 -0
- package/src/mcp/token.js +31 -0
- package/src/mcp/tools.js +171 -0
- package/src/mcp-ui/board/block-ctx.js +22 -0
- package/src/mcp-ui/board/bridge.js +12 -2
- package/src/mcp-ui/board/core.js +2 -0
- package/src/mcp-ui/board/lifecycle.js +47 -9
- package/src/mcp-ui/board/render.js +36 -44
- package/src/mcp-ui/board/vendors.js +56 -11
- package/src/spec/blocks/chart.js +8 -4
- package/src/spec/constants.js +19 -0
- package/src/spec/index.js +1 -0
- package/src/spec/lookup.js +78 -0
- package/src/spec/normalize.js +9 -4
- package/src/spec/ready.js +15 -1
- package/src/ui/manifest.js +1 -1
- package/types/cli/agent-topics.d.ts +46 -0
- package/types/mcp/boards.d.ts +168 -0
- package/types/{mcp.d.ts → mcp/config.d.ts} +1 -8
- package/types/mcp/constants.d.ts +21 -0
- package/types/mcp/index.d.ts +4 -0
- package/types/mcp/page.d.ts +27 -0
- package/types/mcp/schemas.d.ts +46 -0
- package/types/mcp/serve.d.ts +16 -0
- package/types/mcp/server.d.ts +4 -0
- package/types/mcp/store.d.ts +52 -0
- package/types/mcp/token.d.ts +5 -0
- package/types/mcp/tools.d.ts +17 -0
- package/types/server/result.d.ts +10 -0
- package/types/server/sanitize.d.ts +6 -0
- package/types/spec/blocks/chart.d.ts +1 -1
- package/types/spec/constants.d.ts +14 -0
- package/types/spec/index.d.ts +1 -0
- package/types/spec/lookup.d.ts +57 -0
- package/types/spec/ready.d.ts +2 -0
- package/src/mcp.js +0 -483
package/src/mcp/token.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// The per-board token an iframe presents to the app-only tools.
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { HOME } from '../store.js';
|
|
6
|
+
|
|
7
|
+
const KEY_FILE = path.join(HOME, 'mcp-key');
|
|
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) {
|
|
11
|
+
try {
|
|
12
|
+
const existing = fs.readFileSync(file, 'utf8').trim();
|
|
13
|
+
if (existing) return existing;
|
|
14
|
+
} catch {
|
|
15
|
+
// first run: create it below
|
|
16
|
+
}
|
|
17
|
+
const key = crypto.randomBytes(32).toString('hex');
|
|
18
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
19
|
+
fs.writeFileSync(file, key + '\n', { mode: 0o600 });
|
|
20
|
+
return key;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const boardToken = (key, boardId) => crypto.createHmac('sha256', key).update(String(boardId)).digest('hex');
|
|
24
|
+
|
|
25
|
+
/** Constant-time comparison, so a wrong token leaks nothing about the right one. */
|
|
26
|
+
export function tokenValid(key, boardId, token) {
|
|
27
|
+
if (typeof token !== 'string') return false;
|
|
28
|
+
const want = Buffer.from(boardToken(key, boardId));
|
|
29
|
+
const got = Buffer.from(token);
|
|
30
|
+
return want.length === got.length && crypto.timingSafeEqual(want, got);
|
|
31
|
+
}
|
package/src/mcp/tools.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// registerRelay: the relay tools and the board resource on any MCP server.
|
|
2
|
+
import { registerAppResource, registerAppTool } from '@modelcontextprotocol/ext-apps/server';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { renderAgentTopic, topicIndex } from '../cli/agent-topics.js';
|
|
6
|
+
import { lookupSchema } from '../spec/index.js';
|
|
7
|
+
import { sleep } from '../util.js';
|
|
8
|
+
import {
|
|
9
|
+
boardResult, createMcpBoard, errorResult, isFinal, recordEvent, resultOf, saveDraft, specError, submitBoard,
|
|
10
|
+
} from './boards.js';
|
|
11
|
+
import { BOARD_URI, MAX_WAIT_SECONDS, TOOL, UI_MIME, VENDOR_URI_PREFIX } from './constants.js';
|
|
12
|
+
import { BOARD_RESOURCE_META, boardPage, DOCS_DIR, vendorChunk, vendorText, VENDOR_FILES } from './page.js';
|
|
13
|
+
import { actionInput, aliasInput, assetInput, boardInput, draftInput, helpInput, resultInput, submitInput, viewInput } from './schemas.js';
|
|
14
|
+
import { fileStore } from './store.js';
|
|
15
|
+
import { boardToken, loadServerKey, tokenValid } from './token.js';
|
|
16
|
+
|
|
17
|
+
const BOARD_DESCRIPTION = `Put a board in front of the person and collect their answers. It renders inline; the result is a summary with the boardId. Read the outcome with relay_result.
|
|
18
|
+
Spec: {title, intro?, blocks?:[...], questions?:[...]}. With no questions the board is display-only and needs no reply.
|
|
19
|
+
Question: {id,type,label,required?,options?:[{value,label,description?,blocks?}|"text"]}. Types: single multi yesno text textarea scale(min,max) color rank checklist allocate(total).
|
|
20
|
+
Blocks: markdown(md|mdFile) code(code|codeFile) diff(diffFile) image(src,alt?,pins?) compare(before,after) chart(kind,labels,series:[{label,data}]) table(columns,rows) kpi(items) mermaid(code) graphviz(dot) html palette video pdf a2ui(express). Local files take absolute paths; inline boards cannot open local links, so embed file content.
|
|
21
|
+
Blocks go on the board, on a question, or on an option. Use ids that stay stable.
|
|
22
|
+
For exact fields call relay_help {topic: questions|blocks|annotate|lifecycle|a2ui|sharing|mcp} or {schema:"chart"}.`;
|
|
23
|
+
|
|
24
|
+
const readDoc = (file) => fs.readFileSync(path.join(DOCS_DIR, file), 'utf8');
|
|
25
|
+
/** @returns {import('./boards.js').ToolResult} */
|
|
26
|
+
const text = (t) => ({ content: [{ type: 'text', text: t }] });
|
|
27
|
+
/** @returns {import('./boards.js').ToolResult} */
|
|
28
|
+
const json = (value, structured) => ({ content: [{ type: 'text', text: JSON.stringify(value) }], ...(structured ? { structuredContent: structured } : {}) });
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Adds the relay tools and the board resource to `server`.
|
|
32
|
+
*
|
|
33
|
+
* @param {any} server an McpServer
|
|
34
|
+
* @param {object} [options]
|
|
35
|
+
* @param {import('./store.js').RelayStore} [options.store] where boards live; defaults to the relay home on disk
|
|
36
|
+
* @param {string | Buffer} [options.tokenKey] the secret behind board tokens; defaults to a key file in the relay home
|
|
37
|
+
* @param {(name: string) => string} [options.assetUrl] URL of a vendor file, for hosts that can fetch it
|
|
38
|
+
* @param {(boardId: string) => string} [options.linkUrl] a URL where a person can open the board outside the host
|
|
39
|
+
* @returns the app-only tools, so a server can hide them from a client that cannot render the board
|
|
40
|
+
*/
|
|
41
|
+
export function registerRelay(server, options = {}) {
|
|
42
|
+
const ctx = { server, options, store: options.store ?? fileStore(), key: options.tokenKey ?? loadServerKey() };
|
|
43
|
+
registerBoardTools(ctx);
|
|
44
|
+
registerReadTools(ctx);
|
|
45
|
+
const appTools = registerAppTools(ctx);
|
|
46
|
+
registerResources(server);
|
|
47
|
+
return appTools;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Every app call reads a board and writes it back whole. Two clicks forwarded at once,
|
|
51
|
+
// or a draft racing the submit, would otherwise drop one write. The queue is per
|
|
52
|
+
// process, not per server, because the HTTP transport builds a server per request.
|
|
53
|
+
const boardQueues = new Map();
|
|
54
|
+
function oneAtATime(boardId, task) {
|
|
55
|
+
const key = String(boardId);
|
|
56
|
+
const run = (boardQueues.get(key) ?? Promise.resolve()).then(task);
|
|
57
|
+
const tail = run.catch(() => {});
|
|
58
|
+
boardQueues.set(key, tail);
|
|
59
|
+
tail.then(() => { if (boardQueues.get(key) === tail) boardQueues.delete(key); });
|
|
60
|
+
return run;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const appMeta = (visibility) => ({ ui: { resourceUri: BOARD_URI, visibility } });
|
|
64
|
+
const modelMeta = { ...appMeta(['model', 'app']), 'openai/outputTemplate': BOARD_URI };
|
|
65
|
+
|
|
66
|
+
function registerBoardTools({ server, options, store, key }) {
|
|
67
|
+
const openBoard = (displayOnly) => async (args) => {
|
|
68
|
+
let made;
|
|
69
|
+
try {
|
|
70
|
+
made = await createMcpBoard(store, args, { displayOnly });
|
|
71
|
+
} catch (err) {
|
|
72
|
+
return specError(err);
|
|
73
|
+
}
|
|
74
|
+
const result = boardResult(made.record, made.spec, made.mode);
|
|
75
|
+
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) } };
|
|
77
|
+
return result;
|
|
78
|
+
};
|
|
79
|
+
registerAppTool(server, TOOL.board, { title: 'Relay board', description: BOARD_DESCRIPTION, inputSchema: boardInput, _meta: modelMeta }, openBoard(false));
|
|
80
|
+
registerAppTool(server, TOOL.ask, { description: 'Deprecated alias of relay_board.', inputSchema: aliasInput, _meta: modelMeta }, openBoard(false));
|
|
81
|
+
registerAppTool(server, TOOL.show, { description: 'Deprecated alias of relay_board for a display-only board.', inputSchema: aliasInput, _meta: modelMeta }, openBoard(true));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function registerReadTools({ server, store }) {
|
|
85
|
+
const modelOnly = { ui: { visibility: ['model'] } };
|
|
86
|
+
registerAppTool(server, TOOL.help, {
|
|
87
|
+
description: 'Exact Relay field shapes. topic: questions, blocks, annotate, lifecycle, a2ui, sharing, mcp. schema: one block or question type.',
|
|
88
|
+
inputSchema: helpInput,
|
|
89
|
+
_meta: modelOnly,
|
|
90
|
+
}, ({ topic, schema }) => {
|
|
91
|
+
if (schema) {
|
|
92
|
+
const found = lookupSchema(schema);
|
|
93
|
+
return found ? json(found) : errorResult(`relay: no block or question type "${schema}". ${topicIndex()}`);
|
|
94
|
+
}
|
|
95
|
+
return text(topic ? renderAgentTopic(topic, readDoc) : topicIndex());
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
registerAppTool(server, TOOL.result, {
|
|
99
|
+
description: 'The answers on a board (answers, notes, comment, annotations, blockEdits), or its draft while the person is still filling it in. Pass wait_seconds to block until they submit.',
|
|
100
|
+
inputSchema: resultInput,
|
|
101
|
+
_meta: modelOnly,
|
|
102
|
+
}, async ({ boardId, wait_seconds = 0 }, ctx) => {
|
|
103
|
+
const deadline = Date.now() + Math.min(wait_seconds, MAX_WAIT_SECONDS) * 1000;
|
|
104
|
+
for (;;) {
|
|
105
|
+
const record = await store.get(boardId);
|
|
106
|
+
if (!record) return errorResult(`relay: no board "${boardId}"`);
|
|
107
|
+
if (isFinal(record) || Date.now() >= deadline || ctx?.mcpReq?.signal?.aborted) {
|
|
108
|
+
const out = resultOf(record);
|
|
109
|
+
return json(out, { boardId, status: out.status });
|
|
110
|
+
}
|
|
111
|
+
await sleep(500);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function registerAppTools({ server, options, store, key }) {
|
|
117
|
+
const appTools = [];
|
|
118
|
+
const appTool = (name, config, cb) => appTools.push(registerAppTool(server, name, { ...config, _meta: { ui: { visibility: ['app'] } } }, cb));
|
|
119
|
+
|
|
120
|
+
/** The board a valid token opens, or an error result. */
|
|
121
|
+
const guard = async (args) => {
|
|
122
|
+
if (!tokenValid(key, args.boardId, args.token)) return { error: errorResult('relay: board token mismatch') };
|
|
123
|
+
const record = await store.get(args.boardId);
|
|
124
|
+
return record ? { record } : { error: errorResult('relay: board not found') };
|
|
125
|
+
};
|
|
126
|
+
/** An app tool that acts on one unfinished board. */
|
|
127
|
+
const onOpenBoard = (act) => (args) => oneAtATime(args.boardId, async () => {
|
|
128
|
+
const { record, error } = await guard(args);
|
|
129
|
+
if (error) return error;
|
|
130
|
+
if (isFinal(record)) return errorResult('relay: board is finished');
|
|
131
|
+
return act(record, args);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
appTool(TOOL.view, { description: 'The board spec, for the board iframe.', inputSchema: viewInput }, async (args) => {
|
|
135
|
+
const { record, error } = await guard(args);
|
|
136
|
+
if (error) return error;
|
|
137
|
+
const vendorUrls = options.assetUrl ? Object.fromEntries(VENDOR_FILES.map((f) => [f, options.assetUrl(f)])) : undefined;
|
|
138
|
+
return json({ boardId: record.id }, { boardId: record.id, spec: record.spec, draft: record.draft ?? null, finished: Boolean(record.result), vendorUrls });
|
|
139
|
+
});
|
|
140
|
+
appTool(TOOL.draft, { description: 'Saves the answers so far.', inputSchema: draftInput }, onOpenBoard(async (record, args) => {
|
|
141
|
+
await saveDraft(store, record.id, args.draft);
|
|
142
|
+
return text('saved');
|
|
143
|
+
}));
|
|
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);
|
|
146
|
+
return outcome.ok ? text('recorded') : errorResult(`relay: ${outcome.error}`);
|
|
147
|
+
}));
|
|
148
|
+
appTool(TOOL.submit, { description: 'Stores the final answers.', inputSchema: submitInput }, (args) => oneAtATime(args.boardId, async () => {
|
|
149
|
+
const { record, error } = await guard(args);
|
|
150
|
+
if (error) return error;
|
|
151
|
+
const outcome = await submitBoard(store, record, args.payload);
|
|
152
|
+
return outcome.ok ? json({ status: outcome.status }) : errorResult(`relay: ${outcome.error}`);
|
|
153
|
+
}));
|
|
154
|
+
appTool(TOOL.asset, { description: 'One chunk of a vendored library, for hosts that refuse resources/read.', inputSchema: assetInput }, ({ name, index }) => {
|
|
155
|
+
const chunk = vendorChunk(name, index);
|
|
156
|
+
return chunk ? json({ name, index, count: chunk.count }, chunk) : errorResult(`relay: no asset "${name}" chunk ${index}`);
|
|
157
|
+
});
|
|
158
|
+
return appTools;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function registerResources(server) {
|
|
162
|
+
registerAppResource(server, 'Relay board', BOARD_URI, { mimeType: UI_MIME, description: 'The interactive board shown by relay_board.', _meta: { ui: BOARD_RESOURCE_META } }, () => ({
|
|
163
|
+
contents: [{ uri: BOARD_URI, mimeType: UI_MIME, text: boardPage(), _meta: { ui: BOARD_RESOURCE_META } }],
|
|
164
|
+
}));
|
|
165
|
+
for (const file of VENDOR_FILES) {
|
|
166
|
+
const uri = VENDOR_URI_PREFIX + file;
|
|
167
|
+
server.registerResource(`vendor ${file}`, uri, { mimeType: 'application/javascript' }, () => ({
|
|
168
|
+
contents: [{ uri, mimeType: 'application/javascript', text: vendorText(file) }],
|
|
169
|
+
}));
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -1,3 +1,23 @@
|
|
|
1
|
+
// A button click in an a2ui block reaches the agent before the person submits.
|
|
2
|
+
// Events already in the stored snapshot were sent when they happened.
|
|
3
|
+
function forwardA2uiEvents(blockId, before, after) {
|
|
4
|
+
if (!BOARD.token || !after || after.type !== 'a2ui' || !Array.isArray(after.events)) return;
|
|
5
|
+
for (const e of unsentA2uiEvents(before, after.events)) {
|
|
6
|
+
callServerTool('a2ui_action', { boardId: BOARD.id, token: BOARD.token, blockId, name: e.name, context: e.context }).catch(() => {});
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
// A snapshot keeps only the newest events, so once it is full a click drops the
|
|
10
|
+
// oldest one and the count stays the same. What was sent is the longest run at
|
|
11
|
+
// the start of the new list that also ends the old one.
|
|
12
|
+
function unsentA2uiEvents(before, events) {
|
|
13
|
+
const prior = before && Array.isArray(before.events) ? before.events.map((e) => JSON.stringify(e)) : [];
|
|
14
|
+
const next = events.map((e) => JSON.stringify(e));
|
|
15
|
+
for (let kept = Math.min(prior.length, next.length); kept > 0; kept--) {
|
|
16
|
+
if (next.slice(0, kept).every((e, i) => e === prior[prior.length - kept + i])) return events.slice(kept);
|
|
17
|
+
}
|
|
18
|
+
return events;
|
|
19
|
+
}
|
|
20
|
+
|
|
1
21
|
function blockCtx(questionId) {
|
|
2
22
|
return {
|
|
3
23
|
theme: effectiveTheme,
|
|
@@ -14,8 +34,10 @@
|
|
|
14
34
|
},
|
|
15
35
|
edits: state.blockEdits,
|
|
16
36
|
onBlockEdit: (blockId, codeOrNull) => {
|
|
37
|
+
const before = state.blockEdits[blockId];
|
|
17
38
|
if (codeOrNull === null || codeOrNull === undefined) delete state.blockEdits[blockId];
|
|
18
39
|
else state.blockEdits[blockId] = codeOrNull;
|
|
40
|
+
forwardA2uiEvents(blockId, before, codeOrNull);
|
|
19
41
|
},
|
|
20
42
|
};
|
|
21
43
|
}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// host frame gone — nothing we can do
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
|
-
function request(method, params) {
|
|
17
|
+
function request(method, params, timeoutMs = 15000) {
|
|
18
18
|
const id = 'rly-' + (++rpcSeq);
|
|
19
19
|
return new Promise((resolve, reject) => {
|
|
20
20
|
pending.set(id, { resolve, reject });
|
|
@@ -25,9 +25,19 @@
|
|
|
25
25
|
pending.delete(id);
|
|
26
26
|
reject(new Error('timeout: ' + method));
|
|
27
27
|
}
|
|
28
|
-
},
|
|
28
|
+
}, timeoutMs);
|
|
29
29
|
});
|
|
30
30
|
}
|
|
31
|
+
// Calls one of the relay server's tools through the host. A tool-level error
|
|
32
|
+
// rejects, so callers handle "the host refused" and "the server said no" alike.
|
|
33
|
+
async function callServerTool(name, args, timeoutMs) {
|
|
34
|
+
const res = await request('tools/call', { name, arguments: args }, timeoutMs);
|
|
35
|
+
if (!res || res.isError) {
|
|
36
|
+
const msg = res && Array.isArray(res.content) && res.content[0] && res.content[0].text;
|
|
37
|
+
throw new Error(msg || 'tool failed: ' + name);
|
|
38
|
+
}
|
|
39
|
+
return res.structuredContent || {};
|
|
40
|
+
}
|
|
31
41
|
function notify(method, params) {
|
|
32
42
|
post({ jsonrpc: '2.0', method, params: params || {} });
|
|
33
43
|
}
|
package/src/mcp-ui/board/core.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
try { return JSON.parse(document.getElementById('boot').textContent); } catch { return {}; }
|
|
3
3
|
})();
|
|
4
4
|
const PROTOCOL = '2025-06-18';
|
|
5
|
+
// Set from the relay_board tool result; every server call for this board presents it.
|
|
6
|
+
const BOARD = { id: null, token: null };
|
|
5
7
|
|
|
6
8
|
// ---------- tiny DOM helper (mirrors app.js / blocks.js) ----------
|
|
7
9
|
function el(tag, attrs = {}, ...children) {
|
|
@@ -54,21 +54,59 @@
|
|
|
54
54
|
previewTimer = setTimeout(() => { previewTimer = null; if (!booted && !submitted) render(); }, 120);
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
// The
|
|
58
|
-
//
|
|
59
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
64
|
-
if (
|
|
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
|
-
|
|
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;
|
|
@@ -119,63 +119,55 @@
|
|
|
119
119
|
return lines.join('\n');
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
+
// The full answers go to the server, which keeps them for relay_result; the
|
|
123
|
+
// agent gets a one-line nudge. A host that refuses app tool calls gets the
|
|
124
|
+
// whole transcript as the message instead, so the answers still arrive.
|
|
122
125
|
async function onSubmit(submitBtn, saveEl) {
|
|
123
126
|
if (submitted) return;
|
|
124
127
|
if (!validate()) return;
|
|
125
128
|
submitBtn.disabled = true;
|
|
126
129
|
submitBtn.textContent = 'Submitting…';
|
|
127
130
|
const data = payload();
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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' });
|
|
131
|
+
const stored = BOARD.token ? await storeSubmission(data) : false;
|
|
132
|
+
const text = stored
|
|
133
|
+
? 'Relay board ' + BOARD.id + ' submitted. Read it with relay_result {"boardId":"' + BOARD.id + '"}.'
|
|
134
|
+
: summarize(data);
|
|
135
|
+
const content = [{ type: 'text', text }];
|
|
136
|
+
if (!stored) {
|
|
137
|
+
for (const a of data.annotations || []) {
|
|
138
|
+
const crop = a && a.target && a.target.crop;
|
|
139
|
+
if (!crop || typeof crop.data !== 'string' || !crop.data) continue;
|
|
140
|
+
content.push({ type: 'image', data: crop.data, mimeType: crop.mime || 'image/png' });
|
|
141
|
+
}
|
|
144
142
|
}
|
|
145
|
-
|
|
146
|
-
|
|
143
|
+
const messageDelivered = await sendUserMessage(content, text);
|
|
144
|
+
submitted = true;
|
|
145
|
+
showDone(messageDelivered, stored);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function storeSubmission(data) {
|
|
147
149
|
try {
|
|
148
|
-
|
|
149
|
-
|
|
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;
|
|
150
|
+
await callServerTool('relay_submit', { boardId: BOARD.id, token: BOARD.token, payload: data });
|
|
151
|
+
return true;
|
|
153
152
|
} catch {
|
|
154
|
-
|
|
155
|
-
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// A completed relay form is a user reply, so it goes as a user message to wake
|
|
158
|
+
// the agent. Older hosts reject image content or the content array; each retry
|
|
159
|
+
// keeps the text.
|
|
160
|
+
async function sendUserMessage(content, text) {
|
|
161
|
+
const attempts = [content, [{ type: 'text', text }], { type: 'text', text }];
|
|
162
|
+
for (const attempt of attempts) {
|
|
156
163
|
try {
|
|
157
|
-
await request('ui/message', { role: 'user', content:
|
|
158
|
-
|
|
164
|
+
await request('ui/message', { role: 'user', content: attempt });
|
|
165
|
+
return true;
|
|
159
166
|
} catch {
|
|
160
|
-
try
|
|
161
|
-
await request('ui/message', { role: 'user', content: { type: 'text', text } });
|
|
162
|
-
messageDelivered = true;
|
|
163
|
-
} catch { /* app-initiated messages unavailable */ }
|
|
167
|
+
// try a simpler shape
|
|
164
168
|
}
|
|
165
169
|
}
|
|
166
|
-
|
|
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);
|
|
170
|
+
return false;
|
|
179
171
|
}
|
|
180
172
|
|
|
181
173
|
function showDone(messageDelivered, contextDelivered) {
|
|
@@ -21,20 +21,65 @@
|
|
|
21
21
|
}
|
|
22
22
|
return types;
|
|
23
23
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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.
|
|
59
|
+
s.src = url;
|
|
60
|
+
s.onload = () => resolve('');
|
|
61
|
+
s.onerror = () => reject(new Error('script failed'));
|
|
33
62
|
document.head.appendChild(s);
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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);
|
package/src/spec/blocks/chart.js
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
// The chart block.
|
|
2
2
|
import { CliError } from '../../util.js';
|
|
3
3
|
import { asStr, clampInt } from '../sources.js';
|
|
4
|
-
import { BLOCK_HEIGHT, CHART_KINDS } from '../constants.js';
|
|
4
|
+
import { BLOCK_HEIGHT, CHART_KINDS, CHART_KIND_FIELDS, CHART_SERIES_FIELDS } from '../constants.js';
|
|
5
|
+
|
|
6
|
+
// The first spelling of a field the agent used, so `chartType` or Chart.js's `datasets` work.
|
|
7
|
+
const firstDefined = (raw, names) => raw[names.find((n) => raw[n] !== undefined)];
|
|
5
8
|
|
|
6
9
|
// Normalizes one chart block. `id` is the already-assigned block id.
|
|
7
|
-
export function normalizeChartBlock(
|
|
10
|
+
export function normalizeChartBlock(raw, id, cwd, where, hasHeight) {
|
|
11
|
+
const rawBlock = { ...raw, kind: firstDefined(raw, CHART_KIND_FIELDS), series: firstDefined(raw, CHART_SERIES_FIELDS) };
|
|
8
12
|
const hasConfig = rawBlock.config && typeof rawBlock.config === 'object' && !Array.isArray(rawBlock.config);
|
|
9
13
|
const hasShorthand =
|
|
10
14
|
typeof rawBlock.kind === 'string' ||
|
|
11
15
|
Array.isArray(rawBlock.labels) ||
|
|
12
16
|
Array.isArray(rawBlock.series);
|
|
13
17
|
if (!hasConfig && !hasShorthand) {
|
|
14
|
-
throw new CliError(`${where}: chart needs "
|
|
18
|
+
throw new CliError(`${where}: a chart needs "kind" (${CHART_KINDS.join('|')}), "labels" and "series": [{"label","data":[...]}], or a full Chart.js "config". \`rly schema chart\` shows the fields.`);
|
|
15
19
|
}
|
|
16
20
|
const block = { id, type: 'chart' };
|
|
17
21
|
block.height = clampInt(rawBlock.height, BLOCK_HEIGHT.min, BLOCK_HEIGHT.max, 320);
|
|
@@ -21,7 +25,7 @@ export function normalizeChartBlock(rawBlock, id, cwd, where, hasHeight) {
|
|
|
21
25
|
}
|
|
22
26
|
// Shorthand form: validate kind/labels/series.
|
|
23
27
|
const kind = asStr(rawBlock.kind).trim().toLowerCase();
|
|
24
|
-
if (!kind) throw new CliError(`${where}:
|
|
28
|
+
if (!kind) throw new CliError(`${where}: add "kind": one of ${CHART_KINDS.join('|')}.`);
|
|
25
29
|
if (!CHART_KINDS.includes(kind)) {
|
|
26
30
|
throw new CliError(`${where}: unknown chart kind "${rawBlock.kind}". Valid: ${CHART_KINDS.join(', ')}.`);
|
|
27
31
|
}
|
package/src/spec/constants.js
CHANGED
|
@@ -33,6 +33,25 @@ export const ALIASES = {
|
|
|
33
33
|
points: 'allocate',
|
|
34
34
|
};
|
|
35
35
|
|
|
36
|
+
// Block type names agents reach for that mean one of ours. A chart kind used as
|
|
37
|
+
// the block type ({"type":"bar", labels, series}) is handled in normalizeBlock.
|
|
38
|
+
export const BLOCK_ALIASES = {
|
|
39
|
+
md: 'markdown',
|
|
40
|
+
img: 'image',
|
|
41
|
+
picture: 'image',
|
|
42
|
+
flowchart: 'mermaid',
|
|
43
|
+
diagram: 'mermaid',
|
|
44
|
+
stats: 'kpi',
|
|
45
|
+
metrics: 'kpi',
|
|
46
|
+
widget: 'a2ui',
|
|
47
|
+
patch: 'diff',
|
|
48
|
+
swatches: 'palette',
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
// Chart field spellings that mean `kind` and `series` (Chart.js calls the second one `datasets`).
|
|
52
|
+
export const CHART_KIND_FIELDS = ['kind', 'chartType', 'chart_type'];
|
|
53
|
+
export const CHART_SERIES_FIELDS = ['series', 'datasets'];
|
|
54
|
+
|
|
36
55
|
export const HTML_HEIGHT = { min: 100, max: 2400, boardDefault: 400, questionDefault: 360 };
|
|
37
56
|
|
|
38
57
|
// Block heights clamp to the same window; defaults vary per block type.
|
package/src/spec/index.js
CHANGED