import foundation from "~/common/foundation.js";
import { effect } from "~/common/signal.js";
import * as TID from "@atcute/tid";
import * as Output from "~/common/output.js";
import { resolveFacetTile } from "~/common/loader.js";
import {
filterByPlaylist,
gather,
match as matchPlaylistItem,
orderByPlaylist,
sort as sortPlaylistItems,
} from "~/common/playlist.js";
import { groupTracksPerScheme } from "~/common/utils.js";
import { countWords, matchesWords, searchablePaths } from "~/common/search.js";
import { isAudioFile } from "~/components/input/common.js";
import {
htmlFacetTile,
tileFromFiles,
tileResourceEntries,
} from "~/common/tiles.js";
/**
* @import {Facet, PlaylistItem, Track} from "~/definitions/types.d.ts"
*/
const FACET_TYPE = "sh.diffuse.output.facet";
const PLAYLIST_ITEM_TYPE = "sh.diffuse.output.playlistItem";
/** The catalogue URI of the WebMCP facet itself. */
export const WEBMCP_FACET_URI = "diffuse://facets/misc/webmcp/prelude/index.tile";
/** @param {string} text */
const ok = (text) => ({ content: [{ type: "text", text }] });
////////////////////////////////////////////
// DOCS
////////////////////////////////////////////
// The facet development documentation is bundled with the Diffuse build (the
// same content the offline `diffuse-facet` agent skill ships), fetched relative
// to the build root — the loader page's `` element makes this resolve.
const DOCS_BASE = "skills/diffuse-facet/";
const DOCS = [
{
path: "SKILL.md",
description:
"Start here: the step-by-step guide for creating and editing facets — mandatory rules, skeleton, reactivity, audio control.",
},
{
path: "docs/architecture.txt",
description:
"System overview: components, definitions, facets and the foundation.",
},
{
path: "docs/elements.txt",
description:
"Every available custom element (artwork, engines, orchestrators, output, transformers, …) with its description and full source. Large: read without 'query' for the catalog, then use 'query' to read specific elements.",
},
{
path: "docs/foundation.js",
description:
"The foundation API source: element accessors, signals and configuration.",
},
{
path: "example/index.html",
description:
"A representative interface facet to use as a reference.",
},
{
path: "docs/definitions/index.ts",
description:
"TypeScript types for all data structures (Facet, Track, PlaylistItem, Setting, …). Individual schemas live under docs/definitions/, e.g. docs/definitions/output/track.json for the Track lexicon.",
},
];
/** @param {string} path */
async function fetchDoc(path) {
try {
const res = await fetch(DOCS_BASE + path.replace(/^\/+/, ""));
if (!res.ok) return undefined;
return await res.text();
} catch {
return undefined;
}
}
/**
* The elements documentation carries every component's full source and is far
* too large to return at once. Without a query, return just the catalog (every
* element's name and group); with one, return the matching sections.
*
* @param {string} text
* @param {string | undefined} query
*/
function elementsDoc(text, query) {
/** @type {{ group: string; name: string; body: string }[]} */
const sections = [];
let group = "";
/** @type {{ group: string; name: string; body: string } | undefined} */
let current;
for (const line of text.split("\n")) {
if (line.startsWith("## ")) {
group = line.slice(3).trim();
current = undefined;
} else if (line.startsWith("### ")) {
current = { group, name: line.slice(4).trim(), body: "" };
sections.push(current);
} else if (current) {
current.body += line + "\n";
}
}
if (!query) {
return JSON.stringify({
total: sections.length,
note:
"Call again with 'query' to read the matching elements' description " +
"and source code, e.g. query: \"queue\" or query: \"browser\".",
elements: sections.map((s) => ({ group: s.group, name: s.name })),
}, null, 2);
}
const q = query.trim().toLowerCase();
const matches = sections.filter((s) =>
s.name.toLowerCase().includes(q) || s.body.toLowerCase().includes(q)
);
if (!matches.length) {
return `No elements match "${query}". Call without 'query' for the catalog.`;
}
// Sections can be sizeable (each embeds the element's full source), so cap
// the amount returned per call.
const max = 5;
const doc = matches.slice(0, max)
.map((s) => `## ${s.group}\n### ${s.name}\n${s.body.trimEnd()}`)
.join("\n\n");
return matches.length > max
? `${doc}\n\n(${matches.length - max} more matches — refine 'query'.)`
: doc;
}
////////////////////////////////////////////
// FACETS
////////////////////////////////////////////
/** @returns {Promise} */
async function listFacets() {
const out = await foundation.orchestrator.output();
return /** @type {Facet[]} */ (await Output.data(out.facets));
}
/** @param {Facet} facet */
async function saveFacet(facet) {
const out = await foundation.orchestrator.output();
const col = await Output.data(out.facets);
const withoutId = col.filter((c) => c.id !== facet.id);
await out.facets.save([...withoutId, {
...facet,
updatedAt: new Date().toISOString(),
}]);
}
/**
* Where a facet's code lives: inline in the record ("custom"), the Diffuse
* bundle ("bundle"), or an external URI ("external"). Mirrors the dashboard's
* "custom code" vs "tracking the original URI" distinction.
*
* @param {Facet} facet
*/
function facetSource(facet) {
if (facet.uri && !facet.resources) {
return facet.uri.startsWith("diffuse://") ? "bundle" : "external";
}
return "custom";
}
/** @param {Facet} facet */
function facetSummary(facet) {
return {
id: facet.id,
name: facet.name,
kind: facet.kind ?? "interactive",
description: facet.description ?? "",
enabled: facet.enabled ?? true,
favourite: facet.favourite ?? false,
source: facetSource(facet),
uri: facet.uri,
tags: facet.tags,
};
}
/**
* Resolves a facet's tile files (every resource's path and text content), or
* undefined when the facet's content can't be resolved. Facets that don't ship
* a tile resolve as a single `/` file.
*
* @param {Facet} facet
* @returns {Promise<{ path: string; content: string }[] | undefined>}
*/
async function facetFiles(facet) {
const tile = await resolveFacetTile(facet);
if (!tile) return undefined;
const decoder = new TextDecoder();
const entries = [...tileResourceEntries(tile.resources, tile.blocks)]
.map(([path, entry]) => ({ path, content: decoder.decode(entry.bytes) }));
if (!entries.length) return [{ path: "/", content: tile.html }];
return entries.sort((a, b) =>
a.path === "/" ? -1 : b.path === "/" ? 1 : a.path.localeCompare(b.path)
);
}
////////////////////////////////////////////
// TRACKS & PLAYLISTS
////////////////////////////////////////////
/** @returns {Promise