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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add support for Brilliant Labs Frame and Even Realities G1 smart glasses
originols35b2f0482fb7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5d543ea9..d6c0d23eb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Grind-Bounty Market** (`/vanity/bounties`) — A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.- **Guided Tour** (`/tour`) — A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.- **Proof-of-Grind Gallery** (`/vanity/gallery`) — A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.+- **/irl now pairs with smart glasses** — You can connect companion smart glasses to the /irl augmented-reality view and see the nearest agent right on your lens — its name, the direction to turn, how far away it is, and a flash when one walks into range. Your phone keeps doing all the GPS, compass and discovery work; the glasses just show the cue, so you can keep your head up instead of staring at a screen. Brilliant Labs Frame is fully supported (official SDK); Even Realities G1 works too via its two-arm pairing (experimental, community protocol). Pairing uses an encrypted Web Bluetooth link in Chromium browsers — your location is never sent to the glasses, only the direction and distance you already see on screen. (`/irl`) `[feature]`- **Choose where you walk — six environments for the Walk page** — Your avatar no longer strolls in one fixed studio. A new environment picker lets you drop into six distinct worlds: a sunlit Park with shade trees and benches, a neon Cyberpunk street, a bright Beach with palm trees and a turquoise sea, a white-walled Gallery with pedestals and hung art, an abstract Void grid for pure focus, and the three.ws Office with desks and plants. Open the picker from the environment button in the Walk HUD to see a preview of each scene, or press V to cycle through them. Switching fades smoothly to the new sky and back — the ground, lighting, reflections, and props all change to match, and the avatar walks and collides correctly in every world. Link straight to a scene with ?env=beach (or park, cyberpunk, gallery, void, office), and your last choice is remembered next time you visit. Every scene is a real 3D model with its own HDR lighting, authored and owned by three.ws. (`/features/walk`) `[feature]`- **Express yourself in Walk — wave, dance, sit, point, cheer and more** — Your avatar can now emote while you stroll. Hold G on desktop — or long-press the action button on mobile — to pop a radial gesture wheel, aim, and release to play one of eight gestures: wave, dance, sit, point, cheer, agree, disagree, and a talking idle. Keys 1–8 fire them instantly, and a quick-access tray sits in the corner. Upper-body gestures like wave and cheer blend over your walk so you keep moving while you gesture; sit and dance take over the whole body, and a single step rises you back up. Everything crossfades — no stiff T-pose flashes between moves — and gestures replicate to other players in the same world. Chat messages now animate the avatar as it 'talks', and developers can trigger any gesture programmatically with window.walk.playGesture('wave'). (`/features/walk`) `[feature]`- **Grind-bounty market: post a reward, a fleet grinds your hard vanity address** — A 5-to-8-character vanity address is hours-to-years on one machine, so until now "hard" vanity meant running your browser overnight and hoping. The new grind-bounty market makes it a liquid, pay-for-results service. Post the pattern you want, escrow a USDC bounty, and a fleet of independent workers grinds it in parallel — the first one to find a verified match is paid automatically. The breakthrough is that the found key is sealed to your encryption key before the worker ever submits it, so the worker earns the bounty yet never sees your wallet, and three.ws never holds your secret either. Settlement is trustless via x402: no valid match, no payout; only one worker can win; and a bounty that goes unfilled refunds your escrow when it expires. You also get an honest difficulty meter and a fair-price oracle when posting (priced off the real grind odds, not made-up numbers), a live board with biggest-reward and expiring-soon sorts, and a one-click way to open your won wallet locally with your private key. Want to earn instead? Flip on "Grind & earn," point your spare cores at the open bounties, and get paid in USDC for every fill — there's a leaderboard of the top grinders. (`/vanity/bounties`) `[feature, security, sdk]`diff --git a/api/_lib/balances.js b/api/_lib/balances.jsindex c08dacd01..a08d38148 100644--- a/api/_lib/balances.js+++ b/api/_lib/balances.js@@ -225,21 +225,21 @@ async function getSolanaBalancesViaDas(address) {.catch(() => {});// Direct write (cheaper than going through getMetadataForMints):try {- const { sql } = await import('./db.js');+ const { sql, sqlValues } = await import('./db.js');+ const now = new Date();+ const rows = metaPayload.map((m) => [+ m.mint,+ 'solana',+ m.symbol,+ m.name,+ m.logo,+ m.decimals,+ 'helius-das',+ now,+ ]);await sql`INSERT INTO token_metadata (mint, chain, symbol, name, logo, decimals, source, refreshed_at)- SELECT * FROM ${sql(- metaPayload.map((m) => [- m.mint,- 'solana',- m.symbol,- m.name,- m.logo,- m.decimals,- 'helius-das',- new Date(),- ]),- )}+ VALUES ${sqlValues(rows)}ON CONFLICT (mint) DO UPDATE SETsymbol = EXCLUDED.symbol,name = EXCLUDED.name,diff --git a/api/_lib/db.js b/api/_lib/db.jsindex 9365e1818..c6e6858ab 100644--- a/api/_lib/db.js+++ b/api/_lib/db.js@@ -101,6 +101,40 @@ function makeFragment(strings, values) {};}+// Build a composable multi-row `VALUES` fragment for bulk INSERTs:+// sql`INSERT INTO t (a, b) VALUES ${sqlValues(rows)} ON CONFLICT …`+// where `rows` is an array of equal-length value arrays. Every value becomes a+// `$N` placeholder, renumbered against the parent query by composeFragment, so+// dates/strings/jsonb are bound as parameters — never stringified into the SQL+// text. This replaces the postgres.js-style `SELECT * FROM ${sql(rows)}` idiom,+// which the Neon wrapper does NOT support: it would stringify each row array+// inline (a Date's ISO `:` then triggering `syntax error at or near ":"`).+export function sqlValues(rows) {+ if (!Array.isArray(rows) || rows.length === 0) {+ throw new Error('sqlValues requires a non-empty array of row arrays');+ }+ const width = rows[0].length;+ if (width === 0) throw new Error('sqlValues rows must have at least one column');+ const strings = [];+ const values = [];+ let pending = '';+ for (let r = 0; r < rows.length; r++) {+ const row = rows[r];+ if (!Array.isArray(row) || row.length !== width) {+ throw new Error('sqlValues: every row must be an array of the same width');+ }+ pending += r === 0 ? '(' : '), (';+ for (let c = 0; c < width; c++) {+ strings.push(pending);+ pending = c < width - 1 ? ', ' : '';+ values.push(row[c]);+ }+ }+ pending += ')';+ strings.push(pending);+ return makeFragment(strings, values);+}+export const sql = new Proxy(function () {}, {apply(_t, _this, args) {// Neon dispatches on the first argument: a string is the ordinarydiff --git a/api/_lib/token-metadata.js b/api/_lib/token-metadata.jsindex 2af0d694c..4c106503e 100644--- a/api/_lib/token-metadata.js+++ b/api/_lib/token-metadata.js@@ -13,7 +13,7 @@// - no Helius key → returns only cached + bare {mint, symbol: mint.slice(0,6)}// - DB unreachable → in-memory map for the request lifetime-import { sql } from './db.js';+import { sql, sqlValues } from './db.js';const REFRESH_AFTER_MS = 1000 * 60 * 60 * 24 * 30; // 30 days@@ -57,11 +57,13 @@ async function fetchFromCache(mints) {async function persist(entries) {if (entries.length === 0) return;try {+ const now = new Date();+ const rows = entries.map((e) => [+ e.mint, 'solana', e.symbol, e.name, e.logo, e.decimals, 'helius-das', now,+ ]);await sql`INSERT INTO token_metadata (mint, chain, symbol, name, logo, decimals, source, refreshed_at)- SELECT * FROM ${sql(- entries.map((e) => [e.mint, 'solana', e.symbol, e.name, e.logo, e.decimals, 'helius-das', new Date()]),- )}+ VALUES ${sqlValues(rows)}ON CONFLICT (mint) DO UPDATE SETsymbol = EXCLUDED.symbol,name = EXCLUDED.name,diff --git a/api/irl/interactions.js b/api/irl/interactions.jsindex 24c42f445..fe3e22d78 100644--- a/api/irl/interactions.js+++ b/api/irl/interactions.js@@ -49,6 +49,13 @@ import { isUuid } from '../_lib/validate.js';// view | tap — passive/active sighting of the agent. message — a note left for// the owner. pay — an x402 settlement against the agent (see PAY note below).const TYPES = new Set(['view', 'tap', 'message', 'pay']);+// The surface the encounter happened on, so an owner can tell an IRL phone tap from a+// smart-glasses (Frame / G1) encounter. Whitelisted — an unknown value collapses to+// 'phone' rather than storing arbitrary caller text.+const DEVICE_TYPES = new Set(['phone', 'glasses']);+function normDeviceType(v) {+ return typeof v === 'string' && DEVICE_TYPES.has(v) ? v : 'phone';+}const VIEW_DEDUPE_MS = 5 * 60 * 1000; // collapse repeat views from one deviceconst MAX_MESSAGE_LEN = 280;@@ -169,6 +176,9 @@ async function runMigrations() {await sql`ALTER TABLE irl_interactions ADD COLUMN IF NOT EXISTS amount NUMERIC`;await sql`ALTER TABLE irl_interactions ADD COLUMN IF NOT EXISTS currency_mint TEXT`;await sql`ALTER TABLE irl_interactions ADD COLUMN IF NOT EXISTS payload JSONB DEFAULT '{}'::jsonb`;+ // The encounter surface (phone | glasses). Defaults to 'phone' so legacy rows and+ // any caller that omits it read as the common case.+ await sql`ALTER TABLE irl_interactions ADD COLUMN IF NOT EXISTS device_type TEXT DEFAULT 'phone'`;// One settlement → one pay row. Indexed for the de-dupe lookup on insert.await sql`CREATE INDEX IF NOT EXISTS irl_interactions_paysig ON irl_interactions ((payload->>'signature')) WHERE type = 'pay'`;}@@ -196,6 +206,7 @@ export default wrap(async (req, res) => {const session = await getSessionUser(req).catch(() => null);const viewerUserId = session?.id ?? null;const viewerDevice = readDeviceToken(req);+ const deviceType = normDeviceType(body.device_type);// Confirm the pin exists (and is live) and snapshot its location + agent.const [pin] = await sql`@@ -287,7 +298,7 @@ export default wrap(async (req, res) => {const [row] = await sql`INSERT INTO irl_interactions(pin_id, agent_id, type, message, viewer_user_id, viewer_device, lat, lng,- amount, currency_mint, payload, seen_at)+ amount, currency_mint, payload, seen_at, device_type)VALUES (${pinId},${pin.agent_id ?? null},@@ -300,7 +311,8 @@ export default wrap(async (req, res) => {${amount},${currencyMint},${payloadJson}::jsonb,- ${seenAt}+ ${seenAt},+ ${deviceType})RETURNING id, type, created_at`;@@ -398,7 +410,7 @@ export default wrap(async (req, res) => {SELECTix.id, ix.pin_id, ix.agent_id, ix.type, ix.message,ix.lat, ix.lng, ix.seen_at, ix.created_at,- ix.amount, ix.currency_mint, ix.payload,+ ix.amount, ix.currency_mint, ix.payload, ix.device_type,p.avatar_name, p.captionFROM irl_interactions ixJOIN irl_pins p ON p.id = ix.pin_id@@ -411,7 +423,7 @@ export default wrap(async (req, res) => {SELECTix.id, ix.pin_id, ix.agent_id, ix.type, ix.message,ix.lat, ix.lng, ix.seen_at, ix.created_at,- ix.amount, ix.currency_mint, ix.payload,+ ix.amount, ix.currency_mint, ix.payload, ix.device_type,p.avatar_name, p.captionFROM irl_interactions ixJOIN irl_pins p ON p.id = ix.pin_iddiff --git a/data/changelog.json b/data/changelog.jsonindex 69ddc8052..52c60ece7 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-20",+ "title": "/irl now pairs with smart glasses",+ "summary": "You can connect companion smart glasses to the /irl augmented-reality view and see the nearest agent right on your lens — its name, the direction to turn, how far away it is, and a flash when one walks into range. Your phone keeps doing all the GPS, compass and discovery work; the glasses just show the cue, so you can keep your head up instead of staring at a screen. Brilliant Labs Frame is fully supported (official SDK); Even Realities G1 works too via its two-arm pairing (experimental, community protocol). Pairing uses an encrypted Web Bluetooth link in Chromium browsers — your location is never sent to the glasses, only the direction and distance you already see on screen.",+ "tags": [+ "feature"+ ],+ "link": "/irl"+ },{"date": "2026-06-20","title": "Transaction history and the Brain Studio editor are stable again",diff --git a/pages/irl.html b/pages/irl.htmlindex 1033f6d4b..622ccc7c1 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -225,6 +225,9 @@.irl-cue-mute.is-muted .irl-cue-off { display: inline; }.irl-cue-mute.is-muted { color: var(--text-3); }.irl-cue-mute[aria-pressed="false"] { color: var(--green); border-color: rgba(74,222,128,0.32); }+ /* Smart-glasses pairing — icon-only, lights blue when a lens is linked. */+ .irl-glasses-btn { padding: 6px; display: inline-flex; align-items: center; justify-content: center; margin-right: 8px; }+ .irl-glasses-btn.is-connected { color: #7aa2ff; border-color: rgba(122,162,255,0.45); background: rgba(79,124,255,0.12); }/* ── Joystick ────────────────────────────────────────────── */#irl-joystick {@@ -430,7 +433,7 @@/* Touch devices: every fixed control meets the 44×44 Apple HIG tap target. */@media (hover: none) {.irl-pill-btn { min-height: 44px; }- .irl-share-btn, .irl-privacy-btn, .irl-cue-mute { min-height: 44px; min-width: 44px; }+ .irl-share-btn, .irl-privacy-btn, .irl-cue-mute, .irl-glasses-btn { min-height: 44px; min-width: 44px; }.irl-back { min-height: 44px; }}#irl-clear-btn { color: var(--danger); border-color: rgba(248,113,113,0.3); background: rgba(248,113,113,0.06); }@@ -1868,6 +1871,9 @@<button class="irl-share-btn irl-privacy-btn" id="irl-privacy-btn" type="button" aria-label="Location & privacy" title="Location & privacy"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9 12 2 2 4-4"/></svg></button>+ <button class="irl-share-btn irl-glasses-btn" id="irl-glasses-btn" type="button" aria-pressed="false" aria-label="Connect smart glasses" title="Connect smart glasses">+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="15" r="4"/><circle cx="18" cy="15" r="4"/><path d="M10 15a2 2 0 0 1 4 0"/><path d="m2.5 13 1.5-5a2 2 0 0 1 2-1.5"/><path d="m21.5 13-1.5-5a2 2 0 0 0-2-1.5"/></svg>+ </button><button class="irl-share-btn" id="irl-share-btn" type="button" aria-label="Share">Share</button></header>diff --git a/pages/tour.html b/pages/tour.htmlindex d347c37c1..6088010ae 100644--- a/pages/tour.html+++ b/pages/tour.html@@ -20,7 +20,7 @@content="A 3D avatar walks the live site, points at every feature, and narrates how to use it. Roughly half an hour, paced by you."/><meta property="og:url" content="https://three.ws/tour" />- <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Guided+Tour&d=A+3D+guide+walks+you+through+every+feature%2C+live%2C+on+the+real+site.&p=%2Ftour" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Guided+Tour&d=A+3D+guide+walks+across+the+live+site%2C+points+at+every+feature%2C+and+narrates+what+each+one+does+and+how+to+use+it+%E2%80%94+voice+plus+an+on-screen+chat+bubble%2C+paced+b&p=%2Ftour" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" /><meta name="twitter:card" content="summary_large_image" />@@ -29,7 +29,7 @@name="twitter:description"content="A 3D avatar walks the live site, points at every feature, and narrates how to use it."/>- <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Guided+Tour&d=A+3D+guide+walks+you+through+every+feature%2C+live%2C+on+the+real+site.&p=%2Ftour" />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Guided+Tour&d=A+3D+guide+walks+across+the+live+site%2C+points+at+every+feature%2C+and+narrates+what+each+one+does+and+how+to+use+it+%E2%80%94+voice+plus+an+on-screen+chat+bubble%2C+paced+b&p=%2Ftour" /><link rel="icon" href="/favicon.ico" sizes="any" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" />@@ -307,7 +307,12 @@margin: 0 0 22px;}</style>- </head>++ <meta property="og:locale" content="en_US">+ <meta property="og:image:alt" content="Guided Tour — three.ws">+ <meta name="twitter:site" content="@trythreews">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Guided Tour","description":"A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.","url":"https://three.ws/tour","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Guided+Tour&d=A+3D+guide+walks+across+the+live+site%2C+points+at+every+feature%2C+and+narrates+what+each+one+does+and+how+to+use+it+%E2%80%94+voice+plus+an+on-screen+chat+bubble%2C+paced+b&p=%2Ftour"}]}</script>+</head><body class="tour-page"><header><div id="nav-container"></div></header><script src="/nav.js"></script>diff --git a/public/changelog.json b/public/changelog.jsonindex c909b1f58..00ae70532 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-20T06:58:46.940Z",+ "generated_at": "2026-06-20T07:37:55.056Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -36,6 +36,16 @@"launch"]},+ {+ "date": "2026-06-20",+ "type": "update",+ "title": "/irl now pairs with smart glasses",+ "summary": "You can connect companion smart glasses to the /irl augmented-reality view and see the nearest agent right on your lens — its name, the direction to turn, how far away it is, and a flash when one walks into range. Your phone keeps doing all the GPS, compass and discovery work; the glasses just show the cue, so you can keep your head up instead of staring at a screen. Brilliant Labs Frame is fully supported (official SDK); Even Realities G1 works too via its two-arm pairing (experimental, community protocol). Pairing uses an encrypted Web Bluetooth link in Chromium browsers — your location is never sent to the glasses, only the direction and distance you already see on screen.",+ "link": "/irl",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-20","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 7d162eeaa..052363b01 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -30,6 +30,14 @@<category>launch</category><description>A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.</description></item>+ <item>+ <title>/irl now pairs with smart glasses</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-20:/irl now pairs with smart glasses</guid>+ <pubDate>Sat, 20 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>You can connect companion smart glasses to the /irl augmented-reality view and see the nearest agent right on your lens — its name, the direction to turn, how far away it is, and a flash when one walks into range. Your phone keeps doing all the GPS, compass and discovery work; the glasses just show the cue, so you can keep your head up instead of staring at a screen. Brilliant Labs Frame is fully supported (official SDK); Even Realities G1 works too via its two-arm pairing (experimental, community protocol). Pairing uses an encrypted Web Bluetooth link in Chromium browsers — your location is never sent to the glasses, only the direction and distance you already see on screen.</description>+ </item><item><title>Choose where you walk — six environments for the Walk page</title><link>https://three.ws/features/walk</link>diff --git a/public/features.json b/public/features.jsonindex 833c37776..010ed5231 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-20T06:58:46.924Z",+ "generated_at": "2026-06-20T07:37:55.044Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 311903272..8e22e2edc 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -56,6 +56,25 @@.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }.sm-brand:hover { text-decoration: none; }</style>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:locale" content="en_US">+ <meta property="og:title" content="Sitemap · three.ws">+ <meta property="og:description" content="Human-readable index of every page on three.ws.">+ <meta property="og:url" content="https://three.ws/sitemap">+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="Sitemap — three.ws">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Sitemap · three.ws">+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script></head><body><header class="sm-topbar">diff --git a/src/irl.js b/src/irl.jsindex 0a4f2dc5d..7b441c6c7 100644--- a/src/irl.js+++ b/src/irl.js@@ -73,6 +73,8 @@ import {import { loadInto } from './shared/async-state.js';import { openMapPlacePicker } from './irl/map-place.js';import { openPrivacyCenter, maybeShowFirstRunDisclosure, getDiscoveryPrecision } from './irl/privacy-center.js';+import { GlassesBridge } from './irl/glasses/bridge.js';+import { openGlassesConnect } from './irl/glasses/connect-ui.js';import { loadLeaflet } from './shared/leaflet-loader.js';import { initDiscovery } from './irl/discovery.js';import { walletChipEl, hasWallet } from './shared/agent-wallet-chip.js';@@ -1340,6 +1342,13 @@ function deviceHeaders(extra = {}) {return _deviceToken ? { 'x-irl-device': _deviceToken, ...extra } : { ...extra };}+// Smart-glasses bridge — mirrors the nearest-agent cue (direction · distance ·+// arrivals) to companion glasses (Brilliant Labs Frame / Even Realities G1) over Web+// Bluetooth. Idle until the user pairs from the topbar; the render loop pushes live+// state to it every frame (it self-throttles + early-outs when not connected), and a+// connected link stamps interaction telemetry as a 'glasses' encounter.+const glassesBridge = new GlassesBridge();+const gpsState = { lat: null, lng: null, ready: false, watchId: null, accuracy: null, altitude: null };// DEV-only simulated-location guard (L1). Always false in production — the mock// machinery that flips it lives entirely inside an `import.meta.env.DEV` block and@@ -3011,6 +3020,8 @@ function fireArrivalCue() {try { navigator.vibrate?.([18, 40, 18]); } catch {}playArrivalChime();showArrivalBanner();+ // Flash the arrival on paired glasses too (no-op when none connected).+ glassesBridge.announce('Agent nearby — look around');}onPinStable(() => fireArrivalCue());@@ -3086,6 +3097,44 @@ function _hideNudge() {_nudgeEl?.classList.remove('is-visible');}+// ── Smart-glasses HUD push ──────────────────────────────────────────────────+// The same nearest-agent read that drives the on-screen directional nudge, reshaped+// for the glasses bridge: which agent, how far, and the screen-relative bearing+// (0 = ahead, + = turn right). Privacy-preserving by construction — it consumes the+// world offset the scene already renders, never a coordinate, exactly like the nudge.+function glassesNearbyState() {+ let candidates = null;+ let count = 0;+ for (const pin of nearbyPins) {+ if (!pin.group) continue;+ count++;+ (candidates ??= []).push({ pin, distance: bandDistance(pin) });+ }+ const target = candidates && nearestAgent(candidates);+ if (!target) return { nearest: null, count };+ const wp = target.pin.group.position;+ return {+ nearest: {+ name: target.pin.avatar_name || 'Agent',+ distanceM: target.distance,+ relBearingRad: relativeBearing(wp.x, wp.z, cameraYaw),+ },+ count,+ };+}++// Per-frame push, gated + accumulated so we only build state at ~6 Hz; the bridge+// throttles the actual BLE write further and skips byte-identical frames.+let _glassesAccum = 0;+const GLASSES_PUSH_INTERVAL = 0.16;+function pushGlassesHud(dt) {+ if (!glassesBridge.connected) return;+ _glassesAccum += dt;+ if (_glassesAccum < GLASSES_PUSH_INTERVAL) return;+ _glassesAccum = 0;+ glassesBridge.pushState(glassesNearbyState());+}+// Briefly tint a pin's floating label so a deep-linked target (?highlight= or// ?agent=) is easy to spot among the nearby agents. No-op for a missing pin/label.function flashPinLabel(pin) {@@ -4399,6 +4448,25 @@ document.getElementById('irl-privacy-btn')?.addEventListener('click', () => {openPrivacyCenter({ getGhost: getShareGhost, setGhost: applyGhost, onManagePins: openMyPinsSheet });});+// Connect smart glasses — mirror the nearest-agent cue to a Frame / G1 lens over Web+// Bluetooth. The button reflects the live link state so a connected pair reads at a+// glance; the sheet owns the capability gate, pairing flow and disconnect.+const glassesBtn = document.getElementById('irl-glasses-btn');+function syncGlassesButton() {+ if (!glassesBtn) return;+ const on = glassesBridge.connected;+ glassesBtn.classList.toggle('is-connected', on);+ glassesBtn.setAttribute('aria-pressed', String(on));+ const label = on ? `Glasses connected — ${glassesBridge.deviceName || 'tap to manage'}` : 'Connect smart glasses';+ glassesBtn.setAttribute('aria-label', label);+ glassesBtn.title = label;+}+glassesBtn?.addEventListener('click', () => openGlassesConnect(glassesBridge));+glassesBridge.on('status', syncGlassesButton);+syncGlassesButton();+// Clean BLE teardown if the page goes away while paired.+window.addEventListener('pagehide', () => { try { glassesBridge.destroy(); } catch {} });+document.getElementById('irl-mypins-close')?.addEventListener('click', closeMyPinsSheet);document.getElementById('irl-mypins-list')?.addEventListener('click', (e) => {@@ -4618,7 +4686,7 @@ function postInteraction(body) {method: 'POST',credentials: 'include',headers: deviceHeaders({ 'Content-Type': 'application/json' }),- body: JSON.stringify({ deviceToken: _deviceToken, ...body }),+ body: JSON.stringify({ deviceToken: _deviceToken, device_type: glassesBridge.deviceType(), ...body }),});}@@ -4936,6 +5004,7 @@ function openPinSheet(pin) {pinId: pin.id,type: 'view',deviceToken: _deviceToken,+ device_type: glassesBridge.deviceType(),agentId: pin.agent_id ?? null,}),}).catch(() => {});@@ -4998,6 +5067,7 @@ document.getElementById('irl-sheet-msg')?.addEventListener('submit', async (e) =type: 'message',message: text,deviceToken: _deviceToken,+ device_type: glassesBridge.deviceType(),agentId: sheet.dataset.agentId || null,}),});@@ -5996,6 +6066,8 @@ function tick() {// Non-map directional hint (task 03): point the edge glow toward the nearest// in-range agent and fade it once it's on-screen. ~20 Hz internally, no map.updateDirectionalNudge(dt);+ // Mirror that same nearest-agent cue onto paired smart glasses (no-op until paired).+ pushGlassesHud(dt);// Radar DOM is rebuilt at ~5 Hz, not every frame (it was a per-frame churn)._radarAccum += dt;if (_radarAccum >= RADAR_INTERVAL) { _radarAccum = 0; updateRadar(); }diff --git a/src/irl/glasses/bridge.js b/src/irl/glasses/bridge.jsnew file mode 100644index 000000000..0f3822c61--- /dev/null+++ b/src/irl/glasses/bridge.js@@ -0,0 +1,172 @@+// src/irl/glasses/bridge.js — the /irl ⇄ smart-glasses controller.+//+// One long-lived object irl.js holds. It owns the active device adapter, turns the+// live proximity read into HUD frames, and rate-limits the BLE writes so a 60 fps+// render loop never floods a 3 Hz display. The adapters (frame.js, g1.js) know how to+// talk to one device; this knows WHEN to push, WHAT changed, and how to recover from a+// dropped link — mirroring IrlNet's status-event shape so the two transports read the+// same to callers.++import { buildHud, buildAnnouncement, hudSignature } from './protocol.js';+import { FrameGlasses } from './frame.js';+import { G1Glasses } from './g1.js';+import { glassesSupport } from './transport.js';+import { log } from '../../shared/log.js';++// Devices offered in the connect UI, in priority order (best-supported first).+export const GLASSES_DEVICES = [FrameGlasses, G1Glasses];++const MIN_PUSH_MS = 333; // ≈3 Hz ceiling on display writes — smooth, never flooding+const HEARTBEAT_MS = 4000; // resend an unchanged frame this often (recovers a dropped write)+const ANNOUNCE_MS = 3500; // how long a transient announcement holds the lens++export class GlassesBridge {+ constructor() {+ this.adapter = null;+ this.status = 'idle'; // idle | connecting | connected | error+ this.error = null;+ this.lastModel = null; // last frame pushed — backs the connect-UI live preview+ this._handlers = { status: new Set() };+ this._lastSig = '';+ this._lastPushAt = 0;+ this._announceUntil = 0;+ this._sending = false; // single-flight: never overlap BLE writes+ this._pending = null; // frame to render once the in-flight write finishes+ this._destroyed = false;+ }++ static support() {+ return glassesSupport();+ }++ on(event, fn) {+ const bucket = this._handlers[event];+ if (!bucket) throw new Error(`GlassesBridge: unknown event "${event}"`);+ bucket.add(fn);+ return () => bucket.delete(fn);+ }++ _emit(event, ...args) {+ for (const fn of this._handlers[event]) {+ try { fn(...args); } catch (e) { log.error(`[glasses] ${event} handler threw:`, e); }+ }+ }++ _setStatus(status, error = null) {+ this.status = status;+ this.error = error;+ this._emit('status', { status, error, deviceName: this.deviceName });+ }++ get connected() {+ return this.status === 'connected' && !!this.adapter?.connected;+ }++ get deviceName() {+ return this.adapter?.deviceName || '';+ }++ // What irl.js stamps on interaction telemetry so an owner can tell a glasses+ // encounter from a phone one.+ deviceType() {+ return this.connected ? 'glasses' : 'phone';+ }++ // The connect UI hands a fully-paired adapter here (Frame: one step; G1: after both+ // arms). We mark connected, wire the disconnect callback, and clear the frame cache+ // so the first push always renders.+ attach(adapter) {+ this.adapter = adapter;+ this._lastSig = '';+ this._lastPushAt = 0;+ this._announceUntil = 0;+ // An UNEXPECTED drop (arm out of range, battery dead) → surface 'error' so the UI+ // offers reconnect. An intentional disconnect() detaches before this can fire.+ adapter._onClose = (reason) => {+ if (this._destroyed || this.adapter !== adapter) return;+ this._setStatus('error', reason || 'disconnected');+ };+ this._setStatus('connected');+ }++ _setConnecting() {+ this._setStatus('connecting');+ }++ /**+ * Push the live proximity read to the lens. Cheap to call every frame: it early-outs+ * when not connected, while an announcement holds the screen, under the rate limit,+ * and when the frame is byte-identical to the last (until the heartbeat re-asserts).+ * @param {{nearest:object|null, count:number}} raw+ */+ pushState(raw) {+ if (!this.connected) return;+ const now = Date.now();+ if (now < this._announceUntil) return;+ if (now - this._lastPushAt < MIN_PUSH_MS) return;++ const model = buildHud(raw || {});+ const sig = hudSignature(model);+ const unchanged = sig === this._lastSig;+ if (unchanged && now - this._lastPushAt < HEARTBEAT_MS) return;++ this.lastModel = model;+ this._lastPushAt = now;+ this._lastSig = sig;+ this._enqueue(model);+ }++ // Flash a transient line (e.g. arrival cue), then let the next pushState revert to+ // the live HUD once the hold elapses. The arrival flash is the headline feature, so+ // it must never be lost: if a write is in flight it's queued, not dropped.+ announce(text) {+ if (!this.connected) return;+ const model = buildAnnouncement(text);+ this.lastModel = model;+ this._announceUntil = Date.now() + ANNOUNCE_MS;+ this._lastSig = ''; // force the post-announcement frame to re-render+ this._enqueue(model);+ }++ // Single-flight with a one-slot queue: at most one BLE write runs at a time, and the+ // latest frame requested during a write is flushed the moment it completes — so a+ // fast arrival cue lands right after the frame it interrupted instead of vanishing.+ _enqueue(model) {+ if (this._sending) { this._pending = model; return; }+ this._render(model);+ }++ async _render(model) {+ this._sending = true;+ try {+ await this.adapter.render(model);+ } catch (e) {+ log.warn('[glasses] render failed:', e?.message || e);+ } finally {+ this._sending = false;+ const next = this._pending;+ this._pending = null;+ if (next && this.connected) this._render(next);+ }+ }++ // Intentional teardown — detach the drop handler so it doesn't fire 'error', clear+ // the lens, drop the adapter, settle to idle.+ async disconnect() {+ const adapter = this.adapter;+ this.adapter = null;+ this._pending = null;+ if (adapter) {+ adapter._onClose = null;+ try { await adapter.disconnect(); } catch { /* best effort */ }+ }+ this.lastModel = null;+ if (!this._destroyed) this._setStatus('idle');+ }++ destroy() {+ this._destroyed = true;+ this.disconnect();+ this._handlers.status.clear();+ }+}diff --git a/src/irl/glasses/connect-ui.js b/src/irl/glasses/connect-ui.jsnew file mode 100644index 000000000..58554757e--- /dev/null+++ b/src/irl/glasses/connect-ui.js@@ -0,0 +1,367 @@+// src/irl/glasses/connect-ui.js — the "Connect glasses" surface for /irl.+//+// One designed, reachable sheet that pairs companion smart glasses to the live /irl+// session over Web Bluetooth and mirrors the nearest-agent HUD to the lens. Every+// state is built: an honest capability gate (Web Bluetooth is Chromium-only — no iOS+// Safari), a device picker, a real async connecting state (no fake progress bar), the+// G1's two-arm staged pairing, a connected view with a live preview of what's on the+// lens, and an error state with retry. Visual language matches privacy-center.js+// (dark bottom-sheet, blue accent) with an `irlg-` namespace.++import { GLASSES_DEVICES, GlassesBridge } from './bridge.js';+import { FrameGlasses } from './frame.js';+import { G1Glasses } from './g1.js';++const STYLE_ID = 'irlg-styles';++function ensureStyles() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const el = document.createElement('style');+ el.id = STYLE_ID;+ el.textContent = `+.irlg-root{position:fixed;inset:0;z-index:10001;display:flex;align-items:flex-end;justify-content:center}+.irlg-back{position:absolute;inset:0;background:rgba(4,6,12,.62);backdrop-filter:blur(2px);animation:irlg-fade .2s ease}+.irlg-sheet{position:relative;width:100%;max-width:540px;max-height:90vh;overflow-y:auto;background:#0c0f17;+ border:1px solid #232838;border-bottom:none;border-radius:18px 18px 0 0;box-shadow:0 -8px 40px rgba(0,0,0,.55);+ animation:irlg-rise .26s cubic-bezier(.2,.8,.2,1)}+@media(min-width:600px){.irlg-root{align-items:center}.irlg-sheet{border-radius:18px;border-bottom:1px solid #232838}}+@keyframes irlg-rise{from{transform:translateY(14px);opacity:.4}to{transform:translateY(0);opacity:1}}+@keyframes irlg-fade{from{opacity:0}to{opacity:1}}+.irlg-head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px 6px}+.irlg-title{font:600 16px/1.2 system-ui,sans-serif;color:#eef1f7;display:flex;align-items:center;gap:9px}+.irlg-title svg{color:#7aa2ff}+.irlg-x{appearance:none;background:none;border:none;color:#8b93a7;font-size:24px;line-height:1;cursor:pointer;+ width:34px;height:34px;border-radius:8px;display:flex;align-items:center;justify-content:center;transition:background .15s,color .15s}+.irlg-x:hover,.irlg-x:focus-visible{background:#1a1f2e;color:#eef1f7;outline:none}+.irlg-sec{padding:12px 18px}+.irlg-lead{font:400 13px/1.5 system-ui,sans-serif;color:#aeb6c8;margin:0 0 6px}+.irlg-card{display:flex;align-items:center;gap:13px;width:100%;text-align:left;appearance:none;cursor:pointer;+ background:#11151f;border:1px solid #232838;border-radius:13px;padding:14px;margin-top:10px;transition:background .15s,border-color .15s,transform .1s}+.irlg-card:hover{background:#1a2032;border-color:#34406a}+.irlg-card:active{transform:scale(.99)}+.irlg-card:focus-visible{outline:2px solid #4f7cff;outline-offset:2px}+.irlg-card .ic{width:40px;height:40px;flex-shrink:0;border-radius:10px;display:flex;align-items:center;justify-content:center;+ background:#0a0d14;border:1px solid #232838;color:#7aa2ff}+.irlg-card .meta{flex:1;min-width:0}+.irlg-card .nm{font:600 14px/1.25 system-ui,sans-serif;color:#eef1f7;display:flex;align-items:center;gap:7px}+.irlg-card .sub{font:400 11.5px/1.35 system-ui,sans-serif;color:#8b93a7;margin-top:3px}+.irlg-card .ar{color:#8b93a7;font-size:19px;flex-shrink:0}+.irlg-exp{font:600 9px/1.4 system-ui,sans-serif;letter-spacing:.05em;text-transform:uppercase;color:#cda13a;+ background:#2a2410;border:1px solid #4a3f17;border-radius:5px;padding:1px 5px}+.irlg-note{margin-top:12px;font:400 11.5px/1.5 system-ui,sans-serif;color:#7b8398}+.irlg-spin{width:34px;height:34px;border-radius:50%;border:3px solid #232838;border-top-color:#4f7cff;+ animation:irlg-spin .9s linear infinite;margin:6px auto 14px}+@keyframes irlg-spin{to{transform:rotate(360deg)}}+@media(prefers-reduced-motion:reduce){.irlg-spin{animation-duration:2s}}+.irlg-status{text-align:center;padding:18px 12px}+.irlg-status .st{font:600 14px/1.3 system-ui,sans-serif;color:#eef1f7;margin-bottom:5px}+.irlg-status .sd{font:400 12.5px/1.5 system-ui,sans-serif;color:#8b93a7}+.irlg-steps{list-style:none;margin:14px 0 0;padding:0}+.irlg-step{display:flex;align-items:center;gap:11px;padding:11px 13px;border:1px solid #232838;border-radius:11px;margin-bottom:9px;background:#11151f}+.irlg-step .dot{width:22px;height:22px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;+ border:2px solid #2a3042;color:#8b93a7;font:600 11px system-ui,sans-serif}+.irlg-step.done .dot{background:#34c759;border-color:#34c759;color:#06210f}+.irlg-step.active .dot{border-color:#4f7cff;color:#7aa2ff}+.irlg-step .lb{flex:1;font:600 13px/1.25 system-ui,sans-serif;color:#eef1f7}+.irlg-step .lb small{display:block;font-weight:400;font-size:11px;color:#8b93a7;margin-top:2px}+.irlg-step button{appearance:none;background:#4f7cff;color:#fff;border:none;border-radius:9px;padding:9px 14px;+ font:600 12.5px system-ui,sans-serif;cursor:pointer;transition:background .15s;flex-shrink:0}+.irlg-step button:hover{background:#3d6af0}+.irlg-step button:disabled{opacity:.5;cursor:default}+.irlg-lens{margin:4px auto 0;max-width:340px;background:#05070c;border:1px solid #232838;border-radius:13px;+ padding:18px 16px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}+.irlg-lens.g1{background:#04130a;border-color:#0f3a1f}+.irlg-lens .ll{font-size:15px;line-height:1.7;color:#dfe6f5;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-height:1.7em}+.irlg-lens.g1 .ll{color:#67f6a3;text-shadow:0 0 8px rgba(70,240,140,.45)}+.irlg-lens .ll.l0{font-size:18px;font-weight:600}+.irlg-lens .ll.dim{color:#5a6377}+.irlg-lens.g1 .ll.dim{color:#2f7a4c}+.irlg-caption{text-align:center;font:400 11px/1.4 system-ui,sans-serif;color:#7b8398;margin-top:9px}+.irlg-connpill{display:inline-flex;align-items:center;gap:7px;font:600 12px system-ui,sans-serif;color:#34c759;+ background:#0f2417;border:1px solid #1f6b3a;border-radius:999px;padding:6px 12px}+.irlg-connpill::before{content:'';width:8px;height:8px;border-radius:50%;background:#34c759;box-shadow:0 0 7px #34c759}+.irlg-foot{padding:14px 18px 18px;display:flex;flex-direction:column;gap:9px}+.irlg-btn{width:100%;appearance:none;border-radius:11px;font:600 14px system-ui,sans-serif;padding:13px;cursor:pointer;transition:background .15s,border-color .15s}+.irlg-btn.primary{background:#4f7cff;color:#fff;border:none}+.irlg-btn.primary:hover{background:#3d6af0}+.irlg-btn.ghost{background:#11151f;border:1px solid #232838;color:#eef1f7}+.irlg-btn.ghost:hover{background:#1a2032}+.irlg-btn.danger{background:#1c1014;border:1px solid #4a2630;color:#ff9a9a}+.irlg-btn.danger:hover{background:#2a1620;border-color:#6a3340;color:#ffb3b3}+.irlg-err{background:#1c1014;border:1px solid #4a2630;border-radius:11px;padding:13px 14px;color:#ffb3b3;+ font:500 12.5px/1.5 system-ui,sans-serif}+.irlg-gate{text-align:center;padding:8px 6px 4px}+.irlg-gate .gic{font-size:30px;display:block;margin-bottom:10px}+.irlg-gate .gt{font:600 15px/1.3 system-ui,sans-serif;color:#eef1f7;margin-bottom:7px}+.irlg-gate .gb{font:400 13px/1.55 system-ui,sans-serif;color:#aeb6c8;max-width:380px;margin:0 auto}+.irlg-gate .gb b{color:#dfe6f5}+`;+ document.head.appendChild(el);+}++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++const GLASSES_SVG = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="15" r="4"/><circle cx="18" cy="15" r="4"/><path d="M10 15a2 2 0 0 1 4 0"/><path d="m2.5 13 1.5-5a2 2 0 0 1 2-1.5"/><path d="m21.5 13-1.5-5a2 2 0 0 0-2-1.5"/></svg>';++function deviceIcon(Dev) {+ return Dev.id === 'g1'+ ? '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="14" r="3.4"/><circle cx="18" cy="14" r="3.4"/><path d="M9.4 14a2.6 2.6 0 0 1 5.2 0"/></svg>'+ : '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="7" width="18" height="10" rx="3"/><path d="M7 11h2M15 11h2"/></svg>';+}++// Generic modal shell (backdrop + Esc + focus return), matching privacy-center.+// `onClose` runs on EVERY dismissal path (backdrop, Esc, or a [data-close] button) so+// callers can tear down timers/subscriptions without re-wiring each path.+function modal(buildInner, onClose) {+ ensureStyles();+ const root = document.createElement('div');+ root.className = 'irlg-root';+ root.setAttribute('role', 'dialog');+ root.setAttribute('aria-modal', 'true');+ root.setAttribute('aria-label', 'Connect smart glasses');+ const back = document.createElement('div');+ back.className = 'irlg-back';+ const sheet = document.createElement('div');+ sheet.className = 'irlg-sheet';+ root.append(back, sheet);+ document.body.appendChild(root);+ const prevOverflow = document.body.style.overflow;+ document.body.style.overflow = 'hidden';+ const prevFocus = document.activeElement;++ let closed = false;+ const close = () => {+ if (closed) return;+ closed = true;+ document.removeEventListener('keydown', onKey, true);+ root.remove();+ document.body.style.overflow = prevOverflow;+ try { onClose?.(); } catch { /* teardown best-effort */ }+ try { prevFocus?.focus?.(); } catch { /* element gone */ }+ };+ const onKey = (ev) => { if (ev.key === 'Escape') { ev.stopPropagation(); close(); } };+ document.addEventListener('keydown', onKey, true);+ back.addEventListener('click', close);+ buildInner(sheet, close);+ return close;+}++function head(title) {+ return `<div class="irlg-head"><div class="irlg-title">${GLASSES_SVG}<span>${esc(title)}</span></div>+ <button class="irlg-x" type="button" data-close aria-label="Close">×</button></div>`;+}++/**+ * Open the Connect-glasses sheet.+ * @param {GlassesBridge} bridge the live bridge instance from irl.js+ */+export function openGlassesConnect(bridge) {+ let previewTimer = null;+ let unsub = null;+ let g1 = null; // staged G1 adapter across the two-arm flow+ const stopPreview = () => { if (previewTimer) { clearInterval(previewTimer); previewTimer = null; } };+ // Runs on every dismissal (backdrop / Esc / Close button) via modal()'s onClose.+ const teardown = () => { stopPreview(); if (unsub) { unsub(); unsub = null; } };++ modal((sheet, close) => {+ const wireClose = () => sheet.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', close));++ const isCancel = (e) => e && (e.name === 'NotFoundError' || e.name === 'AbortError');++ // React to a link drop while the sheet is open (arm out of range, battery dead).+ unsub = bridge.on('status', ({ status }) => {+ if (status === 'error' && !sheet.querySelector('[data-err]')) {+ renderError(bridge.error || 'The glasses disconnected.', () => renderPicker());+ }+ });++ // ── Capability gate ──────────────────────────────────────────────────────+ function renderGate(reason) {+ stopPreview();+ const copy = reason === 'ios'+ ? { ic: '📵', t: 'Glasses pairing isn’t available on iOS', b: 'Apple’s browser engine has no Web Bluetooth, so iPhone and iPad can’t pair glasses directly. Open <b>three.ws/irl in Chrome on an Android phone</b> to connect Frame or G1 — the AR view still works here.' }+ : reason === 'insecure'+ ? { ic: '🔒', t: 'A secure connection is required', b: 'Web Bluetooth only runs over <b>HTTPS</b>. Open the live <b>three.ws/irl</b> (not a plain-http preview) and try again.' }+ : { ic: '🖥️', t: 'This browser can’t pair glasses', b: 'Pairing uses <b>Web Bluetooth</b>, available in Chrome, Edge and other Chromium browsers. The AR view works everywhere — glasses just need a Chromium browser.' };+ sheet.innerHTML = `${head('Connect glasses')}+ <div class="irlg-sec"><div class="irlg-gate">+ <span class="gic">${copy.ic}</span>+ <div class="gt">${esc(copy.t)}</div>+ <div class="gb">${copy.b}</div>+ </div></div>+ <div class="irlg-foot"><button class="irlg-btn ghost" type="button" data-close>Close</button></div>`;+ wireClose();+ }++ // ── Device picker ────────────────────────────────────────────────────────+ function renderPicker() {+ stopPreview();+ const cards = GLASSES_DEVICES.map((Dev) => `+ <button class="irlg-card" type="button" data-dev="${Dev.id}">+ <span class="ic">${deviceIcon(Dev)}</span>+ <span class="meta">+ <span class="nm">${esc(Dev.label)}${Dev.experimental ? '<span class="irlg-exp">Experimental</span>' : ''}</span>+ <span class="sub">${esc(Dev.tagline || '')}</span>+ </span>+ <span class="ar" aria-hidden="true">→</span>+ </button>`).join('');+ sheet.innerHTML = `${head('Connect glasses')}+ <div class="irlg-sec">+ <p class="irlg-lead">Mirror the nearest agent — direction, distance and arrivals — onto your glasses. Your phone keeps doing the GPS, compass and discovery; the lens just shows the cue.</p>+ ${cards}+ <p class="irlg-note">Pairing uses Web Bluetooth over an encrypted link. We never send your location to the glasses — only the on-screen direction and distance you already see.</p>+ </div>+ <div class="irlg-foot"><button class="irlg-btn ghost" type="button" data-close>Close</button></div>`;+ wireClose();+ sheet.querySelectorAll('[data-dev]').forEach((b) => b.addEventListener('click', () => {+ if (b.dataset.dev === 'g1') startG1();+ else connectFrame();+ }));+ }++ function renderConnecting(label, detail) {+ sheet.innerHTML = `${head('Connecting')}+ <div class="irlg-sec"><div class="irlg-status">+ <div class="irlg-spin" aria-hidden="true"></div>+ <div class="st">${esc(label)}</div>+ <div class="sd">${esc(detail)}</div>+ </div></div>`;+ // No close-to-cancel mid-chooser; the browser prompt owns that. A backdrop+ // click still closes the sheet.+ }++ function renderError(message, retry) {+ stopPreview();+ sheet.innerHTML = `${head('Couldn’t connect')}+ <div class="irlg-sec">+ <div class="irlg-err" data-err>${esc(message)}</div>+ </div>+ <div class="irlg-foot">+ <button class="irlg-btn primary" type="button" data-retry>Try again</button>+ <button class="irlg-btn ghost" type="button" data-back>Choose a different device</button>+ </div>`;+ sheet.querySelector('[data-retry]')?.addEventListener('click', () => retry());+ sheet.querySelector('[data-back]')?.addEventListener('click', () => renderPicker());+ sheet.querySelector('[data-close]')?.addEventListener('click', close);+ }++ // ── Connected — live lens preview ─────────────────────────────────────────+ function renderConnected() {+ stopPreview();+ const isG1 = bridge.adapter instanceof G1Glasses;+ sheet.innerHTML = `${head('Glasses connected')}+ <div class="irlg-sec">+ <div style="text-align:center;margin-bottom:14px"><span class="irlg-connpill">${esc(bridge.deviceName || 'Connected')}</span></div>+ <div class="irlg-lens ${isG1 ? 'g1' : ''}" data-lens aria-live="off">+ <div class="ll l0" data-l0></div>+ <div class="ll" data-l1></div>+ <div class="ll" data-l2></div>+ </div>+ <p class="irlg-caption">Live preview of what’s on your lens — updates as you move.</p>+ </div>+ <div class="irlg-foot"><button class="irlg-btn danger" type="button" data-disc>Disconnect glasses</button></div>`;+ wireClose();+ sheet.querySelector('[data-disc]')?.addEventListener('click', async () => {+ const btn = sheet.querySelector('[data-disc]');+ if (btn) { btn.disabled = true; btn.textContent = 'Disconnecting…'; }+ await bridge.disconnect();+ renderPicker();+ });+ const paint = () => {+ const m = bridge.lastModel;+ const lines = (m?.lines || [' ', ' ', ' ']).map((l) => (l === ' ' ? '' : l));+ const set = (sel, txt) => {+ const elx = sheet.querySelector(sel);+ if (!elx) return;+ elx.textContent = txt || '—';+ elx.classList.toggle('dim', !txt);+ };+ set('[data-l0]', lines[0]);+ set('[data-l1]', lines[1]);+ set('[data-l2]', lines[2]);+ };+ paint();+ previewTimer = setInterval(paint, 400);+ }++ // ── Frame: single-step connect ────────────────────────────────────────────+ async function connectFrame() {+ const adapter = new FrameGlasses();+ bridge._setConnecting();+ renderConnecting(FrameGlasses.label, 'Pick your Frame in the browser prompt…');+ try {+ await adapter.request();+ renderConnecting(FrameGlasses.label, 'Linking up…');+ await adapter.connect();+ bridge.attach(adapter);+ renderConnected();+ } catch (e) {+ if (isCancel(e)) { renderPicker(); return; }+ bridge._setStatus('error', e?.message || 'connect failed');+ renderError(friendly(e), connectFrame);+ }+ }++ // ── G1: two-arm staged connect ────────────────────────────────────────────+ function startG1() {+ g1 = new G1Glasses();+ renderG1Staged();+ }++ function renderG1Staged() {+ stopPreview();+ const leftDone = !!g1?.ports.left?.connected;+ const rightDone = !!g1?.ports.right?.connected;+ const stepHTML = (n, side, label, done, active) => `+ <li class="irlg-step ${done ? 'done' : ''} ${active ? 'active' : ''}">+ <span class="dot">${done ? '✓' : n}</span>+ <span class="lb">${esc(label)}<small>${done ? 'Paired' : active ? 'Select this arm in the prompt' : 'Pair the previous arm first'}</small></span>+ ${done ? '' : `<button type="button" data-arm="${side}" ${active ? '' : 'disabled'}>Pair</button>`}+ </li>`;+ sheet.innerHTML = `${head('Pair Even Realities G1')}+ <div class="irlg-sec">+ <p class="irlg-lead">The G1’s two arms pair as separate Bluetooth devices — connect the left, then the right.</p>+ <ul class="irlg-steps">+ ${stepHTML(1, 'left', 'Left arm', leftDone, !leftDone)}+ ${stepHTML(2, 'right', 'Right arm', rightDone, leftDone && !rightDone)}+ </ul>+ <p class="irlg-note">Experimental: the G1 has no official SDK, so this uses the community-documented protocol. Direction and distance render as green text.</p>+ </div>+ <div class="irlg-foot"><button class="irlg-btn ghost" type="button" data-back>Back</button></div>`;+ sheet.querySelector('[data-back]')?.addEventListener('click', () => renderPicker());+ sheet.querySelectorAll('[data-arm]').forEach((b) => b.addEventListener('click', () => connectG1Arm(b.dataset.arm)));+ }++ async function connectG1Arm(side) {+ renderConnecting(G1Glasses.label, side === 'left' ? 'Select the LEFT arm in the prompt…' : 'Select the RIGHT arm in the prompt…');+ try {+ await g1.requestArm(side, { onClose: (reason) => bridge._setStatus('error', reason || 'disconnected') });+ if (g1.connected) {+ bridge.attach(g1);+ renderConnected();+ } else {+ renderG1Staged();+ }+ } catch (e) {+ if (isCancel(e)) { renderG1Staged(); return; }+ renderError(friendly(e), () => renderG1Staged());+ }+ }++ function friendly(e) {+ const msg = e?.message || String(e || '');+ if (e?.name === 'SecurityError') return 'The browser blocked the Bluetooth request. Make sure the page is served over HTTPS and try again.';+ if (e?.name === 'NetworkError') return 'Lost the connection to the glasses. Bring them closer and try again.';+ if (/User cancelled|chooser/i.test(msg)) return 'Pairing was cancelled. Tap a device to try again.';+ return msg || 'Something went wrong while connecting. Try again.';+ }++ // Initial view: already connected → preview; otherwise gate or picker.+ const support = GlassesBridge.support();+ if (bridge.connected) renderConnected();+ else if (!support.supported) renderGate(support.reason);+ else renderPicker();+ }, teardown);+}diff --git a/src/irl/glasses/frame.js b/src/irl/glasses/frame.jsnew file mode 100644index 000000000..f51945f3c--- /dev/null+++ b/src/irl/glasses/frame.js@@ -0,0 +1,86 @@+// src/irl/glasses/frame.js — Brilliant Labs Frame adapter.+//+// Frame is the cleanest companion target: first-party, fully documented, a single BLE+// peripheral, and a 640×400 colour micro-OLED. It runs an on-device Lua interpreter+// reachable over a Nordic-UART-style custom GATT service — we write UTF-8 Lua to TX and+// the device evaluates it, so rendering the HUD is just streaming a handful of+// frame.display.text(...) calls and a frame.display.show() flip.+//+// GATT (docs.brilliant.xyz/frame/frame-sdk-bluetooth-specs):+// service 7A230001-5475-A6A4-654C-8431F6AD49C4+// TX (write, host→Frame) 7A230002-…+// RX (notify, Frame→host) 7A230003-…+// A plain UTF-8 write is evaluated as a Lua chunk; a write prefixed with 0x01 is raw+// data, 0x03 is a break (interrupt the running script), 0x04 a reset. We send a break+// before our first frame so any default app loop on the device stops fighting us for+// the display.++import { GattPort } from './transport.js';+import { frameLuaStatements } from './protocol.js';++const SERVICE = '7a230001-5475-a6a4-654c-8431f6ad49c4';+const TX = '7a230002-5475-a6a4-654c-8431f6ad49c4';+const RX = '7a230003-5475-a6a4-654c-8431f6ad49c4';++const SIGNAL_BREAK = 0x03; // interrupt the currently-running Lua loop on the device++export class FrameGlasses {+ static id = 'frame';+ static label = 'Brilliant Labs Frame';+ static experimental = false;+ static tagline = 'Colour micro-OLED · official SDK · single pairing';++ constructor() {+ this.port = new GattPort({+ serviceUuid: SERVICE,+ txUuid: TX,+ rxUuid: RX,+ filters: [{ services: [SERVICE] }, { namePrefix: 'Frame' }],+ optionalServices: [SERVICE],+ });+ this._onClose = null;+ }++ // Step 1 — open the chooser (inside the connect button's click handler).+ async request() {+ return this.port.request();+ }++ // Step 2 — connect GATT and quiet any on-device app loop so we own the display.+ async connect({ onClose } = {}) {+ this._onClose = onClose || null;+ await this.port.connect({ onClose: (r) => this._onClose?.(r) });+ // Break any running default loop, then clear to a known blank frame.+ try { await this.port.write(new Uint8Array([SIGNAL_BREAK])); } catch { /* non-fatal */ }+ await this.clear();+ return this;+ }++ // Render a HUD model: one BLE write per Lua statement, ending with show(). Each+ // statement is a standalone chunk Frame evaluates independently — text() calls+ // accumulate in the back buffer and show() presents them atomically.+ async render(model) {+ const stmts = frameLuaStatements(model);+ for (const stmt of stmts) {+ await this.port.writeString(stmt);+ }+ }++ async clear() {+ await this.port.writeString('frame.display.text(" ",1,1)');+ await this.port.writeString('frame.display.show()');+ }++ async disconnect() {+ try { await this.clear(); } catch { /* device may already be gone */ }+ await this.port.disconnect();+ }++ get connected() {+ return !!this.port.connected;+ }++ get deviceName() {+ return this.port.name || FrameGlasses.label;+ }+}diff --git a/src/irl/glasses/g1.js b/src/irl/glasses/g1.jsnew file mode 100644index 000000000..494e71ddc--- /dev/null+++ b/src/irl/glasses/g1.js@@ -0,0 +1,104 @@+// src/irl/glasses/g1.js — Even Realities G1 adapter (community protocol).+//+// The G1 has no official SDK; this implements the open-source even_glasses protocol+// (github.com/emingenc/even_glasses) — well-characterised but reverse-engineered, so+// the connect UI flags it as experimental. Two quirks shape this adapter:+//+// 1. TWO peripherals. The left and right arms are independent BLE devices, each+// exposing a Nordic UART Service. Web Bluetooth returns one device per user+// gesture, so pairing is a two-step flow the connect UI drives: requestArm('left')+// on one click, requestArm('right') on the next. Display writes go to BOTH arms,+// left first, so the two halves of the binocular HUD stay in sync.+// 2. Text via the 0x4E command (see protocol.g1TextPackets). The 640×200 green+// display word-wraps the text block itself, so we send the joined HUD lines.+//+// NUS: service 6E400001-B5A3-F393-E0A9-E50E24DCCA9E, TX …0002 (write), RX …0003 (notify).++import { GattPort } from './transport.js';+import { g1Text, g1TextPackets } from './protocol.js';++const NUS = '6e400001-b5a3-f393-e0a9-e50e24dcca9e';+const NUS_TX = '6e400002-b5a3-f393-e0a9-e50e24dcca9e';+const NUS_RX = '6e400003-b5a3-f393-e0a9-e50e24dcca9e';++const ARM_GAP_MS = 60; // small left→right stagger so both arms commit the same frame++function delay(ms) {+ return new Promise((r) => setTimeout(r, ms));+}++function makeArmPort() {+ return new GattPort({+ serviceUuid: NUS,+ txUuid: NUS_TX,+ rxUuid: NUS_RX,+ // G1 arms advertise as "Even G1_<n>_L_…" / "…_R_…". Web Bluetooth filters only+ // support namePrefix (not contains), so we surface both arms under the shared+ // prefix and the wearer picks left, then right, in the two-step flow.+ filters: [{ namePrefix: 'Even G1_' }, { namePrefix: 'Even' }],+ optionalServices: [NUS],+ });+}++export class G1Glasses {+ static id = 'g1';+ static label = 'Even Realities G1';+ static experimental = true;+ static tagline = 'Green HUD · two-arm pairing · community protocol';+ // The connect UI reads this to render the staged pairing flow.+ static arms = [+ { side: 'left', label: 'Pair left arm' },+ { side: 'right', label: 'Pair right arm' },+ ];++ constructor() {+ this.ports = { left: null, right: null };+ this._seq = 0;+ this._onClose = null;+ }++ // Open the chooser for one arm (inside a click handler) and connect it immediately,+ // so a half-finished pairing still surfaces a working arm and the UI can advance.+ async requestArm(side, { onClose } = {}) {+ if (side !== 'left' && side !== 'right') throw new Error('arm side must be left or right');+ this._onClose = onClose || this._onClose;+ const port = makeArmPort();+ await port.request();+ await port.connect({ onClose: (r) => this._onClose?.(r, side) });+ this.ports[side] = port;+ return { side, name: port.name };+ }++ get connected() {+ return !!(this.ports.left?.connected && this.ports.right?.connected);+ }++ async render(model) {+ const packets = g1TextPackets(g1Text(model), { seq: this._seq });+ this._seq = (this._seq + 1) & 0xff;+ // Left first, then right — the binocular pair reads as one frame.+ for (const side of ['left', 'right']) {+ const port = this.ports[side];+ if (!port?.connected) continue;+ for (const pkt of packets) {+ await port.write(pkt);+ }+ if (side === 'left') await delay(ARM_GAP_MS);+ }+ }++ async clear() {+ await this.render({ lines: [' ', ' ', ' '] });+ }++ async disconnect() {+ for (const side of ['left', 'right']) {+ try { await this.ports[side]?.disconnect(); } catch { /* best effort */ }+ this.ports[side] = null;+ }+ }++ get deviceName() {+ return G1Glasses.label;+ }+}diff --git a/src/irl/glasses/protocol.js b/src/irl/glasses/protocol.jsnew file mode 100644index 000000000..13000a194--- /dev/null+++ b/src/irl/glasses/protocol.js@@ -0,0 +1,289 @@+// src/irl/glasses/protocol.js — pure HUD protocol for the /irl smart-glasses bridge.+//+// Why this exists+// ───────────────+// Companion smart glasses (Brilliant Labs Frame, Even Realities G1) have no browser+// and no WebXR. They are thin Bluetooth displays: the phone running /irl does all the+// GPS, compass, discovery and presence work, then streams a COMPACT heads-up frame to+// the lens over Web Bluetooth. We never render a 3D avatar on the glasses — we render+// the same "nearest agent · which way · how far" signal /irl already computes for the+// on-screen directional nudge (src/irl/proximity-cue.js), reshaped for a tiny mono or+// micro-OLED display.+//+// This module is the pure core of that: it turns a few numbers (nearest agent name,+// distance in metres, screen-relative bearing in radians, nearby count) into a+// device-agnostic HUD model, and then serialises that model to each device's wire+// format. No DOM, no Bluetooth, no clock — so the formatting, the direction glyph and+// the byte-level packet framing are all proven in a unit test, exactly like+// room-anchor.js / proximity-cue.js. The transport + adapter layers above only move+// the bytes this module produces.+//+// Coordinate convention (shared with proximity-cue.js): relBearing is the agent's+// bearing RELATIVE TO WHERE THE VIEWER LOOKS, in radians — 0 = dead ahead,+// + = turn right, − = turn left, ±π = directly behind.++// ── Distance ────────────────────────────────────────────────────────────────+// Glasses real estate is tiny, so distance reads as a single short token. Under a+// metre the agent is effectively on top of you, so we say "here" rather than "0 m";+// kilometre scale (never reached by the ≤60 m discovery radius, but kept honest for+// reuse) collapses to one decimal.+export function formatDistance(metres) {+ if (!Number.isFinite(metres) || metres < 0) return '';+ if (metres < 1) return 'here';+ if (metres < 1000) return `${Math.round(metres)} m`;+ return `${(metres / 1000).toFixed(1)} km`;+}++// ── Direction ─────────────────────────────────────────────────────────────────+// Normalise any angle (radians) to (-π, π] so a bearing reads as the SHORTEST turn —+// +0.1 rad is "barely right", not "almost all the way around". Mirrors+// proximity-cue.normalizeAngle (kept local so this module stays import-free + pure).+export function normalizeAngle(rad) {+ let a = rad % (Math.PI * 2);+ if (a > Math.PI) a -= Math.PI * 2;+ if (a <= -Math.PI) a += Math.PI * 2;+ return a;+}++const PI_8 = Math.PI / 8; // 22.5°+const PI_4 = Math.PI / 4; // 45°++// Eight-way unicode arrow pointing toward the agent, indexed clockwise from "ahead".+// 0 = ↑ ahead, 2 = → hard right, 4 = ↓ behind, 6 = ← hard left. The Frame's colour+// OLED renders these directly; if a device font lacks a glyph the turn WORD on the+// second line still carries the meaning, so the arrow is enhancement, never the sole+// signal.+const ARROW_GLYPHS = ['↑', '↗', '→', '↘', '↓', '↙', '←', '↖'];++// The arrow glyph for a screen-relative bearing. Round the bearing to the nearest 45°+// octant; positive (turn-right) bearings map to the right-hand arrows.+export function arrowGlyph(relBearingRad) {+ if (!Number.isFinite(relBearingRad)) return '';+ const oct = ((Math.round(normalizeAngle(relBearingRad) / PI_4) % 8) + 8) % 8;+ return ARROW_GLYPHS[oct];+}++// Plain-language turn hint — the glyph's words, so meaning survives a missing glyph.+// Symmetric 8-bucket scheme: dead-ahead cone ±22.5°, then slight / square / hard on+// each side, collapsing to "behind" past 157.5°.+export function turnHint(relBearingRad) {+ if (!Number.isFinite(relBearingRad)) return '';+ const a = normalizeAngle(relBearingRad);+ const mag = Math.abs(a);+ if (mag <= PI_8) return 'ahead';+ if (mag >= 7 * PI_8) return 'behind';+ const side = a > 0 ? 'right' : 'left';+ if (mag <= 3 * PI_8) return `slight ${side}`;+ if (mag <= 5 * PI_8) return side;+ return `hard ${side}`;+}++// ── HUD model ───────────────────────────────────────────────────────────────+// The device-agnostic frame. `lines` is the ordered text every simple renderer draws;+// the structured fields back the browser preview + richer layouts. We always emit a+// FIXED number of line slots (LINE_SLOTS) so a renderer that can't clear stale rows+// (it just overdraws fixed positions) never leaves a ghost of the previous frame —+// empty slots are a single space, which overwrites cleanly.+export const LINE_SLOTS = 3;++// Trim an agent name to something a 640px-wide lens can show without wrapping. Keeps+// it honest (ellipsis, not a hard cut mid-word where avoidable).+export function clampName(name, max = 18) {+ const s = String(name ?? '').trim();+ if (!s) return 'Agent';+ if (s.length <= max) return s;+ return `${s.slice(0, max - 1).trimEnd()}…`;+}++function padSlots(lines) {+ const out = lines.slice(0, LINE_SLOTS);+ while (out.length < LINE_SLOTS) out.push(' ');+ return out;+}++/**+ * Build the steady-state HUD from the live proximity read.+ * @param {object} input+ * @param {null|{name:string, distanceM:number, relBearingRad:number}} input.nearest+ * the closest in-range agent, or null when none are within the bubble+ * @param {number} [input.count] how many agents are currently in range (for the tally)+ * @returns {{ hasTarget:boolean, title:string, arrow:string, turn:string,+ * distance:string, count:number, countText:string, lines:string[] }}+ */+export function buildHud({ nearest = null, count = 0 } = {}) {+ const n = Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0;++ if (!nearest) {+ return {+ hasTarget: false,+ title: 'No agents near',+ arrow: '',+ turn: '',+ distance: '',+ count: n,+ countText: '',+ lines: padSlots(['three.ws · IRL', 'No agents near', 'Keep exploring']),+ };+ }++ const name = clampName(nearest.name);+ const arrow = arrowGlyph(nearest.relBearingRad);+ const turn = turnHint(nearest.relBearingRad);+ const distance = formatDistance(nearest.distanceM);+ // More than the one you're being pointed at? Tally the rest so the wearer knows the+ // spot is busy without listing anyone (privacy: a direction + a count, never a roster).+ const countText = n > 1 ? `+${n - 1} more nearby` : '';++ const head = arrow ? `${arrow} ${name}` : name;+ const detail = [distance, turn].filter(Boolean).join(' · ');++ return {+ hasTarget: true,+ title: name,+ arrow,+ turn,+ distance,+ count: n,+ countText,+ lines: padSlots([head, detail, countText]),+ };+}++/**+ * A transient one-off frame — e.g. the arrival cue ("an agent just entered range").+ * Shown briefly by the bridge, then it reverts to the live HUD.+ * @param {string} text headline to flash on the lens+ * @returns {{ announcement:true, lines:string[] }}+ */+export function buildAnnouncement(text) {+ const t = String(text ?? '').trim() || 'Agent nearby';+ return { announcement: true, lines: padSlots(['three.ws · IRL', t, 'Look around']) };+}++// A stable signature for a model's visible content, so the bridge can skip re-sending+// an identical frame (BLE writes are precious) while still detecting any change.+export function hudSignature(model) {+ return (model?.lines || []).join('');+}++// ── Brilliant Labs Frame wire format (first-party, documented) ────────────────+// The Frame runs an on-device Lua interpreter: you write UTF-8 Lua to its TX+// characteristic and it evaluates each write as a chunk. We draw text into the+// double-buffered display with frame.display.text(str, x, y) and flip it with+// frame.display.show(). Each statement is emitted SEPARATELY (and kept well under the+// BLE MTU) so the adapter can write them one packet at a time — Frame evaluates each+// independently, the text() calls accumulate in the back buffer, and the final show()+// presents them atomically. Docs: docs.brilliant.xyz/frame/frame-sdk-lua.++// Escape a JS string for embedding in a Lua double-quoted literal.+export function luaEscape(str) {+ return String(str ?? '')+ .replace(/\\/g, '\\\\')+ .replace(/"/g, '\\"')+ .replace(/\n/g, '\\n')+ .replace(/\r/g, '\\r')+ .replace(/\t/g, ' ');+}++// Vertical baselines for the fixed line slots on the 640×400 panel. Generous spacing+// keeps the default font legible through a 20° waveguide.+const FRAME_LINE_Y = [1, 150, 270];++/**+ * Lua statements that render a model on a Frame, in write order. The caller writes+ * each string as its own BLE packet, ending with the show() flip.+ * @returns {string[]}+ */+export function frameLuaStatements(model) {+ const lines = padSlots(model?.lines || []);+ const stmts = lines.map((line, i) => {+ const y = FRAME_LINE_Y[i] ?? (1 + i * 130);+ return `frame.display.text("${luaEscape(line)}",1,${y})`;+ });+ stmts.push('frame.display.show()');+ return stmts;+}++// ── Even Realities G1 wire format (community-reverse-engineered) ───────────────+// The G1 has no official SDK; its protocol is documented by the open-source+// even_glasses project (github.com/emingenc/even_glasses). Each arm exposes a Nordic+// UART Service. Text is pushed with the 0x4E "Send Text" command, a 9-byte header+// followed by UTF-8 text, split across packets when it exceeds the MTU:+//+// [0] 0x4E command+// [1] seq 0–255, increments per send (wraps)+// [2] total_packets how many packets this text spans+// [3] packet_index 0-based index of this packet+// [4] screen_status 0x71 = Text Show (0x70) | New Content (0x01)+// [5..6] new_char_pos big-endian char offset (0 for a fresh push)+// [7] current_page 1-based+// [8] max_page total pages (1 for our single-screen HUD)+// [9..] UTF-8 text bytes+//+// The G1 renders the text block itself (it word-wraps to the 640×200 green display),+// so we join the HUD line slots with newlines rather than positioning each one.+export const G1_CMD_SEND_TEXT = 0x4e;+export const G1_SCREEN_TEXT_SHOW = 0x71; // Text Show | New Content+const G1_HEADER_LEN = 9;+// Conservative payload cap so header+text fits a single BLE write on every G1 firmware+// (negotiated MTU is typically 200+; 180 leaves margin and never needs fragmenting+// for our short HUD, but the chunker is correct for longer text too).+const G1_MAX_PACKET = 180;++function utf8Bytes(str) {+ if (typeof TextEncoder !== 'undefined') return new TextEncoder().encode(str);+ // Node/test fallback — Buffer is UTF-8 by default.+ return Uint8Array.from(Buffer.from(str, 'utf-8'));+}++/**+ * Frame a string into one or more G1 0x4E text packets.+ * @param {string} text the full text block to display+ * @param {object} [opts]+ * @param {number} [opts.seq=0] sequence byte (the adapter increments this per send)+ * @returns {Uint8Array[]} packets to write to the arm's TX characteristic, in order+ */+export function g1TextPackets(text, { seq = 0 } = {}) {+ const body = utf8Bytes(String(text ?? ''));+ const maxChunk = G1_MAX_PACKET - G1_HEADER_LEN;+ // Split on the BYTE boundary, then heal any UTF-8 sequence the cut landed inside so+ // a multibyte glyph never straddles two packets corrupted.+ const chunks = [];+ let i = 0;+ while (i < body.length) {+ let end = Math.min(i + maxChunk, body.length);+ if (end < body.length) {+ // Walk back off any UTF-8 continuation byte (10xxxxxx) so we break on a+ // character boundary.+ while (end > i && (body[end] & 0xc0) === 0x80) end--;+ if (end === i) end = Math.min(i + maxChunk, body.length); // pathological: force progress+ }+ chunks.push(body.subarray(i, end));+ i = end;+ }+ if (chunks.length === 0) chunks.push(new Uint8Array(0)); // a clear-screen blank push++ const total = chunks.length;+ return chunks.map((chunk, idx) => {+ const pkt = new Uint8Array(G1_HEADER_LEN + chunk.length);+ pkt[0] = G1_CMD_SEND_TEXT;+ pkt[1] = seq & 0xff;+ pkt[2] = total & 0xff;+ pkt[3] = idx & 0xff;+ pkt[4] = G1_SCREEN_TEXT_SHOW;+ pkt[5] = 0x00; // new_char_pos hi+ pkt[6] = 0x00; // new_char_pos lo+ pkt[7] = 0x01; // current_page+ pkt[8] = 0x01; // max_page+ pkt.set(chunk, G1_HEADER_LEN);+ return pkt;+ });+}++// The text block a G1 render sends — the fixed line slots joined by newlines, with+// trailing blank slots trimmed so the green display isn't padded with empty rows.+export function g1Text(model) {+ const lines = (model?.lines || []).map((l) => (l === ' ' ? '' : l));+ while (lines.length && lines[lines.length - 1] === '') lines.pop();+ return lines.join('\n');+}diff --git a/src/irl/glasses/transport.js b/src/irl/glasses/transport.jsnew file mode 100644index 000000000..18afbfa90--- /dev/null+++ b/src/irl/glasses/transport.js@@ -0,0 +1,187 @@+// src/irl/glasses/transport.js — Web Bluetooth GATT plumbing for the glasses bridge.+//+// The device adapters (frame.js, g1.js) speak in HUD models + bytes; this layer is the+// one place that touches navigator.bluetooth. It does three jobs:+// 1. Honest capability detection — Web Bluetooth is Chromium-only (no iOS Safari /+// WebKit), and only over HTTPS, so the connect UI can show a real "why not here"+// state instead of a dead button.+// 2. A small GattPort: requestDevice (must be inside a user gesture), connect to one+// GATT service, write to a TX characteristic (chunked under the MTU), subscribe to+// an RX notify characteristic, and surface unexpected disconnects.+// 3. Nothing else — no rendering, no protocol. Bytes in, bytes out.++// Conservative write chunk. Web Bluetooth doesn't expose the negotiated ATT MTU, and+// older stacks fall back to 20-byte writes; Chrome on Android negotiates 100s. 180 is+// safe for modern firmware (Frame + G1 both negotiate ≥185) and the adapters keep+// individual writes small anyway, so fragmentation here is rare.+const DEFAULT_CHUNK = 180;++/**+ * Is Web Bluetooth usable in this browser/context, and if not, why?+ * @returns {{ supported: boolean, reason?: 'insecure'|'ios'|'unsupported' }}+ */+export function glassesSupport() {+ if (typeof navigator === 'undefined') return { supported: false, reason: 'unsupported' };+ const ua = navigator.userAgent || '';+ // iPadOS reports a Mac UA but is touch — treat any touch-Mac as iOS for messaging.+ const isIOS = /iP(hone|ad|od)/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1);+ if (!('bluetooth' in navigator) || !navigator.bluetooth) {+ return { supported: false, reason: isIOS ? 'ios' : 'unsupported' };+ }+ // Web Bluetooth requires a secure context (HTTPS or localhost).+ if (typeof window !== 'undefined' && window.isSecureContext === false) {+ return { supported: false, reason: 'insecure' };+ }+ return { supported: true };+}++/**+ * One GATT connection to one device + service. Stateless about WHAT it carries — the+ * adapter owns the protocol; this owns the socket.+ */+export class GattPort {+ /**+ * @param {object} cfg+ * @param {string} cfg.serviceUuid primary service to connect to+ * @param {string} cfg.txUuid characteristic we WRITE to (host → device)+ * @param {string} [cfg.rxUuid] characteristic we SUBSCRIBE to (device → host)+ * @param {object[]} cfg.filters requestDevice() filters (services / namePrefix)+ * @param {string[]} [cfg.optionalServices] extra services to grant access to+ * @param {number} [cfg.chunk] write chunk size in bytes+ */+ constructor(cfg) {+ this.cfg = cfg;+ this.chunk = cfg.chunk || DEFAULT_CHUNK;+ this.device = null;+ this.server = null;+ this.tx = null;+ this.rx = null;+ this.connected = false;+ this._onClose = null;+ this._onData = null;+ this._onDisc = this._handleDisconnect.bind(this);+ this._notifyHandler = this._handleNotify.bind(this);+ }++ // Open the browser device chooser. MUST run inside a user gesture (a click). Throws+ // a DOMException with name 'NotFoundError' when the user dismisses the chooser — the+ // caller treats that as a cancel, not an error.+ async request() {+ if (!navigator.bluetooth) throw new Error('Web Bluetooth is unavailable in this browser.');+ const optionalServices = Array.from(+ new Set([this.cfg.serviceUuid, ...(this.cfg.optionalServices || [])]),+ );+ this.device = await navigator.bluetooth.requestDevice({+ filters: this.cfg.filters,+ optionalServices,+ });+ return { id: this.device.id, name: this.device.name || '' };+ }++ /**+ * Connect the GATT server, resolve the TX/RX characteristics, and start RX notifies.+ * @param {object} [opts]+ * @param {(reason:string)=>void} [opts.onClose] called on an UNEXPECTED disconnect+ * @param {(bytes:Uint8Array)=>void} [opts.onData] called with each RX notification+ */+ async connect({ onClose, onData } = {}) {+ if (!this.device) throw new Error('Call request() before connect().');+ this._onClose = onClose || null;+ this._onData = onData || null;++ this.device.addEventListener('gattserverdisconnected', this._onDisc);+ this.server = await this.device.gatt.connect();+ const service = await this.server.getPrimaryService(this.cfg.serviceUuid);+ this.tx = await service.getCharacteristic(this.cfg.txUuid);++ if (this.cfg.rxUuid) {+ try {+ this.rx = await service.getCharacteristic(this.cfg.rxUuid);+ await this.rx.startNotifications();+ this.rx.addEventListener('characteristicvaluechanged', this._notifyHandler);+ } catch {+ // RX notify is optional telemetry (battery, taps). A device that doesn't+ // expose it still drives the display fine over TX.+ this.rx = null;+ }+ }+ this.connected = true;+ return this;+ }++ // Write raw bytes, fragmented to the chunk size. Prefers write-without-response+ // (throughput) and falls back to acknowledged writes on stacks that reject it.+ async write(bytes) {+ if (!this.connected || !this.tx) throw new Error('Not connected.');+ const buf = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);+ for (let off = 0; off < buf.length || (buf.length === 0 && off === 0); off += this.chunk) {+ const slice = buf.subarray(off, off + this.chunk);+ await this._writeOne(slice);+ if (buf.length === 0) break; // a single zero-length write (e.g. clear)+ }+ }++ // Write a UTF-8 string (used by the Frame Lua transport).+ async writeString(str) {+ const enc = typeof TextEncoder !== 'undefined'+ ? new TextEncoder().encode(str)+ : Uint8Array.from(Buffer.from(str, 'utf-8'));+ return this.write(enc);+ }++ async _writeOne(slice) {+ // A fresh BufferSource per call — some implementations retain the view.+ const out = slice.slice();+ if (this.tx.writeValueWithoutResponse) {+ try {+ await this.tx.writeValueWithoutResponse(out);+ return;+ } catch {+ // fall through to acknowledged write+ }+ }+ await this.tx.writeValue(out);+ }++ _handleNotify(ev) {+ if (!this._onData) return;+ const dv = ev.target.value;+ if (!dv) return;+ this._onData(new Uint8Array(dv.buffer, dv.byteOffset, dv.byteLength));+ }++ _handleDisconnect() {+ const wasConnected = this.connected;+ this.connected = false;+ this.tx = null;+ this.rx = null;+ this.server = null;+ if (wasConnected && this._onClose) {+ try { this._onClose('disconnected'); } catch { /* swallow */ }+ }+ }++ // Intentional teardown — detaches the disconnect handler first so it doesn't fire+ // the unexpected-close path.+ async disconnect() {+ this.connected = false;+ const device = this.device;+ if (device) {+ device.removeEventListener('gattserverdisconnected', this._onDisc);+ try {+ if (this.rx) {+ this.rx.removeEventListener('characteristicvaluechanged', this._notifyHandler);+ await this.rx.stopNotifications().catch(() => {});+ }+ } catch { /* best effort */ }+ try { device.gatt?.connected && device.gatt.disconnect(); } catch { /* best effort */ }+ }+ this.tx = null;+ this.rx = null;+ this.server = null;+ }++ get name() {+ return this.device?.name || '';+ }+}diff --git a/tests/db-sql-compose.test.js b/tests/db-sql-compose.test.jsindex e1aee31d4..5bca35386 100644--- a/tests/db-sql-compose.test.js+++ b/tests/db-sql-compose.test.js@@ -11,9 +11,10 @@import { describe, it, expect, beforeAll } from 'vitest';let sql;+let sqlValues;beforeAll(async () => {process.env.DATABASE_URL = process.env.DATABASE_URL || 'postgresql://u:p@localhost/db';- ({ sql } = await import('../api/_lib/db.js'));+ ({ sql, sqlValues } = await import('../api/_lib/db.js'));});describe('sql fragment composition', () => {@@ -106,3 +107,53 @@ describe('sql fragment composition', () => {});});});++describe('sqlValues — multi-row VALUES fragment', () => {+ it('renders one row as a single parameterized tuple', () => {+ const { query, params } = sql`insert into t (a, b) values ${sqlValues([[1, 'x']])}`+ .parameterizedQuery;+ expect(query).toBe('insert into t (a, b) values ($1, $2)');+ expect(params).toEqual(['1', 'x']);+ });++ it('renders multiple rows with contiguous, renumbered placeholders', () => {+ const { query, params } = sql`insert into t (a, b) values ${sqlValues([+ [1, 'x'],+ [2, 'y'],+ [3, 'z'],+ ])}`.parameterizedQuery;+ expect(query).toBe('insert into t (a, b) values ($1, $2), ($3, $4), ($5, $6)');+ expect(params).toEqual(['1', 'x', '2', 'y', '3', 'z']);+ });++ it('renumbers against a parent query that also binds params', () => {+ const { query, params } = sql`+ insert into token_metadata (mint, source) values ${sqlValues([+ ['mintA', 'helius-das'],+ ['mintB', 'helius-das'],+ ])}+ on conflict (mint) do update set source = ${'updated'}+ `.parameterizedQuery;+ expect(query).toContain('values ($1, $2), ($3, $4)');+ expect(query).toContain('set source = $5');+ expect(params).toEqual(['mintA', 'helius-das', 'mintB', 'helius-das', 'updated']);+ });++ it('binds Date values as parameters (never inlines the colon-bearing ISO string)', () => {+ const ts = new Date('2026-06-20T06:40:10.000Z');+ const { query, params } = sql`insert into t (m, at) values ${sqlValues([['x', ts]])}`+ .parameterizedQuery;+ expect(query).toBe('insert into t (m, at) values ($1, $2)');+ // The colon-bearing timestamp is a bound param, not raw SQL — this is the+ // exact failure mode (`syntax error at or near ":"`) the helper prevents.+ expect(query).not.toContain(':');+ expect(params[0]).toBe('x');+ expect(String(params[1])).toContain('2026-06-20');+ });++ it('rejects empty input and ragged rows', () => {+ expect(() => sqlValues([])).toThrow();+ expect(() => sqlValues('nope')).toThrow();+ expect(() => sqlValues([[1, 2], [3]])).toThrow();+ });+});diff --git a/tests/irl-glasses-protocol.test.js b/tests/irl-glasses-protocol.test.jsnew file mode 100644index 000000000..dbcea90d2--- /dev/null+++ b/tests/irl-glasses-protocol.test.js@@ -0,0 +1,269 @@+// Tests for the /irl smart-glasses HUD protocol (src/irl/glasses/protocol.js).+//+// This is the pure core of the glasses bridge: it turns the live proximity read+// (nearest agent name, distance, screen-relative bearing) into a device-agnostic HUD+// model and serialises that model to each device's wire format. The transport ++// adapters above only move the bytes produced here, so pinning the formatting, the+// direction mapping and the byte-level packet framing here is what makes the whole+// bridge trustworthy without hardware in the loop.++import { describe, it, expect } from 'vitest';++import {+ formatDistance,+ normalizeAngle,+ arrowGlyph,+ turnHint,+ clampName,+ buildHud,+ buildAnnouncement,+ hudSignature,+ LINE_SLOTS,+ luaEscape,+ frameLuaStatements,+ g1TextPackets,+ g1Text,+ G1_CMD_SEND_TEXT,+ G1_SCREEN_TEXT_SHOW,+} from '../src/irl/glasses/protocol.js';++describe('formatDistance — one short token for a tiny lens', () => {+ it('rounds metres to a whole number', () => {+ expect(formatDistance(12.4)).toBe('12 m');+ expect(formatDistance(12.6)).toBe('13 m');+ });+ it('says "here" under a metre rather than "0 m"', () => {+ expect(formatDistance(0)).toBe('here');+ expect(formatDistance(0.6)).toBe('here');+ });+ it('collapses to one-decimal km past 1000 m', () => {+ expect(formatDistance(1500)).toBe('1.5 km');+ });+ it('returns empty for non-finite / negative input', () => {+ expect(formatDistance(NaN)).toBe('');+ expect(formatDistance(-5)).toBe('');+ });+});++describe('normalizeAngle — shortest-turn wrapping', () => {+ it('leaves an in-range angle untouched', () => {+ expect(normalizeAngle(0)).toBe(0);+ expect(normalizeAngle(Math.PI / 4)).toBeCloseTo(Math.PI / 4, 10);+ });+ it('wraps past +π to the negative equivalent', () => {+ expect(normalizeAngle((3 * Math.PI) / 2)).toBeCloseTo(-Math.PI / 2, 10);+ });+});++describe('arrowGlyph — eight-way pointer toward the agent', () => {+ it('points up when the agent is dead ahead', () => {+ expect(arrowGlyph(0)).toBe('↑');+ });+ it('points right for a +90° (turn-right) bearing', () => {+ expect(arrowGlyph(Math.PI / 2)).toBe('→');+ });+ it('points left for a −90° (turn-left) bearing', () => {+ expect(arrowGlyph(-Math.PI / 2)).toBe('←');+ });+ it('points down when the agent is directly behind', () => {+ expect(arrowGlyph(Math.PI)).toBe('↓');+ });+ it('uses the diagonal for a 45° bearing', () => {+ expect(arrowGlyph(Math.PI / 4)).toBe('↗');+ expect(arrowGlyph(-Math.PI / 4)).toBe('↖');+ });+ it('returns empty for a non-finite bearing', () => {+ expect(arrowGlyph(NaN)).toBe('');+ });+});++describe('turnHint — the glyph in words, so meaning survives a missing glyph', () => {+ it('reads "ahead" inside the dead-ahead cone', () => {+ expect(turnHint(0)).toBe('ahead');+ expect(turnHint(Math.PI / 10)).toBe('ahead');+ });+ it('distinguishes slight / square / hard on each side', () => {+ expect(turnHint(Math.PI / 4)).toBe('slight right');+ expect(turnHint(Math.PI / 2)).toBe('right');+ expect(turnHint((3 * Math.PI) / 4)).toBe('hard right');+ expect(turnHint(-Math.PI / 4)).toBe('slight left');+ expect(turnHint(-Math.PI / 2)).toBe('left');+ expect(turnHint(-(3 * Math.PI) / 4)).toBe('hard left');+ });+ it('reads "behind" past 157.5°', () => {+ expect(turnHint(Math.PI)).toBe('behind');+ expect(turnHint(-Math.PI)).toBe('behind');+ });+});++describe('clampName — fits a name on a 640px lens', () => {+ it('passes a short name through', () => {+ expect(clampName('Nyx')).toBe('Nyx');+ });+ it('falls back to "Agent" for an empty name', () => {+ expect(clampName('')).toBe('Agent');+ expect(clampName(null)).toBe('Agent');+ });+ it('ellipsises an over-long name', () => {+ const out = clampName('A very long agent display name', 18);+ expect(out.length).toBeLessThanOrEqual(18);+ expect(out.endsWith('…')).toBe(true);+ });+});++describe('buildHud — the device-agnostic frame', () => {+ it('renders a fixed number of line slots, padding short frames', () => {+ const m = buildHud({ nearest: null, count: 0 });+ expect(m.lines).toHaveLength(LINE_SLOTS);+ });+ it('shows the keep-exploring empty state when nothing is in range', () => {+ const m = buildHud({ nearest: null, count: 0 });+ expect(m.hasTarget).toBe(false);+ expect(m.lines.join(' ')).toMatch(/No agents near/);+ });+ it('builds the head line as arrow + name and the detail as distance · turn', () => {+ const m = buildHud({+ nearest: { name: 'Nyx', distanceM: 12, relBearingRad: -Math.PI / 2 },+ count: 1,+ });+ expect(m.hasTarget).toBe(true);+ expect(m.lines[0]).toBe('← Nyx');+ expect(m.lines[1]).toBe('12 m · left');+ expect(m.arrow).toBe('←');+ expect(m.distance).toBe('12 m');+ expect(m.turn).toBe('left');+ });+ it('tallies extra agents without listing them (privacy: a count, never a roster)', () => {+ const m = buildHud({+ nearest: { name: 'Nyx', distanceM: 5, relBearingRad: 0 },+ count: 3,+ });+ expect(m.countText).toBe('+2 more nearby');+ expect(m.lines[2]).toBe('+2 more nearby');+ });+ it('omits the tally when only the pointed-at agent is in range', () => {+ const m = buildHud({ nearest: { name: 'Nyx', distanceM: 5, relBearingRad: 0 }, count: 1 });+ expect(m.countText).toBe('');+ });+ it('clamps a long name into the head line', () => {+ const m = buildHud({+ nearest: { name: 'An extremely long agent name here', distanceM: 4, relBearingRad: 0 },+ count: 1,+ });+ expect(m.lines[0].length).toBeLessThanOrEqual(2 + 18); // arrow + space + clamped name+ });+});++describe('buildAnnouncement — a transient flash', () => {+ it('wraps the headline in the fixed slot count', () => {+ const m = buildAnnouncement('Agent nearby');+ expect(m.announcement).toBe(true);+ expect(m.lines).toHaveLength(LINE_SLOTS);+ expect(m.lines.join(' ')).toMatch(/Agent nearby/);+ });+ it('falls back to a default headline for empty text', () => {+ expect(buildAnnouncement('').lines.join(' ')).toMatch(/Agent nearby/);+ });+});++describe('hudSignature — change detection for the bridge throttle', () => {+ it('is stable for identical content and differs when a line changes', () => {+ const a = buildHud({ nearest: { name: 'Nyx', distanceM: 12, relBearingRad: 0 }, count: 1 });+ const b = buildHud({ nearest: { name: 'Nyx', distanceM: 12, relBearingRad: 0 }, count: 1 });+ const c = buildHud({ nearest: { name: 'Nyx', distanceM: 13, relBearingRad: 0 }, count: 1 });+ expect(hudSignature(a)).toBe(hudSignature(b));+ expect(hudSignature(a)).not.toBe(hudSignature(c));+ });+});++describe('luaEscape — safe Lua string literals', () => {+ it('escapes quotes and backslashes', () => {+ expect(luaEscape('a"b\\c')).toBe('a\\"b\\\\c');+ });+ it('flattens newlines so a statement stays one line', () => {+ expect(luaEscape('a\nb')).toBe('a\\nb');+ });+});++describe('frameLuaStatements — Brilliant Labs Frame draw calls', () => {+ it('emits one text() per slot then a single show() flip', () => {+ const stmts = frameLuaStatements(buildHud({+ nearest: { name: 'Nyx', distanceM: 12, relBearingRad: 0 }, count: 1,+ }));+ expect(stmts).toHaveLength(LINE_SLOTS + 1);+ expect(stmts.slice(0, LINE_SLOTS).every((s) => s.startsWith('frame.display.text('))).toBe(true);+ expect(stmts[stmts.length - 1]).toBe('frame.display.show()');+ });+ it('escapes a quote inside an agent name so the Lua stays valid', () => {+ const stmts = frameLuaStatements(buildHud({+ nearest: { name: 'A"B', distanceM: 1, relBearingRad: 0 }, count: 1,+ }));+ expect(stmts[0]).toContain('\\"');+ });+ it('keeps each statement well under the BLE MTU', () => {+ const stmts = frameLuaStatements(buildHud({+ nearest: { name: 'An extremely long agent name', distanceM: 12, relBearingRad: Math.PI }, count: 9,+ }));+ for (const s of stmts) expect(s.length).toBeLessThan(180);+ });+});++describe('g1TextPackets — Even Realities G1 0x4E framing', () => {+ it('frames short text in a single packet with the documented header', () => {+ const pkts = g1TextPackets('12 m · left', { seq: 7 });+ expect(pkts).toHaveLength(1);+ const p = pkts[0];+ expect(p[0]).toBe(G1_CMD_SEND_TEXT); // command+ expect(p[1]).toBe(7); // seq+ expect(p[2]).toBe(1); // total packets+ expect(p[3]).toBe(0); // packet index+ expect(p[4]).toBe(G1_SCREEN_TEXT_SHOW); // screen status+ expect(p[7]).toBe(1); // current page+ expect(p[8]).toBe(1); // max page+ });+ it('carries the UTF-8 text after the 9-byte header', () => {+ const pkts = g1TextPackets('ab', { seq: 0 });+ const p = pkts[0];+ expect(p.length).toBe(9 + 2);+ expect(p[9]).toBe('a'.charCodeAt(0));+ expect(p[10]).toBe('b'.charCodeAt(0));+ });+ it('masks the seq byte to 8 bits', () => {+ expect(g1TextPackets('x', { seq: 300 })[0][1]).toBe(300 & 0xff);+ });+ it('splits long text across packets, each tagged with its index and the total', () => {+ const long = 'x'.repeat(500);+ const pkts = g1TextPackets(long, { seq: 1 });+ expect(pkts.length).toBeGreaterThan(1);+ pkts.forEach((p, i) => {+ expect(p[2]).toBe(pkts.length); // total+ expect(p[3]).toBe(i); // index+ expect(p.length).toBeLessThanOrEqual(180);+ });+ // All payload bytes reassemble to the original length.+ const payloadBytes = pkts.reduce((n, p) => n + (p.length - 9), 0);+ expect(payloadBytes).toBe(500);+ });+ it('never splits a multibyte glyph across a packet boundary', () => {+ // '•' is 3 UTF-8 bytes; a wall of them stresses the boundary-healing logic.+ const pkts = g1TextPackets('•'.repeat(200), { seq: 0 });+ // Each packet's payload length must be a multiple of 3 (no straddled glyph).+ for (const p of pkts) expect((p.length - 9) % 3).toBe(0);+ });+ it('emits a single blank packet for empty text (a clear-screen push)', () => {+ const pkts = g1TextPackets('', { seq: 0 });+ expect(pkts).toHaveLength(1);+ expect(pkts[0].length).toBe(9);+ });+});++describe('g1Text — the joined block for the green display', () => {+ it('joins line slots with newlines and trims trailing blank slots', () => {+ const m = buildHud({ nearest: { name: 'Nyx', distanceM: 5, relBearingRad: 0 }, count: 1 });+ // slot 3 (count tally) is empty here, so it should be trimmed off the block.+ expect(g1Text(m)).toBe('↑ Nyx\n5 m · ahead');+ });+ it('converts padded space slots to empty and drops them', () => {+ expect(g1Text({ lines: ['hi', ' ', ' '] })).toBe('hi');+ });+});