Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(glance): put the agent on the Windows 11 widgets board

nirholasfa0f47c51e16
diff --git a/api/_lib/glance-adaptive.js b/api/_lib/glance-adaptive.js
new file mode 100644
index 000000000..4961a25d9
--- /dev/null
+++ b/api/_lib/glance-adaptive.js
@@ -0,0 +1,121 @@
+/**
+ * The glance card as an Adaptive Card.
+ *
+ * The Windows 11 widgets board renders Adaptive Cards, not HTML: the PWA
+ * manifest points at a template (`ms_ac_template`) and the service worker
+ * feeds it data, and the host does the binding. Other hosts would rather be
+ * handed a card that is already bound.
+ *
+ * Both come from ONE layout function so the template and the bound card can
+ * never drift: `field()` either emits a binding expression or the real value.
+ */
+
+const FALLBACK_IMAGE = 'https://three.ws/pwa-192x192.png';
+
+export const ADAPTIVE_VERSION = '1.6';
+
+function layout(field) {
+ return {
+ type: 'AdaptiveCard',
+ $schema: 'http://adaptivecards.io/schemas/adaptive-card.json',
+ version: ADAPTIVE_VERSION,
+ body: [
+ {
+ type: 'ColumnSet',
+ columns: [
+ {
+ type: 'Column',
+ width: 'auto',
+ items: [
+ {
+ type: 'Image',
+ url: field('image', FALLBACK_IMAGE),
+ size: 'Small',
+ style: 'RoundedCorners',
+ altText: field('name'),
+ },
+ ],
+ },
+ {
+ type: 'Column',
+ width: 'stretch',
+ items: [
+ { type: 'TextBlock', text: field('name'), weight: 'Bolder', size: 'Medium', wrap: false },
+ {
+ type: 'TextBlock',
+ text: field('headline'),
+ isSubtle: true,
+ size: 'Small',
+ wrap: true,
+ maxLines: 2,
+ spacing: 'None',
+ },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'ColumnSet',
+ spacing: 'Medium',
+ columns: [
+ {
+ type: 'Column',
+ width: 'auto',
+ items: [
+ {
+ type: 'TextBlock',
+ text: field('metric.value'),
+ size: 'ExtraLarge',
+ weight: 'Bolder',
+ spacing: 'None',
+ },
+ ],
+ },
+ {
+ type: 'Column',
+ width: 'stretch',
+ verticalContentAlignment: 'Bottom',
+ items: [
+ {
+ type: 'TextBlock',
+ text: field('metric.label'),
+ isSubtle: true,
+ size: 'Small',
+ spacing: 'None',
+ },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'FactSet',
+ spacing: 'Small',
+ facts: [
+ { title: field('stats.0.label'), value: field('stats.0.value') },
+ { title: field('stats.1.label'), value: field('stats.1.value') },
+ { title: field('stats.2.label'), value: field('stats.2.value') },
+ ],
+ },
+ ],
+ actions: [
+ { type: 'Action.OpenUrl', title: 'Open agent', url: field('url') },
+ { type: 'Action.OpenUrl', title: 'New agent', url: field('createUrl', 'https://three.ws/create') },
+ ],
+ };
+}
+
+/** The unbound template the Windows widgets board fetches once. */
+export function adaptiveTemplate() {
+ return layout((path, fallback) =>
+ fallback ? `\${if(${path}, ${path}, '${fallback}')}` : `\${${path}}`,
+ );
+}
+
+/** The same card with this agent's values already in it. */
+export function adaptiveCardFor(card) {
+ return layout((path, fallback) => {
+ const value = path.split('.').reduce((acc, key) => (acc == null ? acc : acc[key]), card);
+ if (value === null || value === undefined || value === '') return fallback ?? '';
+ return typeof value === 'number' ? String(value) : value;
+ });
+}
diff --git a/api/_lib/glance-card.js b/api/_lib/glance-card.js
new file mode 100644
index 000000000..59bff5331
--- /dev/null
+++ b/api/_lib/glance-card.js
@@ -0,0 +1,207 @@
+/**
+ * Glance card model + renderers.
+ * ------------------------------
+ * One agent, reduced to what fits in a home screen slot: who it is, one live
+ * number, and a way back into the app. The same model feeds four consumers, so
+ * it is built once here rather than four times at the edges:
+ *
+ * - JSON -> the Windows 11 widgets board (Adaptive Card data binding),
+ * the <agent-glance> element, and any third-party surface.
+ * - SVG -> README badges, Slack unfurls, docs, and any <img> slot.
+ * - Adaptive -> a fully bound Adaptive Card for consumers that render one
+ * without doing their own templating.
+ *
+ * No widget runtime on any of those platforms can execute WebGL, which is why
+ * a glance card is a flat card and not the live 3D avatar: the avatar's own
+ * thumbnail is the image, and the 3D lives one tap away on the agent page.
+ *
+ * Everything here reads real platform state (agent_identities, agent_actions).
+ * A card for an agent that has never acted is a designed state, not an error.
+ */
+
+import { sql } from './db.js';
+import { getRedis } from './redis.js';
+import { thumbnailUrl } from './r2.js';
+import { sha256 } from './crypto.js';
+
+export const GLANCE_CARD_VERSION = 1;
+
+// Long enough that a widget board polling every few minutes mostly hits cache,
+// short enough that "moves today" is not visibly stale on a busy agent.
+export const GLANCE_CACHE_TTL_S = 120;
+const CACHE_KEY = (id) => `glance:card:v${GLANCE_CARD_VERSION}:${id}`;
+
+const SITE = 'https://three.ws';
+
+/**
+ * Load an agent's glance card from real platform state.
+ *
+ * @param {string} agentId agent uuid (caller validates the shape)
+ * @param {{ fresh?: boolean }} [opts]
+ * @returns {Promise<object|null>} card model, or null when no such agent
+ */
+export async function loadGlanceCard(agentId, { fresh = false } = {}) {
+ const redis = await getRedis();
+ if (!fresh && redis) {
+ try {
+ const cached = await redis.get(CACHE_KEY(agentId));
+ if (cached) return { ...cached, cache: 'hit' };
+ } catch {
+ /* cache unavailable: recompute, never fail the read */
+ }
+ }
+
+ const [[agent], [activity], [last]] = await Promise.all([
+ sql`
+ SELECT i.id, i.name, i.description, i.skills, i.created_at,
+ a.thumbnail_key AS avatar_thumbnail_key,
+ a.visibility AS avatar_visibility
+ FROM agent_identities i
+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL
+ WHERE i.id = ${agentId} AND i.deleted_at IS NULL
+ LIMIT 1
+ `,
+ sql`
+ SELECT
+ count(*)::int AS total,
+ count(*) FILTER (WHERE created_at > now() - interval '24 hours')::int AS day,
+ count(*) FILTER (WHERE created_at > now() - interval '7 days')::int AS week
+ FROM agent_actions
+ WHERE agent_id = ${agentId}
+ `,
+ sql`
+ SELECT type, created_at
+ FROM agent_actions
+ WHERE agent_id = ${agentId}
+ ORDER BY created_at DESC
+ LIMIT 1
+ `,
+ ]);
+
+ if (!agent) return null;
+
+ const card = buildGlanceCard({ agent, activity: activity || {}, last: last || null });
+
+ if (redis) {
+ try {
+ await redis.set(CACHE_KEY(agentId), card, { ex: GLANCE_CACHE_TTL_S });
+ } catch {
+ /* a cache write failure must never fail the read */
+ }
+ }
+ return { ...card, cache: 'miss' };
+}
+
+/**
+ * Shape the card from already-loaded rows. Pure, so the renderers and the
+ * tests can build a card without touching the database.
+ */
+export function buildGlanceCard({ agent, activity = {}, last = null, now = new Date() }) {
+ const day = Number(activity.day) || 0;
+ const total = Number(activity.total) || 0;
+ const week = Number(activity.week) || 0;
+ const skills = Array.isArray(agent.skills) ? agent.skills.length : 0;
+ const lastAt = last?.created_at ? new Date(last.created_at) : null;
+ const createdAt = agent.created_at ? new Date(agent.created_at) : null;
+
+ // The avatar thumbnail only resolves for an avatar the public may see;
+ // a private or missing one falls back to the generated monogram, never to
+ // a broken image.
+ const publicAvatar =
+ agent.avatar_visibility === 'public' || agent.avatar_visibility === 'unlisted';
+ const image =
+ publicAvatar && agent.avatar_thumbnail_key ? thumbnailUrl(agent.avatar_thumbnail_key) : null;
+
+ const name = String(agent.name || 'Untitled agent').slice(0, 64);
+ const status = deriveStatus({ total, lastAt, now });
+
+ return {
+ version: GLANCE_CARD_VERSION,
+ id: agent.id,
+ name,
+ description: agent.description ? String(agent.description).slice(0, 160) : null,
+ url: `${SITE}/agents/${agent.id}`,
+ createUrl: `${SITE}/create`,
+ image,
+ monogram: monogramOf(name),
+ accent: accentOf(String(agent.id)),
+ status,
+ headline: HEADLINE[status],
+ metric: { label: 'Moves today', value: day },
+ stats: [
+ { label: 'This week', value: week },
+ { label: 'All time', value: total },
+ { label: 'Skills', value: skills },
+ ],
+ lastAction: lastAt
+ ? {
+ type: String(last.type || 'action').slice(0, 40),
+ at: lastAt.toISOString(),
+ relative: relativeTime(lastAt, now),
+ }
+ : null,
+ bornAt: createdAt ? createdAt.toISOString() : null,
+ ageDays: createdAt ? Math.max(0, Math.floor((now - createdAt) / 86_400_000)) : null,
+ updatedAt: now.toISOString(),
+ ttl: GLANCE_CACHE_TTL_S,
+ };
+}
+
+const HEADLINE = {
+ // The empty state has to earn its slot too: it says what to do next
+ // rather than showing a zero and leaving the owner to guess.
+ new: 'Not started yet. Open to give it a first job.',
+ idle: 'Quiet today. Tap to put it back to work.',
+ active: 'Working.',
+};
+
+function deriveStatus({ total, lastAt, now }) {
+ if (!total || !lastAt) return 'new';
+ return now - lastAt < 86_400_000 ? 'active' : 'idle';
+}
+
+export function monogramOf(name) {
+ const words = String(name || '')
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean);
+ if (!words.length) return '3';
+ const first = [...words[0]][0] || '';
+ const second = words.length > 1 ? [...words[1]][0] || '' : '';
+ return (first + second).toUpperCase().slice(0, 2);
+}
+
+/**
+ * A stable pair of hues per agent, so a card without a thumbnail still looks
+ * like that specific agent and not like every other blank card.
+ */
+export function accentOf(seed) {
+ let h = 2166136261;
+ for (let i = 0; i < seed.length; i++) {
+ h ^= seed.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ const hue = Math.abs(h) % 360;
+ return { from: `hsl(${hue} 82% 58%)`, to: `hsl(${(hue + 48) % 360} 84% 46%)`, hue };
+}
+
+export function relativeTime(then, now = new Date()) {
+ const s = Math.max(0, Math.floor((now - then) / 1000));
+ if (s < 60) return 'just now';
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.floor(m / 60);
+ if (h < 24) return `${h}h ago`;
+ const d = Math.floor(h / 24);
+ if (d < 30) return `${d}d ago`;
+ const mo = Math.floor(d / 30);
+ if (mo < 12) return `${mo}mo ago`;
+ return `${Math.floor(mo / 12)}y ago`;
+}
+
+export async function glanceEtag(card) {
+ const digest = await sha256(
+ [card.id, card.metric.value, card.stats.map((s) => s.value).join(','), card.status].join('|'),
+ );
+ return `W/"glance-${GLANCE_CARD_VERSION}-${digest.slice(0, 24)}"`;
+}
diff --git a/api/_lib/glance-svg.js b/api/_lib/glance-svg.js
new file mode 100644
index 000000000..95d3d0016
--- /dev/null
+++ b/api/_lib/glance-svg.js
@@ -0,0 +1,172 @@
+/**
+ * Glance card, rendered as a self-contained SVG.
+ *
+ * One file of markup with no external CSS, no script and no font dependency
+ * beyond the system stack, so the same bytes render in a README, a Slack
+ * unfurl, an <img> on a third-party page and a widget host that only accepts
+ * an image. Theme follows the reader: `auto` ships both palettes and lets
+ * prefers-color-scheme pick, which is what GitHub and Slack actually honour.
+ *
+ * Sizes map to the slots the OS widget boards hand out:
+ * small 240x240 square tile (Android 2x2, iOS small, Windows small)
+ * medium 480x200 the default (Android 4x2, Windows medium, README badge)
+ * large 480x300 adds the stat row and the last action
+ */
+
+export const GLANCE_SIZES = {
+ small: { w: 240, h: 240 },
+ medium: { w: 480, h: 200 },
+ large: { w: 480, h: 300 },
+};
+
+const LIGHT = {
+ bg: '#ffffff',
+ panel: '#f4f5f9',
+ text: '#0b0b18',
+ muted: '#5b5f73',
+ line: '#e4e6ef',
+};
+const DARK = {
+ bg: '#0b0b16',
+ panel: '#15162a',
+ text: '#f6f7fb',
+ muted: '#a2a7bd',
+ line: '#262842',
+};
+
+// Control characters are not representable in XML 1.0. One stray byte inside an
+// agent name would otherwise make the whole document unparseable, which is the
+// same class of failure that stalled the chain indexer: strip, keep serving.
+const CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g;
+
+export function escapeXml(value) {
+ return String(value ?? '')
+ .replace(CONTROL_CHARS, '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&apos;');
+}
+
+export function truncate(value, max) {
+ const chars = [...String(value ?? '')];
+ if (chars.length <= max) return chars.join('');
+ return `${chars.slice(0, Math.max(1, max - 1)).join('').trimEnd()}…`;
+}
+
+export function formatCount(n) {
+ const value = Number(n) || 0;
+ if (value < 1000) return String(value);
+ if (value < 100_000) return `${(value / 1000).toFixed(value < 10_000 ? 1 : 0)}k`;
+ if (value < 1_000_000) return `${Math.round(value / 1000)}k`;
+ return `${(value / 1_000_000).toFixed(1)}m`;
+}
+
+/**
+ * @param {object} card a model from buildGlanceCard()
+ * @param {{ theme?: 'auto'|'light'|'dark', size?: 'small'|'medium'|'large' }} [opts]
+ * @returns {string} a complete SVG document
+ */
+export function renderGlanceSvg(card, { theme = 'auto', size = 'medium' } = {}) {
+ const dim = GLANCE_SIZES[size] || GLANCE_SIZES.medium;
+ const large = size === 'large';
+ const small = size === 'small';
+ // Ids and CSS selectors are namespaced per card. Two cards inlined into one
+ // HTML document would otherwise share a `svg{}` rule and a gradient id, and
+ // the last one on the page would repaint every other one.
+ const ns = `g${String(card.id || '').replace(/[^a-z0-9]/gi, '').slice(0, 8) || 'card'}${size[0]}${theme[0]}`;
+ const label = `${card.name}: ${card.metric.value} ${card.metric.label.toLowerCase()} on three.ws`;
+ const pSize = small ? 56 : 64;
+ const pAt = small ? 20 : 24;
+
+ return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${dim.w}" height="${dim.h}" viewBox="0 0 ${dim.w} ${dim.h}" class="${ns}" role="img" aria-label="${escapeXml(label)}" font-family="ui-sans-serif, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif">
+<title>${escapeXml(label)}</title>
+<defs>
+<linearGradient id="${ns}a" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${escapeXml(card.accent.from)}"/><stop offset="1" stop-color="${escapeXml(card.accent.to)}"/></linearGradient>
+<radialGradient id="${ns}g" cx="0.12" cy="0" r="0.9"><stop offset="0" stop-color="${escapeXml(card.accent.from)}" stop-opacity="0.20"/><stop offset="1" stop-color="${escapeXml(card.accent.from)}" stop-opacity="0"/></radialGradient>
+<clipPath id="${ns}c"><rect x="0" y="0" width="${dim.w}" height="${dim.h}" rx="20"/></clipPath>
+<clipPath id="${ns}p"><rect x="${pAt}" y="${pAt}" width="${pSize}" height="${pSize}" rx="18"/></clipPath>
+</defs>
+<style>${themeCss(theme, ns)}</style>
+<g clip-path="url(#${ns}c)">
+<rect width="${dim.w}" height="${dim.h}" class="bg"/>
+<rect width="${dim.w}" height="${dim.h}" fill="url(#${ns}g)"/>
+<rect width="${dim.w}" height="3" fill="url(#${ns}a)"/>
+${small ? smallBody(card, ns) : wideBody(card, ns, dim, large)}
+</g>
+<rect x="0.5" y="0.5" width="${dim.w - 1}" height="${dim.h - 1}" rx="19.5" fill="none" class="line"/>
+</svg>`;
+}
+
+function themeCss(theme, ns) {
+ const vars = (t) =>
+ `--bg:${t.bg};--panel:${t.panel};--text:${t.text};--muted:${t.muted};--line:${t.line}`;
+ const base = `.${ns} .bg{fill:var(--bg)}.${ns} .panel{fill:var(--panel)}.${ns} .t{fill:var(--text)}.${ns} .m{fill:var(--muted)}.${ns} .line{stroke:var(--line)}`;
+ if (theme === 'light') return `.${ns}{${vars(LIGHT)}}${base}`;
+ if (theme === 'dark') return `.${ns}{${vars(DARK)}}${base}`;
+ return `.${ns}{${vars(LIGHT)}}@media (prefers-color-scheme:dark){.${ns}{${vars(DARK)}}}${base}`;
+}
+
+function portrait(card, ns, x, y, s) {
+ if (card.image) {
+ // Both href forms: SVG 2 renderers read `href`, older sanitizers and
+ // renderers (Slack, some feed readers) still only read the xlink form.
+ return `<image href="${escapeXml(card.image)}" xlink:href="${escapeXml(card.image)}" x="${x}" y="${y}" width="${s}" height="${s}" clip-path="url(#${ns}p)" preserveAspectRatio="xMidYMid slice"/>`;
+ }
+ const fontSize = Math.round(s * 0.42);
+ return `<rect x="${x}" y="${y}" width="${s}" height="${s}" rx="18" fill="url(#${ns}a)"/><text x="${x + s / 2}" y="${y + s / 2 + fontSize * 0.36}" text-anchor="middle" font-size="${fontSize}" font-weight="700" fill="#ffffff">${escapeXml(card.monogram)}</text>`;
+}
+
+const STATUS_FILL = { active: '#22c55e', idle: '#f59e0b', new: '#64748b' };
+
+function statusDot(card, x, y) {
+ return `<circle cx="${x}" cy="${y}" r="4" fill="${STATUS_FILL[card.status] || STATUS_FILL.new}"/>`;
+}
+
+function wideBody(card, ns, dim, large) {
+ const sub = card.description || card.headline;
+ const metric = formatCount(card.metric.value);
+ const metricY = large ? 140 : 148;
+ const last = card.lastAction
+ ? `${truncate(card.lastAction.type, 22)} ${card.lastAction.relative}`
+ : 'no activity yet';
+
+ const chips = large
+ ? card.stats
+ .map((s, i) => {
+ const x = 24 + i * 112;
+ return `<rect x="${x}" y="186" width="104" height="58" rx="14" class="panel"/>
+<text x="${x + 16}" y="212" font-size="18" font-weight="700" class="t">${escapeXml(formatCount(s.value))}</text>
+<text x="${x + 16}" y="230" font-size="11" class="m">${escapeXml(s.label)}</text>`;
+ })
+ .join('\n')
+ : card.stats
+ .map((s, i) => {
+ const y = 112 + i * 22;
+ return `<text x="${dim.w - 24}" y="${y}" text-anchor="end" font-size="12" class="m">${escapeXml(s.label)} <tspan font-weight="700" class="t">${escapeXml(formatCount(s.value))}</tspan></text>`;
+ })
+ .join('\n');
+
+ return `${portrait(card, ns, 24, 24, 64)}
+<text x="104" y="50" font-size="21" font-weight="700" class="t">${escapeXml(truncate(card.name, 22))}</text>
+<text x="104" y="72" font-size="12.5" class="m">${escapeXml(truncate(sub, 44))}</text>
+${statusDot(card, dim.w - 90, 38)}
+<text x="${dim.w - 24}" y="42" text-anchor="end" font-size="11" class="m">three.ws</text>
+<text x="24" y="${metricY}" font-size="42" font-weight="800" class="t">${escapeXml(metric)}</text>
+<text x="${30 + metric.length * 24}" y="${metricY}" font-size="13" class="m">${escapeXml(card.metric.label.toLowerCase())}</text>
+<text x="24" y="${metricY + 24}" font-size="11.5" class="m">${escapeXml(truncate(`last: ${last}`, 46))}</text>
+${chips}
+${large ? `<text x="24" y="274" font-size="11.5" class="m">${escapeXml(truncate(card.headline, 60))}</text>` : ''}`;
+}
+
+function smallBody(card, ns) {
+ const metric = formatCount(card.metric.value);
+ return `${portrait(card, ns, 20, 20, 56)}
+${statusDot(card, 214, 32)}
+<text x="20" y="100" font-size="16" font-weight="700" class="t">${escapeXml(truncate(card.name, 16))}</text>
+<text x="20" y="156" font-size="40" font-weight="800" class="t">${escapeXml(metric)}</text>
+<text x="20" y="176" font-size="11.5" class="m">${escapeXml(card.metric.label.toLowerCase())}</text>
+<text x="20" y="208" font-size="11" class="m">${escapeXml(truncate(card.lastAction ? `last ${card.lastAction.relative}` : 'no activity yet', 26))}</text>
+<text x="220" y="222" text-anchor="end" font-size="10.5" class="m">three.ws</text>`;
+}
diff --git a/api/glance/card.js b/api/glance/card.js
new file mode 100644
index 000000000..29e1d8c2e
--- /dev/null
+++ b/api/glance/card.js
@@ -0,0 +1,116 @@
+/**
+ * GET /api/glance/card
+ * --------------------
+ * One agent, in whatever shape the surface asking for it can render.
+ *
+ * ?agent=<uuid> required
+ * &format=json | svg | adaptive default json
+ * &size=small | medium | large svg only, default medium
+ * &theme=auto | light | dark svg only, default auto
+ *
+ * json the glance card model. What the Windows 11 widgets board binds
+ * to its Adaptive Card template, and what <agent-glance> renders.
+ * svg a self-contained card image for a README, a Slack unfurl, an
+ * <img>, or any widget host that only takes a picture.
+ * adaptive a fully bound Adaptive Card, for hosts that render one without
+ * doing their own templating.
+ *
+ * Public, cacheable, side-effect free: an agent profile is already public
+ * (api/agent-og.js serves the same agent to any crawler), so a card of it is
+ * too. Private avatars never leak: the thumbnail is only attached when the
+ * avatar is public or unlisted, otherwise the card falls back to the generated
+ * monogram. Nothing here needs a session, which is what lets a widget board
+ * poll it from an OS process with no cookies.
+ *
+ * A missing agent answers with a real card that says so (and a 404 status),
+ * never a broken image in someone's home screen slot.
+ */
+
+import { loadGlanceCard, glanceEtag } from '../_lib/glance-card.js';
+import { renderGlanceSvg, GLANCE_SIZES } from '../_lib/glance-svg.js';
+import { adaptiveCardFor } from '../_lib/glance-adaptive.js';
+import { cors, json, error, wrap, method, varyOn } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
+
+// Widget boards poll on their own schedule (Windows every ~15 min, a page
+// every few minutes). The card is cheap and non-critical, so let the CDN
+// answer most of it and keep serving a slightly stale card while revalidating
+// rather than showing an empty slot.
+const CACHE = 'public, max-age=60, s-maxage=120, stale-while-revalidate=600';
+const CACHE_MISS = 'public, max-age=30, s-maxage=60';
+
+const FORMATS = new Set(['json', 'svg', 'adaptive']);
+const THEMES = new Set(['auto', 'light', 'dark']);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many card reads');
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agent') || url.searchParams.get('id') || '';
+ const format = FORMATS.has(url.searchParams.get('format'))
+ ? url.searchParams.get('format')
+ : 'json';
+ const size = GLANCE_SIZES[url.searchParams.get('size')] ? url.searchParams.get('size') : 'medium';
+ const theme = THEMES.has(url.searchParams.get('theme')) ? url.searchParams.get('theme') : 'auto';
+
+ // The theme and size live in the query string, so the CDN keys on them
+ // already; Vary keeps a shared cache from handing an SVG to a JSON caller.
+ varyOn(res, 'accept');
+
+ if (!isUuid(agentId)) return notFound(res, format, size, theme, 'That agent id is not valid.');
+
+ const card = await loadGlanceCard(agentId);
+ if (!card) return notFound(res, format, size, theme, 'This agent is not on three.ws.');
+
+ const etag = await glanceEtag(card);
+ res.setHeader('etag', etag);
+ res.setHeader('cache-control', card.cache === 'hit' ? CACHE : CACHE_MISS);
+ if (req.headers['if-none-match'] === etag) {
+ res.statusCode = 304;
+ return res.end();
+ }
+
+ if (format === 'svg') {
+ res.statusCode = 200;
+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');
+ return res.end(renderGlanceSvg(card, { size, theme }));
+ }
+ if (format === 'adaptive') return json(res, 200, adaptiveCardFor(card));
+ return json(res, 200, card);
+});
+
+/**
+ * The not-found state is designed, not blank: an SVG caller gets a card that
+ * explains itself in the slot it was placed in, a JSON caller gets a 404 body
+ * it can branch on.
+ */
+function notFound(res, format, size, theme, message) {
+ if (format !== 'svg') return error(res, 404, 'not_found', message);
+ const placeholder = {
+ id: 'missing',
+ name: 'Agent not found',
+ description: message,
+ headline: message,
+ url: 'https://three.ws/agents',
+ image: null,
+ monogram: '3',
+ accent: { from: '#64748b', to: '#334155', hue: 215 },
+ status: 'new',
+ metric: { label: 'Moves today', value: 0 },
+ stats: [
+ { label: 'This week', value: 0 },
+ { label: 'All time', value: 0 },
+ { label: 'Skills', value: 0 },
+ ],
+ lastAction: null,
+ };
+ res.statusCode = 404;
+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');
+ res.setHeader('cache-control', 'public, max-age=60');
+ return res.end(renderGlanceSvg(placeholder, { size, theme }));
+}
diff --git a/api/glance/mine.js b/api/glance/mine.js
new file mode 100644
index 000000000..6a2ba9d96
--- /dev/null
+++ b/api/glance/mine.js
@@ -0,0 +1,67 @@
+/**
+ * GET /api/glance/mine
+ * --------------------
+ * The card for the signed-in owner's agent, plus the list of agents they could
+ * point a widget at instead. This is what the widget service worker calls: a
+ * home screen slot has no UI to pick an agent in, so the platform answers
+ * "your agent" and lets the owner change it from the page.
+ *
+ * ?agent=<uuid> pin a specific agent (must be one the caller owns)
+ *
+ * Signed out is a designed answer, not a 401: the widget shows a card that
+ * says sign in, because a widget that renders an error is a widget people
+ * remove. The response carries `signedIn` so the caller can branch.
+ */
+
+import { loadGlanceCard } from '../_lib/glance-card.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, wrap, method, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
+
+export default wrap(async (req, res) => {
+ // credentials: the widget SW sends the session cookie, so the response is
+ // per-user and must never be shared by a cache.
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+ res.setHeader('cache-control', 'private, no-store');
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many card reads');
+
+ const session = await getSessionUser(req, res);
+ if (!session) {
+ return json(res, 200, {
+ signedIn: false,
+ card: null,
+ agents: [],
+ signInUrl: 'https://three.ws/login',
+ createUrl: 'https://three.ws/create',
+ });
+ }
+
+ const owned = await sql`
+ SELECT id, name
+ FROM agent_identities
+ WHERE user_id = ${session.id} AND deleted_at IS NULL
+ ORDER BY created_at ASC
+ LIMIT 25
+ `;
+
+ const url = new URL(req.url, 'http://x');
+ const requested = url.searchParams.get('agent') || '';
+ // A pinned agent the caller does not own falls back to their own first
+ // agent rather than erroring: the widget keeps working after an agent is
+ // deleted or a different account signs in on the same device.
+ const pinned = isUuid(requested) && owned.some((a) => a.id === requested) ? requested : null;
+ const target = pinned || owned[0]?.id || null;
+
+ return json(res, 200, {
+ signedIn: true,
+ card: target ? await loadGlanceCard(target) : null,
+ agents: owned.map((a) => ({ id: a.id, name: a.name })),
+ signInUrl: 'https://three.ws/login',
+ createUrl: 'https://three.ws/create',
+ });
+});
diff --git a/api/glance/template.js b/api/glance/template.js
new file mode 100644
index 000000000..5ed531431
--- /dev/null
+++ b/api/glance/template.js
@@ -0,0 +1,17 @@
+/**
+ * GET /api/glance/template
+ *
+ * The Adaptive Card template the Windows 11 widgets board fetches once (the
+ * `ms_ac_template` in the PWA manifest's `widgets` member) and then binds to
+ * whatever /api/glance/card returns. Static per deploy, so it caches hard.
+ */
+
+import { adaptiveTemplate } from '../_lib/glance-adaptive.js';
+import { cors, json, wrap, method } from '../_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+ res.setHeader('cache-control', 'public, max-age=3600, s-maxage=86400');
+ return json(res, 200, adaptiveTemplate());
+});
diff --git a/public/glance-sw.js b/public/glance-sw.js
new file mode 100644
index 000000000..d3a4a38d6
--- /dev/null
+++ b/public/glance-sw.js
@@ -0,0 +1,190 @@
+//
+// Glance widget handlers, imported into the VitePWA-generated service worker
+// via `workbox.importScripts` (see vite.config.js). Plain classic worker
+// script (no imports) so importScripts can pull it in, same as
+// push-sw.js and share-target-sw.js.
+//
+// This is the Windows 11 widgets board half of Glance. The manifest's
+// `widgets` member declares the widget and points at the Adaptive Card
+// template (/api/glance/template); the host then hands this worker the widget
+// lifecycle and expects it to supply the data:
+//
+// widgetinstall the user pinned the widget -> render it now
+// widgetresume the board woke up -> render from cache, refresh
+// widgetclick a custom verb fired -> refresh on demand
+// widgetuninstall the user removed it -> drop the cached payload
+// periodicsync the platform granted a tick -> refresh every pinned widget
+//
+// The data comes from /api/glance/mine, which answers per session cookie, so a
+// signed-out board renders a real "sign in" card instead of an error. The last
+// good payload is kept in the Cache API: an offline device shows the card it
+// last saw, with its own timestamp, rather than an empty slot.
+//
+
+const GLANCE_TAG = 'agent-glance';
+const GLANCE_CACHE = 'threews-glance';
+const GLANCE_STATE_KEY = '/_glance/state';
+const GLANCE_DATA_URL = '/api/glance/mine';
+const GLANCE_REFRESH_TAG = 'glance-refresh';
+// A widget board is a background surface: a request that hangs there burns the
+// platform's refresh budget and leaves the slot stale anyway.
+const GLANCE_TIMEOUT_MS = 8000;
+
+/**
+ * Shape the widget payload from the /api/glance/mine response. Pure, so the
+ * signed-out and empty states are testable without a network or a widget host.
+ * @param {object|null} body
+ * @param {{ offline?: boolean, at?: string }} [opts]
+ */
+function glancePayload(body, opts = {}) {
+ const stamp = opts.at || new Date().toISOString();
+ if (!body || body.signedIn === false) {
+ return {
+ name: 'Sign in to three.ws',
+ headline: 'Sign in to put your agent on the home screen.',
+ image: '/pwa-192x192.png',
+ url: (body && body.signInUrl) || 'https://three.ws/login',
+ createUrl: (body && body.createUrl) || 'https://three.ws/create',
+ metric: { label: 'Moves today', value: '0' },
+ stats: [
+ { label: 'This week', value: '0' },
+ { label: 'All time', value: '0' },
+ { label: 'Skills', value: '0' },
+ ],
+ state: 'signed-out',
+ updatedAt: stamp,
+ };
+ }
+ if (!body.card) {
+ return {
+ name: 'No agent yet',
+ headline: 'Create your first agent and it lands here.',
+ image: '/pwa-192x192.png',
+ url: body.createUrl || 'https://three.ws/create',
+ createUrl: body.createUrl || 'https://three.ws/create',
+ metric: { label: 'Moves today', value: '0' },
+ stats: [
+ { label: 'This week', value: '0' },
+ { label: 'All time', value: '0' },
+ { label: 'Skills', value: '0' },
+ ],
+ state: 'empty',
+ updatedAt: stamp,
+ };
+ }
+ const card = body.card;
+ return {
+ name: card.name,
+ headline: opts.offline ? `${card.headline} (offline)` : card.headline,
+ image: card.image || '/pwa-192x192.png',
+ url: card.url,
+ createUrl: card.createUrl || 'https://three.ws/create',
+ metric: { label: card.metric.label, value: String(card.metric.value) },
+ stats: (card.stats || []).map((s) => ({ label: s.label, value: String(s.value) })),
+ state: opts.offline ? 'offline' : card.status,
+ updatedAt: opts.at || card.updatedAt || stamp,
+ };
+}
+
+async function readCachedPayload() {
+ try {
+ const cache = await caches.open(GLANCE_CACHE);
+ const hit = await cache.match(GLANCE_STATE_KEY);
+ return hit ? await hit.json() : null;
+ } catch {
+ return null;
+ }
+}
+
+async function writeCachedPayload(payload) {
+ try {
+ const cache = await caches.open(GLANCE_CACHE);
+ await cache.put(
+ GLANCE_STATE_KEY,
+ new Response(JSON.stringify(payload), { headers: { 'content-type': 'application/json' } }),
+ );
+ } catch {
+ /* a cache write failure must never break the render */
+ }
+}
+
+/**
+ * Fetch the live card, falling back to the last one this device saw. Returns
+ * a payload every time: a widget slot always has something in it.
+ */
+async function loadPayload() {
+ try {
+ const res = await fetch(GLANCE_DATA_URL, {
+ credentials: 'include',
+ signal: AbortSignal.timeout(GLANCE_TIMEOUT_MS),
+ });
+ if (!res.ok) throw new Error(`glance data ${res.status}`);
+ const payload = glancePayload(await res.json());
+ await writeCachedPayload(payload);
+ return payload;
+ } catch {
+ const cached = await readCachedPayload();
+ if (cached) return { ...cached, state: 'offline', headline: offlineHeadline(cached) };
+ return glancePayload(null);
+ }
+}
+
+function offlineHeadline(cached) {
+ const base = String(cached.headline || '').replace(/ \(offline\)$/, '');
+ return `${base} (offline)`;
+}
+
+/** Push the payload into every instance of the widget the host has pinned. */
+async function renderGlanceWidget(widget) {
+ const payload = await loadPayload();
+ const tag = (widget && widget.definition && widget.definition.tag) || GLANCE_TAG;
+ if (!self.widgets) return payload;
+ await self.widgets.updateByTag(tag, {
+ template: JSON.stringify(widget && widget.definition ? widget.definition.msAcTemplate : ''),
+ data: JSON.stringify(payload),
+ });
+ return payload;
+}
+
+self.addEventListener('widgetinstall', (event) => {
+ event.waitUntil(renderGlanceWidget(event.widget));
+});
+
+self.addEventListener('widgetresume', (event) => {
+ event.waitUntil(renderGlanceWidget(event.widget));
+});
+
+self.addEventListener('widgetclick', (event) => {
+ // `refresh` is the only verb the template declares; anything else is a host
+ // lifecycle nudge and re-rendering is the right answer for both.
+ event.waitUntil(renderGlanceWidget(event.widget));
+});
+
+self.addEventListener('widgetuninstall', (event) => {
+ event.waitUntil(
+ (async () => {
+ try {
+ const cache = await caches.open(GLANCE_CACHE);
+ await cache.delete(GLANCE_STATE_KEY);
+ } catch {
+ /* nothing pinned, nothing to clean */
+ }
+ })(),
+ );
+});
+
+self.addEventListener('periodicsync', (event) => {
+ if (event.tag !== GLANCE_REFRESH_TAG) return;
+ event.waitUntil(
+ (async () => {
+ if (!self.widgets) return;
+ const pinned = await self.widgets.matchAll({ tag: GLANCE_TAG });
+ await Promise.all(pinned.map((widget) => renderGlanceWidget(widget)));
+ })(),
+ );
+});
+
+// Exposed for tests (tests/glance-sw.test.js evaluates this file against a
+// fake `self`) and for debugging from the service worker console.
+self.__threewsGlancePayload = glancePayload;
+self.__threewsGlanceRender = renderGlanceWidget;
diff --git a/public/screenshots/glance-widget.png b/public/screenshots/glance-widget.png
new file mode 100644
index 000000000..b1d29e747
Binary files /dev/null and b/public/screenshots/glance-widget.png differ