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.

IRL: server-side geohash, owner pin calibration endpoint, and placement refinements

nirholas7633c9438605
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f5d27b7d..2331f08a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,7 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk** — iPhone Safari has no AR mode, so a placed agent used to drift with the camera. On three.ws/irl it now stays anchored to its real-world spot using the compass and GPS: pan your phone and the agent holds its real bearing instead of following the view, and walk toward it and it grows and keeps its place. Tapping Pin here saves the full placement — facing, ground height, and how good your GPS fix was — so iPhone placements match the AR-anchored version other phones see. If you pin before your location is ready, it waits for the first fix and pins precisely instead of dropping at a default spot. Permission states are designed and recoverable too: if motion or location access is off you get a clear card with the exact iOS Settings path and a Try again button, and if your phone can't read an absolute compass heading you're warned that others may see the agent rotated. (`/irl`) `[improvement]`
- **IRL agents now materialize as you walk up to them** — On three.ws/irl, a 3D agent placed further away first appears as a glowing beacon to keep things light. Previously it stayed a beacon even after you walked right up to it; now it upgrades to the full 3D avatar the moment you come within range, so approaching an agent in real life actually reveals it. Distance to each nearby agent is also recalculated live as you move instead of being frozen at the moment you arrived. Long AR sessions are smoother too: agents that leave the area now fully release their 3D model from memory instead of quietly accumulating, which keeps the camera view fast when you're somewhere busy with lots of agents coming and going. (`/irl`) `[fix, improvement]`
- **IRL agents turn to look at you as you move around them** — On three.ws/irl, a placed 3D agent now notices the viewer. As you move your phone around it, it eases its body toward your camera and layers on a natural head turn so it appears to look right at you — the real-world version of a desktop avatar that follows your cursor. The head movement is clamped to a realistic neck range so it never over-rotates, and an avatar with no head bone falls back to a clean whole-body turn. Back away and the agent eases home to the heading it was placed at. When nobody is close it shows a subtle idle gaze drift instead of a frozen stare, and the first time you step within a few metres it gives a brief notice reaction. Motion is eased throughout and only the nearest on-screen agents are tracked each frame, so it stays smooth even with several agents around you. (`/irl`) `[improvement]`
-- **Place your IRL agent on the real floor with AR anchoring** — On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button. (`/irl`) `[feature]`
+- **Place your IRL agent on the real floor with AR anchoring** — On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. If you tap to anchor before your location is ready, it holds the spot and saves it the instant your first GPS fix lands instead of losing the placement. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button. (`/irl`) `[feature]`
- **Tapping an IRL agent is now reliable — hit the body, not just the tiny label** — On three.ws/irl you can now open an agent by tapping its 3D body, not only its small floating name tag. Tapping near a name also works, with a finger-sized target that meets Apple's 44-pixel minimum, so you no longer have to pixel-hunt on a phone. When two agents stand on top of each other, the one in front wins instead of a random pick. As you move, the nearest agent you can reach lights up with a soft focus ring so you can see what you'll tap before you tap it — and if you've turned on Reduce Motion, the ring stays still. Looking and panning around no longer misfires as a tap. (`/irl`) `[improvement]`
## 2026-06-16
diff --git a/api/_lib/geohash.js b/api/_lib/geohash.js
new file mode 100644
index 000000000..35f4f1b75
--- /dev/null
+++ b/api/_lib/geohash.js
@@ -0,0 +1,46 @@
+// Geohash encoder — the server-side spatial key for IRL placement density caps.
+//
+// A precision-7 cell is ~153m × 153m: the fine geocell D4 uses to cap how many
+// agents one small area can hold (so a single actor can't carpet-bomb a plaza).
+// Kept dependency-free and identical in behaviour to multiplayer/src/geohash.js
+// (the matchmaking key, precision-6) so a lat/lng maps to the same lattice on
+// both the realtime host and the API. Duplicated rather than cross-imported
+// because Vercel bundles api/ functions in isolation from the multiplayer package.
+
+const BASE32 = '0123456789bcdefghjkmnpqrstuvwxyz'; // (no a, i, l, o)
+
+/**
+ * Encode a lat/lng to a geohash string of the given precision.
+ * Returns '' for non-finite input so callers can treat an unplaceable point as
+ * "no cell" rather than crashing the insert path.
+ * @param {number} lat
+ * @param {number} lng
+ * @param {number} [precision=7]
+ * @returns {string}
+ */
+export function encodeGeohash(lat, lng, precision = 7) {
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return '';
+ let idx = 0;
+ let bit = 0;
+ let evenBit = true; // true → bisecting longitude, false → latitude
+ let geohash = '';
+ let latMin = -90, latMax = 90;
+ let lngMin = -180, lngMax = 180;
+
+ while (geohash.length < precision) {
+ if (evenBit) {
+ const mid = (lngMin + lngMax) / 2;
+ if (lng >= mid) { idx = idx * 2 + 1; lngMin = mid; } else { idx = idx * 2; lngMax = mid; }
+ } else {
+ const mid = (latMin + latMax) / 2;
+ if (lat >= mid) { idx = idx * 2 + 1; latMin = mid; } else { idx = idx * 2; latMax = mid; }
+ }
+ evenBit = !evenBit;
+ if (++bit === 5) {
+ geohash += BASE32[idx];
+ bit = 0;
+ idx = 0;
+ }
+ }
+ return geohash;
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 7168cceef..5739d6952 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -204,6 +204,17 @@ export const limits = {
// · irlInteractIp — log a tap/view/message (lighter; legit viewing fans out)
irlPinIp: (ip) => getLimiter('irl:pin:ip', { limit: 20, window: '10 m' }).limit(ip),
irlInteractIp: (ip) => getLimiter('irl:interact:ip', { limit: 60, window: '1 m' }).limit(ip),
+ // IRL placement token bucket (D4) — keyed per (device_token + IP), tighter than
+ // the coarse per-IP `irlPinIp` so one device can't script a rapid placement flood
+ // even from a rotating IP. Two windows: a 5/min burst guard and a 30/hour ceiling.
+ // Non-critical → a Redis outage fails open (degraded + logged once/min) so an
+ // infra hiccup never blocks a legitimate placement.
+ irlPinBurst: (key) => getLimiter('irl:pin:burst', { limit: 5, window: '1 m' }).limit(key),
+ irlPinHourly: (key) => getLimiter('irl:pin:hourly', { limit: 30, window: '1 h' }).limit(key),
+ // IRL report submissions (D4) — one report write per (device + IP) burst. The
+ // distinct-reporter dedup in api/irl/report.js is the real anti-abuse gate; this
+ // just bounds raw POST volume from one source.
+ irlReportIp: (ip) => getLimiter('irl:report:ip', { limit: 10, window: '5 m' }).limit(ip),
// Same-origin image proxy (api/img). A token-cloud view loads dozens of
// thumbnails at once, so the ceiling is generous — but bounded so the proxy
// can't be turned into an open bandwidth relay. Responses are CDN-cached.
diff --git a/api/irl/agent-card.js b/api/irl/agent-card.js
index 2ae28a9c6..6cad5464b 100644
--- a/api/irl/agent-card.js
+++ b/api/irl/agent-card.js
@@ -26,8 +26,8 @@
* what a "tap → pay this service" card should surface.
*
* { agent: { id, name, bio, thumbnail_url, profile_url },
- * reputation: { asset, score, tier, attestation_count, unique_attesters,
- * tasks_accepted, available },
+ * reputation: { asset, network, score, tier, attestation_count,
+ * unique_attesters, tasks_accepted, available },
* services: [{ skill, name, description, price_usd, currency, chain,
* x402_endpoint }],
* x402_endpoint }
@@ -145,10 +145,10 @@ async function buildCard(agentId, fallback = {}) {
} else {
try {
const rep = await fetchReputation(asset, network);
- reputation = { asset, available: true, ...rep };
+ reputation = { asset, network, available: true, ...rep };
} catch (err) {
console.warn('[irl/agent-card] reputation query failed, degrading:', err?.message);
- reputation = { asset, available: false, degraded: true };
+ reputation = { asset, network, available: false, degraded: true };
}
}
diff --git a/api/irl/interactions.js b/api/irl/interactions.js
index 3b1517e55..e64fb06aa 100644
--- a/api/irl/interactions.js
+++ b/api/irl/interactions.js
@@ -8,12 +8,16 @@
*
* POST /api/irl/interactions
* { pinId, type: 'view'|'tap'|'message'|'pay', message?, deviceToken?,
- * amount?, currencyMint?, network?, payload? }
+ * amount?, currencyMint?, network?, payload?, replyTo? }
* agent_id + owner are taken from the pin, never the caller. Anonymous-friendly:
* viewer attribution falls back to the device token. Repeat 'view's from the
* same device on the same pin within VIEW_DEDUPE_MS collapse into the first one.
* A 'pay' must carry a valid settlement signature + a $THREE/USDC mint and is
- * de-duped per signature. 'pay'/'message' fan out an owner notification.
+ * de-duped per signature. A visitor 'pay'/'message' fans out an owner notification.
+ * When the AUTHENTICATED OWNER posts a 'message', it's recorded as a reply
+ * (payload.from='owner', auto-seen) and — if replyTo points at a signed-in
+ * visitor's row — notifies that visitor instead of the owner. Response carries
+ * { notified } so the dashboard can confirm the reply reached someone.
*
* GET /api/irl/interactions?mine=1[&unread=1] — interactions on MY pins
* Owner is matched by session user OR by ?deviceToken= (anonymous placements).
@@ -48,6 +52,7 @@ const MAX_MESSAGE_LEN = 280;
// on by the B3 settlement path, which owns the seller payout + price context.
const EVM_TX_RE = /^0x[0-9a-fA-F]{64}$/;
const SOL_SIG_RE = /^[1-9A-HJ-NP-Za-km-z]{43,88}$/;
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
const USDC_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';
@@ -150,12 +155,18 @@ export default wrap(async (req, res) => {
if (!pin) return json(res, 404, { error: 'pin not found' });
// Don't log an owner inspecting their own pin — that's not an encounter.
+ const isAuthOwner = !!(viewerUserId && pin.user_id && viewerUserId === pin.user_id);
const isOwner =
- (viewerUserId && pin.user_id && viewerUserId === pin.user_id) ||
+ isAuthOwner ||
(viewerDevice && pin.device_token && viewerDevice === pin.device_token);
if (isOwner && type === 'view') {
return json(res, 200, { ok: true, self: true });
}
+ // An authenticated owner posting a `message` is a REPLY to a visitor — a
+ // first-class thread turn, not a self-encounter. It's recorded (stamped
+ // from:'owner', auto-seen so it never inflates the owner's own unread) and,
+ // when the visitor was signed in, fans a notification back to THEM.
+ const isOwnerReply = type === 'message' && isAuthOwner;
// Collapse repeat 'view's from the same device on the same pin.
if (type === 'view' && viewerDevice) {
@@ -172,6 +183,20 @@ export default wrap(async (req, res) => {
let amount = null;
let currencyMint = null;
let payload = clampPayload(body.payload);
+ // `from` / `replyTo` are never client-trusted — a visitor must not be able to
+ // forge a row that looks like an owner reply. Capture the (validated) reply
+ // target first, then strip both; the server re-stamps them only for a genuine
+ // owner reply below.
+ const replyToRaw =
+ (typeof body.replyTo === 'string' && UUID_RE.test(body.replyTo)) ? body.replyTo
+ : (typeof payload.replyTo === 'string' && UUID_RE.test(payload.replyTo)) ? payload.replyTo
+ : null;
+ delete payload.from;
+ delete payload.replyTo;
+ if (isOwnerReply) {
+ payload.from = 'owner';
+ if (replyToRaw) payload.replyTo = replyToRaw;
+ }
if (type === 'pay') {
const sig = payload.signature ?? body.signature ?? null;
const mint = body.currencyMint ?? payload.currencyMint ?? null;
@@ -195,10 +220,13 @@ export default wrap(async (req, res) => {
if (dupe) return json(res, 200, { ok: true, deduped: true, id: dupe.id });
}
+ // An owner reply is authored by the owner, so it lands already-seen — it must
+ // never light up the owner's own unread badge. Every other row is unread.
+ const seenAt = isOwnerReply ? new Date().toISOString() : null;
const [row] = await sql`
INSERT INTO irl_interactions
(pin_id, agent_id, type, message, viewer_user_id, viewer_device, lat, lng,
- amount, currency_mint, payload)
+ amount, currency_mint, payload, seen_at)
VALUES (
${pinId},
${pin.agent_id ?? null},
@@ -210,7 +238,8 @@ export default wrap(async (req, res) => {
${pin.lng},
${amount},
${currencyMint},
- ${JSON.stringify(payload)}::jsonb
+ ${JSON.stringify(payload)}::jsonb,
+ ${seenAt}
)
RETURNING id, type, created_at
`;
@@ -220,10 +249,31 @@ export default wrap(async (req, res) => {
if (type === 'view') {
sql`UPDATE irl_pins SET view_count = view_count + 1 WHERE id = ${pinId}`.catch(() => {});
}
- // High-signal events notify the owner: in-app always (the dashboard inbox +
- // the global nav bell), plus an optional Telegram ping for a pay. Both are
- // fire-and-forget and no-op when the owner is anonymous or creds are absent.
- if ((type === 'pay' || type === 'message') && pin.user_id) {
+ // Fan-out. Both arms are fire-and-forget and no-op when there's no one to
+ // reach (anonymous actor) or creds are absent.
+ let notified = false;
+ if (isOwnerReply) {
+ // The reply reaches the visitor only if they were signed in when they left
+ // the message — an anonymous device has no inbox to deliver to. The owner is
+ // never self-notified for their own reply.
+ if (replyToRaw) {
+ const [orig] = await sql`
+ SELECT viewer_user_id FROM irl_interactions
+ WHERE id = ${replyToRaw} AND pin_id = ${pinId} LIMIT 1
+ `;
+ if (orig?.viewer_user_id && orig.viewer_user_id !== pin.user_id) {
+ insertNotification(orig.viewer_user_id, 'irl_reply', {
+ pin_id: pinId,
+ agent_id: pin.agent_id ?? null,
+ message,
+ link: pin.agent_id ? `/agent/${pin.agent_id}` : undefined,
+ });
+ notified = true;
+ }
+ }
+ } else if ((type === 'pay' || type === 'message') && pin.user_id) {
+ // High-signal visitor events notify the owner: in-app always (the dashboard
+ // inbox + the global nav bell), plus an optional Telegram ping for a pay.
insertNotification(pin.user_id, 'irl_interaction', {
pin_id: pinId,
agent_id: pin.agent_id ?? null,
@@ -242,7 +292,7 @@ export default wrap(async (req, res) => {
);
}
}
- return json(res, 201, { ok: true, interaction: row });
+ return json(res, 201, { ok: true, interaction: row, notified });
}
// ── GET — public count for a single pin ───────────────────────────────────
diff --git a/api/irl/pins.js b/api/irl/pins.js
index dc56a8be4..19e06a31a 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -16,6 +16,111 @@ import { cors, json, wrap, rateLimited } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { WORD_BLACKLIST } from '../../src/profanity.js';
+import { guardianConfig, assess, decide } from '../_lib/granite-guardian.js';
+import { encodeGeohash } from '../_lib/geohash.js';
+
+// ── Moderation, safety & density caps (D4) ──────────────────────────────────
+// Everything below makes the public, shared IRL world safe to launch: content
+// gating on caption/name, a $THREE-only coin guard, an x402 endpoint allow-list,
+// per-area density caps, and per-owner active-pin caps. Each rejection returns a
+// designed error code the client surfaces as an actionable message.
+
+const CAPTION_MAX = 140; // public caption hard length cap
+const NAME_MAX = 40; // avatar name hard length cap
+const GEOCELL_PRECISION = 7; // ~153m × 153m density cell
+const MAX_PINS_PER_CELL = 40; // density ceiling per geocell7
+const MAX_PINS_PER_OWNER_ANON = 20; // active pins for an anonymous device
+const MAX_PINS_PER_OWNER_SIGNED = 60; // higher ceiling once accountable (signed in)
+
+// $THREE is the only coin three.ws references (contract below). The off-brand
+// guard is written generically — it never names a competing ticker — so this
+// codebase stays clean of other coins while still rejecting shills.
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// Always-on hard gate: lower-case substring match against the shared slur/severe
+// list. No external dependency, fails closed and fast — the floor under the
+// smarter Guardian tier. Reused verbatim from the pump.fun feed filter.
+function hardBlocked(text) {
+ const t = String(text || '').toLowerCase();
+ return WORD_BLACKLIST.some((w) => t.includes(w));
+}
+
+// Off-brand-coin guard: reject text that shills a token other than $THREE — a
+// `$TICKER` cashtag that isn't $THREE, or a pump.fun-style mint address (…pump)
+// that isn't the $THREE contract. Generic by construction so no competitor is
+// ever written into source; $THREE (cashtag or contract) is explicitly allowed.
+function namesOffBrandCoin(text) {
+ const t = String(text || '');
+ const cashtags = t.match(/\$[A-Za-z][A-Za-z0-9]{1,9}\b/g) || [];
+ if (cashtags.some((c) => c.slice(1).toUpperCase() !== 'THREE')) return true;
+ const tokens = t.match(/\b[1-9A-HJ-NP-Za-km-z]{32,48}\b/g) || [];
+ if (tokens.some((m) => /pump$/.test(m) && m !== THREE_MINT)) return true;
+ return false;
+}
+
+// Tier-1 content decision over caption + name. Returns the offending field +
+// reason, or null when clean. Pure string work — the cheapest, most decisive gate.
+function contentReject(caption, name) {
+ if (hardBlocked(caption)) return { field: 'caption', reason: 'blocked' };
+ if (hardBlocked(name)) return { field: 'avatarName', reason: 'blocked' };
+ if (namesOffBrandCoin(caption)) return { field: 'caption', reason: 'coin' };
+ if (namesOffBrandCoin(name)) return { field: 'avatarName', reason: 'coin' };
+ return null;
+}
+
+// Tier-2 AI content risk over the free-text caption — Granite Guardian. Best-
+// effort by design (Rule 9): when watsonx isn't configured, or the classifier
+// errors/times out, we DON'T block — the always-on wordlist already caught the
+// hard cases, and a missing key must never 500 a placement. Bounded to 4s so a
+// slow upstream can't stall the POST.
+async function guardianFlags(caption) {
+ const text = String(caption || '').trim();
+ if (!text) return false;
+ const cfg = guardianConfig();
+ if (!cfg.configured) return false;
+ try {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), 4000);
+ try {
+ const verdicts = await assess(cfg, {
+ input: text,
+ risks: ['harm', 'social_bias', 'violence', 'sexual_content'],
+ signal: ctrl.signal,
+ });
+ return decide(verdicts).decision === 'block';
+ } finally {
+ clearTimeout(timer);
+ }
+ } catch (err) {
+ console.warn('[irl/pins] guardian content check degraded:', err?.message || err);
+ return false;
+ }
+}
+
+// x402 pay-endpoint allow-list (D4). A pin's advertised "pay" target is handed to
+// every nearby viewer's Pay button, so an arbitrary external URL is a drain/scam
+// vector. On top of safeRemoteUrl's https + no-private-host checks, the host must
+// be first-party three.ws infrastructure (or an operator-extended allow-list via
+// IRL_X402_ALLOWED_HOSTS). Relative same-origin paths are always first-party.
+// Registered-agent endpoints still flow to the Pay button via the trusted
+// server-resolved agent-card path (card.x402_endpoint), which this never gates.
+const X402_ALLOWED_HOSTS = (
+ process.env.IRL_X402_ALLOWED_HOSTS || 'three.ws,www.three.ws,3d-agent.vercel.app,3d.irish'
+)
+ .split(',')
+ .map((h) => h.trim().toLowerCase())
+ .filter(Boolean);
+
+function safePaymentEndpoint(raw) {
+ const base = safeRemoteUrl(raw, { allowRelative: false });
+ if (!base.ok) return { ok: false };
+ if (base.value == null) return { ok: true, value: null };
+ let host;
+ try { host = new URL(base.value).hostname.toLowerCase(); } catch { return { ok: false }; }
+ const allowed = X402_ALLOWED_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));
+ return allowed ? { ok: true, value: base.value } : { ok: false };
+}
// Validate a URL that will be handed to every nearby viewer's browser — the
// avatar GLB (→ GLTFLoader) and the x402 pay endpoint (→ Pay button). Same-origin
@@ -89,6 +194,13 @@ async function ensureTable() {
await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS anchor_source TEXT`; // 'webxr' | 'gyro-gps'
await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS vps_provider TEXT`; // reserved for visual positioning
await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS vps_id TEXT`; // reserved
+ // Moderation + density (D4). geocell7 is the ~150m density key (precision-7
+ // geohash); hidden_at marks a pin queued out of public view after enough
+ // distinct reporters — set, never deleted, so the owner can appeal and the
+ // review console can restore it.
+ await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS geocell7 TEXT`;
+ await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS hidden_at TIMESTAMPTZ`;
+ await sql`CREATE INDEX IF NOT EXISTS irl_pins_geocell7 ON irl_pins (geocell7) WHERE hidden_at IS NULL`;
_tableReady = true;
}
@@ -196,6 +308,7 @@ export default wrap(async (req, res) => {
SELECT id, lat, lng, avatar_name, caption, placed_at, expires_at, view_count
FROM irl_pins
WHERE (device_token = ${deviceToken ?? ''} OR user_id = ${session?.id ?? null})
+ AND hidden_at IS NULL
AND (expires_at IS NULL OR expires_at > NOW())
ORDER BY placed_at DESC
LIMIT 20
@@ -214,6 +327,7 @@ export default wrap(async (req, res) => {
gps_accuracy_m, altitude_m, anchor_source
FROM irl_pins
WHERE user_id = ${session.id}
+ AND hidden_at IS NULL
ORDER BY placed_at DESC
LIMIT 100
`;
@@ -248,6 +362,7 @@ export default wrap(async (req, res) => {
FROM irl_pins
WHERE lat BETWEEN ${lat - latDelta} AND ${lat + latDelta}
AND lng BETWEEN ${lng - lngDelta} AND ${lng + lngDelta}
+ AND hidden_at IS NULL
AND (expires_at IS NULL OR expires_at > NOW())
ORDER BY placed_at DESC
LIMIT 50
@@ -285,8 +400,13 @@ export default wrap(async (req, res) => {
}
// ── POST — create pin ─────────────────────────────────────────────────────
+ // D4 gate order, cheapest/most-decisive first: coords → content (pure string,
+ // fails closed) → URL/coin safety → rate limit (1 Redis cmd, protects the DB
+ // from a flood) → density + per-owner caps (DB counts) → insert. Each rejection
+ // carries a designed error code the client renders as an actionable message.
if (req.method === 'POST') {
- const rl = await limits.irlPinIp(clientIp(req));
+ const ip = clientIp(req);
+ const rl = await limits.irlPinIp(ip);
if (!rl.success) return rateLimited(res, rl);
const body = req.body ?? {};
@@ -300,16 +420,103 @@ export default wrap(async (req, res) => {
return json(res, 400, { error: 'invalid coordinates' });
}
+ // Clamp text to its public length cap, then run the tier-1 content gate.
+ const caption = body.caption != null ? String(body.caption).slice(0, CAPTION_MAX) : null;
+ const avatarName = body.avatarName != null ? String(body.avatarName).slice(0, NAME_MAX) : null;
+ const bad = contentReject(caption, avatarName);
+ if (bad) {
+ return json(res, 422, {
+ error: 'content',
+ field: bad.field,
+ message: bad.reason === 'coin'
+ ? 'A pin can only reference $THREE — the only coin on three.ws.'
+ : 'That text isn’t allowed on a public pin.',
+ });
+ }
+ // Tier-2 AI risk on the borderline caption (no-op when Guardian unconfigured).
+ if (caption && (await guardianFlags(caption))) {
+ return json(res, 422, {
+ error: 'content',
+ field: 'caption',
+ message: 'That caption was flagged by our content filter. Try rewording it.',
+ });
+ }
+
// Validate the URLs handed to every nearby viewer (avatar GLB + x402 pay).
const avatarUrlChk = safeRemoteUrl(body.avatarUrl);
if (!avatarUrlChk.ok) return json(res, 400, { error: 'invalid avatarUrl' });
- const x402Chk = safeRemoteUrl(body.x402Endpoint, { allowRelative: false });
- if (!x402Chk.ok) return json(res, 400, { error: 'invalid x402Endpoint' });
+ // x402 pay target must be a first-party / allow-listed payment host — never an
+ // arbitrary external drain (D4). Same-origin relative paths are first-party.
+ const x402Chk = safePaymentEndpoint(body.x402Endpoint);
+ if (!x402Chk.ok) {
+ return json(res, 422, {
+ error: 'endpoint',
+ field: 'x402Endpoint',
+ message: 'Pay endpoints must be hosted on three.ws.',
+ });
+ }
// Empty-string device token would otherwise become a shared anonymous owner.
const deviceToken = body.deviceToken || null;
const session = await getSessionUser(req).catch(() => null);
const userId = session?.id ?? null;
+
+ // Placement token bucket (D4) — per (device + IP), tighter than the coarse
+ // per-IP gate above. Burst (5/min) + sustained (30/h). Fails open + logs on a
+ // Redis outage (non-critical) so an infra hiccup never blocks a real placement.
+ const rateKey = `${deviceToken ?? userId ?? 'anon'}:${ip}`;
+ const [burst, hourly] = await Promise.all([
+ limits.irlPinBurst(rateKey),
+ limits.irlPinHourly(rateKey),
+ ]);
+ const throttled = !burst.success ? burst : !hourly.success ? hourly : null;
+ if (throttled) {
+ const retryAfter = Math.max(1, Math.ceil((throttled.reset - Date.now()) / 1000));
+ res.setHeader?.('Retry-After', String(retryAfter));
+ return json(res, 429, {
+ error: 'rate',
+ retryAfter,
+ message: 'You’re placing agents too fast. Wait a moment and try again.',
+ });
+ }
+
+ // Density cap — one fine geocell (~150m) can hold only so many agents, so a
+ // single actor can't carpet-bomb a venue. Counts only live, non-hidden pins.
+ const cell7 = encodeGeohash(lat, lng, GEOCELL_PRECISION);
+ if (cell7) {
+ const [{ n }] = await sql`
+ SELECT count(*)::int AS n FROM irl_pins
+ WHERE geocell7 = ${cell7}
+ AND hidden_at IS NULL
+ AND (expires_at IS NULL OR expires_at > NOW())
+ `;
+ if (n >= MAX_PINS_PER_CELL) {
+ return json(res, 429, {
+ error: 'area_full',
+ message: 'This area already has the maximum number of agents. Try another spot.',
+ });
+ }
+ }
+
+ // Per-owner active-pin cap — a signed-in owner is accountable, so gets a
+ // higher ceiling than an anonymous device. Null-guarded so a NULL user_id or
+ // empty device token can't collide owners.
+ const ownerCap = userId ? MAX_PINS_PER_OWNER_SIGNED : MAX_PINS_PER_OWNER_ANON;
+ const [{ n: owned }] = await sql`
+ SELECT count(*)::int AS n FROM irl_pins
+ WHERE ((${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)
+ OR (${deviceToken}::text IS NOT NULL AND device_token = ${deviceToken}))
+ AND hidden_at IS NULL
+ AND (expires_at IS NULL OR expires_at > NOW())
+ `;
+ if (owned >= ownerCap) {
+ return json(res, 429, {
+ error: 'pin_limit',
+ limit: ownerCap,
+ message: 'You’ve reached your active pin limit. Remove an old pin to place a new one.',
+ });
+ }
+
// Authenticated users get permanent pins; anonymous expire in 7 days.
const expiresAt = userId ? null : new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString();
@@ -339,7 +546,7 @@ export default wrap(async (req, res) => {
(user_id, agent_id, device_token, lat, lng, heading,
avatar_url, avatar_name, caption, x402_endpoint, expires_at,
anchor_height_m, anchor_yaw_deg, anchor_quat,
- gps_accuracy_m, altitude_m, anchor_source)
+ gps_accuracy_m, altitude_m, anchor_source, geocell7)
VALUES (
${userId},
${body.agentId ?? null},
@@ -347,8 +554,8 @@ export default wrap(async (req, res) => {
${lat}, ${lng},
${parseFloat(body.heading) || 0},
${avatarUrlChk.value},
- ${body.avatarName ?? null},
- ${body.caption ?? null},
+ ${avatarName},
+ ${caption},
${x402Chk.value},
${expiresAt},
${anchorHeightM},
@@ -356,7 +563,8 @@ export default wrap(async (req, res) => {
${anchorQuat},
${gpsAccuracyM},
${altitudeM},
- ${anchorSource}
+ ${anchorSource},
+ ${cell7 || null}
)
RETURNING *
`;
diff --git a/data/changelog.json b/data/changelog.json
index bf75e80d7..c90aee14c 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -25,7 +25,7 @@
{
"date": "2026-06-17",
"title": "Place your IRL agent on the real floor with AR anchoring",
- "summary": "On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.",
+ "summary": "On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. If you tap to anchor before your location is ready, it holds the spot and saves it the instant your first GPS fix lands instead of losing the placement. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.",
"tags": ["feature"],
"link": "/irl"
},
diff --git a/public/changelog.json b/public/changelog.json
index c2182dffe..2953be945 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T02:22:10.871Z",
+ "generated_at": "2026-06-17T02:32:22.903Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -52,7 +52,7 @@
"date": "2026-06-17",
"type": "update",
"title": "Place your IRL agent on the real floor with AR anchoring",
- "summary": "On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.",
+ "summary": "On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. If you tap to anchor before your location is ready, it holds the spot and saves it the instant your first GPS fix lands instead of losing the placement. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.",
"link": "/irl",
"tags": [
"feature"
diff --git a/public/changelog.xml b/public/changelog.xml
index 6a7a40727..6ec361aba 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -44,7 +44,7 @@
<guid isPermaLink="false">2026-06-17:Place your IRL agent on the real floor with AR anchoring</guid>
<pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
<category>feature</category>
- <description>On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.</description>
+ <description>On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. If you tap to anchor before your location is ready, it holds the spot and saves it the instant your first GPS fix lands instead of losing the placement. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.</description>
</item>
<item>
<title>Tapping an IRL agent is now reliable — hit the body, not just the tiny label</title>
diff --git a/public/features.json b/public/features.json
index 618f3fdc4..8fca97bec 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T02:22:10.851Z",
+ "generated_at": "2026-06-17T02:32:22.882Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 41689933e..81eec51d8 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,20 +56,6 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
-
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="three.ws">
- <meta property="og:title" content="Sitemap · three.ws">
- <meta property="og:description" content="Human-readable index of every page on three.ws.">
- <meta property="og:url" content="https://three.ws/sitemap">
- <meta property="og:image" content="https://three.ws/og-image.png">
- <meta property="og:image:width" content="1200">
- <meta property="og:image:height" content="630">
- <meta name="twitter:card" content="summary_large_image">
- <meta name="twitter:title" content="Sitemap · three.ws">
- <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
- <meta name="twitter:image" content="https://three.ws/og-image.png">
- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
</head>
<body>
<header class="sm-topbar">
diff --git a/src/dashboard-next/pages/irl-placements.js b/src/dashboard-next/pages/irl-placements.js
index 74393abfb..3cd114c6b 100644
--- a/src/dashboard-next/pages/irl-placements.js
+++ b/src/dashboard-next/pages/irl-placements.js
@@ -25,6 +25,7 @@
import { mountShell } from '../shell.js';
import { requireUser, get, post, patch, esc, relTime } from '../api.js';
import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles, attachRetry } from '../../shared/state-kit.js';
+import { mountReputationPanel } from './irl-reputation.js';
// ── Services / x402 skill pricing ───────────────────────────────────────────
// Canonical prices live in agent_skill_prices and feed the x402 manifest +
@@ -51,12 +52,22 @@ function toAtomic(display, decimals) {
return Math.round(Number(display) * 10 ** decimals);
}
// Integer atomic units → human price string (maximumFractionDigits drops any
-// trailing zeros, so 50000 @ 6dp → "0.05", 1000000 @ 6dp → "1").
+// trailing zeros, so 50000 @ 6dp → "0.05", 1000000 @ 6dp → "1"). Grouped with
+// thousands separators for display — $THREE is cheap, so per-call prices can run
+// to thousands of units and "1,500 $THREE" reads better than "1500 $THREE".
function fromAtomic(amount, decimals) {
const n = Number(amount) / 10 ** decimals;
if (!Number.isFinite(n)) return '0';
return n.toLocaleString('en-US', { maximumFractionDigits: decimals });
}
+// Same conversion WITHOUT grouping separators — for prefilling a <input
+// type="number">, which silently blanks on a value containing commas. So a
+// 1,500-unit price stays editable instead of vanishing when the owner taps Edit.
+function fromAtomicInput(amount, decimals) {
+ const n = Number(amount) / 10 ** decimals;
+ if (!Number.isFinite(n)) return '0';
+ return n.toLocaleString('en-US', { maximumFractionDigits: decimals, useGrouping: false });
+}
function haversineDist(lat1, lng1, lat2, lng2) {
const R = 6371000;
@@ -454,6 +465,11 @@ async function mount(el) {
const card2 = data?.card;
if (!card2) { fillStatError(card, 'reputation'); fillStatError(card, 'services'); return; }
fillStat(card, 'reputation', String(card2.reputation?.score ?? 0));
+ // C3 — turn the Reputation chip into the open/close affordance for an
+ // on-chain reputation panel: the same score/tier the public B2 tap
+ // card shows, plus a verified/credentialed/disputed breakdown lazily
+ // loaded from /api/agents/solana-reputation when the owner opens it.
+ mountReputationPanel(card, { reputation: card2.reputation, agentId: pin.agent_id, pinId: pin.id });
const svc = card2.services || [];
fillStat(card, 'services', String(svc.length));
renderServices(card, svc);
@@ -791,7 +807,7 @@ function openServicesModal(agentId, agentName) {
const cur = currencyForMint(p.currency_mint);
const actions = row.querySelector('[data-actions]');
actions.innerHTML = `
- <input class="irl-pr-input" type="number" min="0" step="any" value="${esc(fromAtomic(p.amount, cur.decimals))}" aria-label="New price in ${esc(cur.label)}" />
+ <input class="irl-pr-input" type="number" min="0" step="any" value="${esc(fromAtomicInput(p.amount, cur.decimals))}" aria-label="New price in ${esc(cur.label)}" />
<span class="irl-pr-cur">${esc(cur.label)}</span>
<button class="irl-link-btn" data-save-edit="${esc(skill)}" type="button">Save</button>
<button class="irl-link-btn" data-cancel-edit type="button">Cancel</button>`;
diff --git a/src/irl.js b/src/irl.js
index af47e434f..0f38630b3 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -39,7 +39,7 @@ import { AnimationManager } from './animation-manager.js';
import { WebXRSession } from './ar/webxr.js';
import { log } from './shared/log.js';
import { createAvatarPicker } from './avatar-picker.js';
-import { errorStateEl, skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';
+import { errorStateEl, skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles, attachRetry } from './shared/state-kit.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';
@@ -994,6 +994,15 @@ function onGPSPosition(pos) {
anchorGpsPin();
}
+ // A WebXR floor anchor was placed before this first fix — persist its pin now.
+ // The XRAnchor already holds the agent in the room; this lands the durable,
+ // shareable record it couldn't save without coordinates.
+ if (_pendingXrAnchorPose) {
+ const pose = _pendingXrAnchorPose;
+ _pendingXrAnchorPose = null;
+ persistFloorAnchor(pose);
+ }
+
// Move pinned avatar to its GPS-anchored world position. anchor_height_m (A2)
// keeps the feet on the ground plane on slopes / indoors — 0 today, but read
// it back so future floor-corrected placements render at the right height.
@@ -1208,6 +1217,11 @@ function startTick() {
}
let xrSession = null;
+// A floor anchor placed before the first GPS fix — held here and persisted the
+// instant onGPSPosition() lands real coordinates (mirrors _pendingGpsLock for the
+// gyro path). The in-session XRAnchor already glues the agent; this rescues its
+// durable, shareable pin from a quick tap during GPS warm-up.
+let _pendingXrAnchorPose = null;
async function detectFloorAnchorSupport() {
try {
@@ -1274,6 +1288,10 @@ async function enterFloorAnchor() {
onAnchored: (pose) => onFloorAnchored(pose),
onEnd: () => {
xrSession = null;
+ // Drop any anchor still waiting on a GPS fix — the user left this
+ // placement, so don't surprise them with a pin saved after they walk
+ // away (parity with the gyro path's arActive gate).
+ _pendingXrAnchorPose = null;
// WebXRSession restores an opaque clear color on exit; IRL renders
// over the page gradient with a transparent canvas — put that back.
renderer.setClearColor(0x000000, 0);
@@ -1300,18 +1318,29 @@ function yawFromQuat(q) {
return Math.atan2(siny, cosy) * 180 / Math.PI;
}
-// Convert the anchored local-space pose to a GPS pin and persist it (A2). The
-// in-session XRAnchor already holds the agent; this is the durable, shareable
-// record. Horizontal offset → lat/lng uses the same metre-per-degree math as the
-// gyro Pin path (local −Z = north, +X = east); height + yaw + GPS-fit trust ride
-// along in the anchor object.
+// Entry point for a placed floor anchor: persist it now if we have a GPS fix,
+// otherwise hold the pose until the first fix lands. The in-session XRAnchor
+// already glues the agent either way — this only governs the durable pin.
function onFloorAnchored(pose) {
- const { position, quaternion } = pose;
if (!gpsState.ready) {
- // The anchor still glues the agent in-session; we just can't save a pin yet.
- setXrHint('Anchored here — enable location to save & share this spot');
+ // The anchor still glues the agent in-session; we just can't convert it to a
+ // GPS pin yet. Hold the pose and finish the save the moment the first fix
+ // lands (onGPSPosition) rather than dropping it — a quick tap during GPS
+ // warm-up should still persist, not vanish.
+ _pendingXrAnchorPose = pose;
+ setXrHint('Anchored here — saving this spot once your location locks in');
return;
}
+ persistFloorAnchor(pose);
+}
+
+// Convert the anchored local-space pose to a GPS pin and persist it (A2) — the
+// durable, shareable record beyond the in-session XRAnchor. Horizontal offset →
+// lat/lng uses the same metre-per-degree math as the gyro Pin path (local −Z =
+// north, +X = east); height + yaw + GPS-fit trust ride along in the anchor object.
+// Split out so onGPSPosition() can replay a pose captured before the first fix.
+function persistFloorAnchor(pose) {
+ const { position, quaternion } = pose;
const mLat = 110540;
const mLng = 111320 * Math.cos(gpsState.lat * (Math.PI / 180));
const pinLat = gpsState.lat + (-position.z / mLat);
@@ -1971,7 +2000,7 @@ async function runX402Payment(endpoint, btn) {
}
// ── Interaction sheet ─────────────────────────────────────────────────────
-async function openPinSheet(pin) {
+function openPinSheet(pin) {
const sheet = document.getElementById('irl-sheet');
if (!sheet) return;
@@ -1997,7 +2026,7 @@ async function openPinSheet(pin) {
const own = isOwnPin(pin);
calBtn.hidden = !own;
calBtn.onclick = own
- ? () => { sheet.classList.remove('is-open'); enterCalibrate(pin); }
+ ? () => { closeInspectSheet(); enterCalibrate(pin); }
: null;
}
@@ -2016,19 +2045,15 @@ async function openPinSheet(pin) {
}
}
- // Clear any previously loaded enriched content
- const descEl = document.getElementById('irl-sheet-description');
- const skillsEl = document.getElementById('irl-sheet-skills');
- const viewsEl = document.getElementById('irl-sheet-views');
- const multiEl = document.getElementById('irl-sheet-multiplayer');
- const repEl = document.getElementById('irl-sheet-rep');
- const servicesEl = document.getElementById('irl-sheet-services');
- if (descEl) { descEl.textContent = ''; descEl.hidden = true; }
- if (skillsEl) { skillsEl.innerHTML = ''; skillsEl.hidden = true; }
- if (viewsEl) { viewsEl.hidden = true; }
- if (multiEl) { multiEl.hidden = true; }
- if (repEl) { repEl.hidden = true; }
- if (servicesEl) { servicesEl.hidden = true; }
+ // Reset the rich-card surfaces before the fresh card resolves: hide the
+ // previous agent's thumbnail + tier badge so neither flashes while the next
+ // card loads. #irl-card-body gets its skeleton from loadAgentCard() below.
+ const multiEl = document.getElementById('irl-sheet-multiplayer');
+ const thumbEl = document.getElementById('irl-sheet-thumb');
+ const tierEl = document.getElementById('irl-sheet-tier');
+ if (thumbEl) { thumbEl.removeAttribute('src'); thumbEl.hidden = true; }
+ if (tierEl) { tierEl.hidden = true; tierEl.removeAttribute('data-tier'); }
+ if (multiEl) multiEl.hidden = true;
sheet.dataset.agentId = pin.agent_id ?? '';
sheet.dataset.agentName = pin.avatar_name ?? '';
@@ -2040,7 +2065,15 @@ async function openPinSheet(pin) {
if (msgInput) { msgInput.value = ''; msgInput.disabled = false; }
if (msgStatus) { msgStatus.hidden = true; msgStatus.classList.remove('is-error'); }
}
+
+ // Open with a designed transition + focus management. Remember what had focus
+ // so closeInspectSheet() can restore it; fade the backdrop in alongside the
+ // sheet and move focus to the dialog so Escape and screen readers land here.
+ _activePin = pin;
+ _lastFocus = document.activeElement;
+ document.getElementById('irl-sheet-backdrop')?.classList.add('is-open');
sheet.classList.add('is-open');
+ try { sheet.focus({ preventScroll: true }); } catch { /* older browsers */ }
// Multiplayer note — always show since all pins are publicly visible
if (multiEl) {
@@ -2069,67 +2102,36 @@ async function openPinSheet(pin) {
pin.view_count = (pin.view_count ?? 0) + 1;
}
- // Async: enrich with the public agent card — description, skills, reputation,
- // and the paid services this agent offers. One cached call resolves by pin so
- // anonymous placements still return a usable card.
- if (pin.id) {
- try {
- const r = await fetch(`/api/irl/agent-card?pin=${encodeURIComponent(pin.id)}`);
- if (r.ok) {
- const { card } = await r.json();
- if (card) {
- if (card.description && descEl) {
- descEl.textContent = card.description;
- descEl.hidden = false;
- }
- if (card.skills?.length && skillsEl) {
- skillsEl.innerHTML = card.skills.slice(0, 6).map(s =>
- `<span class="irl-skill-badge">${_escHtml(s)}</span>`,
- ).join('');
- skillsEl.hidden = false;
- }
- // Reputation — score is 0–100; show it as a bar + label.
- const score = card.reputation?.score ?? 0;
- if (score > 0 && repEl) {
- const fill = document.getElementById('irl-rep-fill');
- const text = document.getElementById('irl-rep-text');
- if (fill) fill.style.width = `${Math.min(100, score)}%`;
- if (text) {
- const chats = card.reputation?.chats ?? 0;
- text.textContent = chats > 0
- ? `Reputation ${score}/100 · ${chats} chat${chats === 1 ? '' : 's'}`
- : `Reputation ${score}/100`;
- }
- repEl.hidden = false;
- }
- // Services the agent offers, with prices.
- if (card.services?.length && servicesEl) {
- const listEl = document.getElementById('irl-services-list');
- if (listEl) {
- listEl.innerHTML = card.services.slice(0, 6).map(s => {
- const price = s.price_usdc != null
- ? `$${Number(s.price_usdc).toFixed(2)} ${(s.network || 'base').toUpperCase()}`
- : 'Free';
- return `<div class="irl-service-row"><span class="irl-service-name">${_escHtml(s.name || s.slug)}</span><span class="irl-service-price">${_escHtml(price)}</span></div>`;
- }).join('');
- servicesEl.hidden = false;
- }
- }
- // Surface a pay button if the card resolved an x402 endpoint.
- if (card.x402_endpoint && payBtn) {
- payBtn.hidden = false;
- payBtn.dataset.endpoint = card.x402_endpoint;
- }
- }
- }
- } catch {}
- }
+ // Rich card: avatar bio + on-chain reputation + the agent's paid x402 services,
+ // from one /api/irl/agent-card aggregation call. loadAgentCard() drops a
+ // skeleton into #irl-card-body immediately, then renders the populated /
+ // empty-services / no-reputation / error+retry state, and aborts the in-flight
+ // fetch when the viewer taps a different agent so stale data never lands.
+ loadAgentCard(pin);
}
-document.getElementById('irl-sheet-close')?.addEventListener('click', () => {
- document.getElementById('irl-sheet')?.classList.remove('is-open');
+document.getElementById('irl-sheet-close')?.addEventListener('click', closeInspectSheet);
+document.getElementById('irl-sheet-backdrop')?.addEventListener('click', closeInspectSheet);
+window.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && document.getElementById('irl-sheet')?.classList.contains('is-open')) {
+ closeInspectSheet();
+ }
});
+// Per-service "Use" CTA → x402 payment; the error-state Retry re-fetches the card.
+// Both delegate off #irl-card-body so they survive every innerHTML re-render
+// (skeleton → populated / error).
+{
+ const cardBody = document.getElementById('irl-card-body');
+ if (cardBody) {
+ cardBody.addEventListener('click', (e) => {
+ const useBtn = e.target.closest('.irl-service-use[data-x402]');
+ if (useBtn) runX402Payment(useBtn.dataset.x402, useBtn);
+ });
+ attachRetry(cardBody, () => { if (_activePin) loadAgentCard(_activePin); });
+ }
+}
+
// Leave-a-message — a visitor's note becomes a 'message' interaction in the
// owner's IRL feed (dashboard). Pin id is stamped on the sheet by openPinSheet.
document.getElementById('irl-sheet-msg')?.addEventListener('submit', async (e) => {
@@ -2253,7 +2255,7 @@ document.getElementById('irl-sheet-view')?.addEventListener('click', () => {
const sheet = document.getElementById('irl-sheet');
const agentId = sheet?.dataset.agentId;
const name = sheet?.dataset.agentName || document.getElementById('irl-sheet-name')?.textContent || '';
- sheet?.classList.remove('is-open');
+ closeInspectSheet();
if (agentId) {
window.open(`/agents/${agentId}`, '_blank', 'noopener');
} else {
@@ -2261,64 +2263,9 @@ document.getElementById('irl-sheet-view')?.addEventListener('click', () => {
}
});
-document.getElementById('irl-sheet-pay')?.addEventListener('click', async (e) => {
- const btn = e.currentTarget;
- const endpoint = btn.dataset.endpoint;
- if (!endpoint) return;
-
- if (!window.ethereum) {
- setStatus('Connect an Ethereum wallet (MetaMask) to pay via x402', { error: true });
- return;
- }
-
- btn.disabled = true;
- const origText = btn.textContent;
-
- // Gate on an authorized wallet before signing. The x402 adapter would prompt
- // lazily on first sign, but doing it up front gives the user a clear connect
- // step and lets us bail cleanly (button re-enabled) if they decline.
- btn.textContent = 'Connecting…';
- try {
- const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
- if (!Array.isArray(accounts) || !accounts.length) {
- setStatus('Connect your wallet to pay via x402', { error: true });
- btn.disabled = false;
- btn.textContent = origText;
- return;
- }
- } catch (err) {
- const m = err?.message ?? String(err);
- setStatus(/reject|denied|4001/i.test(m) ? 'Wallet connection cancelled' : `Couldn't connect wallet — ${m}`, { error: true });
- btn.disabled = false;
- btn.textContent = origText;
- return;
- }
-
- btn.textContent = 'Sending…';
- try {
- const { withX402 } = await import('../packages/x402-fetch/dist/index.esm.js');
- const pay = withX402(window.ethereum, { maxPaymentUsd: 1.00 });
- const r = await pay(endpoint, { method: 'POST' });
- if (r.ok) {
- setStatus('Payment sent');
- btn.textContent = 'Paid ✓';
- btn.disabled = true;
- } else {
- const msg = await r.text().catch(() => r.status);
- setStatus(`Payment failed (${msg})`, { error: true });
- btn.disabled = false;
- btn.textContent = origText;
- }
- } catch (err) {
- const msg = err?.message ?? String(err);
- if (msg.includes('rejected') || msg.includes('denied')) {
- setStatus('Payment cancelled', { error: true });
- } else {
- setStatus(`Payment failed — ${msg}`, { error: true });
- }
- btn.disabled = false;
- btn.textContent = origText;
- }
+// Footer Pay CTA — same x402 flow as the per-service "Use" buttons.
+document.getElementById('irl-sheet-pay')?.addEventListener('click', (e) => {
+ runX402Payment(e.currentTarget.dataset.endpoint, e.currentTarget);
});
// ── Radar minimap ────────────────────────────────────────────────────────
diff --git a/tests/api/irl-pins-calibrate.test.js b/tests/api/irl-pins-calibrate.test.js
new file mode 100644
index 000000000..c4ef8b21e
--- /dev/null
+++ b/tests/api/irl-pins-calibrate.test.js
@@ -0,0 +1,211 @@
+// PATCH /api/irl/pins { calibrate } — IRL-Live A3 cross-user anchor consistency.
+//
+// The calibrate path is a small, owner-gated pose correction: the owner (or the
+// anonymous device that placed the pin) nudges an agent a few centimetres /
+// degrees into its true real-world spot so every nearby viewer sees it there.
+// Because a corrected pose re-saves for EVERYONE, the server is the security
+// boundary — it must reject non-owners and clamp the nudge so calibration can
+// never be abused to teleport someone's agent across the map. These tests prove
+// that boundary holds (the A3 acceptance criterion the client clamp alone can't
+// guarantee). The DB / auth / limiter are mocked so the suite stays offline.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Content-addressed SQL mock: classify the tagged-template query by its text so
+// ensureTable()'s DDL, the ownership SELECT, and the UPDATE each return the right
+// shape regardless of call order. `pinRow` is the row the WHERE-id SELECT returns
+// (null → "not found"); the UPDATE echoes back the bound values so success-path
+// assertions see the persisted pose.
+let pinRow = null;
+const sqlMock = vi.fn((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/SELECT[\s\S]*FROM irl_pins[\s\S]*WHERE id =/i.test(q)) {
+ return Promise.resolve(pinRow ? [pinRow] : []);
+ }
+ if (/UPDATE irl_pins SET/i.test(q)) {
+ const [lat, lng, yaw, heading, height, id] = values;
+ return Promise.resolve([{
+ id,
+ lat, lng,
+ heading: heading ?? pinRow?.heading ?? null,
+ anchor_yaw_deg: yaw ?? pinRow?.anchor_yaw_deg ?? null,
+ anchor_height_m: height ?? pinRow?.anchor_height_m ?? null,
+ gps_accuracy_m: pinRow?.gps_accuracy_m ?? null,
+ }]);
+ }
+ // CREATE TABLE / ALTER TABLE / CREATE INDEX from ensureTable(), and anything else.
+ return Promise.resolve([]);
+});
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+// getSessionUser is overridden per-test to model authed vs anonymous callers.
+let sessionUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { irlPinIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { default: handler } = await import('../../api/irl/pins.js');
+
+// Reference placement: an anonymous device-owned pin near lower Manhattan.
+const ORIGIN = { lat: 40.7128, lng: -74.006 };
+const M_PER_DEG_LAT = 110540;
+
+function makeReq(body) {
+ return { url: '/api/irl/pins', method: 'PATCH', headers: { host: 'x' }, query: {}, body };
+}
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+async function patch(body) {
+ const res = makeRes();
+ await handler(makeReq(body), res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch {}
+ return { res, body: parsed };
+}
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ pinRow = {
+ id: 'pin-1',
+ user_id: null,
+ device_token: 'device-A',
+ lat: ORIGIN.lat,
+ lng: ORIGIN.lng,
+ heading: 90,
+ anchor_yaw_deg: 90,
+ anchor_height_m: 0,
+ gps_accuracy_m: 12,
+ };
+ sessionUser = null;
+});
+
+describe('PATCH /api/irl/pins calibrate — ownership gate', () => {
+ it('404s when the pin no longer exists', async () => {
+ pinRow = null;
+ const { res, body } = await patch({
+ id: 'gone', deviceToken: 'device-A',
+ calibrate: { lat: ORIGIN.lat, lng: ORIGIN.lng },
+ });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toMatch(/not found/i);
+ });
+
+ it('403s a non-owner (device token mismatch, no session)', async () => {
+ const { res, body } = await patch({
+ id: 'pin-1', deviceToken: 'device-B',
+ calibrate: { lat: ORIGIN.lat, lng: ORIGIN.lng },
+ });
+ expect(res.statusCode).toBe(403);
+ expect(body.error).toMatch(/only the owner/i);
+ });
+
+ it('403s a caller with neither matching session nor device token', async () => {
+ const { res } = await patch({
+ id: 'pin-1',
+ calibrate: { lat: ORIGIN.lat, lng: ORIGIN.lng },
+ });
+ expect(res.statusCode).toBe(403);
+ });
+
+ it('never reaches the UPDATE for a denied caller', async () => {
+ await patch({ id: 'pin-1', deviceToken: 'device-B', calibrate: { lat: ORIGIN.lat, lng: ORIGIN.lng } });
+ const ranUpdate = sqlMock.mock.calls.some(([s]) =>
+ /UPDATE irl_pins SET/i.test(Array.isArray(s) ? s.join(' ') : String(s)));
+ expect(ranUpdate).toBe(false);
+ });
+});
+
+describe('PATCH /api/irl/pins calibrate — bounds enforcement', () => {
+ it('400s on out-of-range coordinates', async () => {
+ const { res, body } = await patch({
+ id: 'pin-1', deviceToken: 'device-A',
+ calibrate: { lat: 999, lng: ORIGIN.lng },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/invalid calibrate coordinates/i);
+ });
+
+ it('422s a ground move larger than the calibration ceiling (anti-teleport)', async () => {
+ // ~22 m north — well beyond the ±3 m client clamp and the 5 m server ceiling.
+ const farLat = ORIGIN.lat + 0.0002;
+ const { res, body } = await patch({
+ id: 'pin-1', deviceToken: 'device-A',
+ calibrate: { lat: farLat, lng: ORIGIN.lng },
+ });
+ expect(res.statusCode).toBe(422);
+ expect(body.error).toMatch(/move too large/i);
+ expect(body.max_m).toBe(5);
+ });
+
+ it('422s a yaw nudge beyond the rotation ceiling', async () => {
+ // Same spot (move passes), but 90° off the stored 90° bearing → > 46° cap.
+ const { res, body } = await patch({
+ id: 'pin-1', deviceToken: 'device-A',
+ calibrate: { lat: ORIGIN.lat, lng: ORIGIN.lng, anchorYawDeg: 180 },
+ });
+ expect(res.statusCode).toBe(422);
+ expect(body.error).toMatch(/rotation too large/i);
+ expect(body.max_deg).toBe(46);
+ });
+
+ it('422s a floor-height nudge beyond the rise ceiling', async () => {
+ const { res, body } = await patch({
+ id: 'pin-1', deviceToken: 'device-A',
+ calibrate: { lat: ORIGIN.lat, lng: ORIGIN.lng, anchorHeightM: 5 },
+ });
+ expect(res.statusCode).toBe(422);
+ expect(body.error).toMatch(/height too large/i);
+ });
+});
+
+describe('PATCH /api/irl/pins calibrate — accepted nudges persist for everyone', () => {
+ it('200s a small nudge from the anonymous device owner and writes the corrected pose', async () => {
+ // ~1.1 m north, 10° yaw correction, +30 cm — all within the calibrate envelope.
+ const newLat = ORIGIN.lat + 1.1 / M_PER_DEG_LAT;
+ const { res, body } = await patch({
+ id: 'pin-1', deviceToken: 'device-A',
+ calibrate: { lat: newLat, lng: ORIGIN.lng, anchorYawDeg: 100, anchorHeightM: 0.3 },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(body.calibrated).toBe(true);
+ expect(body.pin.lat).toBeCloseTo(newLat, 9);
+ expect(body.pin.anchor_yaw_deg).toBe(100);
+ // heading mirrors the corrected yaw so legacy clients (heading-only) agree.
+ expect(body.pin.heading).toBe(100);
+ expect(body.pin.anchor_height_m).toBeCloseTo(0.3, 9);
+ });
+
+ it('200s the authenticated owner via session.id (calibrate routes before the auth gate)', async () => {
+ pinRow.user_id = 'owner-uuid';
+ pinRow.device_token = null;
+ sessionUser = { id: 'owner-uuid' };
+ const { res, body } = await patch({
+ id: 'pin-1',
+ calibrate: { lat: ORIGIN.lat, lng: ORIGIN.lng, anchorYawDeg: 90 },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(body.calibrated).toBe(true);
+ });
+
+ it('treats yaw as wrap-around (340° vs stored 90° is 110° apart → rejected)', async () => {
+ const { res } = await patch({
+ id: 'pin-1', deviceToken: 'device-A',
+ calibrate: { lat: ORIGIN.lat, lng: ORIGIN.lng, anchorYawDeg: 340 },
+ });
+ expect(res.statusCode).toBe(422);
+ });
+});