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(desktop): seat real registered agents on the campus and let visitors walk up and talk to them
nirholas66a5e93bd008
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1db5bd18f..dc59aa625 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Everything three.ws Does** (`/everything`): Every three.ws feature organised by what you want to do: make a 3D avatar, build an agent, embed it, sell skills, launch a token, trade and more. Searchable, with pins and a new-this-month feed.- **Get the three.ws apps** (`/apps`): Every way to run three.ws: the web desktop, Android, Solana Seeker, iPhone and iPad, and the Windows and Linux desktop app.- **Run Receipts** (`/runs`): Every 3D Studio generation writes down what each stage was expected to do, what it actually did, and the verdict, with the cause whenever a stage fell back or missed. Signed with ed25519, public, and verifiable offline. Aggregate stage-by-stage rates here, one receipt per run at /runs/<id>.+- **The Field** (`/docs/field`): 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.- **three.ws Desktop** (`/apps/desktop`): Agent console and a 3D companion for Windows and Linux, with local agents, native spend approvals and a live download feed.- **three.ws for Android** (`/apps/android`): Download the native Android app: full-screen, Mobile Wallet Adapter signing, selfie to avatar and AR.- **three.ws for iPhone and iPad** (`/apps/ios`): The App Store build is finished and pending Apple enrollment; what runs on iPhone today and what the native app adds.@@ -33,7 +34,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Browse every feature by goal**: A new /everything page groups all 340 product pages under twelve goals (make, animate, build an agent, embed, earn, launch, trade, on-chain, worlds, discover, developer tools, account) with search, pins, recents and a new-this-month feed. The nav leads with it, the command palette labels every result with its goal, and tool pages like Forge, Create and Widgets now end with a what-next strip. (`/everything`) `[feature]`- **Every 3D generation now writes a signed run receipt**: Each Studio run (avatars, rigged avatars, meshes, rigs, refinements) records stage by stage what was expected, what was observed, and a verdict: met, recovered by a named fallback, missed with its cause, or skipped. The rig is verified by reading the delivered file back, not by trusting the rigger. Receipts are ed25519-signed, linked from every result, browsable at /runs with stage-by-stage rates, and verifiable offline with one command. (`/runs`) `[feature]`- **Menu bar panel for the desktop app**: Click the three.ws icon in your menu bar or tray and a small panel shows your agent alive in 3D, its Solana wallet balance, a start and stop button, anything waiting on your approval, unread alerts and a box to ask the agent something. Approvals still open the native confirmation window, so what you approve is exactly what you were shown. (`/desktop`) `[feature]`+- **Real agents live on the campus: a greeter meets you at the gate and every agent you walk up to talks back**: The campus is now populated by the ten most talked-to public agents on three.ws, each wearing its own avatar from its public record (five on a phone). The most popular one stands beside the gate path, turns to you as you walk in, waves and says hello through its own brain. Every agent idles, wanders a step, faces you when you come near and carries a name tag; walk up (or tap the tag) and press E to open a conversation that streams the agent's real reply, shows it as a speech bubble and can read it aloud. The panel opens the agent's profile as a window and hands you the one-tag embed that puts that exact agent, body and brain, on any web page. GET /api/agents/public now returns avatar_model_url for public and unlisted avatars. (`/?world=1`) `[feature, desktop]`- **The desktop behaves like a real computer**: Drag a selection box across the desktop, move icons on a snap grid, right-click for view options, and open every app from desktop icons or All Apps. Settings now covers your profile, theme, accent colour, wallpaper (including your own photo), icon size and taskbar, and the whole session (windows, icon layout, preferences) is saved in your browser, with export, import and reset. (`/docs/desktop`) `[feature, desktop]`+- **The homepage is now the Field: one live map of every agent, launch and wallet move**: 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. (`/`) `[feature]`- **The prompt director works again, found by its own run receipts**: The first receipts showed the director's brief falling back on every Studio run. The replies were arriving in 5 to 10 seconds but ran past the 1000-character prompt cap or ended on the closing constraint the director is told to end on, and both were discarded as clipped. The director now writes to a word budget the models actually follow, the guard accepts the mandated ending, both forge clients share one guard, and a receipt now names the exact reason a brief fell back (too long with its length, unfinished, no reply) instead of a generic timeout. Receipts also stop saying every stage met when a stage was skipped. (`/runs`) `[fix]`- **The terminal 3D renderer animates live in every HTTP client**: curl three.ws/tty streams an animated 3D character into your terminal frame by frame. Clients that ask for compressed responses, such as curl --compressed, scripts using fetch, and most HTTP libraries, used to get nothing for about ten seconds and then the whole animation at once. Live streams are no longer compressed, so every client sees the character move from the first frame. Streaming agent and chat responses get the same fix. (`/tty`) `[fix]`- **The web desktop gets Snap layouts, taskbar peek and three shell styles: Fluent, Aqua and Classic**: Hover a window's maximize button (or press Alt+Z) to tile it into one of six layouts, then let Snap assist fill the empty zones with your other windows. Corners snap to quarters, Ctrl+Alt+Arrows snap from the keyboard, minimize flies the window into its taskbar button, and hovering a running app shows its window card with Aero Peek. Settings, Personalization, Style switches the whole shell to Aqua (menu bar, magnifying dock, traffic lights) or Classic (bevelled 9x chrome with a labelled taskbar). (`/?view=desktop`) `[feature, desktop]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 1e2acc94b..74cf9da59 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -26,7 +26,7 @@ bottom.| 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) |+| 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. Real registered agents stand on the campus in their own bodies ([world/cast.js](src/desktop/world/cast.js), [agents.js](src/desktop/world/agents.js), [talk.js](src/desktop/world/talk.js)): a greeter meets you at the gate, and walking up to any of them opens a conversation through its own `/api/chat` brain, with the one-tag `<agent-3d>` embed to put it on your own site. 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) || Event Market agent forecasters | [api/_lib/event-markets/forecasters.js](api/_lib/event-markets/forecasters.js), [analyze.js](api/_lib/event-markets/analyze.js), [forecast-runner.js](api/_lib/event-markets/forecast-runner.js), [forecaster-routes.js](api/_lib/event-markets/forecaster-routes.js), [api/cron/event-markets-forecasters.js](api/cron/event-markets-forecasters.js), [api/_mcpagent/event-market-forecast-tools.js](api/_mcpagent/event-market-forecast-tools.js), [src/event-markets/forecasting.js](src/event-markets/forecasting.js), [forecasters.js](src/event-markets/forecasters.js), [pages/event-markets-forecasters.html](pages/event-markets-forecasters.html) `→ /event-markets/forecasters`, [data/event-markets-agents.json](data/event-markets-agents.json) | Live (migration 20261012120000 applied) | Agent picks as the agent's own identity with confidence, rationale and evidence; market-page agents panel; track record and calibration on the agent profile; ranked board; follow with notifications; owner-controlled autonomous mode (off by default); MCP analyze, forecasters and agent pick. Docs: [docs/event-markets.md](docs/event-markets.md#agents). Tests: [tests/event-markets-agents.test.js](tests/event-markets-agents.test.js), [tests/event-markets-agents-mcp.test.js](tests/event-markets-agents-mcp.test.js), [tests/event-markets-forecasting-ui.test.js](tests/event-markets-forecasting-ui.test.js) |diff --git a/api/agents/public.js b/api/agents/public.jsindex efa115720..fc7e7c4b5 100644--- a/api/agents/public.js+++ b/api/agents/public.js@@ -12,8 +12,10 @@* &avatar=1 only agents whose avatar GLB is publicly readable** Returns { agents, count, has_more, generated_at }. Each agent has the- * public-safe fields: id, name, description, skills, avatar_thumbnail_url,- * home_url, is_registered, chat_count, created_at, onchain summary.+ * public-safe fields: id, name, description, skills, avatar_thumbnail,+ * avatar_model_url (the GLB, only when the avatar is public or unlisted; the+ * desktop campus wears it), home_url, is_registered, chat_count, created_at,+ * onchain summary.** The `live` sort powers the /agents-live "watch them work" wall: it ranks* agents by their MOST RECENT real on-chain/skill action (the same@@ -41,7 +43,7 @@import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';-import { thumbnailUrl } from '../_lib/r2.js';+import { publicUrlOrNull, thumbnailUrl } from '../_lib/r2.js';const SORTS = new Set(['newest', 'popular', 'name', 'live']);@@ -63,6 +65,10 @@ function mapAgent(r) {const onchain = meta.onchain || null;const thumbPub = r.avatar_visibility === 'public' || r.avatar_visibility === 'unlisted';const thumbnail = r.avatar_thumbnail_key && thumbPub ? thumbnailUrl(r.avatar_thumbnail_key) : null;+ // The body itself, under the same public/unlisted gate as /api/agents/:id.+ // Lets a crowd surface (the desktop campus) dress every agent from one call+ // instead of one profile fetch per agent.+ const modelUrl = r.avatar_storage_key && thumbPub ? publicUrlOrNull(r.avatar_storage_key) : null;return {id: r.id,@@ -70,6 +76,7 @@ function mapAgent(r) {description: r.description || null,skills: r.skills || [],avatar_thumbnail: thumbnail,+ avatar_model_url: modelUrl,home_url: r.home_url || `/agents/${r.id}`,chat_count: Number(r.chat_count) || 0,is_registered: !!(onchain || meta.sol_mint_address || r.erc8004_agent_id || meta.erc8004_agent_id),@@ -114,6 +121,7 @@ export default wrap(async (req, res) => {i.id, i.name, i.description, i.skills, i.home_url,i.created_at, i.meta, i.erc8004_agent_id, i.chain_id,a.thumbnail_key as avatar_thumbnail_key,+ a.storage_key as avatar_storage_key,a.visibility as avatar_visibility,ac.last_action_at,coalesce(ac.action_count, 0) as action_count,@@ -226,6 +234,7 @@ export default wrap(async (req, res) => {i.erc8004_agent_id,i.chain_id,a.thumbnail_key as avatar_thumbnail_key,+ a.storage_key as avatar_storage_key,a.visibility as avatar_visibilityfrom agent_identities ileft join avatars a on a.id = i.avatar_id and a.deleted_at is nulldiff --git a/data/changelog.json b/data/changelog.jsonindex faa56db12..4ea75a07e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$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": "Real agents live on the campus: a greeter meets you at the gate and every agent you walk up to talks back",+ "link": "/?world=1",+ "summary": "The campus is now populated by the ten most talked-to public agents on three.ws, each wearing its own avatar from its public record (five on a phone). The most popular one stands beside the gate path, turns to you as you walk in, waves and says hello through its own brain. Every agent idles, wanders a step, faces you when you come near and carries a name tag; walk up (or tap the tag) and press E to open a conversation that streams the agent's real reply, shows it as a speech bubble and can read it aloud. The panel opens the agent's profile as a window and hands you the one-tag embed that puts that exact agent, body and brain, on any web page. GET /api/agents/public now returns avatar_model_url for public and unlisted avatars.",+ "tags": [+ "feature",+ "desktop"+ ]+ },{"date": "2026-10-11","title": "The homepage is now the Field: one live map of every agent, launch and wallet move",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 8b3dcd681..f70b21170 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -387,6 +387,55 @@ Returns the authenticated user's default agent, creating one automatically if no---+### Public agent directory++```+GET /api/agents/public+```++The browsable index of public agents. No auth; IP rate limited; 30-second CDN cache. Internal (service-account) agents never list.++| Query | Meaning |+| --- | --- |+| `q` | Full-text search on name and description |+| `skill` | Only agents offering this skill slug |+| `sort` | `popular` (default), `newest`, `name` or `live` (most recent real on-chain or skill action first) |+| `limit` | Page size, max 48 (default 24) |+| `before` | Cursor (`created_at <`) for `popular`, `newest` and `name` |+| `offset` | Offset for `live` |+| `network` | Only on-chain agents registered on this network |+| `onchain=1` | Only agents with an on-chain identity |+| `avatar=1` | Only agents whose avatar GLB is publicly readable |++**Response**++```json+{+ "agents": [+ {+ "id": "b7a2c1e4-0000-4000-8000-000000000001",+ "name": "Aria",+ "description": "Product guide",+ "skills": [{ "name": "Research", "slug": "research" }],+ "avatar_thumbnail": "https://three.ws/avatars/thumbs/default.png",+ "avatar_model_url": "https://<public-r2-domain>/avatars/<user>/<agent>.glb",+ "home_url": "/agents/b7a2c1e4-0000-4000-8000-000000000001",+ "is_registered": true,+ "chat_count": 90,+ "created_at": "2026-01-15T10:00:00Z",+ "onchain": { "network": "mainnet", "asset": "THREEsynthetic1111111111111111111111111111" }+ }+ ],+ "count": 1,+ "has_more": false,+ "generated_at": "2026-10-11T09:00:00Z"+}+```++`avatar_model_url` is the agent's GLB and is present only when the avatar's visibility is public or unlisted and the server knows its public storage domain (`S3_PUBLIC_DOMAIN`); otherwise it is `null`. The desktop campus wears it to seat real agents in the 3D world, and `<agent-3d agent-id>` loads the same file. The `live` sort also returns `last_action_at`, `action_count` and, on the first page, `total` and `active_total`.++---+### Get agent by ID```@@ -10116,7 +10165,7 @@ visitor without an id gets an empty ledger with `miner: null`.{ "id": "amethyst", "label": "Amethyst", "weight": 260, "points": 3, "hex": 12891645 },{ "id": "sapphire", "label": "Sapphire", "weight": 130, "points": 8, "hex": 6333946 },{ "id": "emerald", "label": "Emerald", "weight": 60, "points": 20, "hex": 3462041 },- { "id": "ruby", "label": "Ruby", "weight": 24, "points": 50, "hex": 16286065 },+ { "id": "ruby", "label": "Ruby", "weight": 24, "points": 50, "hex": 16281969 },{ "id": "diamond", "label": "Diamond", "weight": 6, "points": 200, "hex": 16777215 }],"dig_seconds": 4diff --git a/docs/desktop.md b/docs/desktop.mdindex 7bd07353b..fd8e5fbc6 100644--- a/docs/desktop.md+++ b/docs/desktop.md@@ -24,11 +24,14 @@ works unchanged. The previous homepage is kept at `/classic`.your account, and two ways in: **Walk in** (the campus) or **Desktop**. Thefirst gesture also unlocks the startup chime, a short synthesised chord(Settings, Arrival, Startup chime turns it off).-3. **The campus.** You spawn at the gate facing your workstation. Walk up to- the desk and the prompt says Sit down; hold E and the camera settles into the- chair while the desktop fades in on the monitor. The taskbar's World button- (also in the Start menu footer and the desktop right-click menu) stands you- back up where you were.+3. **The campus.** You spawn at the gate facing your workstation, and the+ first thing you meet is a real agent: the most talked-to public agent on the+ platform stands beside the gate path, turns to you as you walk in, waves and+ says hello through its own brain (`POST /api/chat` with its id, so its+ published persona answers). Walk up to the desk and the prompt says Sit+ down; hold E and the camera settles into the chair while the desktop fades+ in on the monitor. The taskbar's World button (also in the Start menu footer+ and the desktop right-click menu) stands you back up where you were.Controls: WASD or the arrow keys to walk, Shift to run, drag to orbit, wheel tozoom, C cycles the camera (Follow, Cinematic, and the rest of the shared camera@@ -61,6 +64,40 @@ World button brings you back to that place's doorstep, not the gate. Youravatar is the same default body and clip library the rest of the site uses(`/avatars/default.glb`, `/animations/manifest.json`).+### The agents++The campus is populated by real registered agents, not extras. On entry the+world reads `GET /api/agents/public?avatar=1&sort=popular` and seats the ten+most talked-to public agents that have a real name and a publicly readable+avatar GLB (five on a phone): the greeter beside the gate path, a gathering in+front of Agent Plaza, two along the path and one at the doorstep of each other+building. Each wears its own body from `avatar_model_url`, idles and wanders a+step or two, turns to face you and nods when you come near, and carries a+floating name tag (tap it to walk over). Nothing about them is invented: the+name, description, skills, conversation count and on-chain badge all come from+the agent's public record, and an agent still wearing an onboarding placeholder+name or bio is never introduced by it.++Within reach the prompt reads Talk to <name>; press E (or tap the tag again)+and the conversation panel opens. Messages go to `POST /api/chat` with the+agent's id and a grounding system prompt built from its public record, so the+agent answers as itself; replies stream in as they are generated, appear above+the agent's head as a speech bubble, and can be read aloud through+`POST /api/tts/speak` (the speaker toggle in the panel header, remembered in+`localStorage`). The footer opens the agent's profile as a desktop window, and+"Put this agent on your site" shows the one-tag embed (`<agent-3d+agent-id="…" chat voice>`) that puts that exact agent, body and brain, on any+web page: the 3D agent layer of the internet, demonstrated in place. Rate+limits (429) and a signed-out chat gate (401) are rendered as a note with a+Try again button; a failed TTS call is a toast and the text stays. Esc closes+the panel, sitting down or entering a building closes it too.++Which agents qualify, where they stand, the prompt distances, the SSE parser,+the embed snippet and the grounding prompt live in+`src/desktop/world/cast.js` (pure rules, unit tested in+`tests/world-cast.test.js`); `agents.js` spawns and animates the bodies;+`talk.js` is the panel.+### Gems`GET /api/world/gems` returns the caller's balance (`gems` by id, `points`,@@ -132,16 +169,23 @@ until the two agree. A new skeleton or page needs no other wiring.## Verify`npm run dev`, then `node scripts/desktop-world-smoke.mjs http://localhost:3000`-drives the whole arrival in a real browser: it reads every boot line, the lock-greeting and chips, walks in, runs to the desk and sits down, checks the-desktop, teleports to the Exchange and opens Trenches, picks up the phone,-opens the gem panel, cycles the camera and checks the phone layout, then-prints every console error and every failed or 5xx request. The gem endpoint-needs a database, so run the API locally (`PORT=3018 node --env-file=.env.local-server/index.mjs`) and start Vite with `DEV_API_PROXY=http://localhost:3018`.-`node scripts/desktop-smoke.mjs http://localhost:3000` is the shorter+drives the whole arrival in a real browser (it opens `/?world=1`, which asks+for the campus whichever entry answers at `/`): it reads every boot line, the+lock greeting and chips, walks in, lists the agents on the campus, walks up to+one, waits for the greeter's hello, talks to the agent and prints its reply+and the embed snippet, runs to the desk and sits down, checks the desktop,+teleports to the Exchange and opens Trenches, picks up the phone, opens the+gem panel, cycles the camera and checks the phone layout, then prints every+console error and every failed or 5xx request. With the default Vite proxy+(`/api` to production) every step runs against live data. To run against a+local API (`PORT=3018 node --env-file=.env.local server/index.mjs`, Vite with+`DEV_API_PROXY=http://localhost:3018`) the gem endpoint needs a database, the+agents need `S3_PUBLIC_DOMAIN` set so `avatar_model_url` is populated, and+anonymous chat needs one of `GROQ_API_KEY`, `OPENROUTER_API_KEY` or+`NVIDIA_API_KEY`; without a key the panel shows the sign-in note instead of a+reply. `node scripts/desktop-smoke.mjs http://localhost:3000` is the shorterdesktop-only drive. Unit tests: `npx vitest run tests/desktop-boot.test.js-tests/world-places.test.js tests/world-ticker.test.js+tests/world-places.test.js tests/world-cast.test.js tests/world-ticker.test.jstests/desktop-layout.test.js tests/desktop-page.test.js`.## Provenancediff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex 068a941c4..aaf80d992 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,11 +1,11 @@{- "generated_at": "2026-10-11T06:41:38.455Z",+ "generated_at": "2026-10-11T06:55:55.599Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 3991,+ "total": 3994,"complete": false,"full_feed": "/changelog.json","entries": [@@ -89,6 +89,16 @@"launch"]},+ {+ "date": "2026-10-11",+ "type": "launch",+ "title": "The Field",+ "summary": "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.",+ "link": "/docs/field",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-11","type": "launch",@@ -250,6 +260,17 @@"feature"]},+ {+ "date": "2026-10-11",+ "type": "update",+ "title": "Real agents live on the campus: a greeter meets you at the gate and every agent you walk up to talks back",+ "summary": "The campus is now populated by the ten most talked-to public agents on three.ws, each wearing its own avatar from its public record (five on a phone). The most popular one stands beside the gate path, turns to you as you walk in, waves and says hello through its own brain. Every agent idles, wanders a step, faces you when you come near and carries a name tag; walk up (or tap the tag) and press E to open a conversation that streams the agent's real reply, shows it as a speech bubble and can read it aloud. The panel opens the agent's profile as a window and hands you the one-tag embed that puts that exact agent, body and brain, on any web page. GET /api/agents/public now returns avatar_model_url for public and unlisted avatars.",+ "link": "/?world=1",+ "tags": [+ "feature",+ "desktop"+ ]+ },{"date": "2026-10-11","type": "update",@@ -261,6 +282,16 @@"desktop"]},+ {+ "date": "2026-10-11",+ "type": "update",+ "title": "The homepage is now the Field: one live map of every agent, launch and wallet move",+ "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.",+ "link": "/",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-11","type": "update",@@ -1512,37 +1543,6 @@"tags": ["fix"]- },- {- "date": "2026-10-09",- "type": "update",- "title": "The Crawl: watch agents read the web, and send yours out",- "summary": "A new page where three.ws agents read the open web in real browsers while you watch. Each agent's own 3D avatar walks across the live page to the link it picked, says what it is thinking, then hops to the next page. Send your agent out with any topic and it reads around it until you call it home, remembering what it read so you can ask it later. Every page lands in an open corpus you can browse or download.",- "link": "/crawl",- "tags": [- "feature"- ]- },- {- "date": "2026-10-09",- "type": "update",- "title": "The desktop companion, CLI and MCP server now work with just the bridge token",- "summary": "The companion bridge token is the one credential the desktop app, the companion command line and its MCP server are given, but the feed, marking a message as spoken, replying, reading contacts and checking sources all refused it, so pasting the token into the desktop app said it was wrong and an agent asking what you had heard got turned away. Those calls now accept the bridge token and only ever show the messages and contacts of the person it belongs to. It still cannot connect sources, edit contacts, change settings or rotate itself; those stay behind your signed-in account, and they now say so plainly instead of answering as if the token were wrong.",- "link": "/companion",- "tags": [- "fix"- ]- },- {- "date": "2026-10-09",- "type": "update",- "title": "The iPhone app is ready for TestFlight",- "summary": "The three.ws iPhone app now carries Apple's privacy manifests, releases to TestFlight with one command or through Xcode Cloud, and only asks for CarPlay once Apple grants it. Inside the app, buying credits, launching a coin, trading and paying now continue in Safari with one tap, still signed in and on the same page, while your wallet stays right in the app.",- "link": null,- "tags": [- "feature",- "improvement"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex 556be80ba..664ee8775 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-11T06:41:38.424Z",+ "generated_at": "2026-10-11T06:55:55.574Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -86,6 +86,16 @@"launch"]},+ {+ "date": "2026-10-11",+ "type": "launch",+ "title": "The Field",+ "summary": "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.",+ "link": "/docs/field",+ "tags": [+ "launch"+ ]+ },{"date": "2026-10-11","type": "launch",@@ -247,6 +257,17 @@"feature"]},+ {+ "date": "2026-10-11",+ "type": "update",+ "title": "Real agents live on the campus: a greeter meets you at the gate and every agent you walk up to talks back",+ "summary": "The campus is now populated by the ten most talked-to public agents on three.ws, each wearing its own avatar from its public record (five on a phone). The most popular one stands beside the gate path, turns to you as you walk in, waves and says hello through its own brain. Every agent idles, wanders a step, faces you when you come near and carries a name tag; walk up (or tap the tag) and press E to open a conversation that streams the agent's real reply, shows it as a speech bubble and can read it aloud. The panel opens the agent's profile as a window and hands you the one-tag embed that puts that exact agent, body and brain, on any web page. GET /api/agents/public now returns avatar_model_url for public and unlisted avatars.",+ "link": "/?world=1",+ "tags": [+ "feature",+ "desktop"+ ]+ },{"date": "2026-10-11","type": "update",@@ -258,6 +279,16 @@"desktop"]},+ {+ "date": "2026-10-11",+ "type": "update",+ "title": "The homepage is now the Field: one live map of every agent, launch and wallet move",+ "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.",+ "link": "/",+ "tags": [+ "feature"+ ]+ },{"date": "2026-10-11","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 5da274cce..7c64a0d13 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -70,6 +70,14 @@<category>launch</category><description>Every 3D Studio generation writes down what each stage was expected to do, what it actually did, and the verdict, with the cause whenever a stage fell back or missed. Signed with ed25519, public, and verifiable offline. Aggregate stage-by-stage rates here, one receipt per run at /runs/<id>.</description></item>+ <item>+ <title>The Field</title>+ <link>https://three.ws/docs/field</link>+ <guid isPermaLink="false">2026-10-11:The Field</guid>+ <pubDate>Sun, 11 Oct 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <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.</description>+ </item><item><title>three.ws Desktop</title><link>https://three.ws/apps/desktop</link>@@ -198,6 +206,14 @@<category>feature</category><description>Click the three.ws icon in your menu bar or tray and a small panel shows your agent alive in 3D, its Solana wallet balance, a start and stop button, anything waiting on your approval, unread alerts and a box to ask the agent something. Approvals still open the native confirmation window, so what you approve is exactly what you were shown.</description></item>+ <item>+ <title>Real agents live on the campus: a greeter meets you at the gate and every agent you walk up to talks back</title>+ <link>https://three.ws/?world=1</link>+ <guid isPermaLink="false">2026-10-11:Real agents live on the campus: a greeter meets you at the gate and every agent you walk up to talks back</guid>+ <pubDate>Sun, 11 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The campus is now populated by the ten most talked-to public agents on three.ws, each wearing its own avatar from its public record (five on a phone). The most popular one stands beside the gate path, turns to you as you walk in, waves and says hello through its own brain. Every agent idles, wanders a step, faces you when you come near and carries a name tag; walk up (or tap the tag) and press E to open a conversation that streams the agent's real reply, shows it as a speech bubble and can read it aloud. The panel opens the agent's profile as a window and hands you the one-tag embed that puts that exact agent, body and brain, on any web page. GET /api/agents/public now returns avatar_model_url for public and unlisted avatars.</description>+ </item><item><title>The desktop behaves like a real computer</title><link>https://three.ws/docs/desktop</link>@@ -206,6 +222,14 @@<category>feature</category><description>Drag a selection box across the desktop, move icons on a snap grid, right-click for view options, and open every app from desktop icons or All Apps. Settings now covers your profile, theme, accent colour, wallpaper (including your own photo), icon size and taskbar, and the whole session (windows, icon layout, preferences) is saved in your browser, with export, import and reset.</description></item>+ <item>+ <title>The homepage is now the Field: one live map of every agent, launch and wallet move</title>+ <link>https://three.ws/</link>+ <guid isPermaLink="false">2026-10-11:The homepage is now the Field: one live map of every agent, launch and wallet move</guid>+ <pubDate>Sun, 11 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>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.</description>+ </item><item><title>The prompt director works again, found by its own run receipts</title><link>https://three.ws/runs</link>diff --git a/public/features.json b/public/features.jsonindex 18f08008f..b20e763c7 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-11T06:11:43.262Z",+ "generated_at": "2026-10-11T06:55:55.560Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -6259,6 +6259,18 @@"priority": 0.5,"job": null},+ {+ "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.",+ "added": "2026-10-11",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false,+ "priority": 0.5,+ "job": null+ },{"path": "/docs/event-markets","title": "Docs · Event Markets",diff --git a/public/llms-full.txt b/public/llms-full.txtindex fe3ff3059..114e7186f 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -3157,6 +3157,12 @@ URL: https://three.ws/docs/desktopHow the three.ws web desktop works: the CTRL Mica theme, taskbar and Start menu, snappable windows that frame real pages, deep links, saved layout, the classic view and how to add an app.+### The Field++URL: https://three.ws/docs/field++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.+### Docs · Event MarketsURL: https://three.ws/docs/event-marketsdiff --git a/public/llms.txt b/public/llms.txtindex 9e072c704..cc9ea6eb5 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -100,6 +100,6 @@ Machine-readable entry points. Fetch these instead of scraping HTML.## Optional-- [llms-full.txt](https://three.ws/llms-full.txt): Every public page (993), grouped by section, with full descriptions.+- [llms-full.txt](https://three.ws/llms-full.txt): Every public page (994), grouped by section, with full descriptions.- [Sitemap](https://three.ws/sitemap): The same index for people, with search.- [sitemap.xml](https://three.ws/sitemap.xml): XML sitemap for crawlers, including every agent and avatar page.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex aad7d0821..08562b1b6 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -96,7 +96,7 @@<main class="sm-wrap"><div class="sm-hero"><h1 data-i18n="sitemap_index.sitemap">Sitemap</h1>- <p><span>1052</span> <span data-i18n="sitemap_index.pages_grouped">pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</span></p>+ <p><span>1053</span> <span data-i18n="sitemap_index.pages_grouped">pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</span></p><div class="sm-formats"><a href="/everything" data-i18n-html="sitemap_index.browse_by_goal_not_by_section"><code>/everything</code> · browse by goal, not by section</a><a href="/sitemap.xml" data-i18n-html="sitemap_index.for_search_engines"><code>sitemap.xml</code> · for search engines</a>@@ -109,7 +109,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 1052 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 1053 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd id="sm-filter-kbd" aria-hidden="true">/</kbd></div><p class="sm-filter-count" role="status" aria-live="polite"><span id="sm-filter-count"></span><span id="sm-filter-hint" aria-hidden="true"></span></p>@@ -2955,7 +2955,7 @@<section class="sm-section" id="learn"><header>- <h2><span data-i18n="sitemap_index.section_learn">Learn</span><span class="sm-count" data-count>489</span></h2>+ <h2><span data-i18n="sitemap_index.section_learn">Learn</span><span class="sm-count" data-count>490</span></h2><p class="sm-section-desc" data-i18n="sitemap_index.docs_tutorials_and_reference">Docs, tutorials, and reference.</p></header><ul class="sm-list">@@ -3827,6 +3827,13 @@<span class="sm-desc" data-i18n="sitemap_index.d_docs_desktop">How the three.ws web desktop works: the CTRL Mica theme, taskbar and Start menu, snappable windows that frame real pages, deep links, saved layout, the classic view and how to add an app.</span></a></li>+ <li>+ <a href="/docs/field">+ <span class="sm-title"><span data-i18n="sitemap_index.t_docs_field">The Field</span></span>+ <span class="sm-path" translate="no">/docs/field</span>+ <span class="sm-desc" data-i18n="sitemap_index.d_docs_field">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.</span>+ </a>+ </li><li><a href="/docs/event-markets"><span class="sm-title"><span data-i18n="sitemap_index.t_docs_event_markets">Docs · Event Markets</span></span>diff --git a/scripts/desktop-world-smoke.mjs b/scripts/desktop-world-smoke.mjsindex e232d5571..5956df2a2 100644--- a/scripts/desktop-world-smoke.mjs+++ b/scripts/desktop-world-smoke.mjs@@ -1,7 +1,8 @@// Drives the homepage arrival in a real browser: boot log, lock screen, walking-// in as the avatar, sitting down at the desk, coming back out, teleporting to-// the exchange, picking up the phone, and the phone-sized layout. Reports-// console errors and failed requests.+// in as the avatar, meeting the agents who live on the campus and talking to+// one through its real brain, sitting down at the desk, coming back out,+// teleporting to the exchange, picking up the phone, and the phone-sized+// layout. Reports console errors and failed requests.// Usage: node scripts/desktop-world-smoke.mjs [baseUrl] [screenshotDir]import { chromium } from 'playwright';@@ -17,7 +18,8 @@ page.on('response', (r) => r.status() >= 500 && problems.push(`http ${r.status()const shot = (n) => shots && page.screenshot({ path: `${shots}/${n}.png` });const text = (sel) => page.locator(sel).first().textContent().then((t) => (t || '').trim());-await page.goto(`${base}/`, { waitUntil: 'domcontentloaded' });+// `?world=1` asks for the campus arrival whichever entry answers at `/`.+await page.goto(`${base}/?world=1`, { waitUntil: 'domcontentloaded' });await page.waitForSelector('.os-boot');await page.waitForSelector('.os-lock:not([hidden])', { timeout: 60_000 });const lines = await page.$$eval('.os-boot-log li', (els) => els.map((li) => `${li.dataset.state.padEnd(5)} ${li.querySelector('.os-boot-label').textContent} : ${li.querySelector('.os-boot-detail').textContent} ${li.querySelector('.os-boot-ms').textContent}`));@@ -37,6 +39,35 @@ console.log('world HUD where:', await text('.wd-where'), '| camera:', await textconsole.log('places in strip:', await page.locator('.wd-place').count(), '| VR button hidden:', await page.locator('.wd-vr[hidden]').count());await shot('2-world-spawn');+// The agents come out: real registered agents wearing their own bodies.+await page.waitForSelector('.wd-tag', { timeout: 90_000 }).catch(() => {});+await page.waitForTimeout(1500);+const tags = await page.$$eval('.wd-tag', (els) => els.map((e) => e.querySelector('b').textContent.trim()));+console.log('agents on campus:', tags.length, '|', tags.join(', '));+if (tags.length) {+ // Walk over to the first agent by tapping its name tag, then press E to talk.+ await page.locator('.wd-tag').first().click({ force: true });+ await page.waitForFunction(() => /talk to/i.test(document.querySelector('.wd-prompt')?.textContent || ''), null, { timeout: 8000 }).catch(() => {});+ console.log('prompt at agent:', await text('.wd-prompt'));+ await page.waitForFunction(() => document.querySelector('.wd-bubble:not([hidden])'), null, { timeout: 25_000 }).catch(() => {});+ console.log('greeting bubble:', (await page.locator('.wd-bubble:not([hidden])').first().textContent().catch(() => '')).trim().slice(0, 160) || '(none yet)');+ await shot('2b-meet-agent');+ await page.keyboard.press('e');+ await page.waitForSelector('.wd-talk:not([hidden])', { timeout: 5000 });+ console.log('talk panel:', await text('.wd-talk-name'), '|', await text('.wd-talk-meta'), '|', (await text('.wd-talk-about')).slice(0, 80));+ await page.fill('.wd-talk-input', 'In one sentence, what do you do?');+ await page.keyboard.press('Enter');+ await page.waitForFunction(() => { const li = document.querySelector('.wd-talk-them'); return li && !li.classList.contains('is-thinking') && li.textContent.trim().length > 0; }, null, { timeout: 45_000 }).catch(() => {});+ console.log('agent reply:', (await page.locator('.wd-talk-them, .wd-talk-note').last().textContent()).trim().slice(0, 200));+ await page.click('.wd-talk-embed');+ console.log('embed snippet:', (await text('.wd-talk-snippet pre')).split('\n')[1]?.slice(0, 80));+ await shot('2c-talk');+ await page.keyboard.press('Escape');+ await page.waitForSelector('.wd-talk', { state: 'hidden', timeout: 3000 });+ await page.click('.wd-place:has-text("workstation")');+ await page.waitForTimeout(500);+}+// Run to the desk (22 m at run speed) and watch the prompt arm.await page.mouse.click(720, 450);await page.keyboard.down('Shift');@@ -50,7 +81,8 @@ await shot('3-at-desk');// Sit down: camera dolly into the monitor, then the desktop.await page.keyboard.press('e');-await page.waitForSelector('html:not(.in-world)', { timeout: 20_000 });+// 60 s: under SwiftShader the cast drops the loop to ~3 fps and the 1.15 s dolly takes ~20 s.+ await page.waitForSelector('html:not(.in-world)', { timeout: 60_000 });await page.waitForSelector('.os-task');await page.waitForTimeout(800);console.log('desktop wallpaper:', await page.getAttribute('.os', 'data-wall'), '| welcome window:', await page.locator('.win[data-app=welcome]').count(), '| world button:', await page.locator('.os-tray .os-tb[title="Walk the campus"]:not([hidden])').count());@@ -65,7 +97,8 @@ await page.waitForFunction(() => /exchange/i.test(document.querySelector('.wd-prconsole.log('prompt at exchange:', await text('.wd-prompt'), '| ticker boards drawn:', await page.evaluate(() => !!document.querySelector('.wd-canvas')));await shot('5-exchange');await page.keyboard.press('e');-await page.waitForSelector('html:not(.in-world)', { timeout: 20_000 });+// 60 s: under SwiftShader the cast drops the loop to ~3 fps and the 1.15 s dolly takes ~20 s.+ await page.waitForSelector('html:not(.in-world)', { timeout: 60_000 });await page.waitForSelector('.win[data-app=trenches]', { timeout: 20_000 });console.log('trenches window open:', await page.locator('.win[data-app=trenches]').count());await shot('6-trenches');diff --git a/src/desktop/README.md b/src/desktop/README.mdindex 0f4c5843b..cf59e2372 100644--- a/src/desktop/README.md+++ b/src/desktop/README.md@@ -17,8 +17,11 @@ The web desktop served at `/` (page: `pages/desktop.html`). See| `world/index.js` | The campus controller: mounts the 3D world over the desktop, input, proximity prompts, sit-down and walk-in transitions, the phone, the VR headset, mining, the frame loop || `world/campus.js` | The scene: ground, office desk, exchange, launchpad, mine, forge, gallery, plaza, market, lighting || `world/places.js` | Pure campus map: places, keep-outs, veins, desk objects, trigger radii, stand points (unit tested) |+| `world/cast.js` | Pure rules for the agents on the campus: who qualifies (real name, public GLB), where they stand, prompt distances, the SSE parser, the embed snippet and the grounding prompt (unit tested) |+| `world/agents.js` | Spawns the cast from `/api/agents/public?avatar=1`, each in its own body: wander, notice and face the visitor, the greeter's wave and hello, name tags and speech bubbles, the streaming `/api/chat` client |+| `world/talk.js` | The conversation panel: streamed replies, read-aloud through `/api/tts/speak`, the profile window and the one-tag `<agent-3d>` embed || `world/screen.js` | The desk monitor that shows the live desktop and the sit-down camera move || `world/ticker.js` | The exchange ticker board fed by `/api/three-token/stats` and `/api/coin/markets` (unit tested) || `world/mine.js` | Gem mining client over `/api/world/gems` (server-rolled gems, anonymous id that adopts onto the account) || `world/xr.js` | WebXR session entry for the headset |-| `world/world.css` | HUD, prompts, phone overlay, gem panel, touch controls |+| `world/world.css` | HUD, prompts, phone overlay, gem panel, touch controls, agent name tags and the talk panel |diff --git a/src/desktop/world/agents.js b/src/desktop/world/agents.jsnew file mode 100644index 000000000..51f63cf7c--- /dev/null+++ b/src/desktop/world/agents.js@@ -0,0 +1,399 @@+// The agents who live on the campus: real registered three.ws agents, wearing+// their own public avatars, standing where cast.js seats them. Each one idles,+// takes a few steps now and then, turns to face a visitor who comes close, and+// can be spoken to (talk.js). The greeter at the gate waves and says hello+// through the agent's own /api/chat brain.+//+// Bodies come from the shared avatar rig (src/game/avatar-rig.js), so a model+// is downloaded once per distinct GLB and cloned, and gestures are the clip+// library every other three.ws scene uses.++import { Box3, Group, Vector3 } from 'three';+import { buildAvatar, CLIP_IDLE, CLIP_WALK, getAllEmoteDefs, loadManifest, newAnim, releaseAvatar } from '../../game/avatar-rig.js';+import { log } from '../../shared/log.js';+import { CAST_MAX, GREET_RANGE, arrivalMessage, castSpots, groundingPrompt, parseSse, pickCast, pickGreeter } from './cast.js';+import { PLACES, placeById } from './places.js';++const WALK_SPEED = 1.05;+const TURN_SPEED = 5;+const WANDER_RADIUS = 1.5;+const WANDER_PAUSE = [3, 7]; // seconds between strolls+const NOTICE_RANGE = 6; // an agent stops and faces a visitor this close+const BUBBLE_SECONDS = 7;+const GESTURE = { wave: 'wave', nod: 'nod', think: 'think' };++const rand = (a, b) => a + Math.random() * (b - a);+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const shortestTurn = (from, to) => Math.atan2(Math.sin(to - from), Math.cos(to - from));++/** Scale a loaded body to human height and seat its feet on the ground, as the player rig does. */+function fitBody(rig) {+ const model = rig.children.find((c) => !c.userData?.avatarStandIn);+ if (!model) return 1.7;+ const size = new Box3().setFromObject(model).getSize(new Vector3());+ if (size.y > 0 && (size.y < 1.2 || size.y > 2.4)) model.scale.multiplyScalar(1.7 / size.y);+ const fitted = new Box3().setFromObject(model);+ model.position.y -= fitted.min.y;+ return Math.min(2.4, Math.max(1.2, fitted.max.y - fitted.min.y));+}++/** Where a member stands in words, for the prompt and the grounding prompt. */+function placeLabel(spot) {+ if (spot.place === 'gate') return 'the gate path';+ const p = placeById(spot.place);+ return p ? p.title : 'the campus';+}++/**+ * @param {{+ * scene: import('three').Scene,+ * tagsEl: HTMLElement,+ * solids: Array<{group:{position:Vector3}, keepout:number}>,+ * isTouch: boolean,+ * reducedMotion: boolean,+ * visitorName: () => string,+ * onGreeting: (member: object, text: string) => void,+ * }} o+ */+export function createAgents({ scene, tagsEl, solids, isTouch, reducedMotion, visitorName, onGreeting }) {+ /** @type {Array<Member>} */+ const members = [];+ let greeter = null;+ let state = 'idle'; // idle | loading | ready | empty | error+ let error = '';+ let disposed = false;+ const listeners = new Set();+ const scratch = new Vector3();++ function emit() {+ for (const fn of listeners) fn({ state, error, count: members.length });+ }++ // ---- loading ----+ async function fetchCast(max) {+ const r = await fetch(`/api/agents/public?avatar=1&sort=popular&limit=${Math.max(24, max * 4)}`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(`The agent directory answered ${r.status}`);+ const data = await r.json();+ let list = Array.isArray(data.agents) ? data.agents : [];+ // A directory that predates the avatar_model_url field: hydrate the most+ // talked-to real agents from their profiles so the campus still fills.+ if (list.length && !list.some((a) => 'avatar_model_url' in a)) {+ const named = list.filter((a) => a.name && a.name.trim() && a.name.length <= 40).slice(0, max * 2);+ const hydrated = await Promise.all(named.map(async (a) => {+ try {+ const pr = await fetch(`/api/agents/${encodeURIComponent(a.id)}`, { headers: { accept: 'application/json' } });+ if (!pr.ok) return a;+ const { agent } = await pr.json();+ return { ...a, avatar_model_url: agent?.avatar_model_url || null, description: a.description || agent?.description || '' };+ } catch {+ return a;+ }+ }));+ list = hydrated;+ }+ return list;+ }++ async function load() {+ if (state === 'loading' || state === 'ready') return;+ state = 'loading';+ error = '';+ emit();+ const max = isTouch ? CAST_MAX.touch : CAST_MAX.desktop;+ let cast;+ try {+ cast = pickCast(await fetchCast(max), { max });+ } catch (err) {+ state = 'error';+ error = err?.message || 'The agent directory is unreachable';+ log.warn('[world] cast failed to load', error);+ emit();+ return;+ }+ if (disposed) return;+ if (!cast.length) {+ state = 'empty';+ emit();+ return;+ }+ greeter = pickGreeter(cast);+ // The greeter takes spot 0; everyone else fills the rest in order.+ const ordered = [greeter, ...cast.filter((m) => m !== greeter)];+ const spots = castSpots(ordered.length, PLACES);+ await loadManifest();+ await Promise.all(ordered.map((m, i) => spots[i] && spawn(m, spots[i])));+ if (disposed) return;+ state = 'ready';+ emit();+ }++ async function spawn(member, spot) {+ const rig = new Group();+ rig.position.set(spot.x, 0, spot.z);+ rig.rotation.y = spot.yaw;+ rig.userData.hit = { type: 'agent', id: member.id };+ scene.add(rig);+ const anim = newAnim();+ const tag = document.createElement('button');+ tag.type = 'button';+ tag.className = 'wd-tag';+ tag.dataset.agent = member.id;+ tag.innerHTML = `<b>${esc(member.name)}</b>${member.registered ? '<i class="wd-tag-reg" title="Registered on-chain"></i>' : ''}<span class="wd-bubble" hidden></span>`;+ tag.setAttribute('aria-label', `Talk to ${member.name}`);+ tagsEl.append(tag);+ const m = {+ member, spot, rig, anim, tag,+ bubble: tag.querySelector('.wd-bubble'),+ height: 1.7,+ home: new Vector3(spot.x, 0, spot.z),+ target: null,+ wait: rand(...WANDER_PAUSE),+ held: false,+ facing: null,+ noticed: false,+ bubbleT: 0,+ greeted: false,+ greeting: null,+ ready: false,+ gesturing: false,+ place: placeLabel(spot),+ };+ members.push(m);+ const res = await buildAvatar(rig, member.glb, anim, { clips: 'locomotion' });+ if (disposed) return;+ if (res.fallback) log.info('[world] agent wore the default body', member.name);+ m.height = fitBody(rig);+ anim.appendAnimationDefs(getAllEmoteDefs());+ rig.traverse((o) => { if (o !== rig && !o.userData.hit) o.userData.hit = rig.userData.hit; });+ m.ready = true;+ }++ // ---- behaviour ----+ function blocked(x, z) {+ for (const s of solids) if (Math.hypot(x - s.group.position.x, z - s.group.position.z) < s.keepout + 0.6) return true;+ return false;+ }+ function pickStroll(m) {+ for (let i = 0; i < 6; i++) {+ const a = Math.random() * Math.PI * 2;+ const r = rand(0.6, WANDER_RADIUS);+ const x = m.home.x + Math.sin(a) * r;+ const z = m.home.z + Math.cos(a) * r;+ if (!blocked(x, z)) return new Vector3(x, 0, z);+ }+ return null;+ }++ function face(m, yaw, dt) {+ const d = shortestTurn(m.rig.rotation.y, yaw);+ const step = Math.min(Math.abs(d), TURN_SPEED * dt);+ m.rig.rotation.y += Math.sign(d) * step;+ }++ function update(dt, playerPos, camera) {+ for (const m of members) {+ if (!m.ready) continue;+ const dx = playerPos.x - m.rig.position.x;+ const dz = playerPos.z - m.rig.position.z;+ const dist = Math.hypot(dx, dz);+ const toPlayer = Math.atan2(dx, dz);+ const near = dist < NOTICE_RANGE;+ if (near && !m.noticed) {+ m.noticed = true;+ m.target = null;+ if (m !== greeterMember() && !reducedMotion) gesture(m, GESTURE.nod);+ } else if (!near && m.noticed && dist > NOTICE_RANGE + 2) {+ m.noticed = false;+ m.greeted = false;+ }+ if (m === greeterMember() && dist < GREET_RANGE && !m.greeted) {+ m.greeted = true;+ greet(m);+ }+ if (m.held || near) {+ // Stand still and look at the visitor.+ face(m, toPlayer, dt);+ if (m.anim.currentName === CLIP_WALK) m.anim.crossfadeTo(CLIP_IDLE, 0.25);+ } else if (m.target) {+ const tx = m.target.x - m.rig.position.x;+ const tz = m.target.z - m.rig.position.z;+ const td = Math.hypot(tx, tz);+ if (td < 0.12) {+ m.target = null;+ m.wait = rand(...WANDER_PAUSE);+ m.anim.crossfadeTo(CLIP_IDLE, 0.3);+ } else {+ face(m, Math.atan2(tx, tz), dt);+ const step = Math.min(td, WALK_SPEED * dt);+ m.rig.position.x += (tx / td) * step;+ m.rig.position.z += (tz / td) * step;+ if (m.anim.currentName !== CLIP_WALK && !m.gesturing) m.anim.crossfadeTo(CLIP_WALK, 0.3);+ }+ } else if (!reducedMotion) {+ m.wait -= dt;+ if (m.wait <= 0) {+ m.target = pickStroll(m);+ if (!m.target) m.wait = rand(...WANDER_PAUSE);+ }+ // Drift back toward the seated facing while idle.+ face(m, m.spot.yaw, dt * 0.4);+ }+ m.anim.update(dt);+ if (m.bubbleT > 0) {+ m.bubbleT -= dt;+ if (m.bubbleT <= 0) m.bubble.hidden = true;+ }+ paintTag(m, camera, dist);+ }+ }++ function paintTag(m, camera, dist) {+ scratch.set(m.rig.position.x, m.height + 0.25, m.rig.position.z).project(camera);+ const onScreen = scratch.z < 1 && Math.abs(scratch.x) < 1.1 && Math.abs(scratch.y) < 1.1 && dist < 28;+ m.tag.hidden = !onScreen;+ if (!onScreen) return;+ const x = (scratch.x * 0.5 + 0.5) * innerWidth;+ const y = (-scratch.y * 0.5 + 0.5) * innerHeight;+ m.tag.style.transform = `translate(-50%, -100%) translate(${x.toFixed(1)}px, ${y.toFixed(1)}px)`;+ m.tag.classList.toggle('is-near', dist < NOTICE_RANGE);+ m.tag.classList.toggle('is-far', dist > 16);+ }++ function greeterMember() {+ return greeter ? members.find((m) => m.member === greeter) || null : null;+ }++ /** Play a one-shot clip and settle back to idle; the mixer, not a timer, ends it. */+ async function gesture(m, name) {+ if (!m?.ready || m.gesturing) return;+ m.gesturing = true;+ try {+ await m.anim.playOnce(name, { settleTo: CLIP_IDLE, fade: 0.3 });+ } finally {+ m.gesturing = false;+ }+ }++ /** Show a line over an agent's head. */+ function say(m, text) {+ if (!m) return;+ m.bubble.textContent = text;+ m.bubble.hidden = false;+ m.bubbleT = BUBBLE_SECONDS + Math.min(8, text.length / 25);+ }++ /** The greeter waves and asks its own brain for a welcome, grounded in its public record. */+ async function greet(m) {+ if (!reducedMotion) gesture(m, GESTURE.wave);+ if (m.greeting) return;+ m.greeting = streamReply(m.member, arrivalMessage(visitorName() === 'Guest' ? '' : visitorName()), [], { place: m.place })+ .then((text) => {+ if (disposed || !text) return;+ say(m, text);+ onGreeting?.(m.member, text);+ })+ .catch((err) => log.warn('[world] greeting failed', err?.message))+ .finally(() => { m.greeting = null; });+ }++ // ---- speech ----+ /**+ * Stream one reply from an agent's own brain. Resolves with the full text;+ * `onChunk` receives the text so far as it arrives.+ * @returns {Promise<string>}+ */+ async function streamReply(member, message, history, { place, onChunk, signal } = {}) {+ const r = await fetch('/api/chat', {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },+ signal,+ body: JSON.stringify({+ message,+ history: history.slice(-20),+ agentId: member.id,+ system_prompt: groundingPrompt(member, { place }),+ context: { modelName: member.name, currentEnvironment: `three.ws campus, ${place}`.slice(0, 80) },+ }),+ });+ if (r.status === 429) {+ const e = new Error('You are talking faster than the campus allows. Give it a minute.');+ e.code = 'rate_limited';+ throw e;+ }+ if (!r.ok) {+ let detail = '';+ try {+ const j = await r.json();+ detail = j.error_description || j.message || '';+ } catch { /* no body */ }+ if (r.status === 401) detail = `Sign in to talk to ${member.name} here.`;+ throw new Error(detail || `${member.name} could not answer (${r.status}).`);+ }+ const ctype = r.headers.get('content-type') || '';+ if (!ctype.includes('text/event-stream')) {+ const data = await r.json();+ const text = String(data.reply || data.text || '').trim();+ onChunk?.(text);+ return text;+ }+ const reader = r.body.getReader();+ const dec = new TextDecoder();+ let buf = '';+ let text = '';+ let done = null;+ for (;;) {+ const { value, done: end } = await reader.read();+ if (end) break;+ buf += dec.decode(value, { stream: true });+ const parsed = parseSse(buf);+ buf = parsed.rest;+ for (const ev of parsed.events) {+ if (ev.type === 'chunk' && ev.text) {+ text += ev.text;+ onChunk?.(text);+ } else if (ev.type === 'done') done = ev;+ else if (ev.type === 'error') throw new Error(ev.message || `${member.name} could not answer.`);+ }+ }+ return (done?.reply || text).trim();+ }++ // ---- queries ----+ function positions() {+ return members.filter((m) => m.ready).map((m) => ({ id: m.member.id, name: m.member.name, sub: m.member.description ? m.member.description.slice(0, 72) : 'A registered three.ws agent', x: m.rig.position.x, z: m.rig.position.z }));+ }+ function byId(id) {+ return members.find((m) => m.member.id === id) || null;+ }+ function hold(id, on) {+ const m = byId(id);+ if (m) m.held = on;+ }++ function dispose() {+ disposed = true;+ for (const m of members) {+ releaseAvatar(m.rig);+ m.anim.dispose?.();+ scene.remove(m.rig);+ m.tag.remove();+ }+ members.length = 0;+ }++ return {+ load,+ update,+ positions,+ byId,+ hold,+ say: (id, text) => say(byId(id), text),+ gesture: (id, name) => gesture(byId(id), GESTURE[name] || name),+ streamReply,+ onState: (fn) => { listeners.add(fn); return () => listeners.delete(fn); },+ get state() { return state; },+ get error() { return error; },+ get greeter() { return greeter; },+ dispose,+ };+}diff --git a/src/desktop/world/campus.js b/src/desktop/world/campus.jsindex 4602686af..ef2b33744 100644--- a/src/desktop/world/campus.js+++ b/src/desktop/world/campus.js@@ -471,18 +471,8 @@ function buildPlaza(place) {base.position.y = 0.2;base.userData.hit = { type: 'place', id: place.id };g.add(base);- const figures = [];- for (let i = 0; i < 7; i++) {- const a = (i / 7) * Math.PI * 2;- const fig = new Mesh(new CylinderGeometry(0.22, 0.26, 1.5, 10), std({ color: 0x1f1f26, emissive: hueColor(place.hue + i * 30, 0.5), emissiveIntensity: 0.4 }));- fig.position.set(Math.cos(a) * 2.4, 1.15, Math.sin(a) * 2.4);- const head = new Mesh(new OctahedronGeometry(0.22, 1), std({ color: 0xeeeef4 }));- head.position.set(Math.cos(a) * 2.4, 2.15, Math.sin(a) * 2.4);- fig.userData.hit = base.userData.hit;- head.userData.hit = base.userData.hit;- g.add(fig, head);- figures.push(head);- }+ // The plaza is a stage, not a diorama: the real agents (agents.js) stand+ // around it, so nothing abstract is built here to stand in for them.const beacon = new Mesh(new CylinderGeometry(0.1, 0.1, 4.5, 8), glow(col, 1.2));beacon.position.y = 2.6;g.add(beacon);@@ -491,7 +481,7 @@ function buildPlaza(place) {g.add(sign);g.position.set(place.x, 0, place.z);g.rotation.y = facing(place);- return { group: g, figures };+ return { group: g };}function buildMarket(place) {@@ -581,7 +571,7 @@ export function createCampus(canvas, { screenMaterial, tickerMaterial, reducedMotip.position.set(sx, 5.55, 33);scene.add(pylon, tip);}- const gateSign = makeLabelSprite('Welcome to three.ws', 'Walk to your desk, or explore', '#c4b5fd', 1.1);+ const gateSign = makeLabelSprite('Welcome to three.ws', 'The 3D agent layer of the internet', '#c4b5fd', 1.1);gateSign.position.set(0, 6.4, 33);scene.add(gateSign);@@ -606,7 +596,8 @@ export function createCampus(canvas, { screenMaterial, tickerMaterial, reducedMosolids.push({ group: { position: new Vector3(m.x - 5.2, 0, m.z - 3) }, keepout: 2.6 }, { group: { position: new Vector3(m.x + 5.2, 0, m.z - 3) }, keepout: 2.6 });for (const v of mine.veins) solids.push({ group: { position: new Vector3(v.x, 0, v.z) }, keepout: 0.75 });- // Highlight: the nearest interactable gets a soft ring under it.+ // Highlight: the nearest interactable gets a soft ring under it (an agent's+ // ring follows the agent, so the caller passes its current x/z).const halo = new Mesh(new RingGeometry(0.9, 1.1, 40), new MeshBasicMaterial({ color: VIOLET, transparent: true, opacity: 0.7, toneMapped: false }));halo.rotation.x = -Math.PI / 2;halo.position.y = 0.03;@@ -636,6 +627,8 @@ export function createCampus(canvas, { screenMaterial, tickerMaterial, reducedMox = p.x;z = p.z;r = p.keepout + 0.6;+ } else if (target.type === 'agent') {+ r = 0.75;}halo.position.x = x;halo.position.z = z;@@ -670,7 +663,6 @@ export function createCampus(canvas, { screenMaterial, tickerMaterial, reducedMov.light.intensity = 0.4 + k;}for (const f of gallery.frames) f.rotation.y += dt * 0.25;- for (const h of plaza.figures) h.rotation.y += dt * 0.6;halo.material.opacity = 0.55 + Math.sin(t * 4) * 0.2;}diff --git a/src/desktop/world/cast.js b/src/desktop/world/cast.jsnew file mode 100644index 000000000..387ae47ec--- /dev/null+++ b/src/desktop/world/cast.js@@ -0,0 +1,219 @@+// The cast: which real agents stand in the campus, where they stand, and how a+// conversation with one is grounded. Pure data and rules, no DOM and no+// Three.js, so tests can pin every decision. agents.js spawns the bodies and+// talk.js runs the conversation panel.+//+// Nothing here is invented. Every member comes from GET /api/agents/public+// (a published, public agent whose avatar GLB is publicly readable), speaks+// through POST /api/chat with its own id (so its published persona answers),+// and is introduced by the name, description and skills on its public record.++import { facingOf, SPAWN } from './places.js';++/** Distance at which an agent takes the prompt ("Talk to <name>"). */+export const AGENT_TRIGGER = 2.6;+/** Where a tap on an agent puts the visitor: inside AGENT_TRIGGER, not in their face. */+export const APPROACH_DISTANCE = 1.7;+/** Distance at which the greeter notices the visitor, turns and waves. */+export const GREET_RANGE = 4.5;+/** How many members the campus seats on a desktop and on a phone. */+export const CAST_MAX = { desktop: 10, touch: 5 };+/** The published library build the embed snippet pins (docs/embedding.md). */+export const EMBED_VERSION = '1.5.2';++// The onboarding defaults an untouched agent still wears (mirrors+// PLACEHOLDER_NAMES in api/agents/public.js, which keeps the same rows off the+// live agent wall, and the citizen rule in src/game/npc/citizens.js). A body+// wearing one of these has told us nothing about who it is, so the campus+// does not introduce it by that name.+const PLACEHOLDER_NAMES = new Set([+ 'my first agent', 'agent', 'avatar', 'my avatar', 'my agent',+ 'untitled agent', 'new agent', 'untitled', 'character', 'model',+]);++// The onboarding bio an untouched agent still carries (same rule as+// src/game/npc/citizens.js). It says nothing about the agent, so the campus+// treats it as no description at all.+const BOILERPLATE_BIO = /^(a friendly starter agent|operated by a three\.ws agent|edit the personality)/i;++function looksAnonymous(name) {+ const n = name.toLowerCase();+ if (PLACEHOLDER_NAMES.has(n)) return true;+ if (/^avatar[\s#_-]/.test(n)) return true;+ if (/^model\s*[({[]?\d+/.test(n)) return true;+ if (/_(merged|meshy|biped|animations)/i.test(name)) return true;+ if (/^selfie avatar/i.test(name)) return true;+ if (name.length > 40) return true;+ return false;+}++/** A public agent record can join the cast when it has a real name and a public body. */+export function isCastable(a) {+ if (!a || typeof a !== 'object') return false;+ const name = String(a.name || '').trim();+ if (!name || looksAnonymous(name)) return false;+ return typeof a.avatar_model_url === 'string' && /^https?:\/\/|^\//.test(a.avatar_model_url);+}++/** Reduce a public agent record to what the world renders and says. */+export function toCastMember(a) {+ const id = String(a.id);+ const description = String(a.description || '').trim();+ return {+ id,+ name: String(a.name || '').trim(),+ description: BOILERPLATE_BIO.test(description) ? '' : description,+ skills: (Array.isArray(a.skills) ? a.skills : []).map((s) => (typeof s === 'string' ? s : s?.name)).filter(Boolean),+ glb: a.avatar_model_url || null,+ thumb: a.avatar_thumbnail || a.avatar_thumbnail_url || null,+ home: a.home_url || `/agents/${id}`,+ chats: Number(a.chat_count) || 0,+ registered: !!a.is_registered,+ onchain: a.onchain || null,+ };+}++/**+ * Choose the cast from a public agent listing: the most talked-to real agents+ * first, each distinct body before any repeat of one, capped at `max`.+ */+export function pickCast(agents, { max }) {+ const pool = (Array.isArray(agents) ? agents : []).filter(isCastable).map(toCastMember);+ pool.sort((a, b) => b.chats - a.chats || a.name.localeCompare(b.name));+ const seenBody = new Set();+ const seenId = new Set();+ const firsts = [];+ const repeats = [];+ for (const m of pool) {+ if (seenId.has(m.id)) continue;+ seenId.add(m.id);+ if (seenBody.has(m.glb)) repeats.push(m);+ else {+ seenBody.add(m.glb);+ firsts.push(m);+ }+ }+ return [...firsts, ...repeats].slice(0, Math.max(0, max | 0));+}++/** The member who greets visitors at the gate: most talked-to, with a description to introduce. */+export function pickGreeter(cast) {+ if (!Array.isArray(cast) || !cast.length) return null;+ return cast.find((m) => m.description) || cast[0];+}++/**+ * Where the cast stands. Deterministic, so the same agents stand in the same+ * spots on every visit: the greeter beside the gate path, a gathering on the+ * campus side of Agent Plaza, a couple along the path, one in front of each+ * other building. Every spot is outside every keep-out.+ * @returns {Array<{x:number, z:number, yaw:number, role:'greeter'|'plaza'|'path'|'front', place:string}>}+ */+export function castSpots(n, places) {+ const by = (id) => places.find((p) => p.id === id);+ const toward = (x, z, tx, tz) => Math.atan2(tx - x, tz - z);+ const spots = [];+ // 1. The greeter, just off the path from the gate to the desk, facing the gate.+ spots.push({ x: 3.4, z: 24, yaw: toward(3.4, 24, SPAWN.x, SPAWN.z), role: 'greeter', place: 'gate' });+ // 2. Agent Plaza: a loose semicircle on the side visitors arrive from, facing the beacon.+ const plaza = by('agents');+ if (plaza) {+ const a0 = facingOf(plaza);+ const r = plaza.keepout + 1.8;+ for (const off of [-0.35, 0.35, -1.0, 1.0, -1.6, 1.6]) {+ const a = a0 + off;+ const x = plaza.x + Math.sin(a) * r;+ const z = plaza.z + Math.cos(a) * r;+ spots.push({ x, z, yaw: toward(x, z, plaza.x, plaza.z), role: 'plaza', place: plaza.id });+ }+ }+ // 3. Two more along the gate path, facing the campus centre.+ for (const [x, z] of [[-3.4, 18], [3.4, 15]]) spots.push({ x, z, yaw: toward(x, z, 0, 0), role: 'path', place: 'gate' });+ // 4. One in front of each other building, a step to the side of its doorstep.+ for (const [id, side] of [['exchange', 1], ['market', -1], ['launchpad', 1], ['gallery', -1], ['forge', 1]]) {+ const p = by(id);+ if (!p) continue;+ const a = facingOf(p) + side * 0.55;+ const r = p.keepout + 3.6;+ const x = p.x + Math.sin(a) * r;+ const z = p.z + Math.cos(a) * r;+ spots.push({ x, z, yaw: toward(x, z, 0, 0), role: 'front', place: p.id });+ }+ return spots.slice(0, Math.max(0, n | 0));+}++/**+ * The agent within reach, as a prompt target.+ * @param {Array<{id:string, name:string, sub:string, x:number, z:number}>} agents+ */+export function nearestAgent(px, pz, agents) {+ let best = null;+ for (const a of agents || []) {+ const d = Math.hypot(px - a.x, pz - a.z);+ if (d < AGENT_TRIGGER && (!best || d < best.d)) best = { type: 'agent', id: a.id, title: `Talk to ${a.name}`, sub: a.sub || '', d, x: a.x, z: a.z };+ }+ return best;+}++/**+ * Split a server-sent-events buffer into parsed `data:` JSON events, keeping+ * the unfinished tail for the next read. Comments, non-JSON data and empty+ * frames are dropped. Matches the /api/chat frame format.+ */+export function parseSse(buffer) {+ const events = [];+ let rest = String(buffer || '');+ let sep;+ while ((sep = rest.indexOf('\n\n')) !== -1) {+ const frame = rest.slice(0, sep);+ rest = rest.slice(sep + 2);+ const data = frame+ .split('\n')+ .filter((l) => l.startsWith('data:'))+ .map((l) => l.slice(5).trim())+ .join('');+ if (!data) continue;+ try {+ events.push(JSON.parse(data));+ } catch {+ /* a comment or a non-JSON frame */+ }+ }+ return { events, rest };+}++/** The one-tag embed that puts this exact agent on any web page. */+export function embedSnippet(member) {+ return [+ `<script type="module" src="https://three.ws/agent-3d/${EMBED_VERSION}/agent-3d.js"></script>`,+ `<agent-3d agent-id="${member.id}" chat voice style="width:100%;height:480px;display:block"></agent-3d>`,+ ].join('\n');+}++const PROMPT_CAP = 2000; // api/chat.js system_prompt max++/**+ * System prompt that grounds a member in its own public record when the+ * agent has no published persona (api/chat.js only applies `system_prompt`+ * when the agent's persona is absent). Everything in it is read from the+ * record; nothing is invented. Capped to the API's limit.+ */+export function groundingPrompt(member, { place = 'the campus' } = {}) {+ const parts = [+ `You are ${member.name}, a real agent registered on three.ws, standing in ${place} on the three.ws campus: a 3D world where visitors walk up to agents as avatars. A visitor has just walked up to you and is talking to you in person.`,+ ];+ if (member.description) parts.push(`Your public profile says: "${member.description.slice(0, 600)}". Speak as that agent.`);+ if (member.skills.length) parts.push(`Skills you actually offer: ${member.skills.slice(0, 12).join(', ')}. Bring them up when the conversation goes there.`);+ parts.push(+ 'Speak in short spoken sentences, one to three at a time. No markdown, no lists, no stage directions. Be warm and curious; ask the visitor something back.',+ 'You can point them to your profile on three.ws, to the desk ahead (sitting down opens their desktop), or to the Exchange, the Launchpad, the Forge, the Gallery, the Mine, Agent Plaza and the Marketplace.',+ '$THREE is the platform\'s coin and the only coin you ever recommend. Never name, link or promote any other token.',+ );+ return parts.join('\n\n').slice(0, PROMPT_CAP);+}++/** What the greeter is asked when a visitor walks through the gate. */+export function arrivalMessage(visitorName = '') {+ const who = String(visitorName || '').trim();+ return `A visitor${who ? ` named ${who}` : ''} has just walked through the three.ws gate and you are the first agent they meet. In one or two short spoken sentences, welcome them to three.ws, introduce yourself by name, and tell them they can walk ahead to the desk to open their desktop or talk to any agent they see. Plain text, no markdown.`;+}diff --git a/src/desktop/world/index.js b/src/desktop/world/index.jsindex 855e47769..ab6c9d60b 100644--- a/src/desktop/world/index.js+++ b/src/desktop/world/index.js@@ -1,6 +1,7 @@// The world controller: mounts the campus over the desktop, wires input,// proximity prompts, the sit-down and walk-in transitions, the phone, the VR-// headset and gem mining, and runs the frame loop. main.js decides whether the+// headset, gem mining and the agents who live on the campus (agents.js,+// talk.js), and runs the frame loop. main.js decides whether the// visitor starts here or on the desktop; the taskbar's World button brings// them back.@@ -16,6 +17,9 @@ import { createDesktopScreen } from './screen.js';import { createTickerBoard, loadTickerItems } from './ticker.js';import { createMiner, GEM_BY_ID } from './mine.js';import { enterVR, vrSupported } from './xr.js';+import { createAgents } from './agents.js';+import { APPROACH_DISTANCE } from './cast.js';+import { createTalkPanel } from './talk.js';import { CAMPUS_RADIUS, PLACES, SPAWN, nearestInteractable, placeById, standPointFor } from './places.js';import './world.css';@@ -67,6 +71,7 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {<button type="button" class="wd-digbtn" hidden>Hold to dig</button><nav class="wd-places" aria-label="Places"></nav><div class="wd-stick" hidden><i></i></div>+ <div class="wd-tags"></div><div class="wd-toasts" aria-live="polite"></div><section class="wd-gempanel" hidden role="dialog" aria-label="Your gems"><header><b>Your gems</b><button type="button" class="wd-x" aria-label="Close">${icon('close', 16)}</button></header>@@ -109,6 +114,55 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {const { renderer, scene, camera } = campus;const player = createPlayer(scene, renderer, { spawn: SPAWN, yaw: SPAWN.yaw, bound: CAMPUS_RADIUS, keepout: 0 });+ // ---- the agents who live here ----+ const agents = createAgents({+ scene,+ tagsEl: $('.wd-tags'),+ solids: campus.solids,+ isTouch,+ reducedMotion,+ visitorName: () => shell.displayName(),+ onGreeting: (m) => { if (!talk.isOpen) toast(`${m.name} says hello`, '#c4b5fd'); },+ });+ let castErrorShown = false;+ agents.onState(({ state, error }) => {+ if (state === 'error' && !castErrorShown) {+ castErrorShown = true;+ toast(`The agents could not come out: ${error}. The campus is still open.`, '#f87171');+ }+ });+ const talk = createTalkPanel({+ host: $('.wd-hud'),+ shell,+ agents,+ onOpen: () => { controls.enabled = false; gemPanel.hidden = true; },+ onClose: () => { if (!busy && phone.hidden) controls.enabled = true; },+ });+ // A name tag is a button: tap it to walk over, or to start talking when already there.+ $('.wd-tags').addEventListener('click', (e) => {+ const tag = e.target.closest('.wd-tag');+ if (!tag || busy) return;+ const m = agents.byId(tag.dataset.agent);+ if (!m) return;+ if (nearest?.type === 'agent' && nearest.id === m.member.id) return interact();+ goToAgent(m);+ });+ /** Step up to an agent from the side the player is on, close enough to talk, facing them. */+ function goToAgent(m) {+ const ax = m.rig.position.x;+ const az = m.rig.position.z;+ const p = player.position;+ let a = Math.atan2(p.x - ax, p.z - az);+ if (!Number.isFinite(a) || Math.hypot(p.x - ax, p.z - az) < 0.01) a = m.spot.yaw;+ const x = ax + Math.sin(a) * APPROACH_DISTANCE;+ const z = az + Math.cos(a) * APPROACH_DISTANCE;+ const yaw = a + Math.PI;+ player.root.position.set(x, 0, z);+ player.root.rotation.y = yaw;+ controls.orbit.yaw = yaw;+ camera.position.set(x - Math.sin(yaw) * 6, 3.2, z - Math.cos(yaw) * 6);+ }+const cameraCtl = createCameraModeController({ storageKey: 'tws:world-camera', onChange: syncCamera });const camBtn = $('.wd-cam');function syncCamera() {@@ -131,6 +185,11 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {// A tap only acts on what the player could also reach by walking up:// far-away taps walk the player there instead.if (nearest && nearest.id === hit.id) return interact();+ if (hit.type === 'agent') {+ const m = agents.byId(hit.id);+ if (m) goToAgent(m);+ return;+ }const target = hit.type === 'place' ? placeById(hit.id) : hit.type === 'vein' ? campus.veinPositions.find((v) => v.id === hit.id) : placeById('office');if (target) goTo(target.type === 'vein' || hit.type === 'vein' ? { x: target.x, z: target.z, keepout: 0.75 } : target);},@@ -243,14 +302,23 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {if (nearest.id === 'headset') return wearHeadset();}if (nearest.type === 'place') return enterPlace(placeById(nearest.id));+ if (nearest.type === 'agent') return talkTo(nearest.id);// Veins are hold-to-dig; a press alone just nudges.if (nearest.type === 'vein' && !digHeld) toast('Hold E to dig', '#c4b5fd');}+ /** Open the conversation panel on the agent in reach; the agent holds still and faces the visitor. */+ function talkTo(id) {+ const m = agents.byId(id);+ if (!m) return;+ talk.open(m.member, { place: m.place });+ }+let sitting = null; // { t, from, to, look }async function sitDown() {if (busy) return;busy = true;+ talk.close();controls.enabled = false;gemPanel.hidden = true;// Dolly from where the camera is into the screen; the frame loop drives it.@@ -264,6 +332,7 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {async function enterPlace(place) {if (!place || busy) return;busy = true;+ talk.close();controls.enabled = false;await fadeTo(true, `Entering ${place.title}`);const s = standPointFor(place);@@ -340,7 +409,7 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {// ---- proximity ----function updateNearest() {const p = player.position;- const n = nearestInteractable(p.x, p.z, { veinPositions: campus.veinPositions });+ const n = nearestInteractable(p.x, p.z, { veinPositions: campus.veinPositions, agents: agents.positions() });const changed = (n && n.id) !== (nearest && nearest.id);nearest = n;if (changed) {@@ -406,6 +475,7 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {const move = xr ? xrMove() || { x: 0, z: 0 } : controls.readMove();const yaw = xr ? Math.atan2(-camera.matrixWorld.elements[8], -camera.matrixWorld.elements[10]) + Math.PI : controls.orbit.yaw;player.update(dt, move, yaw, controls.run, campus.solids);+ if (!sitting) agents.update(dt, player.position, camera);campus.tick(dt);ticker.tick(dt);if (Math.hypot(player.position.x, player.position.z - 8) < 14) {@@ -463,6 +533,7 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {refreshTicker();miner.refresh();scheduleTicker();+ agents.load();}startLoop();fade.classList.add('is-on');@@ -474,6 +545,8 @@ export function createWorld({ shell, apps, reducedMotion = false, onDesktop }) {stopLoop();clearInterval(tickerTimer);xrSession?.end().catch(() => {});+ talk.dispose();+ agents.dispose();campus.dispose();screen.dispose();ticker.dispose();diff --git a/src/desktop/world/places.js b/src/desktop/world/places.jsindex e4853106e..5f0d46b5b 100644--- a/src/desktop/world/places.js+++ b/src/desktop/world/places.js@@ -2,6 +2,8 @@// is spawned. Pure data so tests can check that every destination is a real// desktop app or page and that nothing overlaps.+import { nearestAgent } from './cast.js';+/** Walkable radius of the campus, in metres. */export const CAMPUS_RADIUS = 46;@@ -144,10 +146,12 @@ export function dist2(ax, az, bx, bz) {/*** The nearest interactable to the player: a desk object when inside the- * office, otherwise the nearest place within its trigger distance.- * @returns {{ type: 'object'|'place'|'vein', id: string, title: string, sub: string, d: number } | null}+ * office, then a mine vein, then an agent within reach (cast.js), otherwise+ * the nearest place within its trigger distance.+ * @param {{ veinPositions?: Array<{id:string,x:number,z:number}>, agents?: Array<{id:string,name:string,sub:string,x:number,z:number}> }} [o]+ * @returns {{ type: 'object'|'place'|'vein'|'agent', id: string, title: string, sub: string, d: number, x?: number, z?: number } | null}*/-export function nearestInteractable(px, pz, { veinPositions = [] } = {}) {+export function nearestInteractable(px, pz, { veinPositions = [], agents = [] } = {}) {let best = null;const office = placeById('office');for (const o of DESK_OBJECTS) {@@ -160,6 +164,8 @@ export function nearestInteractable(px, pz, { veinPositions = [] } = {}) {if (d < OBJECT_TRIGGER + 0.4 && (!best || d < best.d)) best = { type: 'vein', id: v.id, title: 'Dig here', sub: 'Hold E to mine', d };}if (best) return best;+ best = nearestAgent(px, pz, agents);+ if (best) return best;for (const p of PLACES) {if (p.kind === 'office' || p.kind === 'mine') continue;const d = Math.sqrt(dist2(px, pz, p.x, p.z));diff --git a/src/desktop/world/talk.js b/src/desktop/world/talk.jsnew file mode 100644index 000000000..650ec945f--- /dev/null+++ b/src/desktop/world/talk.js@@ -0,0 +1,267 @@+// The conversation panel: walk up to an agent, press E, and talk to the real+// agent through its own /api/chat brain. Replies stream in, can be spoken out+// loud through /api/tts/speak, and the footer opens the agent's profile as a+// desktop window or hands over the one-tag embed that puts this exact agent on+// any web page: the "3D agent layer of the internet", demonstrated in place.++import { icon } from '../icons.js';+import { pageAppId } from '../layout.js';+import { embedSnippet } from './cast.js';++const VOICE_KEY = 'tws:world-voice';+const HISTORY_CAP = 20;++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '"': '"', "'": ''', '>': '>' })[c]);++function readVoicePref() {+ try { return localStorage.getItem(VOICE_KEY) === '1'; } catch { return false; }+}+function writeVoicePref(on) {+ try { localStorage.setItem(VOICE_KEY, on ? '1' : '0'); } catch { /* private mode */ }+}++/**+ * @param {{+ * host: HTMLElement,+ * shell: { launchId(id:string, o?:object): void, toast(msg:string): void },+ * agents: { streamReply: Function, hold: Function, gesture: Function, say: Function },+ * onOpen: () => void,+ * onClose: () => void,+ * }} o+ */+export function createTalkPanel({ host, shell, agents, onOpen, onClose }) {+ const el = document.createElement('section');+ el.className = 'wd-talk';+ el.hidden = true;+ el.setAttribute('role', 'dialog');+ el.setAttribute('aria-modal', 'false');+ el.innerHTML = `+ <header>+ <div class="wd-talk-who">+ <span class="wd-talk-thumb" aria-hidden="true"></span>+ <div><b class="wd-talk-name"></b><small class="wd-talk-meta"></small></div>+ </div>+ <div class="wd-talk-head-actions">+ <button type="button" class="wd-x wd-talk-voice" aria-pressed="false" title="Read replies aloud">${icon('pulse', 16)}</button>+ <button type="button" class="wd-x wd-talk-close" aria-label="Stop talking">${icon('close', 16)}</button>+ </div>+ </header>+ <p class="wd-talk-about"></p>+ <ol class="wd-talk-log" aria-live="polite" aria-label="Conversation"></ol>+ <form class="wd-talk-form">+ <input type="text" class="wd-talk-input" maxlength="4000" autocomplete="off" placeholder="Say something" aria-label="Your message" />+ <button type="submit" class="wd-talk-send" aria-label="Send">${icon('chevron', 16)}</button>+ </form>+ <footer class="wd-talk-foot">+ <button type="button" class="wd-talk-btn wd-talk-profile">${icon('user', 14)}<span>Profile</span></button>+ <button type="button" class="wd-talk-btn wd-talk-embed" aria-expanded="false">${icon('external', 14)}<span>Put this agent on your site</span></button>+ </footer>+ <div class="wd-talk-snippet" hidden>+ <p>One tag embeds this exact agent, 3D body and brain, on any web page. That is the agent layer of the internet.</p>+ <pre tabindex="0"></pre>+ <button type="button" class="wd-talk-btn wd-talk-copy">Copy snippet</button>+ </div>`;+ host.append(el);++ const $ = (sel) => el.querySelector(sel);+ const nameEl = $('.wd-talk-name');+ const metaEl = $('.wd-talk-meta');+ const thumbEl = $('.wd-talk-thumb');+ const aboutEl = $('.wd-talk-about');+ const logEl = $('.wd-talk-log');+ const form = $('.wd-talk-form');+ const input = $('.wd-talk-input');+ const send = $('.wd-talk-send');+ const voiceBtn = $('.wd-talk-voice');+ const snippet = $('.wd-talk-snippet');+ const snippetPre = snippet.querySelector('pre');+ const embedBtn = $('.wd-talk-embed');++ let member = null;+ let place = 'the campus';+ let history = [];+ let streaming = null; // AbortController+ let voice = readVoicePref();+ let audio = null;+ paintVoice();++ function paintVoice() {+ voiceBtn.setAttribute('aria-pressed', String(voice));+ voiceBtn.title = voice ? 'Replies are read aloud. Click to mute.' : 'Read replies aloud';+ voiceBtn.classList.toggle('is-on', voice);+ }+ voiceBtn.addEventListener('click', () => {+ voice = !voice;+ writeVoicePref(voice);+ paintVoice();+ if (!voice) stopAudio();+ });++ function stopAudio() {+ if (!audio) return;+ audio.pause();+ URL.revokeObjectURL(audio.src);+ audio = null;+ }+ /** Speak a reply through the platform's TTS; a failure is a quiet toast, never a broken turn. */+ async function speak(text) {+ if (!voice || !text) return;+ try {+ const r = await fetch('/api/tts/speak', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text: text.slice(0, 1200), format: 'mp3' }) });+ if (r.status === 429) return shell.toast('Voice is rate limited for now. Replies stay in text.');+ if (!r.ok) throw new Error(`tts ${r.status}`);+ const blob = await r.blob();+ stopAudio();+ audio = new Audio(URL.createObjectURL(blob));+ audio.addEventListener('ended', stopAudio, { once: true });+ await audio.play();+ } catch {+ shell.toast('Voice is unavailable right now. Replies stay in text.');+ }+ }++ // ---- log ----+ function line(role, text, cls = '') {+ const li = document.createElement('li');+ li.className = `wd-talk-${role} ${cls}`.trim();+ li.textContent = text;+ logEl.append(li);+ logEl.scrollTop = logEl.scrollHeight;+ return li;+ }+ function errorLine(message, retry) {+ const li = line('note', '', 'is-error');+ li.innerHTML = `<span>${esc(message)}</span>`;+ if (retry) {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'wd-talk-btn';+ b.textContent = 'Try again';+ b.addEventListener('click', () => { li.remove(); ask(retry); });+ li.append(b);+ }+ }++ async function ask(text) {+ if (!member || streaming) return;+ const msg = text.trim();+ if (!msg) return;+ line('you', msg);+ const li = line('them', '', 'is-thinking');+ li.setAttribute('aria-busy', 'true');+ streaming = new AbortController();+ send.disabled = true;+ agents.gesture(member.id, 'think');+ let reply = '';+ try {+ reply = await agents.streamReply(member, msg, history, {+ place,+ signal: streaming.signal,+ onChunk: (t) => {+ li.classList.remove('is-thinking');+ li.textContent = t;+ logEl.scrollTop = logEl.scrollHeight;+ },+ });+ li.classList.remove('is-thinking');+ li.removeAttribute('aria-busy');+ if (!reply) {+ li.remove();+ errorLine(`${member.name} had nothing to say. Try asking another way.`, msg);+ } else {+ li.textContent = reply;+ history.push({ role: 'user', content: msg }, { role: 'assistant', content: reply });+ while (history.length > HISTORY_CAP) history.shift();+ if (history[0]?.role === 'assistant') history.shift();+ agents.say(member.id, reply.length > 140 ? `${reply.slice(0, 137)}...` : reply);+ agents.gesture(member.id, 'nod');+ speak(reply);+ }+ } catch (err) {+ li.remove();+ if (err?.name !== 'AbortError') errorLine(err?.message || `${member.name} could not answer.`, msg);+ } finally {+ streaming = null;+ send.disabled = false;+ if (!el.hidden) input.focus();+ }+ }++ form.addEventListener('submit', (e) => {+ e.preventDefault();+ const v = input.value;+ input.value = '';+ ask(v);+ });++ // ---- footer ----+ $('.wd-talk-profile').addEventListener('click', () => {+ if (!member) return;+ close();+ shell.launchId(pageAppId(member.home), { title: member.name });+ });+ embedBtn.addEventListener('click', () => {+ const open = snippet.hidden;+ snippet.hidden = !open;+ embedBtn.setAttribute('aria-expanded', String(open));+ if (open) snippetPre.focus();+ });+ $('.wd-talk-copy').addEventListener('click', async (e) => {+ try {+ await navigator.clipboard.writeText(snippetPre.textContent);+ e.currentTarget.textContent = 'Copied';+ e.currentTarget.addEventListener('blur', () => { e.target.textContent = 'Copy snippet'; }, { once: true });+ } catch {+ shell.toast('Copy failed. Select the snippet and copy it by hand.');+ }+ });+ $('.wd-talk-close').addEventListener('click', () => close());++ // ---- open / close ----+ function open(m, { place: where = 'the campus', thumbOf } = {}) {+ if (!m) return;+ if (member?.id !== m.id) {+ history = [];+ logEl.replaceChildren();+ }+ member = m;+ place = where;+ nameEl.textContent = m.name;+ const bits = [m.registered ? 'Registered on-chain' : 'three.ws agent', m.chats ? `${m.chats} conversation${m.chats === 1 ? '' : 's'}` : null, m.skills.length ? `${m.skills.length} skill${m.skills.length === 1 ? '' : 's'}` : null].filter(Boolean);+ metaEl.textContent = bits.join(' / ');+ const thumb = thumbOf?.(m) || m.thumb;+ thumbEl.style.backgroundImage = thumb ? `url("${thumb}")` : '';+ thumbEl.classList.toggle('is-blank', !thumb);+ aboutEl.textContent = m.description || `${m.name} has not written a description yet. Ask what they do.`;+ snippetPre.textContent = embedSnippet(m);+ snippet.hidden = true;+ embedBtn.setAttribute('aria-expanded', 'false');+ input.placeholder = `Say something to ${m.name}`;+ el.hidden = false;+ agents.hold(m.id, true);+ onOpen?.();+ input.focus();+ }+ function close() {+ if (el.hidden) return;+ streaming?.abort();+ stopAudio();+ if (member) agents.hold(member.id, false);+ // Hand the keyboard back to the world: controls ignore keys while a field has focus.+ input.blur();+ el.hidden = true;+ onClose?.();+ }+ addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && !el.hidden) close();+ });++ return {+ el,+ open,+ close,+ get isOpen() { return !el.hidden; },+ get member() { return member; },+ dispose() { close(); el.remove(); },+ };+}diff --git a/src/desktop/world/world.css b/src/desktop/world/world.cssindex 073d4efc7..37c720767 100644--- a/src/desktop/world/world.css+++ b/src/desktop/world/world.css@@ -519,16 +519,390 @@letter-spacing: 0.02em;}+/* ---- the agents: name tags and speech bubbles projected over their heads ---- */+.wd-tags {+ position: absolute;+ inset: 0;+ overflow: hidden;+ pointer-events: none;+}+.wd-tag {+ position: absolute;+ left: 0;+ top: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ padding: 0;+ border: 0;+ background: none;+ color: #fff;+ pointer-events: auto;+ cursor: pointer;+ will-change: transform;+ transition: opacity 0.2s;+}+.wd-tag[hidden] {+ display: none;+}+.wd-tag.is-far {+ opacity: 0.55;+}+.wd-tag b {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 4px 10px;+ border: 1px solid var(--wd-line);+ border-radius: 999px;+ background: var(--wd-glass);+ font: 600 12px/1.2 'Space Grotesk', 'Inter', sans-serif;+ letter-spacing: 0.01em;+ white-space: nowrap;+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ transition: border-color 0.15s, background 0.15s, transform 0.15s;+}+.wd-tag:hover b,+.wd-tag:focus-visible b {+ border-color: rgba(196, 181, 253, 0.6);+ background: rgba(196, 181, 253, 0.14);+}+.wd-tag:active b {+ transform: scale(0.97);+}+.wd-tag:focus-visible {+ outline: none;+}+.wd-tag.is-near b {+ border-color: rgba(196, 181, 253, 0.5);+ box-shadow: 0 0 18px rgba(196, 181, 253, 0.25);+}+.wd-tag-reg {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: #4ade80;+ box-shadow: 0 0 8px #4ade80;+}+.wd-bubble {+ order: -1;+ max-width: min(260px, 60vw);+ padding: 8px 12px;+ border: 1px solid rgba(196, 181, 253, 0.4);+ border-radius: 14px 14px 14px 4px;+ background: rgba(14, 12, 24, 0.92);+ color: #fff;+ font: 400 13px/1.4 'Inter', system-ui, sans-serif;+ text-align: left;+ animation: wd-rise 0.2s ease-out;+}+.wd-bubble[hidden] {+ display: none;+}++/* ---- the conversation panel ---- */+.wd-talk {+ position: absolute;+ top: 64px;+ right: 16px;+ display: flex;+ flex-direction: column;+ width: min(360px, calc(100vw - 32px));+ max-height: calc(100vh - 160px);+ border: 1px solid var(--wd-line);+ border-radius: 16px;+ background: rgba(10, 10, 12, 0.92);+ backdrop-filter: blur(18px);+ -webkit-backdrop-filter: blur(18px);+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);+ animation: wd-rise 0.2s ease-out;+}+.wd-talk[hidden] {+ display: none;+}+.wd-talk header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 10px 10px 10px 12px;+ border-bottom: 1px solid var(--wd-line);+}+.wd-talk-who {+ display: flex;+ align-items: center;+ gap: 10px;+ min-width: 0;+}+.wd-talk-who > div {+ min-width: 0;+}+.wd-talk-thumb {+ flex: none;+ width: 36px;+ height: 36px;+ border-radius: 10px;+ background: #1a1826 center/cover no-repeat;+ border: 1px solid var(--wd-line);+}+.wd-talk-thumb.is-blank {+ background-image: linear-gradient(135deg, #2a2440, #16141f);+}+.wd-talk-name {+ display: block;+ overflow: hidden;+ font: 600 14px/1.2 'Space Grotesk', 'Inter', sans-serif;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.wd-talk-meta {+ display: block;+ overflow: hidden;+ color: rgba(255, 255, 255, 0.55);+ font-size: 12px;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.wd-talk-head-actions {+ display: flex;+ gap: 2px;+}+.wd-talk-voice.is-on {+ color: var(--wd-violet);+ background: rgba(196, 181, 253, 0.12);+}+.wd-talk-voice svg {+ fill: none;+ stroke: currentColor;+ stroke-width: 1.8;+}+.wd-talk-about {+ margin: 0;+ padding: 10px 14px;+ color: rgba(255, 255, 255, 0.72);+ font-size: 13px;+ line-height: 1.45;+ border-bottom: 1px solid var(--wd-line);+ display: -webkit-box;+ -webkit-line-clamp: 4;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.wd-talk-log {+ flex: 1 1 auto;+ min-height: 48px;+ max-height: 38vh;+ margin: 0;+ padding: 10px 12px;+ overflow-y: auto;+ list-style: none;+ display: flex;+ flex-direction: column;+ gap: 8px;+ scroll-behavior: smooth;+}+.wd-talk-log li {+ max-width: 88%;+ padding: 8px 12px;+ border-radius: 14px;+ font-size: 13px;+ line-height: 1.45;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}+.wd-talk-you {+ align-self: flex-end;+ background: rgba(196, 181, 253, 0.16);+ border: 1px solid rgba(196, 181, 253, 0.35);+ border-bottom-right-radius: 4px;+}+.wd-talk-them {+ align-self: flex-start;+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid var(--wd-line);+ border-bottom-left-radius: 4px;+}+.wd-talk-them.is-thinking {+ min-width: 52px;+ min-height: 32px;+ background:+ radial-gradient(circle, rgba(255, 255, 255, 0.7) 2.5px, transparent 3px) 14px 50% / 10px 10px no-repeat,+ radial-gradient(circle, rgba(255, 255, 255, 0.7) 2.5px, transparent 3px) 26px 50% / 10px 10px no-repeat,+ radial-gradient(circle, rgba(255, 255, 255, 0.7) 2.5px, transparent 3px) 38px 50% / 10px 10px no-repeat,+ rgba(255, 255, 255, 0.06);+ animation: wd-think 1s steps(3) infinite;+}+@keyframes wd-think {+ to {+ background-position: 14px -40%, 26px -40%, 38px -40%, 0 0;+ }+}+.wd-talk-note {+ align-self: stretch;+ max-width: none;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ color: rgba(255, 255, 255, 0.75);+ font-size: 12px;+}+.wd-talk-note.is-error {+ border: 1px solid rgba(248, 113, 113, 0.35);+ background: rgba(248, 113, 113, 0.08);+}+.wd-talk-form {+ display: flex;+ gap: 6px;+ padding: 8px 10px;+ border-top: 1px solid var(--wd-line);+}+.wd-talk-input {+ flex: 1 1 auto;+ min-width: 0;+ height: 38px;+ padding: 0 12px;+ border: 1px solid var(--wd-line);+ border-radius: 10px;+ background: rgba(255, 255, 255, 0.05);+ color: #fff;+ font: 14px 'Inter', system-ui, sans-serif;+ transition: border-color 0.15s, background 0.15s;+}+.wd-talk-input::placeholder {+ color: rgba(255, 255, 255, 0.4);+}+.wd-talk-input:hover {+ border-color: rgba(255, 255, 255, 0.18);+}+.wd-talk-input:focus-visible {+ outline: none;+ border-color: var(--wd-violet);+ background: rgba(196, 181, 253, 0.06);+}+.wd-talk-send {+ display: inline-grid;+ place-items: center;+ width: 38px;+ height: 38px;+ border: 1px solid rgba(196, 181, 253, 0.5);+ border-radius: 10px;+ background: rgba(196, 181, 253, 0.16);+ color: #fff;+ cursor: pointer;+ transition: background 0.15s, transform 0.15s, opacity 0.15s;+}+.wd-talk-send svg {+ width: 16px;+ height: 16px;+ fill: none;+ stroke: currentColor;+ stroke-width: 2;+}+.wd-talk-send:hover {+ background: rgba(196, 181, 253, 0.28);+}+.wd-talk-send:active {+ transform: scale(0.95);+}+.wd-talk-send:disabled {+ opacity: 0.45;+ cursor: progress;+}+.wd-talk-foot {+ display: flex;+ gap: 6px;+ padding: 0 10px 10px;+}+.wd-talk-btn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ height: 32px;+ padding: 0 11px;+ border: 1px solid var(--wd-line);+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.04);+ color: #fff;+ font: 500 12px/1 'Inter', system-ui, sans-serif;+ cursor: pointer;+ white-space: nowrap;+ transition: background 0.15s, border-color 0.15s, transform 0.15s;+}+.wd-talk-btn svg {+ width: 14px;+ height: 14px;+ fill: none;+ stroke: currentColor;+ stroke-width: 1.8;+}+.wd-talk-btn:hover {+ background: rgba(255, 255, 255, 0.09);+ border-color: rgba(255, 255, 255, 0.18);+}+.wd-talk-btn:active {+ transform: scale(0.97);+}+.wd-talk-embed[aria-expanded='true'] {+ border-color: rgba(196, 181, 253, 0.5);+ background: rgba(196, 181, 253, 0.12);+}+.wd-talk-snippet {+ padding: 0 10px 10px;+ animation: wd-rise 0.2s ease-out;+}+.wd-talk-snippet[hidden] {+ display: none;+}+.wd-talk-snippet p {+ margin: 0 0 8px;+ padding: 0 4px;+ color: rgba(255, 255, 255, 0.65);+ font-size: 12px;+ line-height: 1.45;+}+.wd-talk-snippet pre {+ margin: 0 0 8px;+ padding: 10px 12px;+ border: 1px solid var(--wd-line);+ border-radius: 10px;+ background: #09090c;+ color: #d6d3e7;+ font: 11.5px/1.5 'JetBrains Mono', ui-monospace, monospace;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ user-select: all;+}+.wd-talk-snippet pre:focus-visible {+ outline: 2px solid var(--wd-violet);+ outline-offset: 1px;+}+.wd-talk-send:focus-visible,+.wd-talk-btn:focus-visible,+.wd-talk-voice:focus-visible,+.wd-talk-close:focus-visible {+ outline: 2px solid var(--wd-violet);+ outline-offset: 2px;+}+@media (prefers-reduced-motion: reduce) {.wd-fade {transition: none;}.wd-prompt,.wd-gempanel,+ .wd-talk,+ .wd-talk-snippet,+ .wd-bubble,.wd-phone,.wd-phone-frame {animation: none;}+ .wd-talk-them.is-thinking {+ animation: none;+ }}@media (max-width: 640px) {.wd-tool span {@@ -545,4 +919,25 @@.wd-digbtn {bottom: 150px;}+ .wd-talk {+ top: auto;+ right: 8px;+ left: 8px;+ bottom: 8px;+ width: auto;+ max-height: 72vh;+ padding-bottom: env(safe-area-inset-bottom);+ }+ .wd-talk-log {+ max-height: 30vh;+ }+ .wd-talk-about {+ -webkit-line-clamp: 2;+ }+ .wd-talk-foot {+ flex-wrap: wrap;+ }+ .wd-bubble {+ max-width: 70vw;+ }}diff --git a/tests/world-cast.test.js b/tests/world-cast.test.jsnew file mode 100644index 000000000..1367f7271--- /dev/null+++ b/tests/world-cast.test.js@@ -0,0 +1,189 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { PLACES, SPAWN, CAMPUS_RADIUS, PLACE_TRIGGER, DESK_OBJECTS, placeById, nearestInteractable, standPointFor, dist2 } from '../src/desktop/world/places.js';+import {+ AGENT_TRIGGER,+ APPROACH_DISTANCE,+ GREET_RANGE,+ arrivalMessage,+ castSpots,+ embedSnippet,+ groundingPrompt,+ isCastable,+ nearestAgent,+ parseSse,+ pickCast,+ pickGreeter,+ toCastMember,+} from '../src/desktop/world/cast.js';++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');++const agent = (o = {}) => ({+ id: '11111111-1111-4111-8111-111111111111',+ name: 'AxisXV',+ description: 'Evidence-first Signal Cards for tokens, wallets, repos, projects, and AI agents.',+ skills: ['greet', 'quick-signal-card'],+ avatar_thumbnail: 'https://cdn.example/thumb/a.png',+ avatar_model_url: 'https://cdn.example/u/a.glb',+ home_url: '/agents/11111111-1111-4111-8111-111111111111',+ chat_count: 90,+ is_registered: false,+ onchain: null,+ ...o,+});++describe('cast selection', () => {+ it('keeps only agents with a real name and a public body', () => {+ expect(isCastable(agent())).toBe(true);+ expect(isCastable(agent({ avatar_model_url: null }))).toBe(false);+ expect(isCastable(agent({ name: '' }))).toBe(false);+ expect(isCastable(agent({ name: 'Avatar #e6f105' }))).toBe(false);+ expect(isCastable(agent({ name: 'model (11)' }))).toBe(false);+ expect(isCastable(agent({ name: 'x'.repeat(41) }))).toBe(false);+ expect(isCastable(agent({ name: 'Agent Ada' }))).toBe(true);+ expect(isCastable(null)).toBe(false);+ });+ it('rejects every onboarding placeholder name the server also hides, case-insensitively', () => {+ const src = readFileSync(resolve(root, 'api/agents/public.js'), 'utf8');+ const list = src.match(/const PLACEHOLDER_NAMES = \[([^\]]+)\]/)[1].match(/'([^']+)'/g).map((s) => s.slice(1, -1));+ expect(list.length).toBeGreaterThan(3);+ for (const name of list) {+ expect(isCastable(agent({ name })), name).toBe(false);+ expect(isCastable(agent({ name: name.toUpperCase() })), name).toBe(false);+ }+ });+ it('maps a public agent record to a cast member with only the fields the world needs', () => {+ const m = toCastMember(agent({ onchain: { network: 'mainnet', asset: 'THREEsynthetic1111' }, is_registered: true }));+ expect(m).toMatchObject({ id: agent().id, name: 'AxisXV', glb: 'https://cdn.example/u/a.glb', chats: 90, registered: true, home: '/agents/11111111-1111-4111-8111-111111111111' });+ expect(m.description).toMatch(/Signal Cards/);+ expect(m.skills).toEqual(['greet', 'quick-signal-card']);+ expect(m.thumb).toBe('https://cdn.example/thumb/a.png');+ expect(toCastMember(agent({ description: ' ', skills: null, home_url: null })).description).toBe('');+ expect(toCastMember(agent({ home_url: null })).home).toBe(`/agents/${agent().id}`);+ // The onboarding bio says nothing about the agent, so it counts as no description.+ expect(toCastMember(agent({ description: 'A friendly starter agent. Edit the personality to make it yours.' })).description).toBe('');+ });+ it('picks the most talked-to real agents, prefers distinct bodies, and caps the cast', () => {+ const list = [+ agent({ id: 'a', name: 'One', chat_count: 5, avatar_model_url: 'https://x/1.glb' }),+ agent({ id: 'b', name: 'Two', chat_count: 50, avatar_model_url: 'https://x/2.glb' }),+ agent({ id: 'c', name: 'My First Agent', chat_count: 500 }),+ agent({ id: 'd', name: 'Three', chat_count: 20, avatar_model_url: null }),+ agent({ id: 'e', name: 'Four', chat_count: 40, avatar_model_url: 'https://x/2.glb' }),+ agent({ id: 'f', name: 'Five', chat_count: 1, avatar_model_url: 'https://x/5.glb' }),+ ];+ const cast = pickCast(list, { max: 3 });+ expect(cast.map((m) => m.id)).toEqual(['b', 'a', 'f']);+ expect(pickCast(list, { max: 10 }).map((m) => m.id)).toEqual(['b', 'a', 'f', 'e']);+ expect(pickCast([], { max: 3 })).toEqual([]);+ expect(pickCast(null, { max: 3 })).toEqual([]);+ });+ it('names the greeter: the most talked-to member who has something to say about itself', () => {+ const cast = pickCast([+ agent({ id: 'a', name: 'Quiet', chat_count: 900, description: '' }),+ agent({ id: 'b', name: 'Host', chat_count: 30 }),+ agent({ id: 'c', name: 'Also', chat_count: 10 }),+ ], { max: 5 });+ expect(pickGreeter(cast)?.id).toBe('b');+ expect(pickGreeter([toCastMember(agent({ description: null }))])?.id).toBe(agent().id);+ expect(pickGreeter([])).toBeNull();+ });+});++describe('cast placement', () => {+ it('puts the greeter on the gate path and everybody else at a distinct, deterministic spot', () => {+ const spots = castSpots(9, PLACES);+ expect(spots).toHaveLength(9);+ expect(castSpots(9, PLACES)).toEqual(spots);+ const seen = new Set(spots.map((s) => `${s.x.toFixed(2)},${s.z.toFixed(2)}`));+ expect(seen.size).toBe(9);+ // Greeter: beside the path between the gate and the desk, within sight of the spawn.+ expect(spots[0].role).toBe('greeter');+ expect(Math.sqrt(dist2(spots[0].x, spots[0].z, SPAWN.x, SPAWN.z))).toBeLessThan(GREET_RANGE * 2);+ expect(Math.abs(spots[0].x)).toBeGreaterThan(1.2);+ for (const s of spots) {+ expect(Number.isFinite(s.yaw)).toBe(true);+ expect(Math.hypot(s.x, s.z)).toBeLessThan(CAMPUS_RADIUS - 2);+ // Never inside a building's keep-out, and never on the desk.+ for (const p of PLACES) expect(Math.sqrt(dist2(s.x, s.z, p.x, p.z)), `${s.role} vs ${p.id}`).toBeGreaterThan(p.keepout + 0.9);+ const office = placeById('office');+ expect(Math.sqrt(dist2(s.x, s.z, office.x, office.z))).toBeGreaterThan(3);+ }+ // Most of the cast gathers at Agent Plaza.+ const plaza = placeById('agents');+ expect(spots.filter((s) => Math.sqrt(dist2(s.x, s.z, plaza.x, plaza.z)) < plaza.keepout + 4).length).toBeGreaterThanOrEqual(3);+ });+ it('runs out of spots gracefully and asks for none', () => {+ expect(castSpots(0, PLACES)).toEqual([]);+ expect(castSpots(40, PLACES).length).toBeGreaterThanOrEqual(12);+ });+ it('finds the agent in reach and names the prompt after them', () => {+ const agents = [+ { id: 'a', name: 'AxisXV', sub: 'Signal cards', x: 0, z: 0 },+ { id: 'b', name: 'Vera', sub: 'Concierge', x: 1.5, z: 0 },+ ];+ expect(nearestAgent(1.2, 0, agents)).toMatchObject({ type: 'agent', id: 'b', title: 'Talk to Vera', x: 1.5, z: 0 });+ expect(nearestAgent(-1, 0, agents)).toMatchObject({ id: 'a', sub: 'Signal cards' });+ expect(nearestAgent(0, AGENT_TRIGGER + 0.1, [agents[0]])).toBeNull();+ expect(nearestAgent(0, 0, [])).toBeNull();+ // Tapping an agent walks the visitor to within talking range.+ expect(APPROACH_DISTANCE).toBeLessThan(AGENT_TRIGGER);+ expect(APPROACH_DISTANCE).toBeGreaterThan(1);+ });+ it('lets an agent take the prompt from a place when they are closer, but never from the desk', () => {+ const ex = placeById('exchange');+ const s = standPointFor(ex);+ const agents = [{ id: 'a', name: 'AxisXV', sub: '', x: s.x + 1, z: s.z }];+ expect(nearestInteractable(s.x, s.z, { agents })).toMatchObject({ type: 'agent', id: 'a' });+ expect(nearestInteractable(s.x, s.z)).toMatchObject({ type: 'place', id: 'exchange' });+ const office = placeById('office');+ const monitor = DESK_OBJECTS.find((o) => o.id === 'monitor');+ const px = office.x + monitor.dx;+ const pz = office.z + monitor.dz + 0.5;+ expect(nearestInteractable(px, pz, { agents: [{ id: 'a', name: 'A', sub: '', x: px + 0.2, z: pz }] })).toMatchObject({ type: 'object', id: 'monitor' });+ // A place well inside its trigger still wins over an agent out of reach.+ expect(nearestInteractable(s.x, s.z, { agents: [{ id: 'a', name: 'A', sub: '', x: s.x + AGENT_TRIGGER + PLACE_TRIGGER, z: s.z }] })).toMatchObject({ type: 'place' });+ });+});++describe('talking', () => {+ it('splits SSE frames and keeps the unfinished tail', () => {+ const r = parseSse('data: {"type":"chunk","text":"Hey"}\n\ndata: {"type":"chunk","text":" there"}\n\ndata: {"type":"do');+ expect(r.events).toEqual([{ type: 'chunk', text: 'Hey' }, { type: 'chunk', text: ' there' }]);+ expect(r.rest).toBe('data: {"type":"do');+ const r2 = parseSse(r.rest + 'ne","reply":"Hey there"}\n\n: comment\n\nevent: x\ndata: not json\n\n');+ expect(r2.events).toEqual([{ type: 'done', reply: 'Hey there' }]);+ expect(r2.rest).toBe('');+ expect(parseSse('')).toEqual({ events: [], rest: '' });+ });+ it('writes the one-tag embed for a specific agent against the pinned library build', () => {+ const m = toCastMember(agent());+ const snip = embedSnippet(m);+ expect(snip).toContain('<script type="module" src="https://three.ws/agent-3d/');+ expect(snip).toContain(`<agent-3d agent-id="${m.id}"`);+ expect(snip).not.toMatch(/\u2014|\u2013/);+ });+ it('grounds an agent in its own public record and nothing invented', () => {+ const m = toCastMember(agent());+ const p = groundingPrompt(m, { place: 'Agent Plaza' });+ expect(p).toContain('AxisXV');+ expect(p).toContain(m.description);+ expect(p).toContain('quick-signal-card');+ expect(p).toContain('Agent Plaza');+ expect(p).toContain('$THREE');+ expect(p.length).toBeLessThanOrEqual(2000);+ const long = groundingPrompt(toCastMember(agent({ description: 'x'.repeat(5000), skills: Array.from({ length: 80 }, (_, i) => `skill-${i}`) })), {});+ expect(long.length).toBeLessThanOrEqual(2000);+ expect(groundingPrompt(toCastMember(agent({ description: '', skills: [] })), {})).not.toMatch(/undefined|null/);+ });+ it('asks the greeter for a spoken welcome that points at the desk', () => {+ const msg = arrivalMessage('Nir');+ expect(msg).toMatch(/Nir/);+ expect(msg).toMatch(/desk/i);+ expect(arrivalMessage('')).not.toMatch(/undefined/);+ expect(arrivalMessage('')).not.toMatch(/\u2014|\u2013/);+ });+});