Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: refine Agora world rendering, API, and citizens worker economy loop
nirholasc29d73230dd0
diff --git a/api/agora/[action].js b/api/agora/[action].jsindex 791127f7e..f8c184b79 100644--- a/api/agora/[action].js+++ b/api/agora/[action].js@@ -45,7 +45,7 @@ const PROFESSIONS = [{ bit: 4, key: 'crier', label: 'Crier', skill: 'TTS / voice / audio2face' },{ bit: 5, key: 'appraiser', label: 'Appraiser', skill: 'token / market intel' },{ bit: 6, key: 'verifier', label: 'Verifier', skill: 're-derive proofHash + attest' },- { bit: 7, key: 'namekeeper', label: 'Namekeeper', skill: '.sol / ENS resolve + mint' },+ { bit: 7, key: 'namekeeper', label: 'Namekeeper', skill: '.sol / ENS resolve' },];function decodeProfessions(bits) {@@ -203,6 +203,9 @@ async function handleBoard(req, res) {requiredCapabilities: t.meta?.requiredCapabilities != null ? String(t.meta.requiredCapabilities) : null,taskType: t.meta?.taskType ?? 'Exclusive',tier: t.meta?.tier ?? null,+ // Verification bounties carry the deliverable to re-derive; the worker reads+ // this as job.target and works it as the Verifier (the trust loop).+ target: t.meta?.target ?? null,postedAt: t.created_at,txSignature: t.tx_signature,taskUrl: t.task_pda@@ -279,7 +282,7 @@ async function handlePulse(req, res) {sql`select count(*)::int as n from agora_activitywhere kind = 'completed_task' and created_at > now() - interval '24 hours'`,sql`select a.id, a.kind, a.narrative, a.reward_label, a.created_at,- a.task_pda, a.deliverable_url, c.display_name as actor, c.profession+ a.task_pda, a.deliverable_url, c.id as citizen_id, c.display_name as actor, c.professionfrom agora_activity a join agora_citizens c on c.id = a.citizen_idorder by a.created_at desc limit 12`,sql`select id, display_name, profession, reputation, earned_three_atomic, tasks_completed@@ -317,6 +320,7 @@ async function handlePulse(req, res) {})),recent: (recent || []).map((r) => ({id: r.id,+ citizenId: r.citizen_id,kind: r.kind,actor: r.actor,profession: r.profession,diff --git a/src/agora/agora-world.js b/src/agora/agora-world.jsindex d7c7c26fb..2a7969758 100644--- a/src/agora/agora-world.js+++ b/src/agora/agora-world.js@@ -97,7 +97,11 @@ async function main() {window.addEventListener('keydown', (e) => {const k = e.key.toLowerCase();if (!PAN_KEYS.has(k)) return;- if (document.activeElement && document.activeElement.tagName === 'BUTTON') return; // let roster nav work+ // Don't hijack typing or scrolling: let form fields, editable content, and any+ // open panel keep arrow/WASD keys. Only pan when the world itself has focus.+ const ae = document.activeElement;+ if (ae && (/^(INPUT|TEXTAREA|SELECT|BUTTON)$/.test(ae.tagName) || ae.isContentEditable+ || (ae.closest && ae.closest('.agora-passport, .agora-panel, .agora-h-root, [role="dialog"]')))) return;if (k.startsWith('arrow')) e.preventDefault();keys.add(k);focusGoal = null;diff --git a/src/agora/api.js b/src/agora/api.jsindex eeab5f199..ee2f9c607 100644--- a/src/agora/api.js+++ b/src/agora/api.js@@ -28,7 +28,7 @@ export async function getJson(url, { signal, timeout = DEFAULT_TIMEOUT } = {}) {let body;try { body = await res.json(); } catch { body = null; }if (!res.ok) {- const msg = body?.message || body?.error || `HTTP ${res.status}`;+ const msg = body?.error_description || body?.message || body?.error || `HTTP ${res.status}`;throw new Error(msg);}return body;@@ -56,7 +56,7 @@ export async function postJson(url, payload, { signal, timeout = DEFAULT_TIMEOUTlet body;try { body = await res.json(); } catch { body = null; }if (!res.ok) {- const msg = body?.message || body?.error || `HTTP ${res.status}`;+ const msg = body?.error_description || body?.message || body?.error || `HTTP ${res.status}`;throw new Error(msg);}return body;diff --git a/workers/agora-citizens/demand.js b/workers/agora-citizens/demand.jsindex e98e00ba4..43753e20c 100644--- a/workers/agora-citizens/demand.js+++ b/workers/agora-citizens/demand.js@@ -81,6 +81,7 @@ export function markPatrons(citizens, cfg) {c.patron = { tiers, budgetAtomic, minPostIntervalMs };c.postedSpentAtomic = 0n;c.lastPostAt = 0;+ c.lastVerifyPostAt = 0;c.postedCount = 0;log.info('patron designated', {citizen: c.spec.displayName,@@ -204,6 +205,88 @@ export async function maybePatronPost(ctx, citizen) {return result;}+/** Is the autonomous trust loop (patron-posted verification bounties) enabled? */+export function verifyEnabled(cfg) {+ return boolEnv('AGORA_ENABLE_VERIFY', cfg.cluster === 'devnet');+}++/** Reward a patron offers for a verification bounty (cluster reward unit, atomic). */+function verifyReward(cfg) {+ return bigEnv('AGORA_VERIFY_REWARD_ATOMIC', BigInt(cfg.taskRewardLamports));+}++const VERIFIER_BITS = 1n << 6n; // capability bit 6 (see roster.js PROFESSIONS)++/**+ * The trust loop (Task 04 DoD): a patron posts a REAL verification bounty against+ * a recent peer deliverable nobody has checked yet. A Verifier-capable citizen+ * claims it, re-downloads the deliverable, re-derives sha256, and attests+ * pass/fail on-chain — agents checking agents' work. Fail-safe: with no+ * unverified deliverable (or no R2-stored artifacts) it simply holds, and the+ * paid-work loop is untouched.+ *+ * @returns {object|null} the post result, or null if held.+ */+export async function maybePatronVerify(ctx, citizen) {+ const { cfg, store } = ctx;+ if (!citizen?.patron || !verifyEnabled(cfg)) return null;+ const now = Date.now();+ if (now - (citizen.lastVerifyPostAt || 0) < citizen.patron.minPostIntervalMs) return null;++ // Find a peer deliverable that's re-downloadable + has an on-chain proof and+ // hasn't been vouched yet. None → hold (honest: nothing to verify).+ const target = await store.recentUnverifiedDeliverable({ excludeCitizenId: citizen.id });+ if (!target) return null;++ const reward = verifyReward(cfg);+ const bal = await onchainBalance(cfg, citizen.client.connection, citizen.signer.publicKey);+ const remainingBudget = citizen.patron.budgetAtomic - citizen.postedSpentAtomic;+ const effectiveBalance = bal < remainingBudget ? bal : remainingBudget;+ if (effectiveBalance < reward + headroomFor(cfg)) return null;+ if (!withinSpendCap(cfg, reward)) return null;++ if (cfg.dryRun) {+ log.loop('[dry] would post verification bounty', { citizen: citizen.spec.displayName, target: target.taskPda });+ return null;+ }++ const result = await postBounty({+ cfg,+ store,+ client: citizen.client,+ poster: { id: citizen.id, agentIdHex: citizen.agentIdHex, displayName: citizen.spec.displayName },+ plan: {+ profession: 'verifier',+ requiredCapabilities: VERIFIER_BITS,+ rewardAtomic: reward,+ minReputation: 0,+ taskType: 'Exclusive',+ maxWorkers: 1,+ tier: 'trust',+ // The deliverable to re-derive — flows board → job.target → runVerifier.+ target: {+ deliverableUrl: target.deliverableUrl,+ proofHash: target.proofHash,+ taskPda: target.taskPda,+ citizenId: target.citizenId,+ profession: target.profession,+ },+ },+ });++ citizen.postedSpentAtomic += BigInt(reward);+ citizen.lastVerifyPostAt = now;+ if (cfg.cluster === 'mainnet') _spentThisRunAtomic += BigInt(reward);++ log.info('verification bounty posted', {+ citizen: citizen.spec.displayName,+ verifyTask: result.taskPda,+ targetTask: target.taskPda,+ tx: result.txSignature,+ });+ return result;+}+/*** Sub-task hiring: a citizen working a high-value job hires a sub-agent (real* agent-to-agent hiring). Pays from the worker's own balance — same scarcity rule.diff --git a/workers/agora-citizens/engine.js b/workers/agora-citizens/engine.jsindex 6bd653caa..f6ea78aee 100644--- a/workers/agora-citizens/engine.js+++ b/workers/agora-citizens/engine.js@@ -19,7 +19,7 @@ import { LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';import { log } from './log.js';import { buildRoster, professionBits, capabilitiesSatisfy, PROFESSIONS } from './roster.js';import { citizenCanClaim } from './policy.js';-import { markPatrons, maybePatronPost, maybeHire, hiringEnabled, subtaskReward } from './demand.js';+import { markPatrons, maybePatronPost, maybePatronVerify, maybeHire, hiringEnabled, subtaskReward } from './demand.js';import { loadOrCreateKeypair, ensureBalance } from './keypair.js';import {makeReadClient,@@ -400,7 +400,7 @@ async function pickBoardBounty(ctx, citizen) {if (Number(onchain.deadline) <= Date.now() / 1000) continue;const rewardAtomic = t.reward?.amountAtomic != null ? Number(t.reward.amountAtomic) : ctx.cfg.taskRewardLamports;- return { taskPda: new PublicKey(t.taskPda), pda: t.taskPda, reward: rewardAtomic, minReputation: t.minReputation ?? 0, fromBoard: true };+ return { taskPda: new PublicKey(t.taskPda), pda: t.taskPda, reward: rewardAtomic, minReputation: t.minReputation ?? 0, fromBoard: true, target: t.target ?? null };}return null;}@@ -436,11 +436,23 @@ export async function tickCitizen(ctx, citizen) {} catch (err) {log.warn('patron post failed', { name, err: err?.message });}+ // Trust loop: also seed verification bounties against peer deliverables+ // so Verifier-capable citizens have work checking others' proofs.+ try {+ await maybePatronVerify(ctx, citizen);+ } catch (err) {+ log.warn('patron verify-post failed', { name, err: err?.message });+ }}await ctx.store.setStatus(citizen.id, 'idle', wander(citizen.home));return citizen.patron ? 'patron-idle' : 'idle';}+ // A verification bounty carries the deliverable to check as job.target; work+ // it as the Verifier regardless of this citizen's headline craft, so the+ // dispatch runs runVerifier (and the trust-loop vouch projects below).+ const workProfession = job.target ? 'verifier' : profession;+// CLAIMawait ctx.store.setStatus(citizen.id, 'seeking', wander(citizen.home));let claim;@@ -498,7 +510,7 @@ export async function tickCitizen(ctx, citizen) {// router, a Verifier re-derives another citizen's proof. Every runner returns// the same proof shape, so PROVE below stays profession-agnostic.const boardService = ctx.board.services.find((s) => typeof s.resource === 'string' && /^https?:\/\//i.test(s.resource));- const work = await runProfession(profession, {+ const work = await runProfession(workProfession, {cfg,citizen: { agentIdHex: citizen.agentIdHex, displayName: name, pubkey: citizen.pubkey },job: { taskPda: job.pda, source: 'agenc', resource: boardService?.resource || defaultTarget(cfg), ...(job.target ? { target: job.target } : {}) },diff --git a/workers/agora-citizens/post.js b/workers/agora-citizens/post.jsindex dcfa38013..e76ee5e58 100644--- a/workers/agora-citizens/post.js+++ b/workers/agora-citizens/post.js@@ -35,7 +35,7 @@ function describeTask({ profession, tier, parentLabel }) {crier: 'Produce a short voice/TTS clip',appraiser: 'Return a token/market intel summary',verifier: 'Re-derive a proofHash and attest pass/fail',- namekeeper: 'Resolve or mint a .threews.sol / ENS name',+ namekeeper: 'Resolve a .threews.sol / ENS name',}[profession] || `Complete a ${profession} job`;if (parentLabel) return `${verb} (sub-task of "${parentLabel}")`.slice(0, 180);return tier ? `${verb} — ${tier} tier`.slice(0, 180) : verb.slice(0, 180);@@ -139,7 +139,8 @@ export async function postBounty({ cfg, store, client, poster, plan, hire = nulltaskType: plan.taskType || 'Exclusive',maxWorkers: plan.maxWorkers || 1,tier: plan.tier || null,- ...(hire ? { parentTaskPda: hire.parentTaskPda } : {}),+ ...(plan.target ? { target: plan.target } : {}),+ ...(hire ? { parentTaskPda: hire.parentTaskPda } : {}),},});diff --git a/workers/agora-citizens/roster.js b/workers/agora-citizens/roster.jsindex cfb414dbf..7a40459bd 100644--- a/workers/agora-citizens/roster.js+++ b/workers/agora-citizens/roster.js@@ -21,7 +21,7 @@ export const PROFESSIONS = [{ bit: 4, key: 'crier', label: 'Crier', skill: 'TTS / voice / audio2face' },{ bit: 5, key: 'appraiser', label: 'Appraiser', skill: 'token / market intel' },{ bit: 6, key: 'verifier', label: 'Verifier', skill: 're-derive proofHash + attest' },- { bit: 7, key: 'namekeeper', label: 'Namekeeper', skill: '.sol / ENS resolve + mint' },+ { bit: 7, key: 'namekeeper', label: 'Namekeeper', skill: '.sol / ENS resolve' },];const PROF_BY_KEY = new Map(PROFESSIONS.map((p) => [p.key, p]));diff --git a/workers/agora-citizens/store.js b/workers/agora-citizens/store.jsindex ce874c1ae..0fa3e373c 100644--- a/workers/agora-citizens/store.js+++ b/workers/agora-citizens/store.js@@ -133,6 +133,42 @@ export function makeStore(cfg) {return r.length > 0;},+ /**+ * A recent peer deliverable nobody has verified yet — the Verifier's work+ * queue. Returns a completed_task by ANOTHER citizen that has a+ * re-downloadable deliverable_url + an on-chain proof_hash and no `vouched`+ * row yet, or null. Powers the trust loop: a patron posts a verification+ * bounty against this, a Verifier claims it and re-derives the proof.+ */+ async recentUnverifiedDeliverable({ excludeCitizenId } = {}) {+ if (!sql || !excludeCitizenId) return null;+ const rows = await sql`+ select a.task_pda, a.proof_hash, a.deliverable_url, a.citizen_id, a.profession+ from agora_activity a+ where a.kind = 'completed_task'+ and a.deliverable_url is not null+ and a.proof_hash is not null+ and a.task_pda is not null+ and a.citizen_id <> ${excludeCitizenId}+ and a.created_at > now() - interval '2 hours'+ and not exists (+ select 1 from agora_activity v+ where v.task_pda = a.task_pda and v.kind = 'vouched'+ )+ order by a.created_at desc+ limit 1+ `;+ const r = rows[0];+ if (!r) return null;+ return {+ taskPda: r.task_pda,+ proofHash: r.proof_hash,+ deliverableUrl: r.deliverable_url,+ citizenId: r.citizen_id,+ profession: r.profession,+ };+ },+/*** Append an activity row (idempotent on tx_signature). Returns the new row* id, or null if it already existed. Every caller passes a non-empty