Skip to content

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

feat: NPC chat, coin community panels, catalog updates

nirholas42e594f04fdb
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index e3da2aa69..af48b9bca 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -2090,3 +2090,140 @@ span.cc-shop-action.cc-owned { align-self: flex-start; }
.cc-shop-panel { width: 100%; max-height: 100%; height: 100%; border: none; border-radius: 0; }
.cc-shop-grid { grid-template-columns: repeat(auto-fill, minmax(132px, 1fr)); }
}
+
+/* ───────────────────────────────────────────────────────────────────────────
+ NPC service counter (npc-services.js). Each townsperson fronts one real
+ x402 endpoint; this is the storefront panel the player fills in to pay.
+ Sits above the world (z 120) but below the x402 checkout overlay, which
+ mounts on top to run the wallet payment.
+ ─────────────────────────────────────────────────────────────────────────── */
+.npc-svc-overlay {
+ position: fixed; inset: 0; z-index: 120; display: grid; place-items: center;
+ padding: 20px; background: rgba(4, 4, 5, 0.66);
+ backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
+ opacity: 0; transition: opacity 0.18s ease;
+}
+.npc-svc-overlay.is-in { opacity: 1; }
+.npc-svc-card {
+ width: min(440px, 100%); max-height: min(86vh, 720px); overflow-y: auto;
+ background: var(--cc-panel-solid); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+ box-shadow: var(--cc-shadow); padding: 18px 18px 16px;
+ transform: translateY(8px) scale(0.985); transition: transform 0.18s ease;
+}
+.npc-svc-overlay.is-in .npc-svc-card { transform: translateY(0) scale(1); }
+.npc-svc-card::-webkit-scrollbar { width: 8px; }
+.npc-svc-card::-webkit-scrollbar-thumb { background: var(--cc-edge); border-radius: 4px; }
+
+.npc-svc-head { display: flex; align-items: flex-start; gap: 10px; }
+.npc-svc-head > div:first-child { flex: 1; min-width: 0; }
+.npc-svc-who { font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--cc-dim); margin-bottom: 3px; }
+.npc-svc-title { font-size: 19px; line-height: 1.15; margin: 0; font-weight: 650; }
+.npc-svc-price-wrap { flex-shrink: 0; }
+.npc-svc-close {
+ flex-shrink: 0; width: 28px; height: 28px; line-height: 1; cursor: pointer;
+ background: transparent; border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius-sm);
+ color: var(--cc-dim); font: inherit; font-size: 13px; transition: all 0.14s ease;
+}
+.npc-svc-close:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.npc-svc-close:focus-visible { outline: 2px solid var(--cc-edge-hi); outline-offset: 1px; }
+
+.npc-svc-intro { margin: 11px 0 16px; font-size: 13.5px; line-height: 1.5; color: var(--cc-dim); }
+
+.npc-svc-form { display: flex; flex-direction: column; gap: 13px; }
+.npc-svc-field { display: flex; flex-direction: column; gap: 5px; }
+.npc-svc-field-label { font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--cc-dim); }
+.npc-svc-field-help { font-size: 11.5px; color: var(--cc-faint); }
+.npc-svc-input {
+ width: 100%; background: var(--cc-bg2); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);
+ padding: 9px 11px; font: inherit; font-size: 14px; transition: border-color 0.14s ease, box-shadow 0.14s ease;
+}
+textarea.npc-svc-input { resize: vertical; min-height: 64px; line-height: 1.45; }
+select.npc-svc-input { cursor: pointer; appearance: none; -webkit-appearance: none;
+ background-image: linear-gradient(45deg, transparent 50%, var(--cc-dim) 50%), linear-gradient(135deg, var(--cc-dim) 50%, transparent 50%);
+ background-position: calc(100% - 16px) 52%, calc(100% - 11px) 52%; background-size: 5px 5px, 5px 5px; background-repeat: no-repeat;
+ padding-right: 30px;
+}
+.npc-svc-input::placeholder { color: var(--cc-faint); }
+.npc-svc-input:focus { outline: none; border-color: var(--cc-edge-hi); box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.08); }
+.npc-svc-input:disabled { opacity: 0.55; cursor: not-allowed; }
+
+.npc-svc-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 5px; }
+.npc-svc-pay, .npc-svc-cancel, .npc-svc-btn {
+ font: inherit; font-size: 13.5px; cursor: pointer; border-radius: var(--cc-radius-sm);
+ padding: 9px 16px; transition: filter 0.14s ease, background 0.14s ease, border-color 0.14s ease, transform 0.06s ease;
+}
+.npc-svc-pay {
+ background: var(--cc-accent); color: var(--cc-ink); border: 1px solid var(--cc-accent); font-weight: 600;
+}
+.npc-svc-pay:hover:not(:disabled) { filter: brightness(0.9); }
+.npc-svc-pay:active:not(:disabled) { transform: translateY(1px); }
+.npc-svc-pay:disabled { opacity: 0.6; cursor: progress; }
+.npc-svc-pay.is-busy .npc-svc-pay-label::before {
+ content: ''; display: inline-block; width: 11px; height: 11px; margin-right: 7px; vertical-align: -1px;
+ border: 2px solid rgba(6, 6, 7, 0.35); border-top-color: var(--cc-ink); border-radius: 50%;
+ animation: npc-svc-spin 0.7s linear infinite;
+}
+@keyframes npc-svc-spin { to { transform: rotate(360deg); } }
+.npc-svc-cancel { background: transparent; color: var(--cc-dim); border: 1px solid var(--cc-edge); }
+.npc-svc-cancel:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.npc-svc-pay:focus-visible, .npc-svc-cancel:focus-visible, .npc-svc-btn:focus-visible, .npc-svc-copy:focus-visible {
+ outline: 2px solid var(--cc-edge-hi); outline-offset: 1px;
+}
+
+.npc-svc-error {
+ margin-top: 4px; padding: 9px 11px; font-size: 13px; line-height: 1.4;
+ background: rgba(255, 255, 255, 0.05); border: 1px solid var(--cc-edge); border-left: 2px solid var(--cc-edge-hi);
+ border-radius: var(--cc-radius-sm); color: var(--cc-text);
+}
+
+/* settled result */
+.npc-svc-result { margin-top: 4px; }
+.npc-svc-settled {
+ font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--cc-faint);
+ margin-bottom: 12px; padding-bottom: 10px; border-bottom: 1px solid var(--cc-edge-soft);
+}
+.npc-svc-payload { display: flex; flex-direction: column; gap: 12px; }
+.npc-svc-headline { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
+.npc-svc-topic { font-size: 15px; font-weight: 600; letter-spacing: 0.02em; }
+.npc-svc-lede { margin: 0; font-size: 14px; line-height: 1.55; color: var(--cc-text); }
+.npc-svc-note { margin: 0; font-size: 13px; line-height: 1.5; color: var(--cc-dim); }
+.npc-svc-sublabel { font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--cc-dim); margin-bottom: -4px; }
+.npc-svc-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(96px, 1fr)); gap: 9px; }
+.npc-svc-kv { display: flex; flex-direction: column; gap: 2px; padding: 9px 10px; background: var(--cc-bg2); border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius-sm); }
+.npc-svc-kv-k { font-size: 10.5px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--cc-faint); }
+.npc-svc-kv-v { font-size: 15px; font-weight: 600; }
+.npc-svc-list { margin: 0; padding-left: 18px; display: flex; flex-direction: column; gap: 5px; font-size: 13px; line-height: 1.45; color: var(--cc-text); }
+.npc-svc-list a { color: var(--cc-text); text-decoration: underline; text-underline-offset: 2px; }
+.npc-svc-list a:hover { color: var(--cc-dim); }
+.npc-svc-code { margin: 0; padding: 11px; background: var(--cc-bg); border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius-sm); font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; max-height: 220px; overflow: auto; }
+.npc-svc-mono { font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: 12px; word-break: break-all; color: var(--cc-dim); margin: 0; }
+.npc-svc-address, .npc-svc-secret { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px; background: var(--cc-bg2); border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius-sm); }
+.npc-svc-secret { flex-direction: column; align-items: stretch; }
+.npc-svc-address code, .npc-svc-secret code { font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size: 12.5px; word-break: break-all; flex: 1; min-width: 0; }
+.npc-svc-copy { flex-shrink: 0; font: inherit; font-size: 12px; cursor: pointer; padding: 5px 10px; background: transparent; color: var(--cc-dim); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm); transition: all 0.14s ease; }
+.npc-svc-copy:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.npc-svc-btn { display: inline-block; text-align: center; text-decoration: none; background: transparent; color: var(--cc-text); border: 1px solid var(--cc-edge-hi); align-self: flex-start; }
+.npc-svc-btn:hover { background: rgba(255, 255, 255, 0.06); }
+
+/* pills */
+.npc-svc-pill {
+ display: inline-flex; align-items: center; font-size: 11px; font-weight: 650; letter-spacing: 0.06em;
+ padding: 4px 9px; border-radius: 999px; border: 1px solid var(--cc-edge); color: var(--cc-text); white-space: nowrap;
+}
+.npc-svc-pill.is-price { background: rgba(255, 255, 255, 0.05); color: var(--cc-text); letter-spacing: 0.02em; }
+.npc-svc-pill.is-up { background: rgba(255, 255, 255, 0.92); color: var(--cc-ink); border-color: transparent; }
+.npc-svc-pill.is-down { background: transparent; color: var(--cc-text); border-color: var(--cc-edge-hi); }
+.npc-svc-pill.is-flat { background: rgba(255, 255, 255, 0.06); color: var(--cc-dim); }
+
+@media (max-width: 520px) {
+ .npc-svc-overlay { padding: 0; place-items: end stretch; }
+ .npc-svc-card { width: 100%; max-height: 92vh; border-radius: var(--cc-radius) var(--cc-radius) 0 0; border-bottom: none; }
+ .npc-svc-overlay.is-in .npc-svc-card { transform: translateY(0); }
+ .npc-svc-card { transform: translateY(14px); }
+}
+@media (prefers-reduced-motion: reduce) {
+ .npc-svc-overlay, .npc-svc-card { transition: none; }
+ .npc-svc-pay.is-busy .npc-svc-pay-label::before { animation: none; }
+}
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 49d4d447b..b9fe87b8e 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -44,6 +44,8 @@ import { CosmeticsShop } from './cosmetics-shop.js';
import { HOME_TOWN, isHomeTown } from './home-town.js';
import { AgentCommerce } from './agent-commerce.js';
import { WorldLife } from './npc/world-life.js';
+import { isChatPanelOpen } from './npc/npc-chat.js';
+import { isServicePanelOpen } from './npc/npc-services.js';
import { VoiceChat, voiceSupported } from './voice-chat.js';
import { requestHolderPass, signInWithX, ensureSolanaWallet, relinkSolanaWallet, getSession, getWorldGate, setWorldGate } from '../community/town-auth.js';
import { ensurePlayAccess } from './play-gate.js';
@@ -1403,6 +1405,9 @@ export class CoinCommunities {
// the home town (no-op elsewhere). Not while building.
if (k === 'e' && !this.buildHud.active) {
e.preventDefault();
+ // A conversation or counter is already open — let it own the moment
+ // instead of reopening on top of itself.
+ if (isChatPanelOpen() || isServicePanelOpen()) return;
// Talk to the nearest townsperson (vendor/quest/flavor); if none is
// in range, fall through to the home town's Agent Exchange.
if (!this.worldLife?.interact()) this.agentCommerce?.interact();
diff --git a/src/game/npc/npc-catalog.js b/src/game/npc/npc-catalog.js
index b36dd0629..50bc89bca 100644
--- a/src/game/npc/npc-catalog.js
+++ b/src/game/npc/npc-catalog.js
@@ -14,18 +14,21 @@
// couple of universal-service locals so its plaza still trades.
import { isHomeTown } from '../home-town.js';
-import { openService } from './npc-services.js';
+import { openChat } from './npc-chat.js';
const AVATAR_A = '/avatars/default.glb';
const AVATAR_B = '/avatars/cz.glb';
-// Bind an NPC to its x402 service. On interact the NPC greets, plays a beat, and
-// opens its service counter; the counter runs the real wallet payment.
-function serve(serviceId, greeting, emote) {
- return ({ npc, ui }) => {
+// Bind an NPC to a conversation. On interact the NPC greets in-world, plays a
+// beat, and opens a real chat: it answers in character, live from the same models
+// the chats use (see npc-chat.js). Vendors pass a serviceId so the chat surfaces
+// the paid counter — the NPC talks you toward the sale, the counter settles it.
+// `persona` is the character voice; `greeting` is the line spoken on walk-up.
+function talk({ serviceId, persona, greeting, emote }) {
+ return ({ npc, ui, world }) => {
if (greeting) npc.say(greeting);
if (emote) npc.emote(emote);
- openService(serviceId, { npc, ui });
+ openChat(npc, { ui, serviceId, persona, greeting, world });
};
}
@@ -45,7 +48,12 @@ export function npcCatalogFor(world) {
yaw: Math.PI / 2,
range: 5,
prompt: 'Read the market',
- onInteract: serve('crypto-intel', 'Want the read on a coin? A cent buys the truth.', 'av-call-me'),
+ onInteract: talk({
+ serviceId: 'crypto-intel',
+ greeting: 'Want the read on a coin? A cent buys the truth.',
+ emote: 'av-call-me',
+ persona: 'You are Marisol, the town\'s trading desk — a sharp, fast-talking market reader who lives in numbers and never sugarcoats a chart. Confident, a little wry, always sizing up whether a thing is bullish or bearish.',
+ }),
});
// Sheriff Boone — the law. Verifies claims (fact-check) with sources.
@@ -58,7 +66,12 @@ export function npcCatalogFor(world) {
yaw: 0,
range: 5,
prompt: 'Bring a claim',
- onInteract: serve('fact-check', 'Heard somethin’ you ain’t sure of? I’ll get to the truth.', 'av-arm-flex'),
+ onInteract: talk({
+ serviceId: 'fact-check',
+ greeting: 'Heard somethin’ you ain’t sure of? I’ll get to the truth.',
+ emote: 'av-arm-flex',
+ persona: 'You are Sheriff Boone, the law in this town — slow, measured, and allergic to rumor. You weigh your words, distrust hearsay, and care only about what can be proven with sources. Plain-spoken frontier lawman.',
+ }),
});
// Saloon Kid — the club. Tips a dancer onto the stage (dance-tip).
@@ -71,7 +84,12 @@ export function npcCatalogFor(world) {
yaw: -Math.PI / 2,
range: 5,
prompt: 'Tip the floor',
- onInteract: serve('dance-tip', 'Drop a coin and somebody dances. Who’s it gonna be?', 'av-call-me'),
+ onInteract: talk({
+ serviceId: 'dance-tip',
+ greeting: 'Drop a coin and somebody dances. Who’s it gonna be?',
+ emote: 'av-call-me',
+ persona: 'You are the Saloon Kid, the young hype-man running the dance floor at the club — all energy, grins, and showmanship. You live for a good time and love getting somebody up on stage.',
+ }),
});
// Old Pete — the prospector. Grinds vanity Solana keys (vanity).
@@ -84,7 +102,12 @@ export function npcCatalogFor(world) {
yaw: -Math.PI * 0.7,
range: 5,
prompt: 'Grind an address',
- onInteract: serve('vanity', 'I mine letters, not gold. Tell me what your address should spell.', 'av-arm-flex'),
+ onInteract: talk({
+ serviceId: 'vanity',
+ greeting: 'I mine letters, not gold. Tell me what your address should spell.',
+ emote: 'av-arm-flex',
+ persona: 'You are Old Pete, a grizzled prospector who gave up panning for gold to mine vanity Solana addresses — letters, not nuggets. Crusty, patient, full of mining metaphors, proud of the keys you grind.',
+ }),
});
// Wendell — the assay office clerk. Checks ticker collisions (symbol).
@@ -97,7 +120,12 @@ export function npcCatalogFor(world) {
yaw: -Math.PI * 0.85,
range: 5,
prompt: 'Stake a name',
- onInteract: serve('symbol-availability', 'Before you stake that ticker — let me check it ain’t already claimed.', 'av-call-me'),
+ onInteract: talk({
+ serviceId: 'symbol-availability',
+ greeting: 'Before you stake that ticker — let me check it ain’t already claimed.',
+ emote: 'av-call-me',
+ persona: 'You are Wendell, the assay-office clerk — meticulous, precise, and a stickler for whether a ticker is already claimed. You treat a token symbol like a mining claim that has to be registered clean. Dry, exacting, a touch bureaucratic.',
+ }),
});
// Mei — the foundry. Forges a token mint into a 3D mesh (mint-to-mesh).
@@ -110,7 +138,12 @@ export function npcCatalogFor(world) {
yaw: Math.PI,
range: 5,
prompt: 'Forge a mesh',
- onInteract: serve('mint-to-mesh', 'Hand me a mint. I’ll forge it into somethin’ you can hold.', 'av-arm-flex'),
+ onInteract: talk({
+ serviceId: 'mint-to-mesh',
+ greeting: 'Hand me a mint. I’ll forge it into somethin’ you can hold.',
+ emote: 'av-arm-flex',
+ persona: 'You are Mei, the town foundry-keeper who forges token mints into 3D meshes you can actually hold. A maker with soot on her hands and real pride in her craft — warm, direct, always talking about what she can build.',
+ }),
});
// Doc Halloran — the audit desk. Audits a pump-agent token (audit).
@@ -123,7 +156,12 @@ export function npcCatalogFor(world) {
yaw: 0,
range: 5,
prompt: 'Audit the books',
- onInteract: serve('pump-agent-audit', 'You don’t pay a token ’til you’ve seen its books. Give me a mint.', 'av-call-me'),
+ onInteract: talk({
+ serviceId: 'pump-agent-audit',
+ greeting: 'You don’t pay a token ’til you’ve seen its books. Give me a mint.',
+ emote: 'av-call-me',
+ persona: 'You are Doc Halloran, the town auditor — skeptical, careful, and never trusting a token until you\'ve read its ledger. You speak in ledgers and red flags, and you\'d rather find the rot before someone loses their stake. Wry, sharp-eyed.',
+ }),
});
// The Oracle — reputation. Reads an agent's on-chain record (reputation).
@@ -136,7 +174,12 @@ export function npcCatalogFor(world) {
yaw: Math.PI / 4,
range: 5,
prompt: 'Vet an agent',
- onInteract: serve('agent-reputation', 'Name the agent. I’ll tell you what the chain remembers.', 'av-arm-flex'),
+ onInteract: talk({
+ serviceId: 'agent-reputation',
+ greeting: 'Name the agent. I’ll tell you what the chain remembers.',
+ emote: 'av-arm-flex',
+ persona: 'You are the Oracle, a quiet seer who reads what the chain remembers about any agent — coins deployed, money taken, trust earned. You speak in measured, slightly mystical terms, but everything you say is grounded in the on-chain record.',
+ }),
});
// The Schoolmarm — the tutor. Answers any question (tutor).
@@ -149,7 +192,12 @@ export function npcCatalogFor(world) {
yaw: 0,
range: 5,
prompt: 'Ask a question',
- onInteract: serve('tutor', 'A cent a question, and you leave knowin’ more than you came. Ask.', 'av-call-me'),
+ onInteract: talk({
+ serviceId: 'tutor',
+ greeting: 'A cent a question, and you leave knowin’ more than you came. Ask.',
+ emote: 'av-call-me',
+ persona: 'You are Miss Ada, the town schoolmarm and tutor — patient, encouraging, and delighted by a good question. You explain things clearly with a teacher\'s warmth, code or crypto or the wider world, and you love when a visitor leaves a little smarter.',
+ }),
});
// The Banker — the launchpad. Deploys a live pump.fun coin (pump-launch).
@@ -162,7 +210,12 @@ export function npcCatalogFor(world) {
yaw: -Math.PI / 2,
range: 5,
prompt: 'Launch a coin',
- onInteract: serve('pump-launch', 'Five dollars and your coin’s on the board by sundown. Name it.', 'av-arm-flex'),
+ onInteract: talk({
+ serviceId: 'pump-launch',
+ greeting: 'Five dollars and your coin’s on the board by sundown. Name it.',
+ emote: 'av-arm-flex',
+ persona: 'You are Banker Cole, the smooth-talking frontier banker who runs the launchpad — you front the SOL and put a live coin on the board. Polished, persuasive, a dealmaker who makes launching sound easy. Confident without being pushy.',
+ }),
});
return list;
@@ -179,7 +232,12 @@ export function npcCatalogFor(world) {
yaw: Math.PI / 3,
range: 5,
prompt: 'Read the market',
- onInteract: serve('crypto-intel', 'New here? A cent gets you the read on any coin.', 'av-call-me'),
+ onInteract: talk({
+ serviceId: 'crypto-intel',
+ greeting: 'New here? A cent gets you the read on any coin.',
+ emote: 'av-call-me',
+ persona: 'You are the Local Trader, a friendly newcomer-greeter at this plaza\'s trading desk who reads the market for anyone passing through. Welcoming, quick with a number, happy to show a stranger the ropes.',
+ }),
});
list.push({
id: 'svc-local-factcheck',
@@ -190,7 +248,12 @@ export function npcCatalogFor(world) {
yaw: -Math.PI * 0.8,
range: 5,
prompt: 'Bring a claim',
- onInteract: serve('fact-check', 'Got a claim you want checked? I’ll run the sources.', 'av-arm-flex'),
+ onInteract: talk({
+ serviceId: 'fact-check',
+ greeting: 'Got a claim you want checked? I’ll run the sources.',
+ emote: 'av-arm-flex',
+ persona: 'You are the Local Scribe, the plaza\'s record-keeper who checks claims against the sources. Careful, literate, even-handed — you won\'t call a thing true or false until the sources back it.',
+ }),
});
return list;
}
diff --git a/src/game/npc/npc-chat.js b/src/game/npc/npc-chat.js
new file mode 100644
index 000000000..3931d1e41
--- /dev/null
+++ b/src/game/npc/npc-chat.js
@@ -0,0 +1,335 @@
+// Talk to the townsfolk — the conversational layer over the interactive NPCs.
+//
+// Ambient life (movement, crowd chatter) stays deterministic and code-driven; no
+// model runs for that. But when a player walks up and presses E, this opens a
+// real conversation: the NPC answers in character, streamed live from the same
+// multi-model proxy the chats use (/api/brain/chat). The player can switch the
+// model mid-conversation from the picker, exactly like the brain playground.
+//
+// Each NPC carries a `persona` (its voice) and, for vendors, a `serviceId` that
+// links to the paid counter in npc-services.js. The chat knows about the counter
+// and surfaces a one-tap button to open it — the NPC talks you toward the sale,
+// the counter settles it on-chain. One coin only, ever: $three.
+
+import { SERVICES, openService, isServicePanelOpen } from './npc-services.js';
+import { log } from '../../shared/log.js';
+
+const THREE = '$three';
+const ENDPOINT = '/api/brain/chat';
+const PROVIDER_KEY = 'npc-chat:provider'; // remembered model across conversations
+const MAX_TOKENS = 512; // short, spoken-length replies
+const HISTORY_CAP = 24; // turns kept in the model context
+
+// ── tiny DOM helper (self-contained; mirrors npc-services.js conventions) ──────
+function el(tag, attrs, kids) {
+ const node = document.createElement(tag);
+ if (attrs) {
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k === 'html') node.innerHTML = v;
+ else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v);
+ else node.setAttribute(k, v === true ? '' : v);
+ }
+ }
+ for (const kid of [].concat(kids || [])) {
+ if (kid == null || kid === false) continue;
+ node.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);
+ }
+ return node;
+}
+
+// ── provider list (fetched once, cached) ──────────────────────────────────────
+// The same models the chats expose. We surface every configured one and let the
+// player pick; unconfigured providers are shown disabled so the roster reads true.
+let providersPromise = null;
+function loadProviders() {
+ if (!providersPromise) {
+ providersPromise = fetch(ENDPOINT, { method: 'GET' })
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
+ .then((j) => (Array.isArray(j.providers) ? j.providers : []))
+ .catch((e) => { providersPromise = null; log.warn('[npc-chat] provider list failed:', e?.message); return []; });
+ }
+ return providersPromise;
+}
+
+function preferredProvider(providers) {
+ const saved = (() => { try { return localStorage.getItem(PROVIDER_KEY); } catch { return null; } })();
+ const isLive = (k) => providers.some((p) => p.key === k && p.available);
+ if (saved && isLive(saved)) return saved;
+ const firstLive = providers.find((p) => p.available);
+ return firstLive ? firstLive.key : (providers[0]?.key || 'gpt-oss-120b');
+}
+
+// ── persona → system prompt ───────────────────────────────────────────────────
+// One coin, ever. The prompt hard-locks the NPC to $three and to its character,
+// and — for vendors — teaches it about its own counter so it can guide the sale.
+function buildSystemPrompt({ npc, svc, persona, greeting }) {
+ const parts = [
+ `You are ${npc.name}, a character who lives and works in a frontier town inside three.ws — a 3D world platform built around ${THREE}, the one and only coin.`,
+ persona,
+ `A visitor has just walked up to you in the town square and started talking. Speak out loud, in character, the way this person really talks — voice, mood, and all.`,
+ `Keep every reply short and natural: usually one to three sentences, like real spoken dialogue. No lists, no headings, no markdown, no stage directions. Stay curious — ask the visitor things back.`,
+ ];
+ if (svc) {
+ parts.push(
+ `Your trade is the "${svc.title}" counter you run right here (${svc.price}). ${svc.intro} You cannot run it from conversation — when the visitor wants it, tell them to tap the "${svc.action}" button to open your counter and pay from their wallet.`,
+ );
+ }
+ if (greeting) parts.push(`You already greeted them with: "${greeting}". Continue naturally from there — don't greet again.`);
+ parts.push(
+ `Rules you never break: stay fully in character; never say or imply you are an AI, a model, a bot, or a program; never mention, name, link, or recommend any coin or token other than ${THREE}. If asked about any other coin, brush it off and bring it back to ${THREE}.`,
+ );
+ return parts.filter(Boolean).join('\n\n');
+}
+
+// ── SSE streaming (matches the /api/brain/chat protocol used by the brain page) ─
+async function streamReply({ provider, messages, system, signal, onChunk, onDone, onError }) {
+ let res;
+ try {
+ res = await fetch(ENDPOINT, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ signal,
+ body: JSON.stringify({ provider, messages, system, maxTokens: MAX_TOKENS }),
+ });
+ } catch (err) {
+ if (err?.name !== 'AbortError') onError?.(err?.message || 'Network error');
+ return;
+ }
+ if (!res.ok || !res.body) {
+ let msg = `HTTP ${res.status}`;
+ try { const j = await res.json(); msg = j.message || j.error || msg; } catch { /* non-JSON body */ }
+ onError?.(msg);
+ return;
+ }
+
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let gotDone = false;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let idx;
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
+ const event = buf.slice(0, idx);
+ buf = buf.slice(idx + 2);
+ let evType = 'message', data = '';
+ for (const line of event.split('\n')) {
+ if (line.startsWith('event:')) evType = line.slice(6).trim();
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
+ }
+ if (evType === 'message' && data && data !== '[DONE]') {
+ try { onChunk?.(JSON.parse(data)); } catch { /* malformed chunk */ }
+ } else if (evType === 'done') {
+ gotDone = true;
+ try { onDone?.(JSON.parse(data)); } catch { onDone?.({}); }
+ } else if (evType === 'error') {
+ try { onError?.(JSON.parse(data).message || 'upstream error'); } catch { onError?.('upstream error'); }
+ }
+ }
+ }
+ } catch (err) {
+ if (err?.name !== 'AbortError') onError?.(err?.message || 'stream error');
+ } finally {
+ if (!gotDone) onDone?.({});
+ }
+}
+
+// ── panel ──────────────────────────────────────────────────────────────────────
+let openPanel = null; // single live conversation at a time
+
+export function isChatPanelOpen() { return !!openPanel; }
+
+function closeChat() {
+ if (!openPanel) return;
+ const { overlay, onKey, opener, abort } = openPanel;
+ abort?.abort();
+ document.removeEventListener('keydown', onKey, true);
+ overlay.classList.remove('is-in');
+ const node = overlay;
+ setTimeout(() => node.remove(), 180);
+ openPanel = null;
+ if (opener && typeof opener.focus === 'function') opener.focus();
+}
+
+// Open a conversation with `npc`. Opts:
+// serviceId links to a SERVICES counter (vendors)
+// persona the character voice baked into the system prompt
+// greeting the line already spoken in-world (seeds the log + prompt)
+export function openChat(npc, { ui, serviceId, persona, greeting, world } = {}) {
+ closeChat();
+ const svc = serviceId ? SERVICES[serviceId] : null;
+
+ // model context: real user/assistant turns only (the greeting is display-only,
+ // kept out of the payload so the history always opens on a user turn).
+ const history = [];
+ const system = buildSystemPrompt({ npc, svc, persona, greeting });
+ let provider = 'gpt-oss-120b';
+ let streaming = false;
+ const abort = new AbortController();
+
+ const titleId = `npc-chat-title-${npc.id}`;
+ const card = el('div', { class: 'npc-chat-card', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId });
+ const overlay = el('div', { class: 'npc-chat-overlay' }, [card]);
+ overlay.addEventListener('mousedown', (e) => { if (e.target === overlay) closeChat(); });
+
+ // Header — who you're talking to + the model driving them.
+ const roleLabel = svc ? `${svc.merchant}` : 'Townsperson · three.ws';
+ const modelSelect = el('select', { class: 'npc-chat-model', 'aria-label': 'Model' }, [
+ el('option', { value: provider }, ['Loading models…']),
+ ]);
+ const close = el('button', { class: 'npc-chat-close', type: 'button', 'aria-label': 'Close', text: '✕', onclick: closeChat });
+ card.appendChild(el('header', { class: 'npc-chat-head' }, [
+ el('div', { class: 'npc-chat-id' }, [
+ el('div', { id: titleId, class: 'npc-chat-who', text: npc.name }),
+ el('div', { class: 'npc-chat-sub', text: roleLabel }),
+ ]),
+ el('div', { class: 'npc-chat-tools' }, [modelSelect, close]),
+ ]));
+
+ // Vendor: a one-tap chip to open the paid counter mid-conversation.
+ if (svc) {
+ card.appendChild(el('div', { class: 'npc-chat-offer' }, [
+ el('button', {
+ class: 'npc-chat-offer-btn', type: 'button',
+ onclick: () => { closeChat(); openService(serviceId, { npc, ui }); },
+ }, [
+ el('span', { class: 'npc-chat-offer-label', text: svc.action }),
+ el('span', { class: 'npc-chat-offer-price', text: svc.price }),
+ ]),
+ ]));
+ }
+
+ const logEl = el('div', { class: 'npc-chat-log', role: 'log', 'aria-live': 'polite' });
+ card.appendChild(logEl);
+
+ // Composer.
+ const input = el('textarea', {
+ class: 'npc-chat-input', rows: '1', maxlength: '600',
+ placeholder: `Say something to ${npc.name.split(/[·.]/)[0].trim()}…`, 'aria-label': 'Your message',
+ });
+ const sendBtn = el('button', { class: 'npc-chat-send', type: 'submit', 'aria-label': 'Send', text: 'Send' });
+ const form = el('form', { class: 'npc-chat-composer' }, [input, sendBtn]);
+ card.appendChild(form);
+
+ // Keep typing out of the world's movement / interaction handlers.
+ const swallow = (e) => e.stopPropagation();
+ input.addEventListener('keydown', swallow);
+ input.addEventListener('keyup', swallow);
+ input.addEventListener('input', () => {
+ input.style.height = 'auto';
+ input.style.height = Math.min(input.scrollHeight, 120) + 'px';
+ });
+
+ function scrollDown() { logEl.scrollTop = logEl.scrollHeight; }
+
+ function addBubble(role, text) {
+ const bubble = el('div', { class: `npc-chat-msg is-${role}` }, [
+ el('div', { class: 'npc-chat-text', text: text || '' }),
+ ]);
+ logEl.appendChild(bubble);
+ scrollDown();
+ return bubble.querySelector('.npc-chat-text');
+ }
+
+ // Seed the conversation with what the NPC already said in-world.
+ if (greeting) addBubble('npc', greeting);
+ else addBubble('npc', `…`);
+
+ function setBusy(busy) {
+ streaming = busy;
+ sendBtn.disabled = busy;
+ sendBtn.textContent = busy ? '…' : 'Send';
+ input.disabled = busy;
+ }
+
+ async function send() {
+ const text = input.value.trim();
+ if (!text || streaming) return;
+ input.value = '';
+ input.style.height = 'auto';
+ addBubble('me', text);
+ history.push({ role: 'user', content: text });
+ if (history.length > HISTORY_CAP) history.splice(0, history.length - HISTORY_CAP);
+
+ setBusy(true);
+ const target = addBubble('npc', '');
+ target.parentElement.classList.add('is-typing');
+ let acc = '';
+ await streamReply({
+ provider,
+ messages: history.slice(),
+ system,
+ signal: abort.signal,
+ onChunk: (chunk) => {
+ acc += chunk;
+ target.textContent = acc;
+ target.parentElement.classList.remove('is-typing');
+ scrollDown();
+ },
+ onDone: () => {
+ target.parentElement.classList.remove('is-typing');
+ const reply = acc.trim();
+ if (reply) {
+ history.push({ role: 'assistant', content: reply });
+ npc.say?.(reply.length > 140 ? reply.slice(0, 137) + '…' : reply);
+ } else {
+ target.parentElement.classList.add('is-error');
+ target.textContent = 'They went quiet. Try again.';
+ }
+ setBusy(false);
+ input.focus();
+ },
+ onError: (msg) => {
+ target.parentElement.classList.remove('is-typing');
+ target.parentElement.classList.add('is-error');
+ target.textContent = /not configured|HTTP 503|api key/i.test(msg)
+ ? 'That model isn’t available — pick another from the menu.'
+ : `Couldn’t reach them: ${msg}`;
+ setBusy(false);
+ input.focus();
+ },
+ });
+ }
+
+ form.addEventListener('submit', (e) => { e.preventDefault(); send(); });
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
+ });
+
+ // Populate the model picker from the live roster.
+ loadProviders().then((providers) => {
+ if (openPanel?.overlay !== overlay) return; // panel closed before list arrived
+ provider = preferredProvider(providers);
+ modelSelect.textContent = '';
+ const opts = providers.length ? providers : [{ key: provider, label: provider, network: '', available: true }];
+ for (const p of opts) {
+ modelSelect.appendChild(el('option', {
+ value: p.key, selected: p.key === provider, disabled: !p.available,
+ }, [p.available ? p.label : `${p.label} (add key)`]));
+ }
+ modelSelect.value = provider;
+ });
+ modelSelect.addEventListener('change', () => {
+ provider = modelSelect.value;
+ try { localStorage.setItem(PROVIDER_KEY, provider); } catch { /* storage blocked */ }
+ });
+
+ // Mount + ESC + focus.
+ const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ const onKey = (e) => {
+ if (e.key === 'Escape' && !isServicePanelOpen()) { e.stopPropagation(); e.preventDefault(); closeChat(); }
+ };
+ document.addEventListener('keydown', onKey, true);
+ document.body.appendChild(overlay);
+ openPanel = { overlay, onKey, opener, abort };
+ requestAnimationFrame(() => {
+ overlay.classList.add('is-in');
+ input.focus();
+ });
+}