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(home): replace the web desktop at / with the Field, a live zoomable map of every agent and surface
nirholasc74edef391ed
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 8f6950a4c..1e2acc94b 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -25,6 +25,7 @@ bottom.| Event Market scoring, leaderboard and rewards | [api/_lib/event-markets/scoring.js](api/_lib/event-markets/scoring.js), [rollup.js](api/_lib/event-markets/rollup.js), [fairness.js](api/_lib/event-markets/fairness.js), [leaderboard.js](api/_lib/event-markets/leaderboard.js), [api/cron/event-markets-rollup.js](api/cron/event-markets-rollup.js), [data/event-market-scoring.json](data/event-market-scoring.json), [pages/event-markets-leaderboard.html](pages/event-markets-leaderboard.html) `→ /event-markets/leaderboard`, [scripts/event-markets-season-payouts.mjs](scripts/event-markets-season-payouts.mjs) | Live once migration 20261012400000 is applied; payouts owner-gated | Scores, streaks, season ranks and badges from the rollup cron; wallet-derived names; fair-play ranking checks; season reward table printed for owner approval, never sent automatically. Docs: [docs/event-markets.md](docs/event-markets.md#scoring-and-seasons). Tests: [tests/event-markets-scoring.test.js](tests/event-markets-scoring.test.js) || Event Market live feed | [api/event-markets/stream.js](api/event-markets/stream.js), [api/_lib/event-markets/hub.js](api/_lib/event-markets/hub.js), [feed.js](api/_lib/event-markets/feed.js), [moves.js](api/_lib/event-markets/moves.js), [live-stats.js](api/_lib/event-markets/live-stats.js), [api/cron/event-markets-feed.js](api/cron/event-markets-feed.js), [src/event-markets/live-feed.js](src/event-markets/live-feed.js), [ticker.js](src/event-markets/ticker.js), [data/event-markets-feed.json](data/event-markets-feed.json) | Live (migration 20261012200000 applied) | SSE odds, picks, moves and lifecycle with Last-Event-ID resume, odds-move detector, home ticker, in-place odds on the market page with polling fallback, pulse and trending additions. Docs: [docs/event-markets.md](docs/event-markets.md#live-feed). Tests: [tests/event-markets-live-feed.test.js](tests/event-markets-live-feed.test.js), [tests/event-markets-live-stats.test.js](tests/event-markets-live-stats.test.js). Bench: [scripts/event-markets-fanout-bench.mjs](scripts/event-markets-fanout-bench.mjs) || App pages (hub plus Android, Seeker, iOS, Desktop, Web) | Pages [pages/apps.html](pages/apps.html) `→ /apps` and `pages/apps-{web,android,seeker,ios,desktop}.html` `→ /apps/*`, code [src/apps.js](src/apps.js), [src/apps.css](src/apps.css) | Built and verified locally | One page per platform with its real install path and status; the desktop page reads the live release feed. Docs: [docs/apps.md](docs/apps.md) |+| Homepage: the Field (a live, zoomable map of every agent and surface) | Page [pages/desktop.html](pages/desktop.html) `→ /`, code [src/field/](src/field) ([README](src/field/README.md)): pure layout and camera [logic.js](src/field/logic.js), feeds [data.js](src/field/data.js), map [field.js](src/field/field.js), entry and legacy switch [entry.js](src/field/entry.js) | Built and verified locally | Public agents drawn as stars in a golden-angle core around ten live districts; semantic zoom from one readout per district to full cards (avatars, launches, $THREE quote and CA, Pulse wallet moves, top skills, most-talked-to agents); Pulse events fly in as comets; search over places, agents and every nav page; any page opens in place at a shareable `/?go=` URL. The windowed desktop and campus stay at `/?view=desktop` and `/?world=1`. Docs: [docs/field.md](docs/field.md) || Web desktop (homepage as an OS, with a 3D campus in front of it) | Page [pages/desktop.html](pages/desktop.html) `→ /`, code [src/desktop/](src/desktop) ([README](src/desktop/README.md)): boot and lock screen [boot.js](src/desktop/boot.js) + [boot-logic.js](src/desktop/boot-logic.js), campus [src/desktop/world/](src/desktop/world), gem ledger [api/world/gems.js](api/world/gems.js) over [api/_lib/world-gems.js](api/_lib/world-gems.js) (migration `20261015000000_world_gems.sql`); previous homepage [pages/home.html](pages/home.html) `→ /classic` | Built and verified locally | Boots with a live log of real checks (GPU, site catalog, account, fonts, avatar, $THREE feed, gem ledger), locks with a greeting and live chips, then the visitor walks in as their avatar: a campus with the home office (sit at the desk to open the desktop on the monitor, pick up the phone for Pocket, put on the headset for WebXR), the three.ws Exchange with a live ticker (Trenches), the Launchpad, the Forge, the Gallery, Agent Plaza, the Marketplace and a gem mine with server-rolled, rate-limited digs. Taskbar, Start, widgets and snappable windows framing real three.ws pages in the CTRL Mica theme; icons on a snap grid, All Apps, Settings (profile, Arrival, accent, wallpaper, icon size), session in localStorage plus IndexedDB. Framed pages hide the site nav via `public/nav.js` (`tws-os:` frame name). Docs: [docs/desktop.md](docs/desktop.md). Tests: [tests/desktop-boot.test.js](tests/desktop-boot.test.js), [tests/world-places.test.js](tests/world-places.test.js), [tests/world-ticker.test.js](tests/world-ticker.test.js), [tests/desktop-layout.test.js](tests/desktop-layout.test.js), [tests/desktop-page.test.js](tests/desktop-page.test.js); browser drives [scripts/desktop-world-smoke.mjs](scripts/desktop-world-smoke.mjs), [scripts/desktop-interact.mjs](scripts/desktop-interact.mjs) || Trenches Pulse (Solana + Robinhood Chain intelligence) | Service [services/pulse/](services/pulse) (vendored nirholas/pulse: firehose, scorer, API, Telegram newsletter), proxy [api/trenches.js](api/trenches.js) `→ /api/trenches`, page [pages/trenches.html](pages/trenches.html) + [src/trenches.js](src/trenches.js) `→ /trenches` | Built and verified locally; service deploy pending owner approval | Real pump.fun firehose over Solana WebSocket: launches, graduations, hottest tokens, runners, scored wallets. Offline upstream is a designed 503 state, never fabricated data. Docs: [docs/trenches.md](docs/trenches.md). Tests: [tests/trenches-api.test.js](tests/trenches-api.test.js) || Browse by goal (every feature grouped into twelve goals, search, pins, what-next strip) | [pages/everything.html](pages/everything.html), [src/everything.js](src/everything.js), [src/everything.css](src/everything.css), taxonomy [scripts/lib/feature-jobs.mjs](scripts/lib/feature-jobs.mjs), [public/next-steps.js](public/next-steps.js) | Live | `/everything` reads `public/features.json`, which `scripts/build-page-index.mjs` builds from `data/pages.json` plus the goal taxonomy, so a new page appears with no extra step. Also drives the goal labels in the ⌘K palette and the nav entry. Docs: [docs/everything.md](docs/everything.md). Tests: [tests/feature-jobs.test.js](tests/feature-jobs.test.js), [tests/next-steps.test.js](tests/next-steps.test.js) |diff --git a/data/changelog.json b/data/changelog.jsonindex fbd4a1d67..faa56db12 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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-11",+ "title": "The homepage is now the Field: one live map of every agent, launch and wallet move",+ "link": "/",+ "summary": "The front page no longer opens a web desktop. It opens the Field, a zoomable map of the whole platform built from live data. Every public agent is a star in the core, newest at the centre, and turns into its avatar as you zoom in; around it sit ten districts (Create, Forge, Gallery, Launchpad, Trenches, Pulse, Marketplace, Chat, Agent Studio, Console). From afar each shows one live readout; zoom in and it opens into a card with real content: the newest avatars, coins agents launched, the $THREE price, market cap, holders and contract address, the latest agent wallet moves, the skills agents carry most. New wallet moves from Pulse fly across the map as comets and land in their district. Search finds any place, agent or page; opening one loads the real page in place, with its own shareable /?go= link, and Back or Esc returns you to the map. It works with mouse, touch, pinch and keyboard, in light and dark, and lays itself out for phones. The windowed desktop is still at /?view=desktop and the 3D campus at /?world=1.",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-11","title": "The web desktop gets Snap layouts, taskbar peek and three shell styles: Fluent, Aqua and Classic",diff --git a/data/pages.json b/data/pages.jsonindex cfa6a0c9f..7c3caca78 100644--- a/data/pages.json+++ b/data/pages.json@@ -4236,6 +4236,14 @@"changefreq": "monthly","added": "2026-10-11"},+ {+ "path": "/docs/field",+ "title": "The Field",+ "description": "How the three.ws homepage works: a live, zoomable map of every agent and product surface, its districts and data sources, semantic zoom, search, deep links and phone layout.",+ "priority": 0.5,+ "changefreq": "monthly",+ "added": "2026-10-11"+ },{"path": "/docs/event-markets","title": "Docs · Event Markets",diff --git a/docs/desktop.md b/docs/desktop.mdindex 485cbf22a..7bd07353b 100644--- a/docs/desktop.md+++ b/docs/desktop.md@@ -1,6 +1,9 @@# three.ws Desktop-`/` is a web desktop with a 3D campus in front of it. The page boots like a+> `/` now opens the [Field](field.md), a live map of the platform. This+> desktop and its campus are at `/?view=desktop` and `/?world=1`.++`/?view=desktop` is a web desktop with a 3D campus in front of it. The page boots like acomputer, locks with a greeting, and then the visitor walks to their desk astheir avatar and sits down; the desktop opens on the monitor. Every windowframes a real three.ws page, so nothing is mocked and every existing surfacediff --git a/docs/field.md b/docs/field.mdnew file mode 100644index 000000000..dfcd11233--- /dev/null+++ b/docs/field.md@@ -0,0 +1,90 @@+# The Field++`/` is the Field: one zoomable map of the whole platform, drawn from live data.+At the centre is the core, every public agent placed as a star on a golden-angle+spiral (newest in the middle). Around it sit the districts, one per product+surface. Wallet moves from Pulse fly across the map as comets and land in the+district they belong to. Nothing on the map is decorative: every number, face+and trail comes from a real endpoint, and when a feed is down its district says+so and offers a retry.++The windowed desktop and the 3D campus are still one click away:+`/?view=desktop` and `/?world=1` (see [desktop.md](desktop.md)). The previous+homepage stays at `/classic`.++## Moving around++| Input | What it does |+| --- | --- |+| Drag, flick | Pan, with inertia |+| Wheel, pinch, `+` / `-` | Zoom about the cursor or the pinch centre |+| Double click | Zoom in on that spot |+| Click a district tag | Fly to the district and read its live card |+| Click an agent star | Open that agent's page in place |+| `0`, `Home`, `Esc` | Fly back to the whole map |+| Arrows | Pan |+| `/` or start typing | Search places, agents and every page in the site nav |+| `Enter` on a focused district | Open it |++Camera moves follow the van Wijk and Nuij smooth zoom path: a long hop pulls+out, travels and comes back in, so you never lose your place. Reduced motion+turns every flight into a cut.++## Semantic zoom++From afar each district is a tag holding one live readout (the newest avatar,+the $THREE price, how long since the last wallet move). Zoom past+`NEAR_K` and the tags open into cards with real content:++| District | Card | Source |+| --- | --- | --- |+| Create | Ways to make an agent | static routes |+| Forge | Prompt box that opens `/forge?prompt=` | user input |+| Gallery | Newest avatar faces, each linking to `/avatars/<slug>` | `GET /api/avatars/public` |+| Launchpad | Coins agents launched through three.ws | `GET /api/pump/launches` |+| Trenches | $THREE price, 24h change, market cap, volume, holders, contract address with copy | `GET /api/three-token/stats` |+| Pulse | The four latest agent wallet moves, linked to the explorer | `GET /api/pulse` |+| Marketplace | Skills the newest agents carry most, linking to `/marketplace?q=` | `GET /api/agents/public` |+| Chat | The most talked-to agents | `GET /api/agents/public` |+| Agent Studio | Author or edit an agent | static routes |+| Console | Your account, or sign in | `GET /api/auth/me` |++Zoomed into the core, stars become avatar thumbnails; hover shows the agent's+name and description.++## Diving in++Opening a district, agent or search result loads the real page in a full-screen+surface over the map (a same-origin iframe named `tws-os:<id>`, which tells+`public/nav.js` to drop the site header). The URL becomes `/?go=<path>`, so the+surface survives a reload and can be shared; Back, the `Field` button and `Esc`+inside the page all return to the map. "Open in new tab" leaves the Field.++Deep links:++- `/?app=<district id>` flies straight to a district and opens it.+- `/?go=/some/path` opens any same-origin page in a surface. Cross-origin and+ protocol-relative values are ignored.++## Live updates++- Pulse is polled every 12 seconds with `?since=<head_cursor>`, so only new+ events cross the wire. Each new event fires a comet into its district.+- The $THREE quote refreshes every 60 seconds.+- Agents stream in page by page (`sort=newest`, `before=<cursor>`, 48 per page,+ up to 384) and fade into the core as each page lands.++## Phones++Portrait screens use a tall ring with districts spaced evenly by height and+alternating sides, and the core draws the newest 192 agents so the ring can stay+narrow enough for every tag to be readable. The agent count moves into the+search bar's placeholder. `tests/field-logic.test.js` checks at several phone+and desktop sizes that no two tags overlap at the home view.++## Code++[src/field/](../src/field/README.md): `logic.js` (pure layout, camera, search+and formatting, unit tested), `data.js` (the feeds), `field.js` (DOM, canvas,+input, surfaces), `field.css`, and `entry.js` (picks the Field or the legacy+desktop for `pages/desktop.html`).diff --git a/pages/desktop.html b/pages/desktop.htmlindex 06897b290..954a6a142 100644--- a/pages/desktop.html+++ b/pages/desktop.html@@ -6,7 +6,7 @@<meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" /><title>three.ws: The 3D Agent Layer of the Internet</title>- <meta name="description" content="three.ws is a web desktop for 3D AI agents. Make an agent from a selfie, forge 3D models from a prompt, and open every part of the platform as a window. Embed your agent anywhere with one HTML tag." />+ <meta name="description" content="three.ws is a living map of 3D AI agents: every agent, launch and wallet move, live. Make an agent from a selfie, forge 3D models from a prompt, and embed your agent anywhere with one HTML tag." /><link rel="canonical" href="https://three.ws/" /><link rel="alternate" type="text/plain" title="llms.txt" href="/llms.txt" /><meta name="theme-color" content="#101010" />@@ -14,14 +14,14 @@<meta property="og:site_name" content="three.ws" /><meta property="og:url" content="https://three.ws/" /><meta property="og:title" content="three.ws: The 3D Agent Layer of the Internet" />- <meta property="og:description" content="A web desktop for 3D AI agents. Make one from a selfie, embed it anywhere." />+ <meta property="og:description" content="Every 3D AI agent, live on one map. Make one from a selfie, embed it anywhere." /><meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Home&d=The+3D+agent+layer+of+the+internet&p=%2F" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:site" content="@trythreews" /><meta name="twitter:title" content="three.ws: The 3D Agent Layer of the Internet" />- <meta name="twitter:description" content="A web desktop for 3D AI agents. Make one from a selfie, embed it anywhere." />+ <meta name="twitter:description" content="Every 3D AI agent, live on one map. Make one from a selfie, embed it anywhere." /><link rel="icon" href="/favicon.ico" sizes="any" /><link rel="icon" type="image/svg+xml" href="/favicon.svg" /><link rel="apple-touch-icon" href="/apple-touch-icon.png" />@@ -49,9 +49,9 @@<li><a href="/pocket">Pocket</a>: A handheld agent console in a phone-sized window</li><li><a href="/tour">Tour</a>: A guided walk through the platform</li></ul>- <p><a href="/classic">Classic website</a> | <a href="/?world=1">Walk in as your avatar</a> | <a href="/?view=desktop">Straight to the desktop</a></p>- <noscript><p>The desktop needs JavaScript. The links above work without it.</p></noscript>+ <p><a href="/classic">Classic website</a> | <a href="/?world=1">Walk in as your avatar</a> | <a href="/?view=desktop">The windowed desktop</a></p>+ <noscript><p>The live map needs JavaScript. The links above work without it.</p></noscript></div>- <script type="module" src="/src/desktop/main.js"></script>+ <script type="module" src="/src/field/entry.js"></script></body></html>diff --git a/src/field/README.md b/src/field/README.mdnew file mode 100644index 000000000..c03d91f18--- /dev/null+++ b/src/field/README.md@@ -0,0 +1,23 @@+# src/field++The Field, the homepage at `/`: a live, zoomable map of every agent and every+product surface. Feature doc: [docs/field.md](../../docs/field.md).++| File | Role |+| --- | --- |+| `entry.js` | Loaded by `pages/desktop.html`. Mounts the Field, or the legacy desktop and campus (`src/desktop/main.js`) when the URL asks for them (`?view=desktop`, `?world=1`, `?boot`). |+| `logic.js` | Pure functions with no DOM: district layout and rings, agent spiral, camera math (`zoomAt`, `fitRect`, `zoomPath`), level of detail, event routing, formatting, search ranking and deep-link parsing. Covered by `tests/field-logic.test.js`. |+| `data.js` | The live feeds: `/api/stats`, `/api/three-token/stats`, `/api/agents/public`, `/api/avatars/public`, `/api/pump/launches`, `/api/pulse`, `/api/auth/me`, and the site nav (`/nav-data.js`) for search. |+| `field.js` | `mountField(root)`: builds the DOM world and canvas sky, runs the camera, input, polling, comets and surfaces. Returns `{ flyTo, dive, close }`. |+| `field.css` | All styles, dark by default and light under `:root[data-theme='light']`. |++## Rules++- Every value shown comes from a feed in `data.js`. A failed feed renders an+ offline state with a retry, never sample data.+- Add a district by appending to `DISTRICTS` in `logic.js` (unique `id`, a+ routed same-origin `href`, a `hue` and a `kind`) and a `case` for its `kind`+ in `field.js`. The tests check every `href` is routed in `vercel.json` and+ that tags and cards never collide.+- Far tags are counter-scaled (`--inv`), so they hold a fixed screen size. On+ phones the CSS caps them at 150px wide, the budget the layout test assumes.diff --git a/src/field/data.js b/src/field/data.jsnew file mode 100644index 000000000..4f7f08295--- /dev/null+++ b/src/field/data.js@@ -0,0 +1,104 @@+// The Field's live feeds. Every value on the map comes from one of these real+// endpoints; when a feed fails the district says so instead of inventing data.++const NAV_DATA = '/nav-data.js';++async function getJson(url, init) {+ const r = await fetch(url, { credentials: 'include', ...init });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ return r.json();+}++/** Platform totals: agents, launches, active strategies. */+export async function loadStats() {+ const d = await getJson('/api/stats', { credentials: 'omit' });+ const s = d?.stats || {};+ return {+ agents: Number(s.agents?.value) || 0,+ launches: Number(s.launches?.value) || 0,+ strategies: Number(s.active_strategies?.value) || 0,+ };+}++/** $THREE price, change, market cap and holders. */+export async function loadToken() {+ const d = await getJson('/api/three-token/stats', { credentials: 'omit' });+ const t = d?.token;+ if (!t || !Number.isFinite(Number(t.price_usd))) throw new Error('no price');+ return {+ price: Number(t.price_usd),+ change: Number(t.price_change_24h),+ cap: Number(t.market_cap),+ volume: Number(t.volume_24h),+ holders: Number(t.holders),+ };+}++/**+ * Public agents, newest first, streamed page by page so the core fills in as+ * each page lands. Stops after `maxPages` or when the directory runs out.+ */+export async function streamAgents(onPage, { maxPages = 8, signal } = {}) {+ let cursor = null;+ for (let i = 0; i < maxPages; i++) {+ const url = `/api/agents/public?sort=newest&limit=48${cursor ? `&before=${encodeURIComponent(cursor)}` : ''}`;+ const d = await getJson(url, { credentials: 'omit', signal });+ onPage(Array.isArray(d.agents) ? d.agents : []);+ if (!d.has_more || !d.next_cursor) return;+ cursor = d.next_cursor;+ }+}++/** Newest public avatars that have a thumbnail. */+export async function loadAvatars(n = 8) {+ const d = await getJson('/api/avatars/public?limit=24', { credentials: 'omit' });+ return (d.avatars || []).filter((a) => a.thumbnail_url).slice(0, n);+}++/** Coins agents launched through three.ws (the platform's own launch records). */+export async function loadLaunches(n = 4) {+ const d = await getJson(`/api/pump/launches?limit=${n}`, { credentials: 'omit' });+ return d?.data?.launches || [];+}++/** The Pulse feed. Pass `since` (a head cursor) for only newer events. */+export async function loadPulse({ since = null, limit = 40 } = {}) {+ const url = since ? `/api/pulse?since=${encodeURIComponent(since)}&limit=${limit}` : `/api/pulse?limit=${limit}`;+ const d = await getJson(url, { credentials: 'omit' });+ return { events: d?.data?.events || [], head: d?.data?.head_cursor || since || null };+}++/** The signed-in account, or null. */+export async function loadAccount() {+ try {+ const d = await getJson('/api/auth/me');+ const u = d?.user;+ return u ? { name: u.display_name || u.username || 'You', avatar: u.avatar_url || null } : null;+ } catch {+ return null;+ }+}++/** Every same-origin page in the site navigation, for search. */+export async function loadPages() {+ try {+ // public/ files are served as-is; a variable keeps vite from bundling it.+ const mod = await import(/* @vite-ignore */ NAV_DATA);+ const seen = new Set();+ const out = [];+ const take = (it) => {+ if (!it || typeof it.href !== 'string' || !it.href.startsWith('/') || it.href.startsWith('//')) return;+ const key = it.href.split('#')[0];+ if (seen.has(key)) return;+ seen.add(key);+ out.push({ title: String(it.title || it.href).replace(/<[^>]*>/g, '').trim(), href: it.href, desc: it.desc || '', keywords: [] });+ };+ for (const g of mod.NAV_GROUPS || []) {+ (g.items || []).forEach(take);+ (g.columns || []).forEach((c) => (c.items || []).forEach(take));+ }+ return out;+ } catch {+ return [];+ }+}diff --git a/src/field/entry.js b/src/field/entry.jsnew file mode 100644index 000000000..58538d2f8--- /dev/null+++ b/src/field/entry.js@@ -0,0 +1,16 @@+// `/` entry. The Field is home; the windowed desktop and the walkable campus+// still answer at `?view=desktop` and `?world=1`.++import { wantsLegacy } from './logic.js';++if (wantsLegacy(location.search)) {+ import('../desktop/main.js');+} else {+ import('./field.js')+ .then(({ mountField }) => mountField(document.getElementById('os')))+ .catch((err) => {+ console.error('[field] failed to start', err);+ const root = document.getElementById('os');+ if (root) root.insertAdjacentHTML('afterbegin', '<p style="padding:24px;color:#fff;font:15px system-ui">The map could not start. Every page is linked below, or <a style="color:#b8a6ff" href="/?view=desktop">open the desktop</a>.</p>');+ });+}diff --git a/src/field/field.css b/src/field/field.cssnew file mode 100644index 000000000..60968deda--- /dev/null+++ b/src/field/field.css@@ -0,0 +1,1179 @@+/* The Field. Dark by default; follows the site-wide twx_theme switch. */++:root {+ --fd-bg: #06060a;+ --fd-bg2: #0d0b18;+ --fd-ink: #f3f1fb;+ --fd-dim: rgba(243, 241, 251, 0.62);+ --fd-faint: rgba(243, 241, 251, 0.38);+ --fd-line: rgba(255, 255, 255, 0.09);+ --fd-glass: rgba(18, 16, 30, 0.72);+ --fd-glass-hi: rgba(30, 27, 48, 0.86);+ --fd-star: #ece7ff;+ --fd-road: rgba(196, 181, 253, 0.08);+ --fd-ring: rgba(196, 181, 253, 0.07);+ --fd-accent: #b8a6ff;+ --fd-up: #4ade80;+ --fd-down: #f87171;+ --fd-shadow: 0 24px 60px -20px rgba(0, 0, 0, 0.7);+}+:root[data-theme='light'] {+ --fd-bg: #f6f5fb;+ --fd-bg2: #ece9f8;+ --fd-ink: #17151f;+ --fd-dim: rgba(23, 21, 31, 0.66);+ --fd-faint: rgba(23, 21, 31, 0.42);+ --fd-line: rgba(23, 21, 31, 0.1);+ --fd-glass: rgba(255, 255, 255, 0.78);+ --fd-glass-hi: rgba(255, 255, 255, 0.94);+ --fd-star: #5b45d6;+ --fd-road: rgba(91, 69, 214, 0.1);+ --fd-ring: rgba(91, 69, 214, 0.08);+ --fd-accent: #5b45d6;+ --fd-up: #15803d;+ --fd-down: #b91c1c;+ --fd-shadow: 0 24px 60px -24px rgba(40, 30, 90, 0.28);+}++html,+body {+ margin: 0;+ height: 100%;+ overflow: hidden;+ background: var(--fd-bg);+ overscroll-behavior: none;+}++.fd {+ position: fixed;+ inset: 0;+ overflow: hidden;+ color: var(--fd-ink);+ background: radial-gradient(120% 90% at 50% 45%, var(--fd-bg2) 0%, var(--fd-bg) 62%);+ font: 14px/1.45 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif;+ -webkit-font-smoothing: antialiased;+ touch-action: none;+ user-select: none;+ -webkit-user-select: none;+ cursor: grab;+}+.fd.is-dragging {+ cursor: grabbing;+}+.fd.is-pointing {+ cursor: pointer;+}+.fd *,+.fd *::before,+.fd *::after {+ box-sizing: border-box;+}+.fd-sr {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+}+.fd a {+ color: inherit;+}+.fd :focus-visible {+ outline: 2px solid var(--fd-accent);+ outline-offset: 2px;+}++.fd-sky {+ position: absolute;+ inset: 0;+ display: block;+}++/* ---- the world layer ---- */+.fd-world {+ position: absolute;+ left: 0;+ top: 0;+ width: 0;+ height: 0;+ transform-origin: 0 0;+}+.fd.is-moving .fd-world {+ will-change: transform;+}++.fd-d {+ position: absolute;+}++/* Far: a name and one live readout, held at a constant screen size. */+.fd-d-tag {+ position: absolute;+ left: 50%;+ top: 50%;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 2px;+ padding: 9px 16px 8px;+ border: 1px solid hsla(var(--hue), 80%, 70%, 0.35);+ border-radius: 999px;+ background: var(--fd-glass);+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ color: var(--fd-ink);+ font: inherit;+ white-space: nowrap;+ cursor: pointer;+ transform: translate(-50%, -50%) scale(var(--inv, 1));+ transition: opacity 0.22s ease, border-color 0.15s ease, background 0.15s ease;+}+.fd-d-tag b {+ font: 600 15px/1.1 'Space Grotesk', 'Inter', sans-serif;+ letter-spacing: -0.01em;+ display: flex;+ align-items: center;+ gap: 7px;+}+.fd-d-tag b::before {+ content: '';+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: hsl(var(--hue), 85%, 66%);+ box-shadow: 0 0 10px hsl(var(--hue), 85%, 66%);+}+.fd-d-read {+ font-size: 12px;+ color: var(--fd-dim);+ font-variant-numeric: tabular-nums;+}+.fd-d-tag:hover {+ border-color: hsla(var(--hue), 85%, 70%, 0.8);+ background: var(--fd-glass-hi);+}+.fd-d-tag:active {+ transform: translate(-50%, -50%) scale(calc(var(--inv, 1) * 0.97));+}++/* Near: the full card of live content. */+.fd-d-card {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ padding: 14px 16px 14px;+ border: 1px solid var(--fd-line);+ border-top: 2px solid hsla(var(--hue), 85%, 66%, 0.85);+ border-radius: 14px;+ background: var(--fd-glass);+ backdrop-filter: blur(14px);+ -webkit-backdrop-filter: blur(14px);+ box-shadow: var(--fd-shadow);+ font-size: 10.5px;+ cursor: default;+ opacity: 0;+ visibility: hidden;+ transition: opacity 0.22s ease, visibility 0s linear 0.22s, box-shadow 0.2s ease;+}+.fd[data-lod='near'] .fd-d-card {+ opacity: 1;+ visibility: visible;+ transition: opacity 0.22s ease, visibility 0s;+}+.fd[data-lod='near'] .fd-d-tag {+ opacity: 0;+ pointer-events: none;+}+.fd-d.is-focus .fd-d-card {+ box-shadow: var(--fd-shadow), 0 0 0 1px hsla(var(--hue), 85%, 66%, 0.35), 0 0 80px -30px hsla(var(--hue), 85%, 60%, 0.6);+}+.fd-d.is-hit .fd-d-tag,+.fd-d.is-hit .fd-d-card {+ animation: fd-hit 0.9s ease-out;+}+@keyframes fd-hit {+ 0% {+ box-shadow: 0 0 0 0 hsla(var(--hue), 90%, 66%, 0.75);+ }+ 100% {+ box-shadow: 0 0 0 18px hsla(var(--hue), 90%, 66%, 0);+ }+}++.fd-d-head {+ display: flex;+ align-items: center;+ gap: 7px;+ margin-bottom: 8px;+}+.fd-d-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: hsl(var(--hue), 85%, 66%);+ box-shadow: 0 0 8px hsl(var(--hue), 85%, 66%);+}+.fd-d-head h2 {+ margin: 0;+ font: 600 15px/1.1 'Space Grotesk', 'Inter', sans-serif;+ letter-spacing: -0.01em;+}+.fd-d-live {+ font-size: 9.5px;+ color: var(--fd-faint);+ font-variant-numeric: tabular-nums;+}+.fd-d-enter {+ margin-left: auto;+ display: inline-flex;+ align-items: center;+ gap: 2px;+ padding: 4px 6px 4px 10px;+ border-radius: 999px;+ border: 1px solid hsla(var(--hue), 80%, 70%, 0.35);+ font-size: 10px;+ font-weight: 600;+ text-decoration: none;+ transition: background 0.15s ease, border-color 0.15s ease;+}+.fd-d-enter:hover {+ background: hsla(var(--hue), 85%, 60%, 0.18);+ border-color: hsla(var(--hue), 85%, 70%, 0.7);+}+.fd-d-enter:active {+ background: hsla(var(--hue), 85%, 60%, 0.28);+}+.fd-d-body {+ flex: 1;+ min-height: 0;+ overflow: hidden;+ user-select: text;+ -webkit-user-select: text;+}++.fd-lede {+ margin: 0 0 8px;+ color: var(--fd-dim);+ font-size: 10.5px;+}+.fd-ca {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 12px;+ padding: 8px 10px;+ border: 1px solid var(--fd-line);+ border-radius: 10px;+ font-size: 11px;+ color: var(--fd-dim);+}+.fd-ca-k {+ font-weight: 600;+ letter-spacing: 0.08em;+ color: var(--fd-faint);+ font-size: 9.5px;+}+.fd-ca code {+ font: 500 11px/1 ui-monospace, 'SF Mono', Menlo, monospace;+ color: var(--fd-ink);+}+.fd-ca-copy,+.fd-ca-more {+ padding: 4px 9px;+ border: 1px solid var(--fd-line);+ border-radius: 999px;+ background: transparent;+ color: var(--fd-ink);+ font-family: inherit;+ font-size: 10.5px;+ font-weight: 500;+ line-height: 1;+ text-decoration: none;+ cursor: pointer;+ transition: background 0.15s ease, border-color 0.15s ease;+}+.fd-ca-copy {+ min-width: 54px;+}+.fd-ca-more {+ margin-left: auto;+}+.fd-ca-copy:hover,+.fd-ca-more:hover {+ background: var(--fd-glass-hi);+ border-color: var(--fd-accent);+}+.fd-ca-copy:active,+.fd-ca-more:active {+ transform: translateY(1px);+}+.fd-ca-copy:focus-visible,+.fd-ca-more:focus-visible {+ outline: 2px solid var(--fd-accent);+ outline-offset: 2px;+}+.fd-hint {+ margin: 8px 0 0;+ color: var(--fd-faint);+ font-size: 9.5px;+}+.fd-empty,+.fd-off {+ margin: 4px 0;+ color: var(--fd-dim);+ font-size: 10.5px;+}+.fd-empty a,+.fd-off button {+ color: hsl(var(--hue), 85%, 72%);+}+:root[data-theme='light'] .fd-empty a,+:root[data-theme='light'] .fd-off button {+ color: hsl(var(--hue), 70%, 38%);+}+.fd-retry {+ border: 0;+ background: none;+ padding: 0;+ font: inherit;+ font-weight: 600;+ text-decoration: underline;+ cursor: pointer;+}++/* Lists (launches, pulse, chat) */+.fd-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ gap: 3px;+}+.fd-list a {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 5px 6px;+ border-radius: 8px;+ text-decoration: none;+ transition: background 0.12s ease;+}+.fd-list a:hover {+ background: hsla(var(--hue), 80%, 60%, 0.12);+}+.fd-list a:active {+ background: hsla(var(--hue), 80%, 60%, 0.2);+}+.fd-li-face {+ flex: none;+ width: 22px;+ height: 22px;+ border-radius: 50%;+ object-fit: cover;+ background: hsla(var(--hue), 60%, 50%, 0.25);+}+.fd-li-init {+ display: grid;+ place-items: center;+ font-size: 10px;+ font-weight: 700;+}+.fd-li-main {+ flex: 1;+ min-width: 0;+ display: grid;+}+.fd-li-main b,+.fd-li-main span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fd-li-main b {+ font-weight: 600;+ font-size: 10.5px;+}+.fd-li-main span {+ color: var(--fd-faint);+ font-size: 9.5px;+}+.fd-li-side {+ flex: none;+ display: grid;+ justify-items: end;+ font-size: 9.5px;+ color: var(--fd-faint);+ font-variant-numeric: tabular-nums;+}+.fd-li-side code {+ font: 600 9.5px 'JetBrains Mono', ui-monospace, monospace;+ color: var(--fd-dim);+}++/* Create tiles */+.fd-tiles {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 6px;+}+.fd-tile {+ display: grid;+ align-content: end;+ gap: 2px;+ min-height: 112px;+ padding: 10px;+ border-radius: 10px;+ border: 1px solid var(--fd-line);+ background: linear-gradient(160deg, hsla(var(--hue), 80%, 60%, 0.16), transparent 70%);+ text-decoration: none;+ transition: border-color 0.15s ease, transform 0.15s ease, background 0.15s ease;+}+.fd-tile b {+ font: 600 11.5px 'Space Grotesk', 'Inter', sans-serif;+}+.fd-tile span {+ color: var(--fd-faint);+ font-size: 9.5px;+}+.fd-tile:hover {+ border-color: hsla(var(--hue), 85%, 70%, 0.6);+ transform: translateY(-1px);+}+.fd-tile:active {+ transform: translateY(0);+ background: linear-gradient(160deg, hsla(var(--hue), 80%, 60%, 0.26), transparent 70%);+}++/* Forge prompt */+.fd-forge {+ display: flex;+ gap: 6px;+}+.fd-forge input {+ flex: 1;+ min-width: 0;+ padding: 8px 10px;+ border-radius: 9px;+ border: 1px solid var(--fd-line);+ background: rgba(0, 0, 0, 0.25);+ color: var(--fd-ink);+ font: inherit;+ font-size: 11px;+ transition: border-color 0.15s ease;+}+:root[data-theme='light'] .fd-forge input {+ background: rgba(255, 255, 255, 0.7);+}+.fd-forge input:hover {+ border-color: hsla(var(--hue), 80%, 70%, 0.45);+}+.fd-forge input:focus {+ outline: none;+ border-color: hsl(var(--hue), 85%, 66%);+}++/* Gallery faces */+.fd-faces {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 6px;+}+.fd-face {+ display: grid;+ gap: 3px;+ justify-items: center;+ text-decoration: none;+ font-size: 9px;+ color: var(--fd-dim);+}+.fd-face img {+ width: 100%;+ aspect-ratio: 1;+ border-radius: 10px;+ object-fit: cover;+ background: hsla(var(--hue), 60%, 50%, 0.18);+ border: 1px solid var(--fd-line);+ transition: border-color 0.15s ease, transform 0.15s ease;+}+.fd-face span {+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fd-face:hover img {+ border-color: hsla(var(--hue), 85%, 70%, 0.7);+ transform: translateY(-1px);+}+.fd-face:active img {+ transform: none;+}++/* $THREE */+.fd-quote {+ display: flex;+ align-items: baseline;+ gap: 8px;+ margin: 4px 0 10px;+}+.fd-sym {+ font: 600 11px 'JetBrains Mono', ui-monospace, monospace;+ color: var(--fd-dim);+}+.fd-quote b {+ font: 600 26px/1 'Space Grotesk', 'Inter', sans-serif;+ letter-spacing: -0.02em;+ font-variant-numeric: tabular-nums;+}+.fd-up {+ color: var(--fd-up);+ font-style: normal;+ font-weight: 600;+}+.fd-down {+ color: var(--fd-down);+ font-style: normal;+ font-weight: 600;+}+.fd-kv {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 6px;+ margin: 0;+}+.fd-kv div {+ padding: 7px 8px;+ border-radius: 9px;+ border: 1px solid var(--fd-line);+}+.fd-kv dt {+ color: var(--fd-faint);+ font-size: 9px;+}+.fd-kv dd {+ margin: 2px 0 0;+ font-weight: 600;+ font-size: 11.5px;+ font-variant-numeric: tabular-nums;+}++/* Skills */+.fd-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 5px;+}+.fd-chip {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 5px 9px;+ border-radius: 999px;+ border: 1px solid var(--fd-line);+ text-decoration: none;+ font-size: 10px;+ transition: border-color 0.15s ease, background 0.15s ease;+}+.fd-chip span {+ color: var(--fd-faint);+ font-variant-numeric: tabular-nums;+}+.fd-chip:hover {+ border-color: hsla(var(--hue), 85%, 70%, 0.6);+ background: hsla(var(--hue), 85%, 60%, 0.1);+}+.fd-chip:active {+ background: hsla(var(--hue), 85%, 60%, 0.2);+}++.fd-steps {+ margin: 0;+ padding: 0 0 0 14px;+ color: var(--fd-dim);+ display: grid;+ gap: 4px;+}++/* Skeletons */+.fd-sk {+ display: block;+ border-radius: 7px;+ background: linear-gradient(90deg, var(--fd-line) 0%, rgba(255, 255, 255, 0.14) 50%, var(--fd-line) 100%);+ background-size: 200% 100%;+ animation: fd-shimmer 1.4s linear infinite;+}+.fd-sk-row {+ height: 28px;+ margin-bottom: 5px;+}+.fd-sk-face {+ aspect-ratio: 1;+ border-radius: 10px;+}+.fd-sk-in {+ display: inline-block;+ width: 64px;+ height: 10px;+ vertical-align: middle;+}+@keyframes fd-shimmer {+ to {+ background-position: -200% 0;+ }+}++/* ---- core label ---- */+.fd-core-tag {+ position: absolute;+ left: 0;+ top: var(--y, -480px);+}+.fd-core-btn {+ position: absolute;+ left: 0;+ top: 0;+ display: flex;+ align-items: baseline;+ gap: 7px;+ padding: 7px 14px;+ border-radius: 999px;+ border: 1px solid rgba(184, 166, 255, 0.3);+ background: var(--fd-glass);+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ color: var(--fd-ink);+ font: inherit;+ white-space: nowrap;+ cursor: pointer;+ transform: translate(-50%, -100%) scale(var(--inv, 1));+ transform-origin: 50% 100%;+ transition: border-color 0.15s ease, background 0.15s ease;+}+.fd-core-btn b {+ font: 600 16px 'Space Grotesk', 'Inter', sans-serif;+ font-variant-numeric: tabular-nums;+}+.fd-core-btn span {+ color: var(--fd-dim);+ font-size: 12px;+}+.fd-core-btn:hover {+ border-color: rgba(184, 166, 255, 0.75);+ background: var(--fd-glass-hi);+}++/* ---- chrome ---- */+.fd-top {+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: max(14px, env(safe-area-inset-top)) max(18px, env(safe-area-inset-right)) 0 max(18px, env(safe-area-inset-left));+ pointer-events: none;+ z-index: 3;+}+.fd-top > * {+ pointer-events: auto;+}+.fd-brand {+ display: flex;+ align-items: baseline;+ gap: 10px;+ text-decoration: none;+}+.fd-brand b {+ font: 700 18px 'Space Grotesk', 'Inter', sans-serif;+ letter-spacing: -0.02em;+}+.fd-crumb {+ color: var(--fd-dim);+ font-size: 13px;+ max-width: 40vw;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fd-crumb::before {+ content: '/';+ margin-right: 8px;+ color: var(--fd-faint);+}+.fd-actions {+ display: flex;+ align-items: center;+ gap: 6px;+}+.fd-acct:empty {+ display: none;+}+.fd-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 32px;+ padding: 0 13px;+ border-radius: 999px;+ border: 1px solid var(--fd-line);+ background: var(--fd-glass);+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ color: var(--fd-ink);+ font: 500 13px 'Inter', system-ui, sans-serif;+ text-decoration: none;+ white-space: nowrap;+ cursor: pointer;+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.1s ease;+}+.fd-btn:hover {+ background: var(--fd-glass-hi);+ border-color: rgba(184, 166, 255, 0.45);+}+.fd-btn:active {+ transform: scale(0.97);+}+.fd-ghost {+ background: transparent;+ backdrop-filter: none;+ -webkit-backdrop-filter: none;+ border-color: transparent;+ color: var(--fd-dim);+}+.fd-ghost:hover {+ color: var(--fd-ink);+}+.fd-solid {+ background: var(--fd-accent);+ border-color: transparent;+ color: #120d24;+ font-weight: 600;+}+:root[data-theme='light'] .fd-solid {+ color: #fff;+}+.fd-solid:hover {+ background: var(--fd-accent);+ filter: brightness(1.08);+}+.fd-d-card .fd-btn {+ height: 30px;+ font-size: 11px;+}++.fd-status {+ position: absolute;+ left: max(18px, env(safe-area-inset-left));+ bottom: max(18px, env(safe-area-inset-bottom));+ display: flex;+ align-items: center;+ gap: 8px;+ max-width: calc(50vw - 260px);+ color: var(--fd-dim);+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ z-index: 3;+ pointer-events: none;+}+.fd-status-text {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fd-live {+ flex: none;+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--fd-up);+ box-shadow: 0 0 0 0 var(--fd-up);+ animation: fd-live 2.4s ease-out infinite;+}+.fd.is-degraded .fd-live {+ background: #fbbf24;+ animation: none;+}+@keyframes fd-live {+ 0% {+ box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.6);+ }+ 100% {+ box-shadow: 0 0 0 9px rgba(74, 222, 128, 0);+ }+}++.fd-zoom {+ position: absolute;+ right: max(18px, env(safe-area-inset-right));+ bottom: max(18px, env(safe-area-inset-bottom));+ display: flex;+ flex-direction: column;+ border-radius: 12px;+ border: 1px solid var(--fd-line);+ background: var(--fd-glass);+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ overflow: hidden;+ z-index: 3;+}+.fd-zbtn {+ display: grid;+ place-items: center;+ width: 38px;+ height: 36px;+ border: 0;+ background: none;+ color: var(--fd-ink);+ font: 500 18px/1 'Inter', sans-serif;+ cursor: pointer;+ transition: background 0.12s ease;+}+.fd-zbtn + .fd-zbtn {+ border-top: 1px solid var(--fd-line);+}+.fd-zbtn:hover {+ background: rgba(184, 166, 255, 0.14);+}+.fd-zbtn:active {+ background: rgba(184, 166, 255, 0.24);+}++/* ---- ask ---- */+.fd-ask {+ position: absolute;+ left: 50%;+ bottom: max(18px, env(safe-area-inset-bottom));+ width: min(520px, calc(100vw - 120px));+ transform: translateX(-50%);+ z-index: 4;+ margin: 0;+}+.fd-ask-row {+ display: flex;+ align-items: center;+ gap: 10px;+ height: 48px;+ padding: 0 12px 0 16px;+ border-radius: 16px;+ border: 1px solid var(--fd-line);+ background: var(--fd-glass-hi);+ backdrop-filter: blur(16px);+ -webkit-backdrop-filter: blur(16px);+ box-shadow: var(--fd-shadow);+ color: var(--fd-dim);+ cursor: text;+ transition: border-color 0.15s ease, box-shadow 0.15s ease;+}+.fd-ask-row:hover {+ border-color: rgba(184, 166, 255, 0.35);+}+.fd-ask-row:focus-within {+ border-color: rgba(184, 166, 255, 0.7);+ box-shadow: var(--fd-shadow), 0 0 0 4px rgba(184, 166, 255, 0.14);+}+.fd-ask-input {+ flex: 1;+ min-width: 0;+ border: 0;+ background: none;+ color: var(--fd-ink);+ font: 500 15px 'Inter', system-ui, sans-serif;+ outline: none;+ user-select: text;+ -webkit-user-select: text;+}+.fd-ask-input::placeholder {+ color: var(--fd-faint);+}+.fd-kbd {+ display: grid;+ place-items: center;+ min-width: 22px;+ height: 22px;+ padding: 0 6px;+ border-radius: 6px;+ border: 1px solid var(--fd-line);+ font: 600 11px 'JetBrains Mono', ui-monospace, monospace;+ color: var(--fd-faint);+}+.fd-ask-row:focus-within .fd-kbd {+ visibility: hidden;+}+.fd-results {+ position: absolute;+ left: 0;+ right: 0;+ bottom: calc(100% + 8px);+ margin: 0;+ padding: 6px;+ list-style: none;+ border-radius: 14px;+ border: 1px solid var(--fd-line);+ background: var(--fd-glass-hi);+ backdrop-filter: blur(16px);+ -webkit-backdrop-filter: blur(16px);+ box-shadow: var(--fd-shadow);+ max-height: min(420px, 55vh);+ overflow-y: auto;+}+.fd-r {+ display: grid;+ grid-template-columns: 52px 1fr;+ grid-template-rows: auto auto;+ column-gap: 10px;+ padding: 8px 10px;+ border-radius: 10px;+ cursor: pointer;+}+.fd-r[aria-selected='true'],+.fd-r:hover {+ background: rgba(184, 166, 255, 0.14);+}+.fd-r-type {+ grid-row: span 2;+ align-self: center;+ font: 600 10px 'JetBrains Mono', ui-monospace, monospace;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--fd-faint);+}+.fd-r b {+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fd-r-sub {+ font-size: 12px;+ color: var(--fd-faint);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fd-r-none {+ padding: 10px;+ color: var(--fd-dim);+ font-size: 13px;+}++/* ---- agent tooltip ---- */+.fd-tip {+ position: absolute;+ left: 0;+ top: 0;+ display: flex;+ gap: 10px;+ width: 280px;+ padding: 10px 12px;+ border-radius: 12px;+ border: 1px solid var(--fd-line);+ background: var(--fd-glass-hi);+ backdrop-filter: blur(14px);+ -webkit-backdrop-filter: blur(14px);+ box-shadow: var(--fd-shadow);+ pointer-events: none;+ z-index: 5;+}+.fd-tip .fd-li-face {+ width: 40px;+ height: 40px;+ --hue: 262;+}+.fd-tip div {+ display: grid;+ gap: 2px;+ min-width: 0;+}+.fd-tip b {+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fd-tip span {+ color: var(--fd-dim);+ font-size: 12px;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.fd-tip em {+ color: var(--fd-faint);+ font-size: 11px;+ font-style: normal;+}++/* `hidden` must beat every display rule below, or a closed layer keeps eating clicks. */+.fd [hidden] {+ display: none !important;+}++/* ---- surface: a real page opened in place ---- */+.fd-surface {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ background: var(--fd-bg);+ z-index: 10;+ opacity: 0;+ transform: scale(0.985);+ transition: opacity 0.24s ease, transform 0.24s ease;+ cursor: default;+ user-select: text;+ -webkit-user-select: text;+}+.fd-surface.is-open {+ opacity: 1;+ transform: none;+}+.fd.is-inside .fd-top,+.fd.is-inside .fd-ask,+.fd.is-inside .fd-zoom,+.fd.is-inside .fd-status {+ visibility: hidden;+}+.fd-surface-bar {+ flex: none;+ display: flex;+ align-items: center;+ gap: 10px;+ height: 46px;+ padding: 0 max(10px, env(safe-area-inset-right)) 0 max(10px, env(safe-area-inset-left));+ border-bottom: 1px solid var(--fd-line);+ background: linear-gradient(90deg, hsla(var(--hue, 262), 80%, 60%, 0.12), transparent 40%), var(--fd-bg);+}+.fd-back {+ height: 30px;+ padding: 0 12px 0 8px;+}+.fd-surface-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: hsl(var(--hue, 262), 85%, 66%);+ box-shadow: 0 0 10px hsl(var(--hue, 262), 85%, 66%);+}+.fd-surface-title {+ font: 600 14px 'Space Grotesk', 'Inter', sans-serif;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.fd-surface-path {+ color: var(--fd-faint);+ font: 12px 'JetBrains Mono', ui-monospace, monospace;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ min-width: 0;+ flex: 1;+}+.fd-surface-tab {+ height: 30px;+}+.fd-surface-body {+ position: relative;+ flex: 1;+ min-height: 0;+}+.fd-frame {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ border: 0;+ background: var(--fd-bg);+}+.fd-surface-load {+ position: absolute;+ inset: 0;+ display: grid;+ place-content: center;+ justify-items: center;+ gap: 12px;+ color: var(--fd-dim);+ font-size: 13px;+ background: var(--fd-bg);+ z-index: 1;+}+.fd-surface-load i {+ width: 160px;+ height: 3px;+ border-radius: 3px;+ background: linear-gradient(90deg, transparent, hsl(var(--hue, 262), 85%, 66%), transparent);+ background-size: 50% 100%;+ background-repeat: no-repeat;+ animation: fd-scan 1.1s ease-in-out infinite;+}+@keyframes fd-scan {+ from {+ background-position: -100% 0;+ }+ to {+ background-position: 200% 0;+ }+}++/* ---- small screens ---- */+@media (max-width: 640px) {+ .fd-hide-sm {+ display: none;+ }+ /* The narrow ring has no room for the count beside the core; the search bar carries it instead. */+ .fd[data-lod='far'] .fd-core-tag {+ display: none;+ }+ /* tests/field-logic.test.js lays phone tags out assuming this width budget. */+ .fd-d-tag {+ max-width: 150px;+ }+ .fd-d-read {+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .fd-status {+ display: none;+ }+ .fd-ask {+ left: 12px;+ right: 66px;+ width: auto;+ transform: none;+ }+ .fd-zoom {+ right: 12px;+ }+ .fd-top {+ padding-left: 14px;+ padding-right: 10px;+ }+ .fd-crumb {+ max-width: 28vw;+ }+ .fd-surface-path {+ display: none;+ }+ .fd-surface-title {+ flex: 1;+ }+ .fd-kbd {+ display: none;+ }+}++@media (prefers-reduced-motion: reduce) {+ .fd *,+ .fd *::before,+ .fd *::after {+ animation-duration: 0.01ms !important;+ transition-duration: 0.01ms !important;+ }+}diff --git a/src/field/field.js b/src/field/field.jsnew file mode 100644index 000000000..39b027270--- /dev/null+++ b/src/field/field.js@@ -0,0 +1,1192 @@+// The Field: three.ws as one zoomable living map instead of a desktop.+//+// Every light in the core is a real public agent, placed newest-first on a+// phyllotaxis spiral; zoom in and the lights become their faces. Around the+// core sit the districts (Forge, Gallery, Launchpad, Trenches, Pulse ...),+// each rendering its own live feed. Real wallet moves from /api/pulse draw+// trails from the agent that made them to the district they landed in, and a+// new one fires a comet across the map as it happens. Zoom far and each+// district is a name and one live number; zoom near and it is a card of real+// content; keep going (or press Enter) and the surface itself opens in place.+// There are no icons, windows, docks or taskbars.++import {+ CARD,+ CORE,+ DISTRICTS,+ NEAR_K,+ agentPosition,+ agentSize,+ clampCam,+ coreRadius,+ deepLink,+ describeEvent,+ districtForEvent,+ easeInOut,+ fitRect,+ fmtCount,+ fmtPct,+ fmtUsd,+ layoutDistricts,+ lodFor,+ relTime,+ ringFor,+ screenToWorld,+ searchField,+ trailAlpha,+ worldBounds,+ zoomAt,+ zoomPath,+} from './logic.js';+import { loadAccount, loadAvatars, loadLaunches, loadPages, loadPulse, loadStats, loadToken, streamAgents } from './data.js';+import './field.css';++const PULSE_POLL_MS = 12_000;+const TOKEN_POLL_MS = 60_000;+const COMET_MS = 1800;+const MAX_TRAILS = 60;+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const clip = (s, n) => {+ const t = String(s ?? '').trim();+ return t.length > n ? `${t.slice(0, n - 1).trimEnd()}…` : t;+};+function hash32(s) {+ let h = 2166136261;+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);+ return h >>> 0;+}++/** Swap a button's label for a moment to confirm an action. */+function flash(btn, text) {+ const was = btn.dataset.label || btn.textContent;+ btn.dataset.label = was;+ btn.textContent = text;+ clearTimeout(btn._flash);+ btn._flash = setTimeout(() => (btn.textContent = was), 1400);+}++/**+ * Mount the Field into `root`.+ * @param {HTMLElement} root+ */+export function mountField(root) {+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;+ const S = {+ stats: null,+ token: null,+ agents: [],+ agentIndex: new Map(),+ avatars: null,+ launches: null,+ events: [],+ head: null,+ account: undefined,+ pages: [],+ err: {},+ agentsDone: false,+ };++ root.classList.add('fd');+ root.setAttribute('aria-label', 'three.ws');+ root.innerHTML = `+ <h1 class="fd-sr">three.ws: every agent, every surface, live on one map</h1>+ <canvas class="fd-sky" aria-hidden="true"></canvas>+ <div class="fd-world"><div class="fd-core-tag"></div></div>+ <header class="fd-top">+ <a class="fd-brand" href="/" aria-label="three.ws, back to the whole map"><b>three.ws</b><span class="fd-crumb" aria-live="polite">Field</span></a>+ <nav class="fd-actions" aria-label="Other ways in">+ <a class="fd-btn fd-ghost" href="/?world=1" title="Walk the 3D campus as your avatar">Walk in</a>+ <a class="fd-btn fd-ghost fd-hide-sm" href="/?view=desktop" title="The windowed desktop">Desktop</a>+ <span class="fd-acct"></span>+ </nav>+ </header>+ <div class="fd-status" role="status" aria-live="polite"><i class="fd-live"></i><span class="fd-status-text">Connecting to the network</span></div>+ <div class="fd-zoom" role="group" aria-label="Zoom">+ <button type="button" class="fd-zbtn" data-z="in" aria-label="Zoom in" title="Zoom in (+)">+</button>+ <button type="button" class="fd-zbtn" data-z="out" aria-label="Zoom out" title="Zoom out (-)">−</button>+ <button type="button" class="fd-zbtn" data-z="home" aria-label="Whole map" title="Whole map (0)"><svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></button>+ </div>+ <form class="fd-ask" role="search" autocomplete="off">+ <ul class="fd-results" role="listbox" id="fd-results" hidden></ul>+ <label class="fd-ask-row">+ <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/><path d="m20 20-3.5-3.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>+ <input class="fd-ask-input" type="text" spellcheck="false" placeholder="Go anywhere. Find any agent." aria-label="Go anywhere or find an agent" role="combobox" aria-expanded="false" aria-controls="fd-results" aria-autocomplete="list" />+ <kbd class="fd-kbd" aria-hidden="true">/</kbd>+ </label>+ </form>+ <div class="fd-tip" hidden></div>+ <section class="fd-surface" hidden aria-label="Open surface">+ <header class="fd-surface-bar">+ <button type="button" class="fd-btn fd-back" title="Back to the map (Esc)"><svg viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path d="M15 6l-6 6 6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg><span>Field</span></button>+ <span class="fd-surface-dot" aria-hidden="true"></span>+ <b class="fd-surface-title"></b>+ <span class="fd-surface-path"></span>+ <a class="fd-btn fd-ghost fd-surface-tab" target="_blank" rel="noopener">Open in new tab</a>+ </header>+ <div class="fd-surface-body"><div class="fd-surface-load"><i></i><span>Opening</span></div></div>+ </section>+ `;++ const $ = (sel) => root.querySelector(sel);+ const sky = $('.fd-sky');+ const g = sky.getContext('2d');+ const world = $('.fd-world');+ const coreTag = $('.fd-core-tag');+ const tip = $('.fd-tip');+ const crumb = $('.fd-crumb');+ const statusText = $('.fd-status-text');+ const ask = $('.fd-ask');+ const input = $('.fd-ask-input');+ const results = $('.fd-results');+ const surface = $('.fd-surface');++ let vw = innerWidth;+ let vh = innerHeight;+ let dpr = Math.min(2, devicePixelRatio || 1);+ let districts = layoutDistricts(DISTRICTS, ringFor(vw, vh));+ let cam = homeCam();+ let focusId = null;++ // ---- districts (DOM) ----+ const dEls = new Map();+ function buildDistricts() {+ world.querySelectorAll('.fd-d').forEach((n) => n.remove());+ dEls.clear();+ for (const d of districts) {+ const el = document.createElement('article');+ el.className = 'fd-d';+ el.dataset.id = d.id;+ el.style.setProperty('--hue', d.hue);+ el.style.left = `${d.rect.x}px`;+ el.style.top = `${d.rect.y}px`;+ el.style.width = `${CARD.w}px`;+ el.style.height = `${CARD.h}px`;+ el.innerHTML = `+ <button type="button" class="fd-d-tag" aria-label="${esc(d.title)}: ${esc(d.desc)}"><b>${esc(d.title)}</b><span class="fd-d-read"></span></button>+ <div class="fd-d-card">+ <header class="fd-d-head">+ <i class="fd-d-dot"></i><h2>${esc(d.title)}</h2><span class="fd-d-live"></span>+ <a class="fd-d-enter" href="${esc(d.href)}" data-dive="${esc(d.id)}" aria-label="Open ${esc(d.title)}">Open<svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></a>+ </header>+ <div class="fd-d-body"></div>+ </div>`;+ world.append(el);+ dEls.set(d.id, el);+ renderDistrict(d.id);+ }+ }++ const district = (id) => districts.find((d) => d.id === id) || null;++ /** Fill a district's readout and card body from the live store. */+ function renderDistrict(id) {+ const el = dEls.get(id);+ const d = district(id);+ if (!el || !d) return;+ const { read, live, body } = content(d);+ el.querySelector('.fd-d-read').innerHTML = read;+ el.querySelector('.fd-d-live').innerHTML = live || '';+ el.querySelector('.fd-d-body').innerHTML = body;+ }++ const skel = (n, cls = 'fd-sk-row') => Array.from({ length: n }, () => `<span class="fd-sk ${cls}"></span>`).join('');+ const offline = (what, key) => `<p class="fd-off">${esc(what)} is not answering right now. <button type="button" class="fd-retry" data-retry="${esc(key)}">Try again</button></p>`;++ function content(d) {+ switch (d.kind) {+ case 'create':+ return {+ read: 'Make an agent',+ body: `<p class="fd-lede">Give an AI a body. Start from whatever you have.</p>+ <div class="fd-tiles">+ <a class="fd-tile" href="/create-selfie" data-dive-path="/create-selfie" data-title="From a selfie"><b>From a selfie</b><span>Your face, rigged and walking</span></a>+ <a class="fd-tile" href="/create/prompt" data-dive-path="/create/prompt" data-title="From a sentence"><b>From a sentence</b><span>Describe it, get a character</span></a>+ <a class="fd-tile" href="/forge" data-dive="forge"><b>A 3D model</b><span>Any object, as a GLB</span></a>+ </div>`,+ };+ case 'forge':+ return {+ read: 'Text to 3D',+ body: `<p class="fd-lede">Type what you want to hold. Forge returns a textured, downloadable model.</p>+ <form class="fd-forge"><input name="prompt" maxlength="1000" placeholder="a brass telescope on a tripod" aria-label="Describe a 3D model" /><button class="fd-btn fd-solid" type="submit">Forge</button></form>+ <p class="fd-hint">Free lane, no account needed.</p>`,+ };+ case 'gallery': {+ if (S.err.avatars) return { read: 'Offline', body: offline('The avatar gallery', 'avatars') };+ if (!S.avatars) return { read: '<span class="fd-sk fd-sk-in"></span>', body: `<div class="fd-faces">${skel(8, 'fd-sk-face')}</div>` };+ if (!S.avatars.length) return { read: 'No avatars yet', body: '<p class="fd-empty">No public avatars yet. <a href="/create-selfie" data-dive-path="/create-selfie" data-title="From a selfie">Make the first one</a>.</p>' };+ const newest = S.avatars[0];+ return {+ read: `Newest: ${esc(clip(newest.name, 18))}`,+ live: relTime(newest.created_at),+ body: `<div class="fd-faces">${S.avatars+ .map((a) => `<a class="fd-face" href="/avatars/${esc(a.slug || a.id)}" data-dive-path="/avatars/${esc(a.slug || a.id)}" data-title="${esc(clip(a.name, 40))}" title="${esc(a.name)}"><img src="${esc(a.thumbnail_url)}" alt="${esc(clip(a.name, 40))}" loading="lazy" decoding="async" /><span>${esc(clip(a.name, 14))}</span></a>`)+ .join('')}</div>`,+ };+ }+ case 'launches': {+ const total = S.stats ? `${fmtCount(S.stats.launches)} launched` : '';+ if (S.err.launches) return { read: total || 'Offline', body: offline('The launch feed', 'launches') };+ if (!S.launches) return { read: '<span class="fd-sk fd-sk-in"></span>', body: skel(4) };+ if (!S.launches.length) return { read: total || 'No launches yet', body: '<p class="fd-empty">No agent has launched a coin yet. <a href="/launcher" data-dive="launcher">Launch the first</a>.</p>' };+ return {+ read: total || `${S.launches.length} recent`,+ live: relTime(S.launches[0].created_at),+ body: `<ul class="fd-list">${S.launches+ .map((l) => `<li><a href="/launcher" data-dive="launcher">${face(l.agent?.avatar_thumbnail_url, l.agent?.name)}<span class="fd-li-main"><b>${esc(clip(l.name, 22))}</b><span>by ${esc(clip(l.agent?.name || 'an agent', 20))}</span></span><span class="fd-li-side"><code>$${esc(clip(String(l.symbol || '').toUpperCase(), 10))}</code><time>${relTime(l.created_at)}</time></span></a></li>`)+ .join('')}</ul>`,+ };+ }+ case 'token': {+ if (S.err.token) return { read: '$THREE offline', body: offline('The $THREE feed', 'token') };+ if (!S.token) return { read: '<span class="fd-sk fd-sk-in"></span>', body: skel(3) };+ const t = S.token;+ const dir = t.change >= 0 ? 'up' : 'down';+ return {+ read: `<span class="fd-hide-sm">$THREE </span>${fmtUsd(t.price)} <em class="fd-${dir}">${fmtPct(t.change)}</em>`,+ body: `<div class="fd-quote"><span class="fd-sym">$THREE</span><b>${fmtUsd(t.price)}</b><em class="fd-${dir}">${fmtPct(t.change)} 24h</em></div>+ <dl class="fd-kv">+ <div><dt>Market cap</dt><dd>${fmtUsd(t.cap) || 'n/a'}</dd></div>+ <div><dt>24h volume</dt><dd>${fmtUsd(t.volume) || 'n/a'}</dd></div>+ <div><dt>Holders</dt><dd>${Number.isFinite(t.holders) ? fmtCount(t.holders) : 'n/a'}</dd></div>+ </dl>+ <div class="fd-ca">+ <span class="fd-ca-k">CA</span>+ <code title="${THREE_MINT}">${THREE_MINT.slice(0, 6)}…${THREE_MINT.slice(-6)}</code>+ <button type="button" class="fd-ca-copy" data-copy="${THREE_MINT}">Copy</button>+ <a class="fd-ca-more" href="/three-token" data-dive-path="/three-token" data-title="$THREE">About $THREE</a>+ </div>+ <p class="fd-hint">Open Trenches for live Solana launches, runners and smart money.</p>`,+ };+ }+ case 'pulse': {+ if (S.err.pulse) return { read: 'Offline', body: offline('Pulse', 'pulse') };+ if (!S.head && !S.events.length) return { read: '<span class="fd-sk fd-sk-in"></span>', body: skel(4) };+ if (!S.events.length) return { read: 'Quiet right now', body: '<p class="fd-empty">No public wallet moves yet. Every trade, tip and launch an agent makes lands here the moment it confirms.</p>' };+ const last = S.events[0];+ return {+ read: `Last move ${relTime(last.ts)}${relTime(last.ts) === 'now' ? '' : ' ago'}`,+ live: `${S.events.length} recent`,+ body: `<ul class="fd-list">${S.events+ .slice(0, 4)+ .map((e) => `<li><a href="${esc(e.explorer || '/pulse')}" ${e.explorer ? 'target="_blank" rel="noopener"' : 'data-dive="pulse"'}>${face(e.agent?.avatar_thumbnail_url, e.agent?.name)}<span class="fd-li-main"><b>${esc(clip(describeEvent(e), 46))}</b><span>${esc(e.kind)}${e.usd ? ` · ${fmtUsd(e.usd)}` : ''}</span></span><span class="fd-li-side"><time>${relTime(e.ts)}</time></span></a></li>`)+ .join('')}</ul>`,+ };+ }+ case 'skills': {+ if (!S.agents.length) return { read: S.stats ? `${S.stats.strategies} live strategies` : '<span class="fd-sk fd-sk-in"></span>', body: skel(3) };+ const skip = new Set(['greet', 'remember', 'think', 'present-model', 'validate-model', 'wave', 'help']);+ const count = new Map();+ for (const a of S.agents) for (const s of a.skills || []) if (!skip.has(s)) count.set(s, (count.get(s) || 0) + 1);+ const top = [...count.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6);+ return {+ read: S.stats ? `${S.stats.strategies} live strategies` : `${count.size} skills in use`,+ body: top.length+ ? `<p class="fd-lede">Skills the newest ${S.agents.length} agents carry most.</p><div class="fd-chips">${top.map(([s, n]) => `<a class="fd-chip" href="/marketplace?q=${encodeURIComponent(s)}" data-dive-path="/marketplace?q=${encodeURIComponent(s)}" data-title="Marketplace"><b>${esc(s)}</b><span>${n}</span></a>`).join('')}</div>`+ : '<p class="fd-empty">No custom skills equipped yet. <a href="/agent-studio" data-dive="studio">Write the first one</a>.</p>',+ };+ }+ case 'chat': {+ if (!S.agents.length) return { read: '<span class="fd-sk fd-sk-in"></span>', body: skel(3) };+ const top = [...S.agents].sort((a, b) => (b.chat_count || 0) - (a.chat_count || 0)).slice(0, 4);+ return {+ read: `Talk to ${esc(clip(top[0]?.name || 'an agent', 16))}`,+ body: `<p class="fd-lede">The most talked-to agents right now.</p><ul class="fd-list">${top+ .map((a) => `<li><a href="${esc(a.home_url)}" data-dive-path="${esc(a.home_url)}" data-title="${esc(clip(a.name, 40))}">${face(a.avatar_thumbnail, a.name)}<span class="fd-li-main"><b>${esc(clip(a.name, 26))}</b><span>${esc(clip(a.description || 'Agent', 40))}</span></span><span class="fd-li-side"><code>${fmtCount(a.chat_count || 0)} chats</code></span></a></li>`)+ .join('')}</ul>`,+ };+ }+ case 'studio':+ return {+ read: 'Author an agent',+ body: `<p class="fd-lede">Write a persona, wire skills, tune a brain, and watch the agent use them.</p>+ <ul class="fd-steps"><li>Persona and voice</li><li>Skills from the marketplace or your own</li><li>Memory and strategy</li></ul>`,+ };+ case 'account': {+ if (S.account === undefined) return { read: '<span class="fd-sk fd-sk-in"></span>', body: skel(2) };+ if (!S.account) return { read: 'Sign in', body: '<p class="fd-lede">Your agents, wallets, keys and usage live here once you sign in.</p><a class="fd-btn fd-solid" href="/login?next=/">Sign in</a>' };+ return { read: esc(clip(S.account.name, 18)), body: `<p class="fd-lede">Signed in as <b>${esc(S.account.name)}</b>. Your agents, wallets, keys and usage.</p>` };+ }+ default:+ return { read: '', body: '' };+ }+ }++ function face(src, name) {+ const initial = esc(String(name || '?').trim().charAt(0).toUpperCase() || '?');+ return src ? `<img class="fd-li-face" src="${esc(src)}" alt="" loading="lazy" decoding="async" />` : `<span class="fd-li-face fd-li-init">${initial}</span>`;+ }++ // Agents drawn in the core. Search still covers every one loaded.+ const shown = () => Math.min(S.agents.length, ringFor(vw, vh).cap);++ function renderCore() {+ const n = shown();+ const total = S.stats?.agents;+ coreTag.style.setProperty('--y', `${-coreRadius(Math.max(n, 48)) - 36}px`);+ coreTag.innerHTML = `<button type="button" class="fd-core-btn" data-dive-path="/discover" data-title="Agents"><b>${total ? fmtCount(total) : n ? fmtCount(n) : ''}</b><span>${total || n ? 'agents' : 'Finding agents'}</span></button>`;+ }++ function renderStatus() {+ const parts = [];+ if (S.stats) parts.push(`${fmtCount(S.stats.agents)} agents`);+ if (S.events[0]) parts.push(`last wallet move ${relTime(S.events[0].ts)}${relTime(S.events[0].ts) === 'now' ? '' : ' ago'}`);+ if (S.token) parts.push(`$THREE ${fmtUsd(S.token.price)}`);+ const offlineCount = Object.values(S.err).filter(Boolean).length;+ root.classList.toggle('is-degraded', offlineCount > 0);+ statusText.textContent = parts.length ? parts.join(' · ') : offlineCount ? 'Some feeds are offline' : 'Connecting to the network';+ if (S.stats?.agents) {+ const n = fmtCount(S.stats.agents);+ input.placeholder = narrow.matches ? `Search ${n} agents and places` : `Go anywhere. Find any of ${n} agents.`;+ }+ }+ const narrow = matchMedia('(max-width: 640px)');+ narrow.addEventListener('change', () => renderStatus());++ function renderAccount() {+ const el = $('.fd-acct');+ if (S.account === undefined) return (el.innerHTML = '');+ el.innerHTML = S.account+ ? `<a class="fd-btn" href="/dashboard" data-dive="dashboard">${esc(clip(S.account.name, 18))}</a>`+ : `<a class="fd-btn fd-solid" href="/login?next=/">Sign in</a>`;+ }++ // ---- camera ----+ function homeCam() {+ return fitRect(worldBounds(ringFor(vw, vh)), vw, vh, 16);+ }+ function nearCam(d) {+ const m = vw < 640 ? 1.15 : 2.1;+ return fitRect({ x: d.x - (CARD.w * m) / 2, y: d.y - (CARD.h * m) / 2, w: CARD.w * m, h: CARD.h * m }, vw, vh, 12);+ }+ let settleTimer = 0;+ function applyCam() {+ cam = clampCam(cam, worldBounds(ringFor(vw, vh)));+ const tx = vw / 2 - cam.x * cam.k;+ const ty = vh / 2 - cam.y * cam.k;+ world.style.transform = `translate(${tx}px, ${ty}px) scale(${cam.k})`;+ root.style.setProperty('--k', cam.k);+ root.style.setProperty('--inv', 1 / cam.k);+ root.dataset.lod = lodFor(cam.k);+ root.classList.add('is-moving');+ clearTimeout(settleTimer);+ settleTimer = setTimeout(() => root.classList.remove('is-moving'), 160);+ updateFocus();+ dirty();+ }++ /** The district the camera is looking at, for the crumb and keyboard Enter. */+ function updateFocus() {+ let best = null;+ let bestD = Infinity;+ if (cam.k >= NEAR_K) {+ for (const d of districts) {+ const dist = Math.hypot(d.x - cam.x, d.y - cam.y);+ if (dist < bestD) {+ bestD = dist;+ best = d;+ }+ }+ if (best && bestD * cam.k > Math.min(vw, vh) * 0.45) best = null;+ }+ const id = best ? best.id : null;+ if (id === focusId) return;+ focusId = id;+ for (const [k, el] of dEls) el.classList.toggle('is-focus', k === id);+ if (surface.hidden) crumb.textContent = best ? best.title : cam.k > 1.2 && Math.hypot(cam.x, cam.y) < coreRadius(shown()) ? 'Agents' : 'Field';+ }++ let flight = null;+ /** Fly the camera along the smooth zoom path. Any user input cancels it. */+ function flyTo(target, { duration } = {}) {+ cancelFlight();+ target = clampCam(target, worldBounds(ringFor(vw, vh)));+ if (reduced) {+ cam = target;+ applyCam();+ return Promise.resolve(true);+ }+ const path = zoomPath(cam, target, vw);+ const ms = duration ?? path.duration;+ return new Promise((resolve) => {+ const t0 = performance.now();+ const f = { raf: 0, resolve };+ flight = f;+ const step = (now) => {+ const t = Math.min(1, (now - t0) / ms);+ cam = path.at(easeInOut(t));+ applyCam();+ if (t < 1) f.raf = requestAnimationFrame(step);+ else {+ flight = null;+ cam = target;+ applyCam();+ resolve(true);+ }+ };+ f.raf = requestAnimationFrame(step);+ });+ }+ function cancelFlight() {+ if (!flight) return;+ cancelAnimationFrame(flight.raf);+ flight.resolve(false);+ flight = null;+ }++ // ---- the sky (canvas) ----+ const imgs = new Map();+ let loadingImgs = 0;+ function agentImg(a) {+ if (!a.avatar_thumbnail) return null;+ let rec = imgs.get(a.id);+ if (rec) return rec.ok ? rec.img : null;+ if (loadingImgs >= 10) return null;+ const img = new Image();+ img.decoding = 'async';+ rec = { img, ok: false };+ imgs.set(a.id, rec);+ loadingImgs++;+ img.onload = () => {+ rec.ok = true;+ loadingImgs--;+ dirty();+ };+ img.onerror = () => loadingImgs--;+ img.src = a.avatar_thumbnail;+ return null;+ }++ function css(name, fallback) {+ return getComputedStyle(root).getPropertyValue(name).trim() || fallback;+ }+ let palette = null;+ function readPalette() {+ palette = { star: css('--fd-star', '#e9e4ff'), road: css('--fd-road', 'rgba(255,255,255,0.06)'), ring: css('--fd-ring', 'rgba(255,255,255,0.05)'), light: root.ownerDocument.documentElement.dataset.theme === 'light' };+ }++ const comets = [];+ let hover = null;+ let pending = false;+ function dirty() {+ if (pending) return;+ pending = true;+ requestAnimationFrame(draw);+ }++ function eventOrigin(e) {+ const a = e.agent?.id && S.agentIndex.get(e.agent.id);+ if (a && a.i < shown()) return a.pos;+ const r = coreRadius(Math.max(shown(), 48));+ const ang = ((hash32(String(e.agent?.id || e.id)) % 3600) / 3600) * Math.PI * 2;+ return { x: Math.cos(ang) * r, y: Math.sin(ang) * r };+ }+ function curve(a, b) {+ const mx = (a.x + b.x) / 2;+ const my = (a.y + b.y) / 2;+ const dx = b.x - a.x;+ const dy = b.y - a.y;+ return { a, b, c: { x: mx - dy * 0.18, y: my + dx * 0.18 } };+ }+ const qAt = (q, t) => ({ x: (1 - t) * (1 - t) * q.a.x + 2 * (1 - t) * t * q.c.x + t * t * q.b.x, y: (1 - t) * (1 - t) * q.a.y + 2 * (1 - t) * t * q.c.y + t * t * q.b.y });++ function draw(now = performance.now()) {+ pending = false;+ if (!palette) readPalette();+ const k = cam.k;+ g.setTransform(dpr, 0, 0, dpr, 0, 0);+ g.clearRect(0, 0, vw, vh);+ g.save();+ g.translate(vw / 2 - cam.x * k, vh / 2 - cam.y * k);+ g.scale(k, k);++ const coreR = coreRadius(Math.max(shown(), 48));+ // Orbit the districts sit on, and the core's glow.+ const ring = ringFor(vw, vh);+ g.lineWidth = 1 / k;+ g.strokeStyle = palette.ring;+ g.beginPath();+ g.ellipse(0, 0, ring.rx, ring.ry, 0, 0, Math.PI * 2);+ g.stroke();+ const glow = g.createRadialGradient(0, 0, 0, 0, 0, coreR * 1.6);+ glow.addColorStop(0, palette.light ? 'rgba(124,92,255,0.10)' : 'rgba(150,120,255,0.16)');+ glow.addColorStop(1, 'rgba(150,120,255,0)');+ g.fillStyle = glow;+ g.beginPath();+ g.arc(0, 0, coreR * 1.6, 0, Math.PI * 2);+ g.fill();++ // District halos and the roads from the core.+ for (const d of districts) {+ const halo = g.createRadialGradient(d.x, d.y, 0, d.x, d.y, CARD.w * 0.95);+ halo.addColorStop(0, `hsla(${d.hue}, 80%, 62%, ${palette.light ? 0.13 : 0.2})`);+ halo.addColorStop(1, `hsla(${d.hue}, 80%, 62%, 0)`);+ g.fillStyle = halo;+ g.beginPath();+ g.arc(d.x, d.y, CARD.w * 0.95, 0, Math.PI * 2);+ g.fill();+ const len = Math.hypot(d.x, d.y);+ const q = curve({ x: (d.x / len) * coreR, y: (d.y / len) * coreR }, { x: d.x, y: d.y });+ g.strokeStyle = palette.road;+ g.lineWidth = 1.5 / k;+ g.beginPath();+ g.moveTo(q.a.x, q.a.y);+ g.quadraticCurveTo(q.c.x, q.c.y, q.b.x, q.b.y);+ g.stroke();+ }++ // Trails: every recent real wallet move, from the agent to where it landed.+ const t = Date.now();+ for (const e of S.events.slice(0, MAX_TRAILS)) {+ const d = district(districtForEvent(e.kind));+ if (!d) continue;+ const q = curve(eventOrigin(e), { x: d.x, y: d.y });+ const alpha = trailAlpha(t - Date.parse(e.ts));+ g.strokeStyle = `hsla(${d.hue}, 85%, 66%, ${alpha})`;+ g.lineWidth = Math.max(1 / k, 1.2);+ g.beginPath();+ g.moveTo(q.a.x, q.a.y);+ g.quadraticCurveTo(q.c.x, q.c.y, q.b.x, q.b.y);+ g.stroke();+ }++ // Agents: points of light far away, faces up close.+ const born = now;+ let animating = false;+ const tl = screenToWorld(cam, vw, vh, -40, -40);+ const br = screenToWorld(cam, vw, vh, vw + 40, vh + 40);+ const cap = shown();+ for (const a of S.agents) {+ if (a.i >= cap) break;+ const { x, y } = a.pos;+ if (x < tl.x || x > br.x || y < tl.y || y > br.y) continue;+ const fade = reduced ? 1 : Math.min(1, (born - a.born) / 700);+ if (fade < 1) animating = true;+ const r = a.size;+ const sr = r * k;+ const hot = hover === a;+ const img = sr >= 9 ? agentImg(a) : null;+ g.globalAlpha = fade;+ if (img) {+ const rr = Math.max(r, 9 / k) * 1.15;+ g.save();+ g.beginPath();+ g.arc(x, y, rr, 0, Math.PI * 2);+ g.clip();+ g.drawImage(img, x - rr, y - rr, rr * 2, rr * 2);+ g.restore();+ g.strokeStyle = hot ? '#fff' : `hsla(${a.hue}, 80%, 72%, 0.9)`;+ g.lineWidth = (hot ? 2.5 : 1.2) / k;+ g.beginPath();+ g.arc(x, y, rr, 0, Math.PI * 2);+ g.stroke();+ } else {+ const rr = Math.max(r * 0.55, 1.2 / k);+ const halo = g.createRadialGradient(x, y, 0, x, y, rr * 4);+ halo.addColorStop(0, `hsla(${a.hue}, 90%, 80%, ${hot ? 0.9 : 0.45})`);+ halo.addColorStop(1, `hsla(${a.hue}, 90%, 80%, 0)`);+ g.fillStyle = halo;+ g.beginPath();+ g.arc(x, y, rr * 4, 0, Math.PI * 2);+ g.fill();+ g.fillStyle = hot ? '#fff' : palette.star;+ g.beginPath();+ g.arc(x, y, rr, 0, Math.PI * 2);+ g.fill();+ }+ }+ g.globalAlpha = 1;++ // Comets: wallet moves that arrived while you were here.+ for (let i = comets.length - 1; i >= 0; i--) {+ const c = comets[i];+ const p = Math.min(1, (now - c.t0) / COMET_MS);+ const head = qAt(c.q, easeInOut(p));+ for (let j = 1; j <= 14; j++) {+ const tp = qAt(c.q, Math.max(0, easeInOut(p) - j * 0.018));+ g.fillStyle = `hsla(${c.hue}, 95%, 72%, ${0.5 * (1 - j / 14)})`;+ g.beginPath();+ g.arc(tp.x, tp.y, (5 - j * 0.25) / Math.max(k, 0.4), 0, Math.PI * 2);+ g.fill();+ }+ g.fillStyle = '#fff';+ g.beginPath();+ g.arc(head.x, head.y, 5 / Math.max(k, 0.4), 0, Math.PI * 2);+ g.fill();+ if (p >= 1) {+ comets.splice(i, 1);+ const el = dEls.get(c.id);+ if (el) {+ el.classList.remove('is-hit');+ void el.offsetWidth;+ el.classList.add('is-hit');+ }+ } else animating = true;+ }+ g.restore();+ if (animating) dirty();+ }++ // ---- data ----+ function addAgents(list) {+ const now = performance.now();+ for (const a of list) {+ if (!a?.id || S.agentIndex.has(a.id)) continue;+ const i = S.agents.length;+ const rec = { ...a, i, pos: agentPosition(i), size: agentSize(a.chat_count), hue: 230 + (hash32(a.id) % 90), born: now + Math.min(600, i * 3) };+ S.agents.push(rec);+ S.agentIndex.set(a.id, rec);+ }+ renderCore();+ renderDistrict('chat');+ renderDistrict('marketplace');+ updateFocus();+ dirty();+ }++ async function guard(key, fn, after) {+ try {+ S.err[key] = false;+ await fn();+ } catch (err) {+ if (err?.name === 'AbortError') return;+ S.err[key] = true;+ console.warn(`[field] ${key} feed failed`, err);+ }+ after?.();+ renderStatus();+ }++ const loaders = {+ stats: () => guard('stats', async () => (S.stats = await loadStats()), () => { renderCore(); renderDistrict('launcher'); renderDistrict('marketplace'); }),+ token: () => guard('token', async () => (S.token = await loadToken()), () => renderDistrict('trenches')),+ avatars: () => guard('avatars', async () => (S.avatars = await loadAvatars(8)), () => renderDistrict('gallery')),+ launches: () => guard('launches', async () => (S.launches = await loadLaunches(4)), () => renderDistrict('launcher')),+ agents: () => guard('agents', () => streamAgents(addAgents, { maxPages: 8 }), () => { S.agentsDone = true; }),+ pulse: () => guard('pulse', async () => {+ const r = await loadPulse({ limit: 50 });+ S.events = r.events;+ S.head = r.head || 'none';+ }, () => { renderDistrict('pulse'); dirty(); }),+ account: async () => {+ S.account = await loadAccount();+ renderAccount();+ renderDistrict('dashboard');+ },+ pages: async () => (S.pages = await loadPages()),+ };++ async function pollPulse() {+ if (document.hidden || S.err.pulse || !S.head || S.head === 'none') return;+ try {+ const r = await loadPulse({ since: S.head, limit: 20 });+ if (r.head) S.head = r.head;+ if (!r.events.length) return;+ const fresh = r.events.filter((e) => !S.events.some((x) => x.id === e.id));+ S.events = [...fresh, ...S.events].slice(0, 200);+ for (const e of fresh.slice(0, 6)) {+ const d = district(districtForEvent(e.kind));+ if (d) comets.push({ q: curve(eventOrigin(e), { x: d.x, y: d.y }), hue: d.hue, id: d.id, t0: performance.now() + comets.length * 260 });+ }+ renderDistrict('pulse');+ renderStatus();+ dirty();+ } catch (err) {+ console.warn('[field] pulse poll failed', err);+ }+ }++ // ---- surfaces: open a real page in place ----+ const sBody = surface.querySelector('.fd-surface-body');+ const sTitle = surface.querySelector('.fd-surface-title');+ const sPath = surface.querySelector('.fd-surface-path');+ const sTab = surface.querySelector('.fd-surface-tab');+ const sLoad = surface.querySelector('.fd-surface-load');+ let frame = null;+ let openFrom = null;++ /**+ * Dive into a surface. Flies to `rect` first when given (the district card+ * or an agent's light), then opens the page over the map.+ */+ async function dive({ title, href, hue = 262, id = 'page', rect = null, push = true }) {+ closeResults();+ hideTip();+ openFrom = { cam: { ...cam }, rect };+ const f = document.createElement('iframe');+ f.className = 'fd-frame';+ // The name tells the framed page it is inside the shell, so it drops its own header (public/nav.js).+ f.name = `tws-os:${id}`;+ f.title = title;+ f.allow = 'clipboard-read; clipboard-write; fullscreen; microphone; camera; xr-spatial-tracking; web-share';+ f.src = href;+ f.addEventListener('load', () => onFrameLoad(f));+ if (frame) frame.remove();+ frame = f;+ sLoad.hidden = false;+ sLoad.querySelector('span').textContent = `Opening ${title}`;+ sBody.append(f);+ setSurfaceMeta(title, href, hue);+ if (rect) await flyTo(fitRect(rect, vw, vh, 0), { duration: reduced ? 0 : 520 });+ surface.hidden = false;+ root.classList.add('is-inside');+ requestAnimationFrame(() => surface.classList.add('is-open'));+ crumb.textContent = title;+ if (push) history.pushState({ fd: 'surface', href, title, id, hue }, '', `/?go=${encodeURIComponent(href)}`);+ surface.querySelector('.fd-back').focus({ preventScroll: true });+ }++ function setSurfaceMeta(title, href, hue) {+ sTitle.textContent = title;+ sPath.textContent = href;+ sTab.href = href;+ surface.style.setProperty('--hue', hue);+ }++ function onFrameLoad(f) {+ sLoad.hidden = true;+ try {+ const w = f.contentWindow;+ const path = w.location.pathname + w.location.search;+ if (path && path !== 'blank') {+ const title = (w.document.title || '').split(/\s[|:·-]\s|: /)[0].trim() || sTitle.textContent;+ setSurfaceMeta(title, path, surface.style.getPropertyValue('--hue') || 262);+ crumb.textContent = title;+ if (history.state?.fd === 'surface') history.replaceState({ ...history.state, href: path, title }, '', `/?go=${encodeURIComponent(path)}`);+ }+ // Esc inside the page returns to the map, unless the page is using Esc itself.+ w.addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && !e.defaultPrevented && !w.document.querySelector('dialog[open], [aria-modal="true"]')) close();+ });+ } catch {+ // A cross-origin redirect inside the frame: keep the last known title.+ }+ }++ async function closeSurface({ pop = false } = {}) {+ if (surface.hidden) return;+ surface.classList.remove('is-open');+ root.classList.remove('is-inside');+ const done = () => {+ surface.hidden = true;+ frame?.remove();+ frame = null;+ };+ if (reduced) done();+ else setTimeout(done, 260);+ if (!pop && history.state?.fd === 'surface') history.back();+ const back = openFrom?.cam && openFrom.rect ? openFrom.cam : null;+ openFrom = null;+ updateFocus();+ if (back) await flyTo(back, { duration: reduced ? 0 : 560 });+ else crumb.textContent = 'Field';+ }+ function close() {+ closeSurface();+ }++ addEventListener('popstate', (e) => {+ const st = e.state;+ if (st?.fd === 'surface') dive({ ...st, push: false });+ else closeSurface({ pop: true });+ });+ surface.querySelector('.fd-back').addEventListener('click', close);++ function diveDistrict(id) {+ const d = district(id) || (id === CORE.id ? null : null);+ if (id === CORE.id || id === 'discover') return dive({ title: 'Agents', href: '/discover', hue: CORE.hue, id: 'discover', rect: coreRect() });+ if (!d) return;+ return dive({ title: d.title, href: d.href, hue: d.hue, id: d.id, rect: d.rect });+ }+ function coreRect() {+ const r = coreRadius(Math.max(shown(), 48));+ return { x: -r, y: -r, w: r * 2, h: r * 2 };+ }+ function diveAgent(a) {+ const r = Math.max(a.size, 10) * 3;+ return dive({ title: a.name, href: a.home_url || `/agents/${a.id}`, hue: a.hue, id: 'agent', rect: { x: a.pos.x - r, y: a.pos.y - r, w: r * 2, h: r * 2 } });+ }++ // Clicks inside the map: links dive in place; modifier clicks keep the browser default.+ root.addEventListener('click', (e) => {+ const retry = e.target.closest('[data-retry]');+ if (retry) {+ loaders[retry.dataset.retry]?.();+ return;+ }+ const copy = e.target.closest('[data-copy]');+ if (copy) {+ navigator.clipboard?.writeText(copy.dataset.copy).then(+ () => flash(copy, 'Copied'),+ () => flash(copy, 'Press Ctrl+C'),+ );+ return;+ }+ const tag = e.target.closest('.fd-d-tag');+ if (tag) {+ const d = district(tag.closest('.fd-d').dataset.id);+ if (d) flyTo(nearCam(d));+ return;+ }+ const a = e.target.closest('a[data-dive], a[data-dive-path], button[data-dive-path]');+ if (!a || e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return;+ e.preventDefault();+ if (a.dataset.dive) return diveDistrict(a.dataset.dive);+ const dEl = a.closest('.fd-d');+ const d = dEl ? district(dEl.dataset.id) : null;+ dive({ title: a.dataset.title || a.textContent.trim(), href: a.dataset.divePath, hue: d?.hue ?? CORE.hue, id: d?.id || 'page', rect: d?.rect || (a.closest('.fd-core-tag') ? coreRect() : null) });+ });+ root.addEventListener('submit', (e) => {+ const form = e.target.closest('.fd-forge');+ if (!form) return;+ e.preventDefault();+ const prompt = String(new FormData(form).get('prompt') || '').trim();+ const d = district('forge');+ dive({ title: 'Forge', href: prompt ? `/forge?prompt=${encodeURIComponent(prompt)}` : '/forge', hue: d.hue, id: 'forge', rect: d.rect });+ });++ // ---- input: pan, zoom, pinch, hover, click ----+ const pointers = new Map();+ let drag = null;+ let pinch = null;+ const interactive = (t) => t.closest('a, button, input, textarea, select, form, .fd-d-card, .fd-surface, .fd-top, .fd-ask, .fd-zoom');++ root.addEventListener('pointerdown', (e) => {+ if (!surface.hidden || e.button > 0) return;+ const onCard = e.target.closest('.fd-d-card');+ if (interactive(e.target) && !(onCard && !e.target.closest('a, button, input, form'))) return;+ cancelFlight();+ root.setPointerCapture?.(e.pointerId);+ pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });+ if (pointers.size === 1) drag = { x: e.clientX, y: e.clientY, cx: cam.x, cy: cam.y, moved: 0, t: performance.now(), vx: 0, vy: 0 };+ else if (pointers.size === 2) {+ const [p1, p2] = [...pointers.values()];+ pinch = { d: Math.hypot(p1.x - p2.x, p1.y - p2.y), k: cam.k, mx: (p1.x + p2.x) / 2, my: (p1.y + p2.y) / 2, cam: { ...cam } };+ drag = null;+ }+ });+ root.addEventListener('pointermove', (e) => {+ if (pointers.has(e.pointerId)) pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });+ if (pinch && pointers.size === 2) {+ const [p1, p2] = [...pointers.values()];+ const d = Math.hypot(p1.x - p2.x, p1.y - p2.y);+ const mx = (p1.x + p2.x) / 2;+ const my = (p1.y + p2.y) / 2;+ const z = zoomAt(pinch.cam, vw, vh, pinch.mx, pinch.my, d / pinch.d);+ cam = { k: z.k, x: z.x - (mx - pinch.mx) / z.k, y: z.y - (my - pinch.my) / z.k };+ applyCam();+ return;+ }+ if (drag) {+ const dx = e.clientX - drag.x;+ const dy = e.clientY - drag.y;+ drag.moved = Math.max(drag.moved, Math.hypot(dx, dy));+ if (drag.moved > 3) {+ root.classList.add('is-dragging');+ const now = performance.now();+ const nx = drag.cx - dx / cam.k;+ const ny = drag.cy - dy / cam.k;+ const dt = Math.max(1, now - drag.t);+ drag.vx = ((nx - cam.x) / dt) * 16;+ drag.vy = ((ny - cam.y) / dt) * 16;+ drag.t = now;+ cam = { ...cam, x: nx, y: ny };+ applyCam();+ hideTip();+ }+ return;+ }+ if (e.pointerType === 'mouse' && surface.hidden) hoverAt(e.clientX, e.clientY);+ });+ function endPointer(e) {+ pointers.delete(e.pointerId);+ if (pinch && pointers.size < 2) pinch = null;+ if (!drag || pointers.size) return;+ const d = drag;+ drag = null;+ root.classList.remove('is-dragging');+ if (d.moved <= 3 && e.type === 'pointerup') {+ const a = agentAt(e.clientX, e.clientY);+ if (a) diveAgent(a);+ return;+ }+ // A flick keeps gliding.+ if (!reduced && Math.hypot(d.vx, d.vy) > 0.4) glide(d.vx, d.vy);+ }+ root.addEventListener('pointerup', endPointer);+ root.addEventListener('pointercancel', endPointer);+ root.addEventListener('pointerleave', (e) => e.pointerType === 'mouse' && hideTip());++ function glide(vx, vy) {+ const f = { raf: 0, resolve: () => {} };+ flight = f;+ const step = () => {+ vx *= 0.92;+ vy *= 0.92;+ cam = { ...cam, x: cam.x + vx, y: cam.y + vy };+ applyCam();+ if (Math.hypot(vx, vy) > 0.05 && flight === f) f.raf = requestAnimationFrame(step);+ else if (flight === f) flight = null;+ };+ f.raf = requestAnimationFrame(step);+ }++ root.addEventListener(+ 'wheel',+ (e) => {+ if (!surface.hidden || e.target.closest('.fd-results, .fd-d-body .fd-list')) return;+ e.preventDefault();+ cancelFlight();+ hideTip();+ const px = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? vh : 1;+ const dy = e.deltaY * px;+ const dx = e.deltaX * px;+ // Pinch on a trackpad arrives as ctrl+wheel; a sideways two-finger swipe pans.+ if (!e.ctrlKey && Math.abs(dx) > Math.abs(dy)) {+ cam = { ...cam, x: cam.x + dx / cam.k, y: cam.y + dy / cam.k };+ } else {+ const factor = Math.exp(-dy * (e.ctrlKey ? 0.01 : 0.0018));+ cam = zoomAt(cam, vw, vh, e.clientX, e.clientY, factor);+ }+ applyCam();+ },+ { passive: false },+ );+ root.addEventListener('dblclick', (e) => {+ if (interactive(e.target) || !surface.hidden) return;+ const target = zoomAt(cam, vw, vh, e.clientX, e.clientY, e.shiftKey ? 0.5 : 2.2);+ flyTo(target, { duration: 420 });+ });++ function agentAt(sx, sy) {+ if (!S.agents.length) return null;+ const p = screenToWorld(cam, vw, vh, sx, sy);+ let best = null;+ let bestD = Infinity;+ const cap = shown();+ for (const a of S.agents) {+ if (a.i >= cap) break;+ const d = Math.hypot(a.pos.x - p.x, a.pos.y - p.y);+ const reach = Math.max(a.size * 1.3, 9 / cam.k);+ if (d < reach && d < bestD) {+ best = a;+ bestD = d;+ }+ }+ return best;+ }+ function hoverAt(sx, sy) {+ const el = document.elementFromPoint(sx, sy);+ const a = el === sky || el === root || el === world ? agentAt(sx, sy) : null;+ if (a !== hover) {+ hover = a;+ root.classList.toggle('is-pointing', !!a);+ dirty();+ }+ if (!a) return hideTip();+ tip.hidden = false;+ tip.innerHTML = `${face(a.avatar_thumbnail, a.name)}<div><b>${esc(clip(a.name, 40))}</b><span>${esc(clip(a.description || 'three.ws agent', 80))}</span><em>${fmtCount(a.chat_count || 0)} chats · joined ${relTime(a.created_at)}${relTime(a.created_at) === 'now' ? '' : ' ago'}</em></div>`;+ const x = Math.min(vw - 300, sx + 16);+ const y = Math.min(vh - 110, sy + 16);+ tip.style.transform = `translate(${x}px, ${y}px)`;+ }+ function hideTip() {+ if (!tip.hidden) tip.hidden = true;+ if (hover) {+ hover = null;+ root.classList.remove('is-pointing');+ dirty();+ }+ }++ // ---- zoom controls ----+ root.querySelector('.fd-zoom').addEventListener('click', (e) => {+ const z = e.target.closest('[data-z]')?.dataset.z;+ if (z === 'home') flyTo(homeCam());+ else if (z) flyTo(zoomAt(cam, vw, vh, vw / 2, vh / 2, z === 'in' ? 1.8 : 1 / 1.8), { duration: 360 });+ });++ // ---- search ----+ let found = [];+ let sel = 0;+ function closeResults() {+ results.hidden = true;+ input.setAttribute('aria-expanded', 'false');+ input.removeAttribute('aria-activedescendant');+ }+ function showResults() {+ found = searchField(input.value, { districts: [CORE, ...districts], agents: S.agents, pages: S.pages }, 8);+ sel = 0;+ if (!found.length) {+ results.innerHTML = `<li class="fd-r-none" role="option" aria-disabled="true">Nothing on the map matches "${esc(clip(input.value, 40))}". Press Enter to search every agent.</li>`;+ } else {+ results.innerHTML = found+ .map((r, i) => `<li id="fd-r-${i}" role="option" class="fd-r" data-i="${i}" aria-selected="${i === sel}"><span class="fd-r-type">${r.type === 'district' ? 'Place' : r.type === 'agent' ? 'Agent' : 'Page'}</span><b>${esc(clip(r.title, 48))}</b><span class="fd-r-sub">${esc(clip(r.sub, 70))}</span></li>`)+ .join('');+ }+ results.hidden = false;+ input.setAttribute('aria-expanded', 'true');+ markSel();+ }+ function markSel() {+ results.querySelectorAll('.fd-r').forEach((li, i) => li.setAttribute('aria-selected', String(i === sel)));+ if (found.length) input.setAttribute('aria-activedescendant', `fd-r-${sel}`);+ }+ async function choose(r) {+ closeResults();+ input.value = '';+ input.blur();+ if (!r) return;+ if (r.type === 'district') {+ if (r.id === CORE.id) {+ await flyTo(fitRect(coreRect(), vw, vh, 40));+ return;+ }+ const d = district(r.id);+ if (d) await flyTo(nearCam(d));+ return;+ }+ if (r.type === 'agent') {+ const a = S.agentIndex.get(r.id);+ if (a) {+ const near = 46;+ await flyTo(fitRect({ x: a.pos.x - near, y: a.pos.y - near, w: near * 2, h: near * 2 }, vw, vh, 60));+ hover = a;+ dirty();+ return;+ }+ }+ dive({ title: r.title, href: r.href, hue: CORE.hue, id: 'page' });+ }+ input.addEventListener('input', showResults);+ input.addEventListener('focus', showResults);+ input.addEventListener('blur', () => setTimeout(closeResults, 120));+ input.addEventListener('keydown', (e) => {+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {+ e.preventDefault();+ if (!found.length) return;+ sel = (sel + (e.key === 'ArrowDown' ? 1 : found.length - 1)) % found.length;+ markSel();+ } else if (e.key === 'Escape') {+ input.value = '';+ input.blur();+ }+ });+ ask.addEventListener('submit', (e) => {+ e.preventDefault();+ const q = input.value.trim();+ if (found[sel]) choose(found[sel]);+ else if (q) {+ closeResults();+ input.value = '';+ dive({ title: 'Agents', href: `/discover?q=${encodeURIComponent(q)}`, hue: CORE.hue, id: 'discover' });+ }+ });+ results.addEventListener('pointerdown', (e) => {+ const li = e.target.closest('.fd-r');+ if (!li) return;+ e.preventDefault();+ choose(found[Number(li.dataset.i)]);+ });++ // ---- keyboard ----+ addEventListener('keydown', (e) => {+ const typing = e.target.closest?.('input, textarea, select, [contenteditable="true"]');+ if (!surface.hidden) {+ if (e.key === 'Escape' && !typing) close();+ return;+ }+ if (typing) return;+ if (e.key === '/' || (e.key.length === 1 && /\S/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey && !'+-=0'.includes(e.key))) {+ e.preventDefault();+ input.focus();+ if (e.key !== '/') {+ input.value = e.key;+ showResults();+ }+ return;+ }+ const step = 120 / cam.k;+ const k = e.key;+ if (k === 'ArrowLeft') cam = { ...cam, x: cam.x - step };+ else if (k === 'ArrowRight') cam = { ...cam, x: cam.x + step };+ else if (k === 'ArrowUp') cam = { ...cam, y: cam.y - step };+ else if (k === 'ArrowDown') cam = { ...cam, y: cam.y + step };+ else if (k === '+' || k === '=') return flyTo(zoomAt(cam, vw, vh, vw / 2, vh / 2, 1.8), { duration: 320 });+ else if (k === '-') return flyTo(zoomAt(cam, vw, vh, vw / 2, vh / 2, 1 / 1.8), { duration: 320 });+ else if (k === '0' || k === 'Home') return flyTo(homeCam());+ else if (k === 'Escape') return flyTo(homeCam());+ else if (k === 'Enter' && focusId && !e.target.closest('a, button')) return diveDistrict(focusId);+ else return;+ e.preventDefault();+ cancelFlight();+ applyCam();+ });++ // Tabbing onto a district flies the camera to it, so keyboard users travel the map too.+ root.addEventListener('focusin', (e) => {+ const el = e.target.closest('.fd-d');+ if (!el || drag) return;+ const d = district(el.dataset.id);+ if (d && focusId !== d.id) flyTo(nearCam(d), { duration: 480 });+ });++ // ---- sizing ----+ function resize() {+ const ringBefore = ringFor(vw, vh);+ vw = innerWidth;+ vh = innerHeight;+ dpr = Math.min(2, devicePixelRatio || 1);+ sky.width = Math.round(vw * dpr);+ sky.height = Math.round(vh * dpr);+ sky.style.width = `${vw}px`;+ sky.style.height = `${vh}px`;+ const ringNow = ringFor(vw, vh);+ if (ringNow !== ringBefore) {+ districts = layoutDistricts(DISTRICTS, ringNow);+ buildDistricts();+ renderCore();+ cam = homeCam();+ }+ applyCam();+ }+ addEventListener('resize', resize);+ new MutationObserver(() => {+ palette = null;+ dirty();+ }).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });++ // ---- start ----+ buildDistricts();+ renderCore();+ renderStatus();+ resize();+ Object.values(loaders).forEach((fn) => fn());+ setInterval(pollPulse, PULSE_POLL_MS);+ setInterval(() => !document.hidden && loaders.token(), TOKEN_POLL_MS);+ // Relative times ("3m") age while the page sits open.+ setInterval(() => {+ if (document.hidden) return;+ ['pulse', 'launcher', 'gallery'].forEach(renderDistrict);+ renderStatus();+ }, 60_000);++ // Arrival: start pulled back past the whole map and settle onto it, unless a link asked for a surface.+ const link = deepLink(location.search, [CORE.id, ...districts.map((d) => d.id)]);+ if (link?.type === 'district') {+ history.replaceState(null, '', '/');+ diveDistrict(link.id);+ } else if (link?.type === 'page') {+ history.replaceState(null, '', '/');+ dive({ title: 'three.ws', href: link.href, hue: CORE.hue, id: 'page' });+ } else if (!reduced) {+ const home = homeCam();+ cam = { ...home, k: home.k * 0.45 };+ applyCam();+ flyTo(home, { duration: 1400 });+ }++ return { flyTo, dive, close };+}diff --git a/src/field/logic.js b/src/field/logic.jsnew file mode 100644index 000000000..9a12407f3--- /dev/null+++ b/src/field/logic.js@@ -0,0 +1,331 @@+// Pure rules for the Field: the district map, camera math, the smooth-zoom+// path between two views, agent placement, level of detail, event routing and+// search. No DOM, no fetch; everything here is unit tested+// (tests/field-logic.test.js).++/** Golden angle in radians: consecutive agents never line up. */+export const GOLDEN = Math.PI * (3 - Math.sqrt(5));+/** World units between neighbouring agents in the core. */+export const AGENT_SPACING = 22;+/** Cards are this size in world units; zooming scales them. */+export const CARD = { w: 380, h: 264 };+/** Below this zoom a district shows only its name and one live readout. */+export const NEAR_K = 0.8;+/** Hard zoom limits. */+export const MIN_K = 0.08;+export const MAX_K = 6;++/**+ * The districts, laid out on an ellipse around the agent core. Each one is a+ * real three.ws surface; `kind` picks the live content its card renders.+ */+export const DISTRICTS = [+ { id: 'create', title: 'Create', href: '/create', hue: 262, kind: 'create', desc: 'Make an agent from a selfie or a sentence', keywords: ['agent', 'avatar', 'new', 'make', 'selfie'] },+ { id: 'forge', title: 'Forge', href: '/forge', hue: 24, kind: 'forge', desc: 'Type a prompt, get a textured 3D model', keywords: ['text to 3d', 'model', 'glb', 'generate', 'mesh'] },+ { id: 'gallery', title: 'Gallery', href: '/gallery', hue: 186, kind: 'gallery', desc: 'Every public 3D avatar', keywords: ['avatars', 'browse', 'characters'] },+ { id: 'launcher', title: 'Launchpad', href: '/launcher', hue: 34, kind: 'launches', desc: 'Coins agents launched on Solana', keywords: ['launch', 'pump', 'token', 'coin', 'mint', 'solana'] },+ { id: 'trenches', title: 'Trenches', href: '/trenches', hue: 152, kind: 'token', desc: '$THREE and live Solana markets', keywords: ['three', 'price', 'market', 'trade', 'solana', 'runners'] },+ { id: 'pulse', title: 'Pulse', href: '/pulse', hue: 340, kind: 'pulse', desc: 'Every public agent wallet move, live', keywords: ['feed', 'wallet', 'activity', 'live', 'money', 'trades'] },+ { id: 'marketplace', title: 'Marketplace', href: '/marketplace', hue: 46, kind: 'skills', desc: 'Buy and sell agent skills', keywords: ['skills', 'buy', 'sell', 'x402', 'store'] },+ { id: 'chat', title: 'Chat', href: '/chat', hue: 168, kind: 'chat', desc: 'Talk to any agent', keywords: ['assistant', 'talk', 'ai', 'conversation'] },+ { id: 'studio', title: 'Agent Studio', href: '/agent-studio', hue: 292, kind: 'studio', desc: 'Author brains, skills and personality', keywords: ['persona', 'prompt', 'skills', 'author', 'brain'] },+ { id: 'dashboard', title: 'Console', href: '/dashboard', hue: 220, kind: 'account', desc: 'Your agents, wallets and usage', keywords: ['dashboard', 'account', 'keys', 'billing', 'wallet'] },+];++/** The agent core sits at the origin; this is its search entry. */+export const CORE = { id: 'discover', title: 'Agents', href: '/discover', hue: 262, kind: 'core', desc: 'Every three.ws agent, newest at the centre', keywords: ['agents', 'directory', 'discover', 'explore', 'people'] };++/** Ellipse radii the districts sit on: wide for landscape, tall for phones. */+// `cap` is how many agents the core draws. A portrait screen gets a smaller+// core so the ring around it can be narrow enough to keep its tags readable.+export const RING = { rx: 1260, ry: 860, cap: 384 };+export const RING_TALL = { rx: 560, ry: 1400, cap: 192, tall: true };++/** The ring that suits a viewport's shape. */+export function ringFor(vw, vh) {+ return vw / Math.max(1, vh) < 0.8 ? RING_TALL : RING;+}++/** World position (card centre) of district `i` of `n`, clockwise from the top. */+export function districtCenter(i, n = DISTRICTS.length, ring = RING) {+ if (ring.tall) {+ // Evenly spaced by height, alternating sides, so no two tags share a row+ // on a narrow screen. Still traces the ellipse, top to bottom.+ const y = n > 1 ? -ring.ry + (i / (n - 1)) * ring.ry * 2 : 0;+ const side = i % 2 ? -1 : 1;+ const x = side * ring.rx * Math.sqrt(Math.max(0, 1 - (y / ring.ry) ** 2));+ return { x: Math.round(x), y: Math.round(y) };+ }+ const a = -Math.PI / 2 + (i / n) * Math.PI * 2;+ return { x: Math.round(Math.cos(a) * ring.rx), y: Math.round(Math.sin(a) * ring.ry) };+}++/** Every district with its world rectangle. */+export function layoutDistricts(list = DISTRICTS, ring = RING) {+ return list.map((d, i) => {+ const c = districtCenter(i, list.length, ring);+ return { ...d, x: c.x, y: c.y, rect: { x: c.x - CARD.w / 2, y: c.y - CARD.h / 2, w: CARD.w, h: CARD.h } };+ });+}++/** World bounds of the whole map, padded. */+export function worldBounds(ring = RING, pad = 120) {+ return {+ x: -ring.rx - CARD.w / 2 - pad,+ y: -ring.ry - CARD.h / 2 - pad,+ w: (ring.rx + CARD.w / 2 + pad) * 2,+ h: (ring.ry + CARD.h / 2 + pad) * 2,+ };+}++/** Agent `i`'s position in the core: a phyllotaxis spiral, newest at the centre. Stable as more load. */+export function agentPosition(i, spacing = AGENT_SPACING) {+ const r = spacing * Math.sqrt(i + 0.5);+ const a = i * GOLDEN;+ return { x: Math.cos(a) * r, y: Math.sin(a) * r };+}++/** Core radius that holds `n` agents. */+export function coreRadius(n, spacing = AGENT_SPACING) {+ return spacing * Math.sqrt(Math.max(1, n) + 0.5) + spacing;+}++/** Star radius in world units, from how much the agent has been talked to. */+export function agentSize(chatCount) {+ const c = Math.max(0, Number(chatCount) || 0);+ return 3 + Math.min(6, Math.log2(1 + c));+}++// ---- camera ----+// A camera is { x, y, k }: the world point at the viewport centre and the zoom.++export const clampK = (k) => Math.min(MAX_K, Math.max(MIN_K, k));++export function worldToScreen(cam, vw, vh, wx, wy) {+ return { x: (wx - cam.x) * cam.k + vw / 2, y: (wy - cam.y) * cam.k + vh / 2 };+}++export function screenToWorld(cam, vw, vh, sx, sy) {+ return { x: (sx - vw / 2) / cam.k + cam.x, y: (sy - vh / 2) / cam.k + cam.y };+}++/** Zoom by `factor` keeping the world point under screen (sx, sy) fixed. */+export function zoomAt(cam, vw, vh, sx, sy, factor) {+ const k = clampK(cam.k * factor);+ const p = screenToWorld(cam, vw, vh, sx, sy);+ return { k, x: p.x - (sx - vw / 2) / k, y: p.y - (sy - vh / 2) / k };+}++/** The camera that fits a world rect in the viewport with `pad` screen pixels around it. */+export function fitRect(rect, vw, vh, pad = 48) {+ const k = clampK(Math.min((vw - pad * 2) / rect.w, (vh - pad * 2) / rect.h));+ return { x: rect.x + rect.w / 2, y: rect.y + rect.h / 2, k };+}++/** Keep the camera centre inside the world bounds so the map can never be lost. */+export function clampCam(cam, bounds = worldBounds()) {+ return {+ k: clampK(cam.k),+ x: Math.min(bounds.x + bounds.w, Math.max(bounds.x, cam.x)),+ y: Math.min(bounds.y + bounds.h, Math.max(bounds.y, cam.y)),+ };+}++/** 'far' shows labels and one readout per district; 'near' shows full cards. */+export function lodFor(k) {+ return k < NEAR_K ? 'far' : 'near';+}++/**+ * The smooth zoom path between two cameras (van Wijk and Nuij, "Smooth and+ * efficient zooming and panning"): long hops pull out, travel, and dive back+ * in, so you always see where you are going. Returns a function of t in [0,1]+ * and its natural duration in ms.+ */+export function zoomPath(from, to, vw, rho = Math.SQRT2) {+ const ux0 = from.x;+ const uy0 = from.y;+ const w0 = vw / from.k;+ const ux1 = to.x;+ const uy1 = to.y;+ const w1 = vw / to.k;+ const dx = ux1 - ux0;+ const dy = uy1 - uy0;+ const d2 = dx * dx + dy * dy;+ const rho2 = rho * rho;+ const rho4 = rho2 * rho2;+ let at;+ let S;+ if (d2 < 1e-12) {+ S = Math.log(w1 / w0) / rho;+ at = (t) => ({ x: ux0 + t * dx, y: uy0 + t * dy, k: vw / (w0 * Math.exp(rho * t * S)) });+ } else {+ const d1 = Math.sqrt(d2);+ const b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1);+ const b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1);+ const r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0);+ const r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);+ S = (r1 - r0) / rho;+ at = (t) => {+ const s = t * S;+ const coshr0 = Math.cosh(r0);+ const u = (w0 / (rho2 * d1)) * (coshr0 * Math.tanh(rho * s + r0) - Math.sinh(r0));+ return { x: ux0 + u * dx, y: uy0 + u * dy, k: vw / ((w0 * coshr0) / Math.cosh(rho * s + r0)) };+ };+ }+ const duration = Math.min(2200, Math.max(380, Math.abs(S) * 1000 * (rho / Math.SQRT2) * 0.9));+ return { at, duration };+}++/** Ease for the path parameter. */+export const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);++// ---- events ----++/** Which district a Pulse event flows into. */+export function districtForEvent(kind) {+ switch (kind) {+ case 'launch':+ return 'launcher';+ case 'trade':+ case 'snipe':+ return 'trenches';+ case 'purchase':+ case 'payment':+ case 'x402':+ return 'marketplace';+ default:+ return 'pulse';+ }+}++/** Opacity of a past event's trail: bright for the last hour, fading over a week. */+export function trailAlpha(ageMs) {+ const h = Math.max(0, ageMs) / 3_600_000;+ if (h <= 1) return 0.55;+ if (h >= 168) return 0.06;+ return 0.06 + 0.49 * (1 - Math.log(h) / Math.log(168));+}++/** One-line human summary of a Pulse event. */+export function describeEvent(e) {+ const who = e?.agent?.name || 'An agent';+ const sym = e?.symbol ? `$${String(e.symbol).toUpperCase()}` : e?.coin_name || 'a coin';+ const amt = Number.isFinite(e?.sol) && e.sol > 0 ? ` ${fmtSol(e.sol)} SOL` : '';+ switch (e?.kind) {+ case 'trade':+ return `${who} ${e.side === 'sell' ? 'sold' : 'bought'} ${sym}${amt ? ` for${amt}` : ''}`;+ case 'snipe':+ return `${who} sniped ${sym}${amt ? ` with${amt}` : ''}`;+ case 'launch':+ return `${who} launched ${sym}`;+ case 'tip':+ return `${who} was tipped${amt}`;+ case 'purchase':+ return `${who} sold a skill${amt}`;+ default:+ return `${who} moved${amt || ' funds'}`;+ }+}++export function fmtSol(n) {+ if (!Number.isFinite(n)) return '';+ if (n >= 100) return n.toFixed(0);+ if (n >= 1) return n.toFixed(2);+ return String(Number(n.toPrecision(2)));+}++export function fmtUsd(n) {+ if (!Number.isFinite(n)) return '';+ if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;+ if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;+ if (n >= 1e4) return `$${(n / 1e3).toFixed(1)}K`;+ if (n >= 1) return `$${n.toFixed(2)}`;+ return `$${n.toPrecision(3)}`;+}++export function fmtPct(n) {+ if (!Number.isFinite(n)) return '';+ return `${n >= 0 ? '+' : ''}${n.toFixed(1)}%`;+}++export function fmtCount(n) {+ if (!Number.isFinite(n)) return '';+ return n >= 10_000 ? `${(n / 1000).toFixed(1)}K` : n.toLocaleString('en-US');+}++/** "now", "4m", "3h", "2d", "Sep 17". */+export function relTime(iso, now = Date.now()) {+ const t = Date.parse(iso);+ if (!Number.isFinite(t)) return '';+ const s = Math.max(0, (now - t) / 1000);+ if (s < 45) return 'now';+ if (s < 3600) return `${Math.round(s / 60)}m`;+ if (s < 86400) return `${Math.round(s / 3600)}h`;+ if (s < 86400 * 14) return `${Math.round(s / 86400)}d`;+ return new Date(t).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });+}++// ---- search ----++/**+ * Rank districts, agents and site pages against a query. Districts win ties,+ * then agents, then pages. Empty query lists the districts.+ * @returns {Array<{type:'district'|'agent'|'page', id:string, title:string, sub:string, href:string, item:object}>}+ */+export function searchField(query, { districts = [], agents = [], pages = [] } = {}, limit = 8) {+ const q = String(query || '').trim().toLowerCase();+ const out = [];+ const score = (title, kws = [], desc = '') => {+ const t = String(title || '').toLowerCase();+ if (!q) return 1;+ if (t === q) return 100;+ if (t.startsWith(q)) return 80;+ if (t.split(/[\s/\-_.]+/).some((w) => w.startsWith(q))) return 60;+ if (kws.some((k) => String(k).toLowerCase().startsWith(q))) return 50;+ if (t.includes(q)) return 40;+ if (kws.some((k) => String(k).toLowerCase().includes(q))) return 30;+ if (String(desc || '').toLowerCase().includes(q)) return 10;+ return 0;+ };+ districts.forEach((d, i) => {+ const s = score(d.title, d.keywords, d.desc);+ if (s) out.push({ s: s + 0.3, i, r: { type: 'district', id: d.id, title: d.title, sub: d.desc, href: d.href, item: d } });+ });+ if (q) {+ agents.forEach((a, i) => {+ const s = score(a.name, a.skills || [], a.description);+ if (s) out.push({ s: s + 0.2, i: 1000 + i, r: { type: 'agent', id: a.id, title: a.name, sub: a.description || 'Agent', href: a.home_url || `/agents/${a.id}`, item: a } });+ });+ pages.forEach((p, i) => {+ const s = score(p.title, p.keywords, p.desc);+ if (s) out.push({ s, i: 100000 + i, r: { type: 'page', id: p.href, title: p.title, sub: p.desc || p.href, href: p.href, item: p } });+ });+ }+ out.sort((a, b) => b.s - a.s || a.i - b.i);+ return out.slice(0, limit).map((o) => o.r);+}++/** Same-origin path only: the Field never frames another site. */+export function isInternalPath(href) {+ return typeof href === 'string' && href.startsWith('/') && !href.startsWith('//');+}++/**+ * Where the URL asks the Field to start: `?app=<district id>` or+ * `?go=<same-origin path>` dives straight in; anything else lands on the map.+ */+export function deepLink(search, ids) {+ const p = new URLSearchParams(search || '');+ const app = p.get('app');+ if (app && ids.includes(app)) return { type: 'district', id: app };+ const go = p.get('go');+ if (go && isInternalPath(go)) return { type: 'page', href: go };+ return null;+}++/** The legacy desktop and campus still live at `?view=desktop` and `?world=1`. */+export function wantsLegacy(search) {+ const p = new URLSearchParams(search || '');+ return p.get('view') === 'desktop' || p.has('world') || p.has('boot');+}diff --git a/tests/field-logic.test.js b/tests/field-logic.test.jsnew file mode 100644index 000000000..35d245653--- /dev/null+++ b/tests/field-logic.test.js@@ -0,0 +1,220 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ CARD,+ CORE,+ DISTRICTS,+ RING,+ RING_TALL,+ agentPosition,+ agentSize,+ clampCam,+ coreRadius,+ deepLink,+ describeEvent,+ districtForEvent,+ fitRect,+ layoutDistricts,+ lodFor,+ relTime,+ ringFor,+ screenToWorld,+ searchField,+ trailAlpha,+ wantsLegacy,+ worldBounds,+ worldToScreen,+ zoomAt,+ zoomPath,+} from '../src/field/logic.js';++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const vercel = JSON.parse(readFileSync(resolve(root, 'vercel.json'), 'utf8'));+const routed = (path) => vercel.routes.some((r) => r.src && new RegExp(`^${r.src}$`).test(path));++const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;++describe('field districts', () => {+ it('points every district at a routed same-origin page with a unique id', () => {+ const ids = [CORE, ...DISTRICTS].map((d) => d.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const d of [CORE, ...DISTRICTS]) expect(routed(d.href), d.href).toBe(true);+ });++ for (const [name, ring] of [['wide', RING], ['tall', RING_TALL]]) {+ it(`keeps cards apart and clear of a full agent core on the ${name} ring`, () => {+ const laid = layoutDistricts(DISTRICTS, ring);+ for (let i = 0; i < laid.length; i++) for (let j = i + 1; j < laid.length; j++) expect(overlap(laid[i].rect, laid[j].rect), `${laid[i].id}/${laid[j].id}`).toBe(false);+ const r = coreRadius(ring.cap);+ for (const d of laid) {+ const nx = Math.max(d.rect.x, Math.min(0, d.rect.x + d.rect.w));+ const ny = Math.max(d.rect.y, Math.min(0, d.rect.y + d.rect.h));+ expect(Math.hypot(nx, ny), d.id).toBeGreaterThan(r);+ }+ const b = worldBounds(ring);+ for (const d of laid) expect(d.rect.x >= b.x && d.rect.x + d.rect.w <= b.x + b.w && d.rect.y >= b.y && d.rect.y + d.rect.h <= b.y + b.h).toBe(true);+ });+ }++ // Far tags are counter-scaled, so they keep their screen size however far out the camera is.+ for (const [vw, vh] of [[390, 844], [360, 740], [430, 932], [1440, 900], [1024, 768]]) {+ it(`keeps every far tag apart and on screen at the home view on ${vw}x${vh}`, () => {+ const ring = ringFor(vw, vh);+ const home = fitRect(worldBounds(ring), vw, vh, 16);+ const tags = layoutDistricts(DISTRICTS, ring).map((d) => {+ const s = worldToScreen(home, vw, vh, d.x, d.y);+ return { id: d.id, x: s.x - 75, y: s.y - 27, w: 150, h: 54 };+ });+ for (let i = 0; i < tags.length; i++) for (let j = i + 1; j < tags.length; j++) expect(overlap(tags[i], tags[j]), `${tags[i].id}/${tags[j].id}`).toBe(false);+ for (const t of tags) expect(t.x >= 0 && t.x + t.w <= vw && t.y >= 56 && t.y + t.h <= vh, t.id).toBe(true);+ });+ }++ it('picks the tall ring for portrait screens', () => {+ expect(ringFor(390, 844)).toBe(RING_TALL);+ expect(ringFor(1440, 900)).toBe(RING);+ });+});++describe('field agents', () => {+ it('places agents on a stable spiral, newest at the centre', () => {+ expect(agentPosition(5)).toEqual(agentPosition(5));+ expect(Math.hypot(agentPosition(0).x, agentPosition(0).y)).toBeLessThan(Math.hypot(agentPosition(100).x, agentPosition(100).y));+ for (let i = 0; i < 384; i++) {+ const p = agentPosition(i);+ expect(Math.hypot(p.x, p.y)).toBeLessThan(coreRadius(384));+ }+ });+ it('sizes stars by conversation, within bounds', () => {+ expect(agentSize(0)).toBe(3);+ expect(agentSize(90)).toBeGreaterThan(agentSize(2));+ expect(agentSize(1e9)).toBe(9);+ expect(agentSize('nope')).toBe(3);+ });+});++describe('field camera', () => {+ const vw = 1440;+ const vh = 900;+ it('round-trips world and screen coordinates', () => {+ const cam = { x: 120, y: -40, k: 1.7 };+ const s = worldToScreen(cam, vw, vh, 300, 200);+ const w = screenToWorld(cam, vw, vh, s.x, s.y);+ expect(w.x).toBeCloseTo(300);+ expect(w.y).toBeCloseTo(200);+ });+ it('zooms about the cursor', () => {+ const cam = { x: 0, y: 0, k: 1 };+ const before = screenToWorld(cam, vw, vh, 200, 150);+ const z = zoomAt(cam, vw, vh, 200, 150, 2.5);+ const after = screenToWorld(z, vw, vh, 200, 150);+ expect(after.x).toBeCloseTo(before.x);+ expect(after.y).toBeCloseTo(before.y);+ expect(z.k).toBeCloseTo(2.5);+ });+ it('clamps zoom and keeps the camera on the map', () => {+ expect(zoomAt({ x: 0, y: 0, k: 5 }, vw, vh, 0, 0, 100).k).toBe(6);+ const c = clampCam({ x: 1e6, y: -1e6, k: 0.0001 });+ const b = worldBounds();+ expect(c.x).toBe(b.x + b.w);+ expect(c.y).toBe(b.y);+ expect(c.k).toBeGreaterThan(0);+ });+ it('fits a rect inside the viewport', () => {+ const cam = fitRect({ x: 0, y: 0, w: CARD.w, h: CARD.h }, vw, vh, 0);+ expect(CARD.w * cam.k).toBeLessThanOrEqual(vw + 1e-6);+ expect(CARD.h * cam.k).toBeLessThanOrEqual(vh + 1e-6);+ expect(cam.x).toBe(CARD.w / 2);+ });+ it('switches level of detail at the near threshold', () => {+ expect(lodFor(0.3)).toBe('far');+ expect(lodFor(1.4)).toBe('near');+ });+ it('smooth-zooms between views and lands exactly', () => {+ const a = { x: 0, y: 0, k: 0.4 };+ const b = { x: 1200, y: -600, k: 2 };+ const p = zoomPath(a, b, vw);+ const start = p.at(0);+ const end = p.at(1);+ expect(start.x).toBeCloseTo(0);+ expect(start.k).toBeCloseTo(0.4);+ expect(end.x).toBeCloseTo(1200);+ expect(end.y).toBeCloseTo(-600);+ expect(end.k).toBeCloseTo(2);+ expect(p.duration).toBeGreaterThan(300);+ });+ it('pulls out mid-flight when the target starts off-screen', () => {+ const p = zoomPath({ x: 0, y: 0, k: 2 }, { x: 3000, y: 0, k: 2 }, vw);+ expect(p.at(0.5).k).toBeLessThan(2);+ expect(p.at(1).x).toBeCloseTo(3000);+ expect(p.at(1).k).toBeCloseTo(2);+ });+ it('handles a pure zoom with no travel', () => {+ const p = zoomPath({ x: 5, y: 5, k: 1 }, { x: 5, y: 5, k: 3 }, vw);+ expect(p.at(1).k).toBeCloseTo(3);+ expect(p.at(1).x).toBeCloseTo(5);+ });+});++describe('field events', () => {+ it('routes each wallet move to the district it lands in', () => {+ expect(districtForEvent('launch')).toBe('launcher');+ expect(districtForEvent('snipe')).toBe('trenches');+ expect(districtForEvent('trade')).toBe('trenches');+ expect(districtForEvent('purchase')).toBe('marketplace');+ expect(districtForEvent('tip')).toBe('pulse');+ const ids = DISTRICTS.map((d) => d.id);+ for (const k of ['launch', 'snipe', 'trade', 'purchase', 'tip', 'x402', 'other']) expect(ids).toContain(districtForEvent(k));+ });+ it('fades trails with age', () => {+ expect(trailAlpha(0)).toBeGreaterThan(trailAlpha(3_600_000 * 24));+ expect(trailAlpha(3_600_000 * 24)).toBeGreaterThan(trailAlpha(3_600_000 * 500));+ expect(trailAlpha(-5)).toBe(trailAlpha(0));+ });+ it('describes events in plain words', () => {+ expect(describeEvent({ kind: 'trade', side: 'buy', sol: 0.01, symbol: 'three', agent: { name: 'Ada' } })).toBe('Ada bought $THREE for 0.01 SOL');+ expect(describeEvent({ kind: 'snipe', sol: 1.5, symbol: 'abc', agent: { name: 'Bo' } })).toBe('Bo sniped $ABC with 1.50 SOL');+ expect(describeEvent({ kind: 'launch', symbol: 'xyz' })).toBe('An agent launched $XYZ');+ });+ it('formats relative time', () => {+ const now = Date.parse('2026-10-11T12:00:00Z');+ expect(relTime('2026-10-11T11:59:50Z', now)).toBe('now');+ expect(relTime('2026-10-11T11:30:00Z', now)).toBe('30m');+ expect(relTime('2026-10-11T09:00:00Z', now)).toBe('3h');+ expect(relTime('2026-10-09T12:00:00Z', now)).toBe('2d');+ expect(relTime('garbage', now)).toBe('');+ });+});++describe('field search and links', () => {+ const agents = [{ id: 'a1', name: 'Forge Bot', description: 'makes things', skills: ['sculpt'], home_url: '/agents/a1' }, { id: 'a2', name: 'Ada', skills: [] }];+ const pages = [{ title: 'Forge Studio', href: '/forge-studio', desc: '' }];+ it('lists the places on an empty query', () => {+ const r = searchField('', { districts: DISTRICTS, agents, pages }, 50);+ expect(r.every((x) => x.type === 'district')).toBe(true);+ expect(r).toHaveLength(DISTRICTS.length);+ });+ it('ranks the place first, then agents, then pages', () => {+ const r = searchField('forge', { districts: DISTRICTS, agents, pages });+ expect(r[0]).toMatchObject({ type: 'district', id: 'forge' });+ expect(r.map((x) => x.type)).toEqual(['district', 'agent', 'page']);+ });+ it('finds agents by skill', () => {+ expect(searchField('sculpt', { agents })[0]).toMatchObject({ type: 'agent', id: 'a1', href: '/agents/a1' });+ });+ it('only dives into same-origin deep links', () => {+ expect(deepLink('?app=forge', ['forge'])).toEqual({ type: 'district', id: 'forge' });+ expect(deepLink('?app=nope', ['forge'])).toBeNull();+ expect(deepLink('?go=%2Fmarketplace', [])).toEqual({ type: 'page', href: '/marketplace' });+ expect(deepLink('?go=https://evil.example', [])).toBeNull();+ expect(deepLink('?go=//evil.example', [])).toBeNull();+ });+ it('keeps the desktop and campus reachable', () => {+ expect(wantsLegacy('?view=desktop')).toBe(true);+ expect(wantsLegacy('?world=1')).toBe(true);+ expect(wantsLegacy('?app=forge')).toBe(false);+ expect(wantsLegacy('')).toBe(false);+ });+});