Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339#!/usr/bin/env node// Builds the docs site: every page in docs/ becomes site/docs/<name>.html in the// albedo.sh style, next to docs.css, docs-lake.js, openapi.yaml and the API reference.import { execFileSync } from 'node:child_process';import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync,} from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';import { Marked } from 'marked';import * as pagefind from 'pagefind';import { createCssVariablesTheme, createHighlighter } from 'shiki';
const site = dirname(fileURLToPath(import.meta.url));const root = dirname(site);const source = join(root, 'docs');const out = join(site, 'docs');const repo = 'https://tangled.org/okami.mom/albedo/blob/main';// Where the docs are served. The host answers /docs as well as /docs/, and a relative address// resolves differently under each, so every address the pages carry starts here.const base = '/docs/';const address = (name) => (name === 'index.html' ? base : base + name);
// The sidebar, in order. A page in docs/ missing here fails the build, so none is dropped silently.const pages = [ { file: 'readme.md', out: 'index.html', group: 'guide', label: 'overview' }, { file: 'install.md', group: 'guide', label: 'install' }, { file: 'web.md', group: 'guide', label: 'web client' }, { file: 'discord.md', group: 'guide', label: 'discord' }, { file: 'photon.md', group: 'guide', label: 'photon' }, { file: 'webhooks.md', group: 'guide', label: 'webhooks' }, { file: 'skills.md', group: 'guide', label: 'skills & instructions' }, { file: 'mcp.md', group: 'guide', label: 'mcp servers' }, { file: 'agents-and-worktrees.md', group: 'guide', label: 'agents & worktrees', }, { file: 'artifacts.md', group: 'guide', label: 'artifacts' }, { file: 'remote-kernels.md', group: 'guide', label: 'remote kernels' }, { file: 'tools-and-environments.md', group: 'guide', label: 'remote, colab & ui', }, { file: 'daemon-lifecycle.md', group: 'operate', label: 'daemon lifecycle' }, { file: 'home-manager.md', group: 'operate', label: 'home-manager' }, { file: 'extensions.md', group: 'contribute', label: 'write an extension' }, { file: 'extension-api.md', group: 'contribute', label: 'extension api' }, { file: 'client-api.md', group: 'api', label: 'client api' }, { file: 'http-api-workflows.md', group: 'api', label: 'http workflows' }, { file: 'http-api-design.md', group: 'api', label: 'http api design' }, { file: 'http-sessions.md', group: 'api', label: 'http sessions' }, { file: 'http-streams.md', group: 'api', label: 'http streams' }, { file: 'http-extensions.md', group: 'api', label: 'http extensions' }, { file: 'http-api-architecture.md', group: 'api', label: 'api architecture' }, { file: 'contributing-api.md', group: 'api', label: 'change the api' }, { file: 'api-client.gen.md', group: 'api', label: 'client reference' }, { file: 'api-extension.gen.md', group: 'api', label: 'extension reference', }, { file: 'api-internal-transfer.gen.md', group: 'api', label: 'transfer reference', },].map((page) => ({ ...page, out: page.out ?? page.file.replace(/\.md$/, '.html'),}));const reference = { label: 'api reference', out: 'api-reference.html' };
const escape = (text) => text.replace( /[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c], );const slug = (text) => text .toLowerCase() .trim() .replace(/<[^>]+>/g, '') .replace(/[^\p{L}\p{N}\s_-]/gu, '') .replace(/\s/g, '-');
// Rewrites a link written for the repository into one that works on the site.function siteHref(href) { const [path, hash] = href.split('#'); if (/^[a-z]+:|^#/.test(href) || !path) return href; const page = pages.find((p) => p.file === path); if (page) return address(page.out) + (hash ? `#${hash}` : ''); if (path === 'api-reference.html' || path === 'openapi.yaml') return base + href; return `${repo}/${join('docs', path)}${hash ? `#${hash}` : ''}`;}
const highlighter = await createHighlighter({ themes: [ createCssVariablesTheme({ name: 'madoromi', variablePrefix: '--shiki-' }), ], langs: [ 'gleam', 'python', 'json', 'go', 'sh', 'yaml', 'toml', 'nix', 'markdown', ],});
function render(markdown) { const headings = []; const images = []; const seen = new Map(); let title = ''; const marked = new Marked({ gfm: true, renderer: { heading({ tokens, depth, text }) { const html = this.parser.parseInline(tokens); if (depth === 1 && !title) { title = text; return `<h1>${html}</h1>\n`; } const level = Math.max(depth, 2); let id = slug(text); const count = seen.get(id) ?? 0; seen.set(id, count + 1); if (count) id += `-${count}`; if (level === 2) headings.push({ id, html }); return `<h${level} id="${id}"><a class="anchor" href="#${id}" aria-hidden="true" data-pagefind-ignore>#</a>${html}</h${level}>\n`; }, code({ text, lang }) { const language = highlighter.getLoadedLanguages().includes(lang) ? lang : 'text'; return ( highlighter.codeToHtml(text, { lang: language, theme: 'madoromi' }) + '\n' ); }, // A picture beside docs/<name>.png called <name>-light.png is shown on the light page. image({ href, text }) { const light = href.replace(/\.png$/, '-light.png'); const themed = light !== href && existsSync(join(source, light)); images.push(href, ...(themed ? [light] : [])); const png = readFileSync(join(source, href)); const size = `width="${png.readUInt32BE(16)}" height="${png.readUInt32BE(20)}"`; const lit = themed ? `<source srcset="${escape(base + light)}" media="(prefers-color-scheme: light)">` : ''; // The picture is a link to itself, so a wide screenshot can be read at full size. return `<a class="shot" href="${escape(base + href)}"><picture>${lit}<img src="${escape(base + href)}" alt="${escape(text)}" ${size} loading="lazy"></picture></a>`; }, link({ href, title: linkTitle, tokens }) { const target = siteHref(href); const external = /^https?:/.test(target) ? ' rel="noopener"' : ''; const titled = linkTitle ? ` title="${escape(linkTitle)}"` : ''; return `<a href="${escape(target)}"${titled}${external}>${this.parser.parseInline(tokens)}</a>`; }, table({ header, rows }) { const labels = header.map((cell) => escape(cell.text)); const head = header .map((cell) => `<th>${this.parser.parseInline(cell.tokens)}</th>`) .join(''); // Long paths in a cell may wrap after a slash, never inside a word. const cell = (tokens) => this.parser .parseInline(tokens) .replace( /<code>([^<]*)<\/code>/g, (_, text) => `<code>${text.replaceAll('/', '/<wbr>')}</code>`, ); const body = rows .map( (row) => `<tr>${row.map((item, i) => `<td data-label="${labels[i]}">${cell(item.tokens)}</td>`).join('')}</tr>`, ) .join('\n'); return `<div class="table"><table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table></div>\n`; }, }, }); return { html: marked.parse(markdown), headings, title, images };}
function nav(current) { const groups = [...new Set(pages.map((page) => page.group))]; const link = (page) => `<a href="${address(page.out)}"${page === current ? ' aria-current="page"' : ''}>${page.label}</a>`; const site = groups .map( (group) => `<p class="grp">${group}</p>\n` + pages .filter((page) => page.group === group) .map(link) .join(''), ) .join('\n'); return { site: `${site}<a href="${address(reference.out)}">${reference.label} <i>↗</i></a>`, line: pages.map(link).join('') + `<a href="${address(reference.out)}">${reference.label}</a>`, };}
function toc(headings) { if (headings.length < 2) return { aside: '', line: '' }; const links = headings.map( (h) => `<a href="#${h.id}">${h.html.replace(/<\/?a[^>]*>/g, '')}</a>`, ); const sentence = links.length === 2 ? links.join(' and ') : `${links.slice(0, -1).join(', ')}, and ${links.at(-1)}`; return { aside: `<aside class="toc"><p class="grp">on this page</p>${links.join('')}</aside>`, line: `<p class="tocline" data-pagefind-ignore>On this page: ${sentence}.</p>`, };}
function pager(index) { const [previous, next] = [pages[index - 1], pages[index + 1]]; if (!previous && !next) return ''; const part = (word, page) => page ? `<span>${word}</span> <a href="${address(page.out)}">${page.label}</a> ` : ''; return `<p class="pager" data-pagefind-ignore>${part('Previous', previous)}${part('Next', next)}</p>`;}
// Search over the pagefind index, shown as text in place of the page while there is a query.const search = `(()=>{const field=document.querySelector('.search input'),article=document.querySelector('article'),found=document.querySelector('.results');let engine,shown='',timer;const words=(n,one,many)=>n+' '+(n===1?one:many);async function show(query){query=query.trim();if(query===shown)return;shown=query;history.replaceState(null,'',query?'?q='+encodeURIComponent(query):location.pathname);if(!query){article.classList.remove('searching');return}engine??=await import('${base}pagefind/pagefind.js');const result=await engine.debouncedSearch(query,{},120);if(!result||query!==shown)return;const pages=await Promise.all(result.results.slice(0,8).map((r)=>r.data()));found.innerHTML='<p class="count">'+(pages.length?words(result.results.length,'page','pages')+' mention '+query.replace(/[&<>]/g,''):'Nothing mentions '+query.replace(/[&<>]/g,'')+'.')+'</p>'+pages.map((page)=>'<div class="hit"><a class="title" href="'+page.url+'">'+page.meta.title+'</a>'+(page.sub_results.length?page.sub_results.slice(0,3).map((s)=>'<a class="part" href="'+s.url+'">'+(s.title===page.meta.title?'':'<span>'+s.title+'</span>')+s.excerpt+'</a>').join(''):'<p class="part">'+page.excerpt+'</p>')+'</div>').join('');article.classList.add('searching')}field.addEventListener('input',()=>show(field.value));field.addEventListener('keydown',(e)=>{if(e.key==='Escape'){field.value='';show('');field.blur()}});addEventListener('keydown',(e)=>{if(e.key==='/'&&document.activeElement!==field){e.preventDefault();field.focus()}});const q=new URLSearchParams(location.search).get('q');if(q){field.value=q;show(q)}})()`;
// Marks the section being read in the right-hand list; the page works the same without it.const spy = `const links=[...document.querySelectorAll('.toc a')];if(links.length){const mark=(id)=>links.forEach((a)=>a.classList.toggle('on',a.hash==='#'+id));mark(links[0].hash.slice(1));const watch=new IntersectionObserver((seen)=>seen.forEach((e)=>e.isIntersecting&&mark(e.target.id)),{rootMargin:'0px 0px -70% 0px'});document.querySelectorAll('h2[id]').forEach((h)=>watch.observe(h))}`;function page(entry, index) { const { html, headings, title, images } = render( readFileSync(join(source, entry.file), 'utf8'), ); for (const image of images) copyFileSync(join(source, image), join(out, image)); const links = nav(entry); const contents = toc(headings); const body = html.replace( /(<\/h1>\n(?:<p>[\s\S]*?<\/p>\n)?)/, `$1${contents.line}\n`, ); return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(title)} · albedo docs</title><meta name="theme-color" content="#1c1e2a"><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Hanken+Grotesk:wght@400;500;600&display=swap" rel="stylesheet"><link rel="stylesheet" href="${base}docs.css"><script>document.documentElement.classList.add('js')</script></head><body><div class="page"><header class="top"><p class="mark"><a href="/">albedo</a> <a href="${base}">docs</a></p><nav class="navline">${links.line}</nav><label class="search"><input type="search" placeholder="search" aria-label="search the docs" autocomplete="off" spellcheck="false"><kbd>/</kbd></label></header><nav class="site" aria-label="docs">${links.site}</nav><article data-pagefind-body><div class="results" aria-live="polite" data-pagefind-ignore></div>${body}${pager(index)}</article>${contents.aside}</div><script>${spy}</script><script>${search}</script><script src="${base}docs-lake.js" defer></script></body></html>`;}
/** Writes every page, the search index, docs.css, docs-lake.js, openapi.yaml and the API reference into site/docs. */export async function build() { const unlisted = readdirSync(source).filter( (name) => name.endsWith('.md') && !pages.some((page) => page.file === name), ); if (unlisted.length) throw new Error( `docs/ pages missing from the sidebar in build-docs.mjs: ${unlisted.join(', ')}`, ); rmSync(out, { recursive: true, force: true }); mkdirSync(out, { recursive: true }); const { index, errors } = await pagefind.createIndex({ forceLanguage: 'en', includeCharacters: '_', }); if (!index) throw new Error(`pagefind: ${errors.join('; ')}`); for (const [position, entry] of pages.entries()) { const html = page(entry, position); writeFileSync(join(out, entry.out), html); await index.addHTMLFile({ url: `/${entry.out}`, content: html }); } await index.writeFiles({ outputPath: join(out, 'pagefind') }); await pagefind.close(); copyFileSync(join(site, 'docs.css'), join(out, 'docs.css')); copyFileSync(join(site, 'docs-lake.js'), join(out, 'docs-lake.js')); copyFileSync(join(source, 'openapi.yaml'), join(out, 'openapi.yaml')); execFileSync( 'python3', [ join(root, 'scripts', 'api-reference.py'), '--output', join(out, reference.out), ], { stdio: 'inherit' }, ); console.log( `built ${pages.length} pages, their search index and the API reference into ${out}`, );}
if (process.argv[1] === fileURLToPath(import.meta.url)) await build();