chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.3.1 Latest 5 packages
0
0
// target/gallery/gallery.json: every entry of entries.mjs, in order, with
// its tile header and its recorded answer (answers.json) as the server
// answers it now, its `_meta.ui` built by `target/debug/hud resolve` (its
// trusted view as this checkout has it now, bundled in views/ or the
// operator's, harness/apps.mjs, given it as HUD_APPS, so a change to one
// shows without recording again); then the header variants, each another
// entry's result.
// Every tree is held to HUD's tree lexicon (place.hud.ui, in
// schemas/): one that is not is said, and the run fails. The apps' icons go
// beside it, target/gallery/icons/<domain>.png. The shape is in
// local://gallery-contract.md; `just gallery-data`.
import { execFileSync } from 'node:child_process';
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { apps } from '../apps.mjs';
import { answersFile, filled, iconsDir, root, schemas, shown, viewOf } from './common.mjs';
import { entries, variants } from './entries.mjs';
const say = (line) => console.log(`==> ${line}`);
const out = join(root, 'target/gallery');
const hud = join(root, 'target/debug/hud');
if (!existsSync(hud)) {
say('no target/debug/hud: building it');
execFileSync('rustup', ['run', 'stable', 'cargo', 'build', '-p', 'hud'], { cwd: root, stdio: 'inherit' });
}
if (!existsSync(answersFile)) {
say('no harness/gallery/answers.json: `node harness/gallery/record.mjs`');
process.exit(2);
}
const book = JSON.parse(readFileSync(answersFile, 'utf8'));
const icons = new Set(existsSync(iconsDir) ? readdirSync(iconsDir).map((f) => f.replace(/\.png$/, '')) : []);
const handles = new Map(book.profiles.map((p) => [p.did, p.handle]));
const lexicons = schemas();
/** An answer as the tool gives it now: its view as this checkout has it, its `_meta.ui` from `hud resolve`, given the operator's apps. */
function resolved(name, args, answer) {
const doc = answer._meta?.view && viewOf(name, args);
const now = doc ? { ...answer, _meta: { ...answer._meta, view: shown(name, doc) } } : answer;
return JSON.parse(execFileSync(hud, ['resolve', name, JSON.stringify(args)], { input: JSON.stringify(now), encoding: 'utf8', env: { ...process.env, HUD_APPS: apps } }));
}
// What a tile's header says of its call, as web/workspace/lib/tiles.ts works it out.
const text = (args, key) => (typeof args[key] === 'string' ? args[key] : '');
const authority = (uri) => (uri.startsWith('at://') ? uri.slice(5).split('/')[0] || null : null);
function accountOf(name, args) {
switch (name) {
case 'describe_repo':
case 'describe_app':
case 'list_records':
case 'describe_collection':
return text(args, 'actor').replace(/^@/, '') || null;
case 'get_record':
return authority(text(args, 'uri'));
case 'query': {
const p = args.params ?? {};
return (typeof p.actor === 'string' && p.actor.replace(/^@/, '')) || (typeof p.uri === 'string' && authority(p.uri)) || null;
}
default:
return null;
}
}
const nsidOf = (name, args) => (name === 'list_records' || name === 'describe_collection' ? text(args, 'collection') : name === 'get_record' ? text(args, 'uri').split('/')[3] : text(args, 'method')) || null;
function domainOf(name, args) {
if (name === 'describe_app') return text(args, 'domain') || null;
const [first, second] = (nsidOf(name, args) ?? '').split('.');
return first && second ? `${second}.${first}` : null;
}
function collectionKind(collection) {
const last = collection.toLowerCase().split('.').slice(-2).join('.');
if (/document|publication|article|entry|post$/.test(last) && !last.startsWith('feed.')) return 'document';
if (last === 'feed.post') return 'thread';
if (/gallery|photo|image/.test(last)) return 'gallery';
if (/repo/.test(last)) return 'repo';
if (/track|album|song|music|play/.test(last)) return 'music';
if (/profile/.test(last)) return 'profile';
return 'record';
}
/** What it shows, as the web's Lucide icon names it (tiles.ts `iconOf`): its icon where its app has none. */
function symbolOf(name, args) {
switch (name) {
case 'query': {
const method = text(args, 'method');
if (method === 'app.bsky.feed.getPostThread') return 'thread';
if (/\.(getTimeline|getFeed|getAuthorFeed|getListFeed|getActorLikes)$/.test(method)) return 'feed';
if (/\.(getProfile|getProfiles)$/.test(method)) return 'profile';
if (/\.(listConvos|getConvo|getMessages)$/.test(method)) return 'chat';
return 'record';
}
case 'describe_repo':
return 'profile';
case 'describe_app':
return 'app';
case 'list_records':
return text(args, 'collection') === 'app.bsky.feed.post' ? 'feed' : collectionKind(text(args, 'collection'));
case 'get_record':
return collectionKind(text(args, 'uri').split('/')[3] ?? '');
default:
return 'record';
}
}
/** The account's handle: as the call names it, else as a profile or the answer gives it; null where none is known. */
function handleOf(account, result) {
if (!account || !account.startsWith('did:')) return account;
const s = result.structuredContent ?? {};
if (s.did === account && typeof s.handle === 'string') return s.handle;
if (s.actor?.did === account && typeof s.actor.handle === 'string') return s.actor.handle;
if (s.response?.did === account && typeof s.response.handle === 'string') return s.response.handle;
return handles.get(account) ?? null;
}
function header(entry, call, result) {
const domain = domainOf(call.name, call.args);
const said = {
title: entry.title,
account: handleOf(accountOf(call.name, call.args), result),
from: entry.from ?? null,
agent: entry.agent === true,
domain,
icon: domain && icons.has(domain) ? `/icon/${domain}` : null,
symbol: symbolOf(call.name, call.args)
};
return { ...said, ...entry.header };
}
const tiles = [];
const bad = [];
const results = new Map();
for (const entry of entries) {
const answer = book.answers[entry.id];
if (!answer) {
bad.push(`${entry.id}: no answer recorded (node harness/gallery/record.mjs)`);
continue;
}
const call = { name: entry.call.name, args: filled(entry.call.args, book.picked) };
let result;
try {
result = resolved(call.name, call.args, answer);
} catch (e) {
bad.push(`${entry.id}: hud resolve failed: ${e.stderr?.trim() || e.message}`);
continue;
}
results.set(entry.id, { call, result });
tiles.push({ id: entry.id, group: entry.group, note: entry.note, header: header(entry, call, result), call, result });
}
for (const v of variants) {
const of = results.get(v.of);
if (!of) {
bad.push(`${v.id}: its entry ${v.of} has no result`);
continue;
}
const call = v.call ? { name: v.call.name, args: filled(v.call.args, book.picked) } : of.call;
tiles.push({ id: v.id, group: 'Header variants', note: v.note, header: header(v, call, of.result), call, result: of.result });
}
const ids = new Set(tiles.map((t) => t.id));
for (const t of tiles) if (t.header.from && !ids.has(t.header.from)) bad.push(`${t.id}: from ${t.header.from}, no such tile`);
// Every tree as HUD's tree lexicon says: the tree, and each node's props as
// its component's (`#<component>Props`), which the tree's own def leaves
// `unknown`.
const props = (c) => `place.hud.ui#${c.charAt(0).toLowerCase()}${c.slice(1)}Props`;
function* nodes(value) {
if (Array.isArray(value)) for (const v of value) yield* nodes(v);
else if (value && typeof value === 'object') {
if (typeof value.c === 'string') yield value;
for (const v of Object.values(value)) yield* nodes(v);
}
}
for (const t of tiles) {
const ui = t.result._meta?.ui;
if (t.result.isError) bad.push(`${t.id}: the answer is an error: ${t.result.content?.[0]?.text}`);
else if (!ui) bad.push(`${t.id}: no _meta.ui`);
else {
const checked = lexicons.validate('place.hud.ui', ui);
if (!checked.success) bad.push(`${t.id}: _meta.ui is not as place.hud.ui says: ${checked.error.message}`);
for (const node of nodes(ui.root)) {
if (node.p === undefined || !lexicons.getDef(props(node.c))) continue;
const one = lexicons.validate(props(node.c), node.p);
if (!one.success) bad.push(`${t.id}: a ${node.c}'s props are not as ${props(node.c)} says: ${one.error.message}`);
}
}
}
mkdirSync(out, { recursive: true });
rmSync(join(out, 'icons'), { recursive: true, force: true });
mkdirSync(join(out, 'icons'));
for (const domain of icons) copyFileSync(join(iconsDir, `${domain}.png`), join(out, 'icons', `${domain}.png`));
const file = join(out, 'gallery.json');
writeFileSync(file, `${JSON.stringify({ v: 1, me: book.me, tiles })}\n`);
for (const b of bad) say(b);
const made = entries.filter((e) => e.made).length;
say(`${tiles.length} tiles (${entries.length - made} recorded, ${made} made up, ${variants.length} header variants) in ${file}`);
process.exit(bad.length ? 1 : 0);