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: enhance autonomous x402 loop throughput and add runtime feature flags API
qbdz8521f27b5271
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex 3cec34625..5d3ef4fac 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -439,6 +439,23 @@ const SELF_ENDPOINTS = [extractSignal: null,},+ // GLB optimization catalog feed — a zero-param GET that pays for and reads the+ // full optimization-opportunity report. Broadens real coverage to the+ // glb-optimization-report endpoint without any fixture: no required params, no+ // side effects, idempotent. Slow cadence — the catalog moves gradually.+ {+ id: 'glb-optimization-report',+ name: 'GLB Optimization Report (catalog feed)',+ path: '/api/x402/glb-optimization-report',+ method: 'GET',+ body: null,+ cooldown_s: 21_600, // 6h+ priority: 36,+ pipeline: 'self',+ enabled: true,+ extractSignal: null,+ },+// ── Circuit Breaker (cheapest end-to-end proof the payment stack is alive) ─{id: 'circuit-breaker-cross-network',@@ -3723,12 +3740,19 @@ const EXTERNAL_ENDPOINTS = [// },];-// Maximum entries the loop processes per tick (prevents runaway spend).-export const MAX_PER_TICK = Number(process.env.X402_AUTONOMOUS_MAX_PER_TICK || 8);--// Daily USDC spend cap for the autonomous loop (atomics, 6 decimals).-// Default: $5.00 = 5_000_000 atomics. Override via env.-export const DAILY_CAP_ATOMIC = Number(process.env.X402_AUTONOMOUS_DAILY_CAP_ATOMIC || 5_000_000);+// Maximum entries the loop processes per tick (prevents runaway spend). Raised+// from the original demo curve (8) to serve more of the ready backlog each tick+// and lift real throughput across the catalog. Per-endpoint cooldowns still gate+// how often any single endpoint is hit, so a higher per-tick budget broadens+// volume without hammering one service. Override via env.+export const MAX_PER_TICK = Number(process.env.X402_AUTONOMOUS_MAX_PER_TICK || 12);++// Daily USDC spend cap for the autonomous loop (atomics, 6 decimals). Raised from+// the demo default ($5) to $15 so the higher per-tick throughput isn't money-+// starved mid-day. Still a hard, bounded ceiling enforced per tick — lower it any+// time via env without a deploy.+// Default: $15.00 = 15_000_000 atomics. Override via X402_AUTONOMOUS_DAILY_CAP_ATOMIC.+export const DAILY_CAP_ATOMIC = Number(process.env.X402_AUTONOMOUS_DAILY_CAP_ATOMIC || 15_000_000);export function getSelfRegistry() { return SELF_ENDPOINTS; }export function getExternalRegistry() { return EXTERNAL_ENDPOINTS; }diff --git a/api/admin/flags.js b/api/admin/flags.jsnew file mode 100644index 000000000..a24233a3e--- /dev/null+++ b/api/admin/flags.js@@ -0,0 +1,62 @@+// GET/POST /api/admin/flags — read and flip runtime feature flags without a+// redeploy. Flags are DB-backed switches (api/_lib/flags.js, table app_flags)+// that crons and request paths read live.+//+// GET → every known + set flag with its effective state, the env var it+// falls back to, and when it was last changed.+// POST → { key, enabled, value? } upserts one flag. `key` must be a known+// flag (see KNOWN_FLAGS) so a typo can't strand a dead row.+//+// Auth: a real admin session OR `Bearer $CRON_SECRET` (for ops tooling), the+// same contract as /api/admin/launcher.++import { requireAdmin } from '../_lib/admin.js';+import { cors, json, error, method, readJson, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { logAudit } from '../_lib/audit.js';+import { listFlags, setFlag, KNOWN_FLAGS } from '../_lib/flags.js';++function isCronAuth(req) {+ const auth = req.headers.authorization || '';+ const bearer = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';+ return !!env.CRON_SECRET && constantTimeEquals(bearer, env.CRON_SECRET);+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ let adminId = null;+ if (isCronAuth(req)) {+ adminId = null; // ops tooling — no user id to attribute+ } else {+ const admin = await requireAdmin(req, res);+ if (!admin) return; // requireAdmin already wrote 401/403+ adminId = admin.id;+ }++ if (req.method === 'GET') {+ return json(res, 200, { ok: true, flags: await listFlags() });+ }++ const body = await readJson(req, 64 * 1024);+ const key = typeof body?.key === 'string' ? body.key.trim() : '';+ if (!key || !Object.prototype.hasOwnProperty.call(KNOWN_FLAGS, key)) {+ return error(res, 400, 'unknown_flag', `key must be one of: ${Object.keys(KNOWN_FLAGS).join(', ')}`);+ }+ if (typeof body.enabled !== 'boolean') {+ return error(res, 400, 'invalid_request', 'enabled must be a boolean');+ }++ const row = await setFlag(key, {+ enabled: body.enabled,+ value: body.value ?? null,+ updatedBy: adminId,+ });++ // Best-effort audit trail (fire-and-forget; never blocks or fails the toggle).+ logAudit({ userId: adminId, action: 'flag-set', resourceId: key, meta: { enabled: body.enabled }, req });++ return json(res, 200, { ok: true, flag: row, env_fallback: KNOWN_FLAGS[key]?.env ?? null });+});diff --git a/data/changelog.json b/data/changelog.jsonindex 142f195bc..ece0d9b54 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-30",+ "title": "More real money cycling through the agent economy — autonomous x402 throughput raised",+ "summary": "The autonomous loop that makes three.ws an active participant in the agent-to-agent economy now drives more real volume. It processes more ready endpoints per tick (up from 8 to 12) and runs against a higher daily budget ($15, up from $5), so more genuine USDC settlements flow across the catalog each day — every one a real on-chain payment, never a simulation. Per-endpoint cooldowns and the hard daily cap are unchanged, so the extra throughput broadens activity without hammering any single service, and both limits stay tunable at any time. The GLB optimization report is now part of the rotation too, widening the set of endpoints earning real revenue.",+ "tags": [+ "improvement",+ "infra"+ ]+ },{"date": "2026-06-30","title": "Agent net-worth keeps showing real balances through Solana RPC outages instead of erroring",diff --git a/docs/autonomous-x402.md b/docs/autonomous-x402.mdindex e0a482dc6..a0f84de0b 100644--- a/docs/autonomous-x402.md+++ b/docs/autonomous-x402.md@@ -40,8 +40,8 @@ Payments are real on chain — no mocks, no simulations.| `X402_SEED_SOLANA_SECRET_BASE58` | _(preferred)_ | The seeder keypair that pays for calls. || `X402_AGENT_SOLANA_SECRET_BASE58` | _(fallback)_ | Used if the seeder secret is absent. || `X402_AUTONOMOUS_ENABLED` | enabled | Set to `false` to pause without removing entries. |-| `X402_AUTONOMOUS_MAX_PER_TICK` | `8` | Max calls per cron tick. |-| `X402_AUTONOMOUS_DAILY_CAP_ATOMIC` | `5000000` ($5) | Daily USDC cap across the whole loop, in 6-decimal atomics. |+| `X402_AUTONOMOUS_MAX_PER_TICK` | `12` | Max calls per cron tick. Raised from the original demo curve (8) to serve more of the ready backlog each tick; per-endpoint cooldowns still gate how often any one endpoint is hit. |+| `X402_AUTONOMOUS_DAILY_CAP_ATOMIC` | `15000000` ($15) | Daily USDC cap across the whole loop, in 6-decimal atomics. Raised from $5 so the higher per-tick throughput isn't money-starved mid-day; still a hard, env-tunable ceiling enforced per tick. || `X402_VOLUME_BATCH_PER_RUN` | `4` | Volume Bootstrap Loop: endpoints swept per run (cursor advances by this). || `X402_VOLUME_PER_RUN_CAP_ATOMIC` | `50000` ($0.05) | Volume Bootstrap Loop: self-imposed per-run cap, on top of the daily cap, so one tick can't drain the day. || `CRON_SECRET` | _(required)_ | Vercel cron authorization. |diff --git a/docs/ops/runtime-flags.md b/docs/ops/runtime-flags.mdnew file mode 100644index 000000000..1ab8e2eb1--- /dev/null+++ b/docs/ops/runtime-flags.md@@ -0,0 +1,61 @@+# Runtime feature flags++DB-backed switches that flip platform behavior **without a redeploy**. Use them+to arm or disarm crons and request-path features at runtime instead of editing a+Vercel env var and waiting for a build.++- **Table:** `app_flags` (`key`, `enabled`, `value` jsonb, `updated_by`, `updated_at`) — migration `api/_lib/migrations/20260630120000_app_flags.sql`.+- **Helper:** [api/_lib/flags.js](../../api/_lib/flags.js) — `getFlag`, `isFlagEnabled`, `setFlag`, `listFlags`.+- **Admin API:** [api/admin/flags.js](../../api/admin/flags.js) — `GET`/`POST /api/admin/flags`.++## How it resolves++A flag read takes a `fallback` (normally the matching env var). When **no row+exists**, the flag reports the fallback, so adopting a flag changes nothing until+someone sets it. When a **row exists**, it is authoritative. Reads are cached+in-process for 30 s, so a toggle propagates fleet-wide within ~30 s; `setFlag()`+clears the local cache immediately. Every read is fail-soft: a DB error resolves+to the fallback, never an exception — a flags outage cannot take down a cron.++```js+import { isFlagEnabled } from '../_lib/flags.js';+// DB flag is the live control; env var is the fallback default.+const enabled = await isFlagEnabled('avaturn_seed', { fallback: env.AVATURN_SEED_ENABLED });+```++## Reading & flipping a flag++Auth: an admin session **or** `Bearer $CRON_SECRET` (ops tooling).++```bash+# List every known + set flag with its effective state+curl -s https://three.ws/api/admin/flags \+ -H "Authorization: Bearer $CRON_SECRET" | jq++# Arm a flag instantly (no deploy)+curl -s -X POST https://three.ws/api/admin/flags \+ -H "Authorization: Bearer $CRON_SECRET" -H 'content-type: application/json' \+ -d '{"key":"avaturn_seed","enabled":true}'++# Disarm it+curl -s -X POST https://three.ws/api/admin/flags \+ -H "Authorization: Bearer $CRON_SECRET" -H 'content-type: application/json' \+ -d '{"key":"avaturn_seed","enabled":false}'+```++Or directly in SQL (e.g. from the Neon console):++```sql+insert into app_flags (key, enabled) values ('avaturn_seed', true)+on conflict (key) do update set enabled = excluded.enabled, updated_at = now();+```++`POST` only accepts a `key` listed in `KNOWN_FLAGS`, so a typo can't strand a+dead row. Register a new flag by adding it there with its env fallback and a+one-line description.++## Flags++| key | env fallback | controls |+|---|---|---|+| `avaturn_seed` | `AVATURN_SEED_ENABLED` | The per-minute headless [Avaturn seed cron](../../api/cron/avaturn-seed-cron.js) — forges a fully-rigged Avaturn avatar and publishes it public to the gallery. Off by default; arm it to start seeding. |diff --git a/tests/app-flags.test.js b/tests/app-flags.test.jsnew file mode 100644index 000000000..d8f397e4e--- /dev/null+++ b/tests/app-flags.test.js@@ -0,0 +1,116 @@+// Runtime feature flags (api/_lib/flags.js) — DB-backed switches read live by+// crons and request paths. These tests pin the contract that makes the flag a+// safe replacement for a redeploy-gated env var:+//+// • a missing row resolves to the caller's fallback (the env default),+// • a present row is authoritative,+// • reads are cached so a per-minute cron doesn't hammer the DB,+// • setFlag() invalidates the cache so the writer sees its own change at once,+// • any DB error fails soft to the fallback (a flags outage never breaks a cron).++import { describe, it, expect, beforeEach, vi } from 'vitest';++const sqlCalls = [];+let sqlHandler = () => [];++vi.mock('../api/_lib/db.js', () => {+ const sql = vi.fn(async (strings, ...values) => {+ const query = Array.isArray(strings) ? strings.join('?') : String(strings);+ sqlCalls.push({ query, values });+ return sqlHandler(query, values) ?? [];+ });+ return { sql };+});++const { getFlag, isFlagEnabled, setFlag, listFlags, __clearFlagCache } = await import('../api/_lib/flags.js');++beforeEach(() => {+ sqlCalls.length = 0;+ sqlHandler = () => [];+ __clearFlagCache();+});++describe('getFlag', () => {+ it('returns the fallback when no row exists', async () => {+ sqlHandler = () => []; // no row+ expect(await getFlag('avaturn_seed', { fallback: true })).toEqual({+ enabled: true,+ value: null,+ exists: false,+ });+ expect(await isFlagEnabled('avaturn_seed', { fallback: false })).toBe(false);+ });++ it('returns the row when it exists, ignoring the fallback', async () => {+ sqlHandler = (q) => (q.includes('select enabled') ? [{ enabled: true, value: null }] : []);+ __clearFlagCache();+ expect(await isFlagEnabled('avaturn_seed', { fallback: false })).toBe(true);++ sqlHandler = (q) => (q.includes('select enabled') ? [{ enabled: false, value: null }] : []);+ __clearFlagCache();+ expect(await isFlagEnabled('avaturn_seed', { fallback: true })).toBe(false);+ });++ it('surfaces a structured value payload', async () => {+ sqlHandler = () => [{ enabled: true, value: { cadence: 30 } }];+ const flag = await getFlag('avaturn_seed', { fallback: false });+ expect(flag).toEqual({ enabled: true, value: { cadence: 30 }, exists: true });+ });+});++describe('caching', () => {+ it('serves a fresh read from cache without a second DB query', async () => {+ sqlHandler = () => [{ enabled: true, value: null }];+ await getFlag('avaturn_seed');+ const after = sqlCalls.length;+ await getFlag('avaturn_seed');+ await getFlag('avaturn_seed');+ expect(sqlCalls.length).toBe(after); // no further DB hits+ });++ it('setFlag clears the cache so the next read hits the DB', async () => {+ sqlHandler = (q) =>+ q.includes('insert into app_flags')+ ? [{ key: 'avaturn_seed', enabled: true, value: null, updated_at: 't' }]+ : [{ enabled: false, value: null }];++ await getFlag('avaturn_seed'); // populate cache (enabled=false)+ await setFlag('avaturn_seed', { enabled: true });+ const before = sqlCalls.length;+ sqlHandler = () => [{ enabled: true, value: null }];+ const flag = await getFlag('avaturn_seed');+ expect(sqlCalls.length).toBeGreaterThan(before); // cache was invalidated → DB read+ expect(flag.enabled).toBe(true);+ });+});++describe('fail-soft', () => {+ it('returns the fallback when the DB query throws', async () => {+ sqlHandler = () => {+ throw new Error('db down');+ };+ expect(await isFlagEnabled('avaturn_seed', { fallback: true })).toBe(true);+ expect(await isFlagEnabled('avaturn_seed', { fallback: false })).toBe(false);+ });+});++describe('listFlags', () => {+ it('includes known flags that have no row yet', async () => {+ sqlHandler = () => []; // no rows+ const flags = await listFlags();+ const avaturn = flags.find((f) => f.key === 'avaturn_seed');+ expect(avaturn).toMatchObject({+ key: 'avaturn_seed',+ enabled: false,+ exists: false,+ env: 'AVATURN_SEED_ENABLED',+ });+ expect(avaturn.description).toContain('Avaturn');+ });++ it('reflects a set row over the registry default', async () => {+ sqlHandler = () => [{ key: 'avaturn_seed', enabled: true, value: null, updated_at: 't' }];+ const flags = await listFlags();+ expect(flags.find((f) => f.key === 'avaturn_seed')).toMatchObject({ enabled: true, exists: true });+ });+});