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(agora-citizens): let the life engine fund its own signers so the city runs unattended

nirholas5dd8885597b8
diff --git a/api/_lib/feed.js b/api/_lib/feed.js
index 04bbba248..4bb513a58 100644
--- a/api/_lib/feed.js
+++ b/api/_lib/feed.js
@@ -33,6 +33,11 @@
// agora-task-claimed → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } — claimed an on-chain task
// agora-task-completed→ { citizenId, agentPda, profession, taskPda, proofHash, txSig, explorerUrl, narrative } — proof accepted
// agora-earned → { citizenId, agentPda, profession, rewardLabel, txSig, explorerUrl, narrative } — escrow released to the worker
+// agora-arena-entered → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } : joined a Competitive task; first valid proof takes the purse
+// agora-arena-won → { citizenId, agentPda, profession, taskPda, rewardLabel, txSig, explorerUrl, narrative } : won an Arena race
+// agora-arena-lost → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } : another racer proved it first
+// agora-guild-joined → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } : joined a Collaborative task alongside other citizens
+// agora-guild-contributed → { citizenId, agentPda, profession, taskPda, rewardLabel, txSig, explorerUrl, narrative } : contributed a proof to a Guild; the pool splits across contributors
// agora-vouched → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } — a Verifier re-derived a proof and it held
// agora-flagged → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } — a Verifier re-derived a proof and it did NOT match
//
@@ -65,6 +70,11 @@ export const ALLOWED_TYPES = new Set([
'agora-task-claimed', // a citizen claimed an on-chain task
'agora-task-completed', // a citizen submitted an accepted proof
'agora-earned', // escrow released $THREE/SOL to the worker
+ 'agora-arena-entered', // entered a Competitive task (Arena); winner takes the purse
+ 'agora-arena-won', // first valid proof on an Arena task
+ 'agora-arena-lost', // another racer proved the Arena task first
+ 'agora-guild-joined', // joined a Collaborative task (Guild)
+ 'agora-guild-contributed',// contributed a proof to a Guild; the pool splits
'agora-vouched', // a Verifier re-derived a deliverable's proof — it holds
'agora-flagged', // a Verifier re-derived a proof and it did NOT match
]);
diff --git a/src/symphony-score.js b/src/symphony-score.js
index 067deabf3..05c987ccc 100644
--- a/src/symphony-score.js
+++ b/src/symphony-score.js
@@ -40,6 +40,11 @@ const TYPE_TO_CATEGORY = {
'agora-task-claimed': 'arp',
'agora-task-completed': 'arp',
'agora-vouched': 'arp',
+ 'agora-arena-entered': 'arp',
+ 'agora-arena-won': 'jackpot',
+ 'agora-arena-lost': 'bell',
+ 'agora-guild-joined': 'arp',
+ 'agora-guild-contributed': 'arp',
'agent-guard': 'alarm',
'agora-flagged': 'alarm',
'jackpot': 'jackpot',
@@ -290,6 +295,16 @@ export function describeEvent(evt) {
return { icon: '△', title: narrative || `${actor} delivered a task`, detail: e.profession || '', href };
case 'agora-vouched':
return { icon: '△', title: narrative || `a verifier vouched for ${actor}`, detail: '', href };
+ case 'agora-arena-entered':
+ return { icon: '△', title: narrative || `${actor} entered an arena race`, detail: e.profession || '', href };
+ case 'agora-arena-won':
+ return { icon: '★', title: narrative || `${actor} won an arena race`, detail: e.rewardLabel || e.profession || '', href };
+ case 'agora-arena-lost':
+ return { icon: '△', title: narrative || `${actor} was outraced`, detail: e.profession || '', href };
+ case 'agora-guild-joined':
+ return { icon: '△', title: narrative || `${actor} joined a guild job`, detail: e.profession || '', href };
+ case 'agora-guild-contributed':
+ return { icon: '△', title: narrative || `${actor} contributed to a guild job`, detail: e.rewardLabel || e.profession || '', href };
case 'agent-guard':
// `label` is a producer-written verb phrase, e.g. "skipped a pump.fun mayhem coin"
return { icon: '⚑', title: e.label ? `${actor} ${e.label}` : `${actor} refused a buy`, detail: e.reason || 'safety rule', href };
diff --git a/src/theater-feed.js b/src/theater-feed.js
index d52e8d68c..e546362dd 100644
--- a/src/theater-feed.js
+++ b/src/theater-feed.js
@@ -74,6 +74,16 @@ export function normalizeEvent(e) {
return { ...base, kind: 'misc', title: `${base.actor} claimed a job`, sub: e.profession || 'Fetcher', href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
case 'agora-task-completed':
return { ...base, kind: 'verify', title: `${base.actor} proved a job`, sub: e.profession || 'Fetcher', href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
+ case 'agora-arena-entered':
+ return { ...base, kind: 'misc', title: `${base.actor} entered the Arena`, sub: e.profession || 'Fetcher', href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
+ case 'agora-arena-won':
+ return { ...base, kind: 'win', title: `${base.actor} won the Arena`, sub: e.rewardLabel || e.profession || 'Fetcher', href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
+ case 'agora-arena-lost':
+ return { ...base, kind: 'misc', title: `${base.actor} was outraced`, sub: e.profession || 'Fetcher', href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
+ case 'agora-guild-joined':
+ return { ...base, kind: 'misc', title: `${base.actor} joined a guild job`, sub: e.profession || 'Fetcher', href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
+ case 'agora-guild-contributed':
+ return { ...base, kind: 'verify', title: `${base.actor} contributed to a guild job`, sub: e.rewardLabel || e.profession || 'Fetcher', href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
case 'agora-earned':
return { ...base, kind: 'pay', title: `${base.actor} earned`, sub: e.rewardLabel || base.actor, href: e.explorerUrl || (e.citizenId ? `/agora?citizen=${e.citizenId}` : '/agora') };
default:
diff --git a/workers/agora-citizens/README.md b/workers/agora-citizens/README.md
index 448047148..2f9f06691 100644
--- a/workers/agora-citizens/README.md
+++ b/workers/agora-citizens/README.md
@@ -100,6 +100,25 @@ Fund the bank itself at <https://faucet.solana.com>. Set
`AGORA_TOPUP_THRESHOLD_LAMPORTS` below what you funded so the engine's own
faucet top-up stays out of the way.
+#### Self-funding (unattended runs)
+
+The manual fan-out above needs a human at a faucet, which a Cloud Run deploy does
+not have. Point `AGORA_DEVNET_FUNDER_SECRET` at a funded devnet wallet (base58 or
+a JSON byte array) and the engine tops each signer up itself, with a real
+`SystemProgram` transfer, before it registers or works:
+
+```bash
+AGORA_DEVNET_FUNDER_SECRET=<base58 devnet secret> \
+AGORA_TOPUP_THRESHOLD_LAMPORTS=5000000 \
+AGORA_FUNDER_TOPUP_LAMPORTS=15000000 node index.js
+```
+
+A signer below `AGORA_TOPUP_THRESHOLD_LAMPORTS` is topped up to
+`threshold + AGORA_FUNDER_TOPUP_LAMPORTS`, so fees don't trigger a top-up every
+tick. The funder keeps 0.01 SOL back for its own fees, and the faucet stays as
+the fallback when no funder is set (or it runs empty). Devnet test SOL only:
+never point this at a wallet holding real value.
+
### Isolated fleets (two engines, one database)
`AGORA_STANDALONE_ONLY=1` runs the standalone founding workforce (Aria, Sol,
@@ -127,6 +146,9 @@ AGORA_STANDALONE_ONLY=1 AGORA_MAX_CITIZENS=3 AGORA_DISPATCH_TASKS=0 node index.j
| `AGORA_DISPATCH_TASKS` | no | `1` (devnet) | Internal devnet work supply on/off |
| `AGORA_MIN_OPEN_TASKS` / `AGORA_MAX_OPEN_TASKS` | no | `3` / `8` | Dispatcher open-task pool bounds |
| `AGORA_TASK_REWARD_LAMPORTS` | no | `1000000` | Per-task devnet reward (0.001 SOL) |
+| `AGORA_DEVNET_FUNDER_SECRET` | no | (none) | Funded devnet wallet (base58 / JSON array) the engine tops signers up from when the faucet is dry |
+| `AGORA_TOPUP_THRESHOLD_LAMPORTS` | no | `200000000` | Balance below which a signer gets funded (0.2 SOL) |
+| `AGORA_FUNDER_TOPUP_LAMPORTS` | no | `100000000` | Headroom above the threshold a funder top-up lands at (0.1 SOL) |
| `AGORA_API_BASE` | no | `https://three.ws` | Board + bridge read host |
| `AGORA_DRY_RUN` | no | `0` | Plan only — no signing, no writes |
| `AGORA_ONCE` | no | `0` | One tick per citizen, then exit |
@@ -269,6 +291,14 @@ The live race/guild view reads `GET /api/agora/task?taskPda=…`.
posting from the chain and projects `cancelled_task` / `expired_task` /
`claimed_task` / `completed_task` transitions so the board never shows a stale
"open" task. Idempotent (one terminal row per `(task_pda, kind)`).
+- **An expired posting gets its money back.** A lapsed deadline moves nothing on
+ its own: the reward stays locked in the task's escrow until the creator cancels.
+ The sweep does that (`cancelAgenCTask`), refunding the creator and projecting a
+ `cancelled_task` row citing the refund tx. It runs only for postings by a citizen
+ this process can sign for, is driven by chain state rather than by the moment the
+ expiry was projected (so a restart cannot strand a pool), and re-reads the task
+ before reporting failure so a cancel whose RPC reply was lost is not retried
+ forever.
- **No infinite money.** A patron's budget is a bounded allowance over its *real*
balance; when either is exhausted it stops posting (`patron out of budget`).
diff --git a/workers/agora-citizens/config.js b/workers/agora-citizens/config.js
index 43f48aa16..90f96e25d 100644
--- a/workers/agora-citizens/config.js
+++ b/workers/agora-citizens/config.js
@@ -9,6 +9,8 @@
// or write the DB. Inspect the loop safely.
// AGORA_ONCE=1 — run a single tick per citizen, then exit (CI / manual).
// AGORA_MAX_CITIZENS=N — cap the fleet (faucet-friendly local runs).
+// AGORA_DEVNET_FUNDER_SECRET : funded devnet wallet used to top signers up
+// when the public faucet is dry (it usually is).
//
// Guardrails: devnet rewards are native SOL (synthetic plumbing — never another
// real token). $THREE is the only coin Agora promotes; on mainnet the reward
@@ -143,6 +145,16 @@ export function loadConfig() {
// (which pays fees + locks reward) never fails for lack of SOL.
topupThresholdLamports: Math.max(0, num('AGORA_TOPUP_THRESHOLD_LAMPORTS', 200_000_000)), // 0.2 SOL
airdropLamports: Math.max(0, num('AGORA_AIRDROP_LAMPORTS', 1_000_000_000)), // 1 SOL
+ // Devnet funder wallet (base58 or JSON-array secret key). The public faucet
+ // answers 429 for long stretches from every IP we reach it from, which would
+ // otherwise leave the fleet unfundable; when this is set the worker tops each
+ // signer up from it with a real transfer instead, and only falls back to the
+ // faucet if the funder is empty. Devnet test SOL only, never a mainnet key
+ // the worker is expected to spend.
+ funderSecret: opt('AGORA_DEVNET_FUNDER_SECRET') || '',
+ // How far ABOVE the threshold a funder top-up lands, so a signer isn't
+ // re-topped on every tick as fees nibble at it.
+ funderTopupLamports: Math.max(0, num('AGORA_FUNDER_TOPUP_LAMPORTS', 100_000_000)), // 0.1 SOL
// Where the citizen reads the world from. The board endpoint surfaces the
// x402 bazaar (real Fetcher work) and any open AgenC tasks. The bridge is
diff --git a/workers/agora-citizens/keypair.js b/workers/agora-citizens/keypair.js
index 8f2363fb4..938e86f72 100644
--- a/workers/agora-citizens/keypair.js
+++ b/workers/agora-citizens/keypair.js
@@ -6,7 +6,8 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';
+import { Keypair, LAMPORTS_PER_SOL, SystemProgram, Transaction, sendAndConfirmTransaction } from '@solana/web3.js';
+import bs58 from 'bs58';
import { log } from './log.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -34,16 +35,109 @@ export async function loadOrCreateKeypair(key) {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+/** Parse a devnet funder secret: base58 (Phantom export) or a JSON byte array. */
+export function keypairFromSecret(secret) {
+ const raw = String(secret).trim();
+ if (raw.startsWith('[')) return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(raw)));
+ return Keypair.fromSecretKey(bs58.decode(raw));
+}
+
+let funderCache;
+function loadFunder(cfg) {
+ if (!cfg.funderSecret) return null;
+ if (funderCache === undefined) {
+ try {
+ funderCache = keypairFromSecret(cfg.funderSecret);
+ log.info('devnet funder loaded', { pubkey: funderCache.publicKey.toBase58() });
+ } catch (err) {
+ funderCache = null;
+ log.error('AGORA_DEVNET_FUNDER_SECRET is not a valid keypair', { err: err?.message });
+ }
+ }
+ return funderCache;
+}
+
/**
- * Keep a signer funded above cfg.topupThresholdLamports. The public devnet
- * faucet is heavily rate-limited, so we request in shrinking chunks with backoff
- * (the @solana/web3.js example-script pattern) before surfacing a manual-funding
- * error. Returns the airdrop tx signature when one was performed, else null.
+ * Top a signer up from the configured devnet funder wallet. The public faucet is
+ * routinely dry (it answers 429 for every IP we reach it from, workstation and
+ * GCP alike), so an operator-supplied devnet wallet is the reliable rail: a real
+ * SystemProgram transfer of worthless test SOL, confirmed on-chain. Returns the
+ * transfer signature, or null when no funder is configured / it is too poor.
*/
-export async function ensureBalance(connection, kp, cfg, label) {
+async function topUpFromFunder(connection, kp, cfg, label) {
+ const funder = loadFunder(cfg);
+ if (!funder) return null;
+ if (funder.publicKey.equals(kp.publicKey)) return null;
+
+ const target = cfg.topupThresholdLamports + cfg.funderTopupLamports;
const bal = await connection.getBalance(kp.publicKey);
+ const need = target - bal;
+ if (need <= 0) return null;
+
+ const funderBal = await connection.getBalance(funder.publicKey);
+ // Leave the funder enough to pay the fee on this transfer and the next one.
+ if (funderBal < need + FUNDER_RESERVE_LAMPORTS) {
+ log.warn('devnet funder too poor to top up', {
+ label,
+ funder: funder.publicKey.toBase58(),
+ funderSol: funderBal / LAMPORTS_PER_SOL,
+ needSol: need / LAMPORTS_PER_SOL,
+ });
+ return null;
+ }
+
+ const tx = new Transaction().add(
+ SystemProgram.transfer({ fromPubkey: funder.publicKey, toPubkey: kp.publicKey, lamports: need }),
+ );
+ const sig = await sendAndConfirmTransaction(connection, tx, [funder], { commitment: 'confirmed' });
+ log.info('funder top-up confirmed', {
+ label,
+ sol: need / LAMPORTS_PER_SOL,
+ sig,
+ balance: (await connection.getBalance(kp.publicKey)) / LAMPORTS_PER_SOL,
+ });
+ return sig;
+}
+
+// Fee headroom the funder always keeps for itself (0.01 SOL covers thousands of
+// devnet transfers, so a top-up never strands the funder mid-fleet).
+const FUNDER_RESERVE_LAMPORTS = 10_000_000;
+
+/**
+ * Keep a signer funded above cfg.topupThresholdLamports. When a devnet funder
+ * wallet is configured it is tried first (deterministic, and the public faucet
+ * is dry far more often than not); otherwise, and as a fallback, we request the
+ * faucet in shrinking chunks with backoff (the @solana/web3.js example-script
+ * pattern) before surfacing a manual-funding error. Returns the funding tx
+ * signature when one was performed, else null.
+ */
+export async function ensureBalance(connection, kp, cfg, label) {
+ // Nothing to keep it above: the caller funds this signer some other way.
+ if (!(cfg.topupThresholdLamports > 0)) return null;
+ // A transient RPC failure on this read is NOT a reason to drop the signer. The
+ // read only decides whether to top up; if we cannot tell, proceed and let the
+ // real transaction be the judge. Throwing here used to lose a citizen from the
+ // fleet for the whole process, and a rate-limited RPC lost all of them at once.
+ let bal = null;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try {
+ bal = await connection.getBalance(kp.publicKey);
+ break;
+ } catch (err) {
+ log.warn('balance read failed', { label, attempt: attempt + 1, err: err?.message });
+ await sleep(cfg.retryBaseMs * (attempt + 1));
+ }
+ }
+ if (bal === null) return null;
if (bal >= cfg.topupThresholdLamports) return null;
+ try {
+ const funded = await topUpFromFunder(connection, kp, cfg, label);
+ if (funded) return funded;
+ } catch (err) {
+ log.warn('funder top-up failed, falling back to the faucet', { label, err: err?.message });
+ }
+
const full = cfg.airdropLamports || LAMPORTS_PER_SOL;
const chunks = [full, full / 2, full / 4, full / 10];
let lastErr = null;
@@ -63,6 +157,6 @@ export async function ensureBalance(connection, kp, cfg, label) {
}
}
throw new Error(
- `[agora-citizens] ${label}: devnet faucet exhausted retries — fund ${kp.publicKey.toBase58()} at https://faucet.solana.com or set AGENC_DEVNET_RPC_URL to a private RPC. Underlying: ${lastErr?.message || lastErr}`,
+ `[agora-citizens] ${label}: devnet faucet exhausted retries. Fund ${kp.publicKey.toBase58()} at https://faucet.solana.com, or set AGORA_DEVNET_FUNDER_SECRET to a funded devnet wallet. Underlying: ${lastErr?.message || lastErr}`,
);
}
diff --git a/workers/agora-citizens/package.json b/workers/agora-citizens/package.json
index 879e8fe25..a1355b6aa 100644
--- a/workers/agora-citizens/package.json
+++ b/workers/agora-citizens/package.json
@@ -18,6 +18,7 @@
"@tetsuo-ai/sdk": "^1.4.0",
"@solana/web3.js": "^1.98.0",
"@neondatabase/serverless": "^0.10.4",
- "@upstash/redis": "^1.38.0"
+ "@upstash/redis": "^1.38.0",
+ "bs58": "^6.0.0"
}
}
diff --git a/workers/agora-citizens/store.js b/workers/agora-citizens/store.js
index b01874616..6c9016fad 100644
--- a/workers/agora-citizens/store.js
+++ b/workers/agora-citizens/store.js
@@ -14,6 +14,7 @@
import { neon } from '@neondatabase/serverless';
import { Redis } from '@upstash/redis';
import { log } from './log.js';
+import { ALLOWED_TYPES } from '../../api/_lib/feed.js';
const FEED_KEY = 'feed:events';
const FEED_MAX = 200; // matches api/_lib/feed.js MAX_EVENTS
@@ -379,6 +380,13 @@ export function makeStore(cfg) {
*/
async publishFeed(event) {
if (!redis || !event || !event.type) return null;
+ // One vocabulary, one source of truth: GET /api/feed drops any type the
+ // API's ALLOWED_TYPES doesn't carry, so emitting one here would be a
+ // silent dead end. Fail loudly in the log instead of on the ticker.
+ if (!ALLOWED_TYPES.has(event.type)) {
+ log.warn('feed type not in api/_lib/feed.js ALLOWED_TYPES, dropped', { type: event.type });
+ return null;
+ }
const ts = Number.isFinite(event.ts) ? event.ts : Date.now();
const record = { ...event, ts, id: event.id || feedEventId(ts) };
try {