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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177import { readFileSync } from 'node:fs';import type { ClientRequest, IncomingMessage, ServerResponse } from 'node:http';import { homedir, hostname } from 'node:os';import { join } from 'node:path';import { svelte } from '@sveltejs/vite-plugin-svelte';import { defineConfig, type Plugin, type ProxyOptions } from 'vite';
// In development the page talks to the running daemon through Vite: the proxy// reads the daemon's port and token the way the CLI does, so the browser never// holds the token. `albedo web` does the same in production. The endpoint is// read once, so restart `npm run dev` after the daemon restarts.function daemonProxy( { port, token }: Endpoint, rewrite: (path: string) => string, answer?: Record<string, string>,): ProxyOptions { return { target: `http://127.0.0.1:${port}`, ws: true, headers: { authorization: `Bearer ${token}` }, rewrite, configure(proxy) { const stripBrowserHeaders = (req: ClientRequest) => { req.removeHeader('origin'); req.removeHeader('cookie'); req.removeHeader('referer'); }; proxy.on('proxyReq', stripBrowserHeaders); proxy.on('proxyReqWs', (outgoing, incoming, socket) => { if (foreignOrigin(incoming)) { outgoing.destroy(); socket.end( 'HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n', ); return; } stripBrowserHeaders(outgoing); }); if (answer) proxy.on('proxyRes', (res) => Object.assign(res.headers, answer)); }, };}
// The proxy drops Origin and adds the token, so it checks the origin first, as// `albedo web` does: a request a browser sent from any page but the dev// server's own (a sandboxed artifact's is "null") never reaches the daemon.function foreignOrigin(incoming: IncomingMessage): boolean { const origin = incoming.headers.origin; return !!origin && origin !== `http://${incoming.headers.host}`;}
// Refuses an ordinary /api request from a foreign origin before it is proxied;// Vite stops at a response that has ended. An upgrade has no response here and// is refused in proxyReqWs. /frame/ is left open as `albedo web` leaves it: an// artifact's own requests come from its opaque origin, and the key in the path// is the capability.function refuseForeignOrigin( req: IncomingMessage, res: ServerResponse | undefined,): string | undefined { if (!res || !foreignOrigin(req)) return undefined; res .writeHead(403, { 'content-type': 'text/plain' }) .end('origin is not allowed'); return req.url;}
// Artifact pages are sandboxed by the same headers `albedo web` sets on its// /frame route (robot-docs/artifacts.md), so the client is tried as it ships.const FRAME_HEADERS = { 'content-security-policy': 'sandbox allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads allow-pointer-lock', 'access-control-allow-origin': '*', 'cross-origin-resource-policy': 'cross-origin', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff',};
function ownNames(): string[] { const name = hostname() .toLowerCase() .replace(/\.local$/, ''); return [name, `${name}.local`, '.ts.net'];}
type Endpoint = { port: number; token: string };
/** The running daemon's port and token, or null with none running (svelte-check loads this config too, in CI). */function daemonEndpoint(): Endpoint | null { const home = process.env.ALBEDO_HOME ?? join(homedir(), '.albedo'); try { return JSON.parse(readFileSync(join(home, 'daemon.json'), 'utf8')); } catch { return null; }}
// @pierre/diffs can highlight with Shiki's regex or WASM engine or with its// own WASM highlighter, and reaches every theme each of them ships through// dynamic imports, so the build would emit them all (about 3 MB). The client// uses Shiki's regex engine and pierre-dark and pierre-light (DiffView,// FileView): the rest resolves to modules that throw if anything asks for them.// Pierre's highlighter is stubbed only for @pierre/diffs: Markdown code blocks// use their own copy of it (markdown.ts), with two of its themes.const UNUSED = [ '@pierre/highlights', '@pierre/highlights/themes/loader', 'shiki/engine/oniguruma', 'shiki/wasm',];const DIFFS = /[/\\]node_modules[/\\]@pierre[/\\]diffs[/\\]/;
const UNAVAILABLE = `const fail = () => { throw new Error('not in this build: see web/vite.config.ts'); };export const LiveTokenizer = fail, codeToTokens = fail, isSupportedLanguage = fail, createOnigurumaEngine = fail, themes = {};export default fail;`;const PIERRE_THEMES = `import { createThemeCollection } from '@pierre/theming';const theme = (name, colorScheme, load) => ({ name, colorScheme, collection: 'pierre', load: async () => { const [raw, { normalizeTheme }] = await Promise.all([load(), import('shiki/core')]); return normalizeTheme(raw.default ?? raw); },});export const themes = createThemeCollection({ themes: [theme('pierre-dark', 'dark', () => import('@pierre/theme/pierre-dark')), theme('pierre-light', 'light', () => import('@pierre/theme/pierre-light'))],});`;
function trimBundle(): Plugin { return { name: 'albedo-trim-bundle', enforce: 'pre', resolveId(id, importer) { const markdown = id.startsWith('@pierre/highlights') && !DIFFS.test(importer ?? ''); if (UNUSED.includes(id) && !markdown) return `\0unused:${id}`; if (id === '@pierre/theming/themes') return '\0pierre-themes'; }, load(id) { if (id.startsWith('\0unused:')) return UNAVAILABLE; if (id === '\0pierre-themes') return PIERRE_THEMES; }, };}
// Only the dev server talks to a daemon, so a build (in the Nix sandbox, say)// never needs daemon.json.export default defineConfig(({ command }) => { const daemon = command === 'serve' ? daemonEndpoint() : null; return { plugins: [trimBundle(), svelte()], // Open to the local network, so other devices at home can try the client. // Only this machine's own names (and Tailscale's MagicDNS ones) pass as Host: // the proxy holds the daemon token, so any name a page could rebind must not. server: { host: true, allowedHosts: ownNames(), proxy: daemon ? { '/api': { ...daemonProxy(daemon, (path) => path.replace(/^\/api/, '')), bypass: refuseForeignOrigin, }, '/frame/': daemonProxy( daemon, (path) => path.replace(/^\/frame/, '/extensions/artifacts/frame'), FRAME_HEADERS, ), } : undefined, }, build: { target: 'es2022', reportCompressedSize: true }, };});