chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.4.0 Latest 5 packages
0
0
// What a tile says of its call: its title, the account it is about, its
// icon, what it names (an at-uri, an NSID), and whether two tiles are the
// same call.
import type { View } from '@hud/shared/result';
import type { IconName } from './icons';
import type { Tile } from './model';
const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
/** A tool's arguments, short, for a tile's header: `key=value`, an inline
* view as `view=…`, long values clipped. */
export function summary(tool: string, args: Record<string, unknown>): string {
const parts = Object.entries(args).map(([key, value]) => {
if (key === 'view') return 'view=…';
if (key === 'params' && typeof value === 'object' && value !== null) {
return Object.entries(value)
.map(([k, v]) => `${k}=${clip(typeof v === 'string' ? v : JSON.stringify(v), 48)}`)
.join(' ');
}
return `${key}=${clip(typeof value === 'string' ? value : JSON.stringify(value), 48)}`;
});
return [tool, ...parts].join(' ');
}
const text = (args: Record<string, unknown>, key: string) => (typeof args[key] === 'string' ? (args[key] as string) : '');
const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);
/** A query's params. */
const params = (args: Record<string, unknown>) => (isObject(args.params) ? args.params : {});
/** The account an at-uri is in: its authority. */
const authority = (uri: string) => (uri.startsWith('at://') ? uri.slice(5).split('/')[0] || null : null);
/** The tools whose words alone make a title HUD made: `query app.bsky…`, `get_record`. */
const TOOLS = ['get_record', 'list_records', 'describe_repo', 'describe_app', 'describe_collection', 'describe_method', 'query'];
/** The titles HUD's page once made of a call, standing for nothing more. */
const PLACEHOLDERS: Record<string, true> = { Record: true, Records: true, Collection: true, Method: true, Query: true, Thread: true };
/** Whether a tile's title is one a person or an agent gave it, not one HUD
* made of its call: an NSID or a handle and who (`app.bsky.feed.post ·
* alice.test`, `site.standard.document · 3mtxb…`), a lone NSID, handle,
* DID or at-uri, the tool and what it is about, or a placeholder. */
function given(title: string): boolean {
const said = title.trim().replace(/…$/, '');
if (!said || PLACEHOLDERS[said]) return false;
if (/^(did:|at:\/\/)/.test(said)) return false;
if (/^@?[^\s·]+\.[^\s·]+$/.test(said) || /^[^\s·]+\.[^\s·]+ · /.test(said)) return false;
return !TOOLS.some((tool) => said === tool || said.startsWith(`${tool} `));
}
/** A title without the `· whose` HUD once ended its own with (`Grain ·
* did:plc:…`, `Posts · alice.test`): the header's second line says whose. */
const whoseless = (title: string) => title.trim().replace(/ · (?:did:[^\s·]+|@?[^\s·]+\.[^\s·]+)$/, '');
/** `listItem` or `getPostThread` as words: `List item`, `Post thread`. */
function words(name: string): string {
const said = name
.replace(/^get(?=[A-Z])/, '')
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.replace(/[_-]+/g, ' ')
.toLowerCase();
return said.charAt(0).toUpperCase() + said.slice(1);
}
/** A noun's plural, as English mostly makes it. */
const plural = (noun: string) => (/(s|x|ch|sh)$/.test(noun) ? `${noun}es` : /[^aeiou]y$/.test(noun) ? `${noun.slice(0, -1)}ies` : `${noun}s`);
/** The collection a tile's records are of, if it shows records. */
export function collectionOf(tool: string, args: Record<string, unknown>): string | null {
switch (tool) {
case 'list_records':
case 'describe_collection':
return text(args, 'collection') || null;
case 'get_record':
return text(args, 'uri').split('/')[3] || null;
default:
return null;
}
}
/** The NSID a tile names: its collection, or its query's or described method. */
export const nsidOf = (tool: string, args: Record<string, unknown>): string | null => collectionOf(tool, args) ?? (text(args, 'method') || null);
/** The account whose data a tile shows, by DID or handle (`me` for the signed-in one), or null for one about no account (a feed). */
export function accountOf(tool: string, args: Record<string, unknown>): string | null {
switch (tool) {
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 asked = params(args);
return (typeof asked.actor === 'string' && asked.actor.replace(/^@/, '')) || (typeof asked.uri === 'string' && authority(asked.uri)) || null;
}
default:
return null;
}
}
/** The at-uri of what a tile shows, given its account's DID where its call names a handle: a record, a collection or a repository. */
export function atUriOf(tool: string, args: Record<string, unknown>, did: string | null): string | null {
if (tool === 'get_record') return text(args, 'uri') || null;
if (tool === 'query') {
const uri = params(args).uri;
return typeof uri === 'string' && uri.startsWith('at://') ? uri : null;
}
if (!did) return null;
const collection = collectionOf(tool, args);
return tool === 'describe_repo' ? `at://${did}` : collection ? `at://${did}/${collection}` : null;
}
/** What a tile learns of itself once drawn: its record's own label, and its collection's name as its view gives it. */
export type Learned = { label: string | null; name: string | null };
/** The names HUD knows by now: a collection's, as the launcher's rows give them, a saved feed's, by its at-uri, and an app's, by its domain. */
export type Names = {
collection: (nsid: string) => string | undefined;
feed: (uri: string) => string | undefined;
app: (domain: string) => string | undefined;
};
/** Words to show as a title, on one line, cut at a word to at most `max` characters. */
function firstWords(said: string, max = 48): string | null {
const line = said.split('\n')[0].replace(/\s+/g, ' ').trim();
if (line.length <= max) return line || null;
const cut = line.slice(0, max - 1);
const space = cut.lastIndexOf(' ');
return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,.;:!?–—-]+$/, '')}…`;
}
/** A record value's own name: its title, name or text. */
function named(value: unknown): string | null {
if (!isObject(value)) return null;
for (const key of ['title', 'name', 'text']) {
const said = value[key];
if (typeof said === 'string' && said.trim()) return firstWords(said);
}
return null;
}
/** What a drawn tile learns of itself, from the view it drew and the text the tool answered with. Its label: the one its
* view's summary gives (`"Coast" by alice: 12 photos.`, `Thread: "hello" by alice.`), else, of one record, its title,
* name or text, and of a thread, its first post's first words. Its collection's name: its view's description (`ui.title`). */
export function learn(view: View, summary: string): Learned {
const quoted = /^(?:[^":]+: )?"(.+?)"(?= by |[.:]|$)/.exec(summary.trim())?.[1] ?? null;
let label = quoted && firstWords(quoted, 60);
const data = view.renderer === 'tree' && isObject(view.data) ? view.data : null;
const records = data && Array.isArray(data.records) ? data.records : null;
if (!label && records && records.length === 1 && !data?.cursor && isObject(records[0])) label = named(records[0].value);
const thread = data && isObject(data.response) ? data.response.thread : null;
if (!label && isObject(thread) && isObject(thread.post)) label = named(thread.post.record);
return { label, name: view.renderer === 'tree' ? view.ui.title?.trim() || null : null };
}
/** A query's name: its feed's, its method's as people say it, else its method's last word. */
function queryName(args: Record<string, unknown>, names: Names | null): string {
const method = text(args, 'method');
const feed = params(args).feed;
switch (method.split('.').at(-1)) {
case 'getTimeline':
return 'Following';
case 'getFeed':
if (typeof feed !== 'string') return 'Feed';
if (!feed.startsWith('at://')) return /^(following|timeline|home)$/i.test(feed) ? 'Following' : feed;
return names?.feed(feed) ?? 'Feed';
case 'getPostThread':
return 'Thread';
case 'getProfile':
case 'getProfiles':
return 'Profile';
case 'getAuthorFeed':
return 'Posts';
case 'getActorLikes':
return 'Likes';
case 'getListFeed':
return 'List';
case 'getFeedGenerators':
return params(args).feeds === 'saved' ? 'My feeds' : 'Feeds';
default:
return method ? words(method.split('.').at(-1)!) : 'Query';
}
}
/**
* A tile's title, as people read it, wherever it shows: the one a person
* or an agent gave it; else its record's own label, once drawn; else its
* collection's name, as its view or the launcher's rows give it; for a
* query, its feed's or method's name; else its NSID's last word. Never an
* rkey, a TID or a DID: the account is said beside it, by its handle.
*/
export function tileTitle(tile: Pick<Tile, 'tool' | 'arguments' | 'title'>, learned: Learned | null | undefined, names: Names | null): string {
const { tool, arguments: args } = tile;
const title = whoseless(tile.title);
if (given(title)) return clip(title, 60);
if (learned?.label) return learned.label;
const collection = collectionOf(tool, args);
if (collection) {
const noun = words(collection.split('.').at(-1)!);
return clip(learned?.name ?? names?.collection(collection) ?? (tool === 'list_records' ? plural(noun) : noun), 60);
}
switch (tool) {
case 'query':
return clip(queryName(args, names), 60);
case 'describe_repo':
return 'Profile';
case 'describe_app':
return text(args, 'domain') ? clip(names?.app(text(args, 'domain')) ?? text(args, 'domain'), 60) : 'App';
case 'describe_method':
return text(args, 'method') ? clip(words(text(args, 'method').split('.').at(-1)!), 60) : 'Method';
default:
return clip(words(tool), 60);
}
}
/** The icon for what a collection holds, by the words its NSID ends in. */
function collectionIcon(collection: string): IconName {
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';
}
/** The icon of a tile: from its tool, and for a query from its method's
* kind (the words its NSID ends in), for a record from its collection. */
export function iconOf(tool: string, args: Record<string, unknown>): IconName {
switch (tool) {
case 'query': {
const method = text(args, 'method');
if (/\.(getPostThread|getThread)$/.test(method)) return 'thread';
if (/\.(getTimeline|getFeed|getAuthorFeed|getListFeed|getActorLikes)$/.test(method)) return 'feed';
if (/\.(getProfile|getProfiles)$/.test(method)) return 'profile';
if (/\.(listConvos|getConvo|getConvoForMembers|getMessages)$/.test(method)) return 'chat';
if (/(Repo|Repos)$/.test(method)) return 'repo';
if (/Notifications$/.test(method)) return 'bell';
if (/Stars$/.test(method)) return 'star';
if (/Commits$/.test(method)) return 'commit';
if (/Checks$/.test(method)) return 'check';
if (/Diff$/.test(method)) return 'diff';
if (/File$/.test(method)) return 'document';
if (/Items$/.test(method)) return 'issue';
if (/Releases$/.test(method)) return 'release';
if (/(Gallery|Galleries)$/.test(method)) return 'gallery';
return 'record';
}
case 'describe_repo':
return 'profile';
case 'describe_app':
return 'app';
case 'list_records':
// A list of posts is a feed, as the feeds are; one post opens as a thread.
return text(args, 'collection') === 'app.bsky.feed.post' ? 'feed' : collectionIcon(text(args, 'collection'));
case 'get_record':
return collectionIcon(text(args, 'uri').split('/')[3] ?? '');
default:
return 'record';
}
}
/** Nothing given: null, undefined, "", [] or {}. */
const empty = (value: unknown) =>
value === null || value === undefined || value === '' || (Array.isArray(value) ? value.length === 0 : typeof value === 'object' && Object.keys(value).length === 0);
/** JSON with each object's keys in order and its empty values dropped, so two equal calls read the same, as the server keeps them (it names handles by DID too). */
function canonical(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
if (typeof value === 'object' && value !== null) {
return `{${Object.keys(value)
.filter((key) => !empty((value as Record<string, unknown>)[key]))
.sort()
.map((key) => `${JSON.stringify(key)}:${canonical((value as Record<string, unknown>)[key])}`)
.join(',')}}`;
}
return JSON.stringify(value);
}
/** What makes a call the same as another: its tool and its arguments, in any order, empties aside. */
export const callKey = (tool: string, args: Record<string, unknown>) => `${tool} ${canonical(args)}`;
/** The domain of the app an NSID is of: its first two segments reversed (app.bsky → bsky.app), whose favicon HUD serves at /icon/<domain>. */
export function appDomain(nsid: string): string | null {
const [first, second] = nsid.split('.');
return first && second ? `${second}.${first}` : null;
}
/** The domain of the app a tile shows: the app page's own, else its NSID's; null for one of no app (a profile). */
export function appOf(tool: string, args: Record<string, unknown>): string | null {
if (tool === 'describe_app') return text(args, 'domain') || null;
const nsid = nsidOf(tool, args);
return nsid ? appDomain(nsid) : null;
}
/** The account a profile tile shows, by DID or handle, or null for another tile. */
export const actorOf = (tool: string, args: Record<string, unknown>): string | null =>
tool === 'describe_repo' && typeof args.actor === 'string' && args.actor ? args.actor.replace(/^@/, '') : null;