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: add Agora task lifecycle migration and economy layer styling

nirholasb57e69455501
diff --git a/api/_lib/migrations/20260629030000_agora_task_lifecycle.sql b/api/_lib/migrations/20260629030000_agora_task_lifecycle.sql
new file mode 100644
index 000000000..b3187aadb
--- /dev/null
+++ b/api/_lib/migrations/20260629030000_agora_task_lifecycle.sql
@@ -0,0 +1,31 @@
+-- Agora — task supply (Task 03). Extends agora_activity.kind so the reconcile
+-- sweep (workers/agora-citizens/reconcile.js) can project the terminal task
+-- transitions the chain reports for a posted bounty:
+--
+-- cancelled_task — the creator cancelled and escrow returned (TaskState=Cancelled)
+-- expired_task — the task lapsed past its deadline unclaimed (TaskState=Expired)
+--
+-- These join the existing claimed/completed/slashed lane that the board's
+-- open-task query (api/agora/[action].js) treats as "no longer open", so the
+-- board never shows a stale open bounty once the chain has moved on. Honest
+-- projection: a row is written only after re-reading the on-chain state.
+--
+-- The original constraint is the inline check from 20260629020000_agora_world.sql,
+-- auto-named agora_activity_kind_check. We drop and re-add it with the widened set.
+
+alter table agora_activity drop constraint if exists agora_activity_kind_check;
+
+alter table agora_activity add constraint agora_activity_kind_check check (kind in (
+ 'registered', -- joined AgenC (registerAgent)
+ 'posted_task', -- createTask (escrow locked)
+ 'claimed_task', -- claimTask
+ 'completed_task', -- completeTask (proof accepted)
+ 'earned', -- escrow released to this citizen
+ 'hired', -- posted a sub-task for another citizen
+ 'paid_service', -- x402 micro-payment to a service
+ 'vouched', -- left an attestation for a citizen
+ 'slashed', -- stake slashed on dispute
+ 'moved', -- changed districts (world-only)
+ 'cancelled_task', -- a posted bounty was cancelled on-chain (reconcile)
+ 'expired_task' -- a posted bounty lapsed past its deadline (reconcile)
+));
diff --git a/api/agora/[action].js b/api/agora/[action].js
index de58b61dc..7255f5150 100644
--- a/api/agora/[action].js
+++ b/api/agora/[action].js
@@ -177,7 +177,7 @@ async function handleBoard(req, res) {
and not exists (
select 1 from agora_activity x
where x.task_pda = a.task_pda
- and x.kind in ('claimed_task', 'completed_task', 'slashed')
+ and x.kind in ('claimed_task', 'completed_task', 'slashed', 'cancelled_task', 'expired_task')
and x.created_at >= a.created_at
)
order by a.created_at desc
diff --git a/src/agora/economy-layer.css.js b/src/agora/economy-layer.css.js
new file mode 100644
index 000000000..cb268b266
--- /dev/null
+++ b/src/agora/economy-layer.css.js
@@ -0,0 +1,183 @@
+// Styles for the Task 06 economy layer, shipped as a string and injected once by
+// economy-layer.js. Kept self-contained (no dependency on the Task 05 page
+// stylesheet) and namespaced under .agora-econ-* so it can't collide with the
+// scaffold's chrome. Honours prefers-reduced-motion and exposes focus rings on
+// every interactive element.
+
+export const ECON_LAYER_CSS = `
+.agora-econ-root {
+ position: fixed; inset: 0; z-index: 40;
+ pointer-events: none;
+ font-family: ui-sans-serif, system-ui, -apple-system, sans-serif;
+ --econ-bg: rgba(12, 15, 22, 0.72);
+ --econ-bg-solid: #0c0f16;
+ --econ-border: rgba(255, 255, 255, 0.1);
+ --econ-text: #e8eef7;
+ --econ-dim: #93a1b5;
+ --econ-gold: #f0b429;
+ --econ-rep: #36d399;
+}
+.agora-econ-root *,
+.agora-econ-root *::before { box-sizing: border-box; }
+.agora-econ-root button {
+ font: inherit; color: inherit; background: none; border: none;
+ cursor: pointer; text-align: left;
+}
+.agora-econ-root button:focus-visible {
+ outline: 2px solid #4ea1ff; outline-offset: 2px; border-radius: 8px;
+}
+
+/* ── Job board roster (right) ─────────────────────────────────────────────── */
+.agora-econ-board-panel {
+ position: absolute; top: 64px; right: 16px; width: 300px;
+ max-height: calc(100vh - 96px); display: flex; flex-direction: column;
+ background: var(--econ-bg); border: 1px solid var(--econ-border);
+ border-radius: 14px; backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px);
+ padding: 14px; pointer-events: auto; color: var(--econ-text);
+ box-shadow: 0 18px 50px rgba(0,0,0,0.45);
+}
+.agora-econ-board-title {
+ margin: 0 0 10px; font-size: 13px; font-weight: 700; letter-spacing: 0.04em;
+ text-transform: uppercase; color: var(--econ-dim); display: flex; align-items: baseline;
+}
+.agora-econ-board-count { color: var(--econ-text); font-weight: 700; }
+.agora-econ-board-list {
+ list-style: none; margin: 0; padding: 0; overflow-y: auto; display: flex;
+ flex-direction: column; gap: 6px; scrollbar-width: thin;
+}
+.agora-econ-board-item {
+ width: 100%; display: flex; gap: 10px; align-items: flex-start;
+ padding: 9px 10px; border-radius: 10px; border: 1px solid transparent;
+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.1s ease;
+}
+.agora-econ-board-item:hover { background: rgba(255,255,255,0.06); border-color: var(--econ-border); }
+.agora-econ-board-item:active { transform: translateY(1px); }
+.agora-econ-board-dot {
+ width: 9px; height: 9px; border-radius: 50%; margin-top: 5px; flex: 0 0 auto;
+ background: var(--accent, #9fb4cc); box-shadow: 0 0 8px var(--accent, #9fb4cc);
+}
+.agora-econ-board-item-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.agora-econ-board-item-title {
+ font-size: 13px; font-weight: 600; line-height: 1.25;
+ overflow: hidden; text-overflow: ellipsis; display: -webkit-box;
+ -webkit-line-clamp: 2; -webkit-box-orient: vertical;
+}
+.agora-econ-board-item-meta { font-size: 11.5px; color: var(--econ-dim); }
+.agora-econ-board-empty { text-align: center; padding: 22px 8px; color: var(--econ-dim); }
+.agora-econ-board-empty-glyph { font-size: 30px; opacity: 0.7; }
+.agora-econ-board-empty-title { margin: 8px 0 4px; font-size: 14px; font-weight: 700; color: var(--econ-text); }
+.agora-econ-board-empty-sub { margin: 0; font-size: 12px; line-height: 1.5; }
+
+/* ── Marker tooltip ────────────────────────────────────────────────────────── */
+.agora-econ-tooltip {
+ position: absolute; top: 0; left: 0; max-width: 260px; z-index: 60;
+ background: var(--econ-bg-solid); border: 1px solid var(--econ-border);
+ border-radius: 10px; padding: 9px 11px; color: var(--econ-text);
+ box-shadow: 0 12px 32px rgba(0,0,0,0.5); pointer-events: none;
+ will-change: transform;
+}
+.agora-econ-tip-title { font-size: 13px; font-weight: 700; margin-bottom: 5px; line-height: 1.3; }
+.agora-econ-tip-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+.agora-econ-tip-prof {
+ font-size: 11px; font-weight: 700; color: var(--accent, #9fb4cc);
+ padding: 2px 7px; border-radius: 999px; border: 1px solid currentColor;
+}
+.agora-econ-tip-reward { font-size: 12px; font-weight: 700; color: var(--econ-gold); }
+.agora-econ-tip-sub { margin-top: 5px; font-size: 11px; color: var(--econ-dim); }
+
+/* ── Ticker (left) ─────────────────────────────────────────────────────────── */
+.agora-econ-ticker {
+ position: absolute; left: 16px; bottom: 16px; width: 320px;
+ max-height: calc(100vh - 120px); display: flex; flex-direction: column; gap: 12px;
+ background: var(--econ-bg); border: 1px solid var(--econ-border);
+ border-radius: 14px; backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px);
+ padding: 14px; pointer-events: auto; color: var(--econ-text);
+ box-shadow: 0 18px 50px rgba(0,0,0,0.45);
+}
+.agora-econ-readout { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
+.agora-econ-stat {
+ display: flex; flex-direction: column; gap: 2px; padding: 8px;
+ background: rgba(255,255,255,0.04); border-radius: 10px; text-align: center;
+}
+.agora-econ-stat-v { font-size: 18px; font-weight: 800; line-height: 1; }
+.agora-econ-stat-l { font-size: 10px; color: var(--econ-dim); letter-spacing: 0.02em; }
+.agora-econ-earners-h, .agora-econ-feed-h {
+ font-size: 11px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase;
+ color: var(--econ-dim); margin-bottom: 6px;
+}
+.agora-econ-earners-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 3px; counter-reset: rank; }
+.agora-econ-earner {
+ width: 100%; display: flex; justify-content: space-between; align-items: center; gap: 8px;
+ padding: 5px 8px; border-radius: 8px; transition: background 0.15s ease;
+}
+.agora-econ-earner::before {
+ counter-increment: rank; content: counter(rank); font-size: 10px; font-weight: 700;
+ color: var(--accent, #9fb4cc); width: 14px; flex: 0 0 auto;
+}
+.agora-econ-earner:hover { background: rgba(255,255,255,0.06); }
+.agora-econ-earner-name { flex: 1; font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.agora-econ-earner-amt { font-size: 12px; font-weight: 700; color: var(--econ-gold); white-space: nowrap; }
+.agora-econ-earners-empty, .agora-econ-feed-empty { font-size: 12px; color: var(--econ-dim); padding: 4px 2px; }
+.agora-econ-feed-wrap { display: flex; flex-direction: column; min-height: 0; flex: 1; }
+.agora-econ-feed {
+ list-style: none; margin: 0; padding: 0; overflow-y: auto; display: flex;
+ flex-direction: column; gap: 3px; scrollbar-width: thin; min-height: 0;
+}
+.agora-econ-feed-item { overflow: hidden; }
+.agora-econ-feed-item.enter .agora-econ-feed-btn { animation: agora-econ-slide-in 0.4s ease; }
+@keyframes agora-econ-slide-in {
+ from { opacity: 0; transform: translateY(-8px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+.agora-econ-feed-btn {
+ width: 100%; display: flex; gap: 8px; align-items: flex-start; padding: 7px 8px;
+ border-radius: 9px; border-left: 2px solid var(--accent, #9fb4cc);
+ background: rgba(255,255,255,0.03); transition: background 0.15s ease;
+}
+.agora-econ-feed-btn:hover { background: rgba(255,255,255,0.08); }
+.agora-econ-feed-glyph { font-size: 13px; flex: 0 0 auto; line-height: 1.4; }
+.agora-econ-feed-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.agora-econ-feed-narr {
+ font-size: 12px; line-height: 1.35;
+ overflow: hidden; text-overflow: ellipsis; display: -webkit-box;
+ -webkit-line-clamp: 2; -webkit-box-orient: vertical;
+}
+.agora-econ-feed-reward { font-size: 11.5px; font-weight: 700; color: var(--econ-gold); }
+
+/* ── Floating world labels (coin reward + reputation tick) ─────────────────── */
+.agora-econ-float {
+ position: absolute; top: 0; left: 0; z-index: 55; pointer-events: none;
+ font-size: 15px; font-weight: 800; white-space: nowrap; will-change: transform, opacity;
+ text-shadow: 0 2px 8px rgba(0,0,0,0.85), 0 0 2px rgba(0,0,0,0.9);
+}
+.agora-econ-float-reward { color: var(--econ-gold); }
+.agora-econ-float-rep { color: var(--econ-rep); }
+
+/* ── Offline pip ───────────────────────────────────────────────────────────── */
+.agora-econ-offline .agora-econ-ticker::after {
+ content: 'reconnecting…'; position: absolute; top: 10px; right: 12px;
+ font-size: 10px; color: #ffb454; opacity: 0.9;
+}
+
+/* ── Responsive ────────────────────────────────────────────────────────────── */
+@media (max-width: 880px) {
+ .agora-econ-board-panel { width: 230px; top: 58px; right: 10px; max-height: 42vh; }
+ .agora-econ-ticker { width: calc(100vw - 250px); max-width: 320px; left: 10px; bottom: 10px; max-height: 42vh; }
+}
+@media (max-width: 560px) {
+ .agora-econ-board-panel {
+ top: auto; bottom: 10px; right: 10px; left: 10px; width: auto;
+ max-height: 34vh; flex-direction: column;
+ }
+ .agora-econ-ticker {
+ left: 10px; right: 10px; bottom: calc(34vh + 18px); width: auto; max-width: none;
+ max-height: 36vh;
+ }
+ .agora-econ-readout { grid-template-columns: repeat(3, 1fr); }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .agora-econ-feed-item.enter .agora-econ-feed-btn { animation: none; }
+ .agora-econ-board-item, .agora-econ-feed-btn, .agora-econ-earner { transition: none; }
+}
+`;
diff --git a/workers/agora-citizens/work/_lib.js b/workers/agora-citizens/work/_lib.js
deleted file mode 100644
index fc9cd43b5..000000000
--- a/workers/agora-citizens/work/_lib.js
+++ /dev/null
@@ -1,228 +0,0 @@
-// Shared plumbing for the Agora profession WORK modules (docs/agora.md § Professions).
-//
-// Every profession module is a pluggable unit with one job: take a claimed task
-// and produce a REAL artifact plus a proof that binds it. The proof is always
-// `sha256(canonical bytes of the deliverable)` — the exact bytes served at the
-// deliverable URL — so any Verifier (or the UI's Verify button) can re-download
-// and re-derive the identical 32-byte hash. This file is where that invariant
-// lives: one sha256, one canonical-JSON encoder, one deliverable store, one set
-// of HTTP helpers against the real three.ws API. No mocks, no placeholders.
-
-import { createHash } from 'node:crypto';
-
-// The real API origin every skill calls. Override for a local/staging deploy via
-// THREE_WS_BASE_URL; the SDK family resolves the same way (packages/*/src/http.js).
-export const BASE_URL = String(process.env.THREE_WS_BASE_URL || 'https://three.ws').replace(/\/+$/, '');
-
-// ── Proof ────────────────────────────────────────────────────────────────────
-
-/** The one true proof primitive: sha256(bytes) → 32-byte Buffer. */
-export function sha256(bytes) {
- return createHash('sha256').update(bytes).digest();
-}
-
-/** Lowercase hex of a byte buffer (64 chars for a 32-byte proof). */
-export function toHex(buf) {
- return Buffer.from(buf).toString('hex');
-}
-
-// Deterministic JSON encoder — keys sorted at every level — so a producer and a
-// Verifier on different machines hash byte-identical bytes for the same object.
-function stableStringify(value) {
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
- if (value && typeof value === 'object') {
- return `{${Object.keys(value)
- .sort()
- .map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`)
- .join(',')}}`;
- }
- return JSON.stringify(value === undefined ? null : value);
-}
-
-/** Canonical UTF-8 bytes of a JSON deliverable — what we both store AND hash. */
-export function canonicalJsonBytes(obj) {
- return Buffer.from(stableStringify(obj), 'utf8');
-}
-
-/** A ≤64-byte on-chain pointer (resultData) — a short URL / CID, UTF-8, truncated. */
-export function pointer64(str) {
- return Buffer.from(String(str ?? ''), 'utf8').subarray(0, 64);
-}
-
-/** Best work prompt from a task, across the board's AgenC and x402 task shapes. */
-export function taskPrompt(task) {
- return String(task?.prompt || task?.title || task?.description || task?.resource || '').trim();
-}
-
-// ── Deliverable storage (R2) ──────────────────────────────────────────────────
-
-// Store the exact deliverable bytes in our bucket and return their public URL —
-// the verifiable supply chain's anchor. R2 is loaded lazily so the profession
-// modules import without the S3 SDK / credentials present (work-only dev runs,
-// tests). When R2 is unconfigured AND the bytes already live at a durable source
-// URL (e.g. forge's hosted GLB), we fall back to that URL: still real, still
-// re-downloadable, still hashes to the same proof. With no durable source and no
-// R2, that is a real failure — never a fabricated link.
-export async function storeDeliverable({ profession, ext, contentType, bytes, sourceUrl = null }) {
- const digest = toHex(sha256(bytes));
- const key = `agora/deliverables/${profession}/${digest}.${ext}`;
- try {
- const { putObject, publicUrl } = await import('../../../api/_lib/r2.js');
- await putObject({ key, body: bytes, contentType });
- return { url: publicUrl(key), key, digest, stored: true };
- } catch (err) {
- if (sourceUrl) return { url: sourceUrl, key: null, digest, stored: false, storeError: err?.message };
- throw new Error(
- `deliverable storage unavailable — configure S3_*/R2 env or supply a durable source URL (${err?.message || err})`,
- );
- }
-}
-
-// ── Real HTTP against the three.ws API ────────────────────────────────────────
-
-/** GET/POST a JSON endpoint; throws a typed error (with .status/.code) on non-2xx. */
-export async function httpJson(path, { method = 'GET', body, headers, query, signal } = {}) {
- const url = new URL(path.startsWith('http') ? path : `${BASE_URL}${path}`);
- if (query) for (const [k, v] of Object.entries(query)) if (v != null && v !== '') url.searchParams.set(k, String(v));
- const res = await fetch(url, {
- method,
- headers: {
- accept: 'application/json',
- ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
- ...(headers || {}),
- },
- body: body !== undefined ? JSON.stringify(body) : undefined,
- signal,
- });
- const text = await res.text();
- let data;
- try {
- data = text ? JSON.parse(text) : {};
- } catch {
- data = { raw: text };
- }
- if (!res.ok) {
- const err = new Error(data?.message || data?.error || `HTTP ${res.status} ${path}`);
- err.status = res.status;
- err.code = data?.error || `http_${res.status}`;
- err.body = data;
- throw err;
- }
- return data;
-}
-
-/** Fetch raw bytes (binary deliverables, re-downloads); throws on non-2xx. */
-export async function httpBytes(path, { method = 'GET', body, headers, signal } = {}) {
- const url = path.startsWith('http') ? path : `${BASE_URL}${path}`;
- const res = await fetch(url, {
- method,
- headers: headers || {},
- body: body !== undefined ? (typeof body === 'string' ? body : JSON.stringify(body)) : undefined,
- signal,
- });
- if (!res.ok) {
- const peek = await res.text().catch(() => '');
- const err = new Error(`HTTP ${res.status} ${url}: ${peek.slice(0, 200)}`);
- err.status = res.status;
- throw err;
- }
- const bytes = Buffer.from(await res.arrayBuffer());
- return { bytes, contentType: res.headers.get('content-type'), headers: res.headers };
-}
-
-// POST /api/brain/chat streams Server-Sent Events; a deliverable is one payload,
-// so we consume the whole stream and collapse the text deltas into a single
-// reply (mirrors the brain-mcp client's protocol). Free open-weight tiers
-// (gpt-oss-120b) need no key; paid flagships read THREE_WS_API_KEY if present.
-export async function brainChat({ provider = 'gpt-oss-120b', system, messages, maxTokens, signal } = {}) {
- const body = { provider, messages };
- if (system) body.system = system;
- if (Number.isFinite(maxTokens)) body.maxTokens = Math.trunc(maxTokens);
-
- const res = await fetch(`${BASE_URL}/api/brain/chat`, {
- method: 'POST',
- headers: {
- accept: 'text/event-stream',
- 'content-type': 'application/json',
- ...(process.env.THREE_WS_API_KEY ? { authorization: `Bearer ${process.env.THREE_WS_API_KEY}` } : {}),
- },
- body: JSON.stringify(body),
- signal,
- });
-
- // A rejected request (unknown provider, rate limit, sign-in required) returns
- // JSON, not SSE — surface it as a real error.
- if (!res.ok || !res.body) {
- const raw = await res.text().catch(() => '');
- let data;
- try {
- data = raw ? JSON.parse(raw) : {};
- } catch {
- data = { raw };
- }
- const err = new Error(data?.message || data?.error || `brain HTTP ${res.status}`);
- err.status = res.status;
- throw err;
- }
-
- const reader = res.body.getReader();
- const decoder = new TextDecoder();
- let buf = '';
- let text = '';
- let meta = null;
- let usage = null;
-
- const handle = (event, data) => {
- if (!data || data === '[DONE]') return;
- if (!event || event === 'message') {
- try {
- const piece = JSON.parse(data);
- if (typeof piece === 'string') text += piece;
- } catch {
- /* non-JSON keepalive */
- }
- return;
- }
- if (event === 'meta') {
- try {
- meta = JSON.parse(data);
- } catch {
- /* ignore */
- }
- } else if (event === 'done') {
- try {
- usage = JSON.parse(data)?.usage ?? usage;
- } catch {
- /* ignore */
- }
- } else if (event === 'error') {
- let message = 'brain stream error';
- try {
- message = JSON.parse(data)?.message || message;
- } catch {
- /* ignore */
- }
- throw new Error(message);
- }
- };
-
- for (;;) {
- const { value, done } = await reader.read();
- if (done) break;
- buf += decoder.decode(value, { stream: true });
- let idx;
- while ((idx = buf.indexOf('\n\n')) !== -1) {
- const frame = buf.slice(0, idx);
- buf = buf.slice(idx + 2);
- let event = null;
- const dataLines = [];
- for (const line of frame.split('\n')) {
- if (line.startsWith('event:')) event = line.slice(6).trim();
- else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));
- }
- handle(event, dataLines.join('\n'));
- }
- }
-
- return { text: text.trim(), meta, usage };
-}