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
Extend genome breeding/lineage, labor settlement, x402 discovery, and creator dashboard
nirholas4f01a2e70afe
diff --git a/api/_lib/services/MonetizationService.js b/api/_lib/services/MonetizationService.jsindex 93e1ff16a..bd8fbadd1 100644--- a/api/_lib/services/MonetizationService.js+++ b/api/_lib/services/MonetizationService.js@@ -24,6 +24,7 @@ import { sql as defaultSql } from '../db.js';import { hasSkillAccess } from '../skill-access.js';import { getAvailableBalance } from '../monetization.js';import { resolveMarketplaceFee } from '../marketplace-platform-fee.js';+import { resolveListingSplit, describeSplit } from '../splits.js';import { invalidateSkillPriceCache } from '../skill-price-cache.js';import {confirmSkillPurchase,@@ -193,7 +194,16 @@ export class MonetizationService {const isPwyw = price.pricing_type === 'pwyw';- const payoutAddress = await resolvePayoutAddress(agentId, price.chain);+ let payoutAddress = await resolvePayoutAddress(agentId, price.chain);++ // Proceeds split: a multi-collaborator listing shows the buyer where money+ // goes ("proceeds split: 70/30"). For an on-chain (0xSplits, EVM) split the+ // creator's net is routed INTO the split contract, so the recipient the+ // buyer pays becomes the split address — confirm verifies against the same.+ const listingSplit = await resolveListingSplit(this.sql, agentId, skillName).catch(() => null);+ if (listingSplit?.split_mode === 'onchain' && listingSplit.split_address && price.chain !== 'solana') {+ payoutAddress = listingSplit.split_address;+ }if (!payoutAddress) {throw svcError(412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');}@@ -343,6 +353,18 @@ export class MonetizationService {}: {};+ // Buyer-facing split disclosure: who shares the creator's net, and how.+ const splitBlock = listingSplit?.recipients?.length+ ? {+ split: {+ mode: listingSplit.split_mode,+ address: listingSplit.split_address,+ creator_net: creatorAmount,+ ...describeSplit(listingSplit.recipients),+ },+ }+ : {};+return {already_owned: false,reference: row.reference,@@ -358,6 +380,7 @@ export class MonetizationService {label,message,...feeBlock,+ ...splitBlock,...(isGift ? { is_gift: true, gift_recipient_id: recipientUserId } : {}),...(isTimePass ? { duration_hours: effectiveDurationHours } : {}),...(price.time_pass_hours && !isPwywdiff --git a/api/_lib/skill-license-verify.js b/api/_lib/skill-license-verify.jsnew file mode 100644index 000000000..0f9e6120d--- /dev/null+++ b/api/_lib/skill-license-verify.js@@ -0,0 +1,78 @@+// Trustless on-chain license gate for skill execution.+// ---------------------------------------------------------------------------+// The DB grant (skill_access_grants) is the fast entitlement check. This adds+// the TRUSTLESS layer the marketplace promises: when a skill purchase minted an+// on-chain `skill_license` (a 1/1 SPL NFT + PDA), the executor honors the+// on-chain state as authoritative for REVOCATION — a license revoked on chain+// (e.g. on refund) blocks execution even if a stale DB row lingers. Entitlement+// is then enforced by the chain, not just a database row.+//+// Design choices (matching the reliability bar):+// • Fail-OPEN on infrastructure trouble: if the program isn't deployed, the+// agent has no on-chain collection, no license was minted, RPC errors, or+// enforcement is off, we DON'T block a user the DB already cleared. We only+// ever block on an AFFIRMATIVELY READ on-chain revocation. A paid user is+// never locked out by a node hiccup.+// • Opt-in cost: the on-chain read only runs when SKILL_LICENSE_ENFORCE is+// truthy, so the hot pay-per-call path isn't taxed with RPC latency unless+// the operator turns enforcement on.++import { verifyOnchainSkillLicense } from './skill-license-onchain.js';++/** Is on-chain license enforcement turned on for this environment? */+export function licenseEnforcementEnabled() {+ const v = (process.env.SKILL_LICENSE_ENFORCE || '').trim().toLowerCase();+ return v === '1' || v === 'true' || v === 'on' || v === 'yes';+}++/**+ * Decide whether an on-chain license revocation should block execution of a+ * skill the DB already granted. Returns { blocked, reason?, license? }.+ *+ * @param {object} o+ * @param {Function} o.sql+ * @param {string} o.userId - the caller (beneficiary) user id+ * @param {string} o.agentId+ * @param {string} o.skill+ * @returns {Promise<{ blocked: boolean, reason?: string, license?: string, network?: string }>}+ */+export async function enforceOnchainLicense({ sql, userId, agentId, skill }) {+ if (!licenseEnforcementEnabled()) return { blocked: false };++ // Was an on-chain license actually minted for this beneficiary's purchase?+ // Only those are subject to on-chain revocation — a skill that never minted a+ // license (no collection / no wallet) stays purely DB-gated.+ let mint;+ try {+ [mint] = await sql`+ SELECT owner_wallet, agent_mint, network, status+ FROM skill_license_mints+ WHERE user_id = ${userId} AND agent_id = ${agentId} AND skill = ${skill}+ AND status IN ('minted', 'already')+ ORDER BY updated_at DESC+ LIMIT 1+ `;+ } catch {+ return { blocked: false }; // table missing → nothing to enforce+ }+ if (!mint?.owner_wallet || !mint?.agent_mint) return { blocked: false };++ try {+ const network = mint.network === 'devnet' ? 'devnet' : 'mainnet';+ const v = await verifyOnchainSkillLicense({+ ownerWallet: mint.owner_wallet,+ agentMint: mint.agent_mint,+ skill,+ network,+ });+ // Program not deployed in this env, or the PDA can't be read → degrade to+ // the DB grant (fail-open). Only a real, decoded revocation blocks.+ if (!v.deployed || !v.exists) return { blocked: false };+ if (v.revoked) {+ return { blocked: true, reason: 'license_revoked_onchain', license: v.license, network };+ }+ return { blocked: false, license: v.license, network };+ } catch {+ return { blocked: false }; // RPC trouble must never lock out a paid user+ }+}diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].jsindex 3d810d7ba..aea36eed6 100644--- a/api/agents/x402/[action].js+++ b/api/agents/x402/[action].js@@ -11,6 +11,7 @@ import { resolvePayoutAddress } from '../../_lib/payout.js';import { calculateFee } from '../../_lib/fee.js';import { insertNotification } from '../../_lib/notify.js';import { hasSkillAccess, consumeTrialUse, logSkillUsage } from '../../_lib/skill-access.js';+import { enforceOnchainLicense } from '../../_lib/skill-license-verify.js';const HANDLERS = { echo: async (args) => ({ ok: true, echoed: args }) };@@ -119,6 +120,23 @@ async function handleInvoke(req, res) {// pay-per-call x402 path below unchanged.const access = await hasSkillAccess(auth.userId, agent.id, body.skill);if (access.paid && access.owned) {+ // Trustless gate: if this purchase minted an on-chain license that has+ // since been revoked on chain (e.g. a refund), entitlement is gone even+ // though the DB grant lingers — enforce the chain's verdict. Fail-open on+ // any infrastructure trouble so a paid user is never locked out by RPC.+ const lic = await enforceOnchainLicense({+ sql,+ userId: auth.userId,+ agentId: agent.id,+ skill: body.skill,+ });+ if (lic.blocked) {+ return error(res, 403, 'license_revoked', 'this skill license was revoked on-chain', {+ reason: lic.reason,+ license: lic.license ?? null,+ });+ }+const startedAt = Date.now();const result = await executeSkill(agent, body, auth, null);if (access.trial) {diff --git a/api/genome/breed.js b/api/genome/breed.jsnew file mode 100644index 000000000..3dd8370c5--- /dev/null+++ b/api/genome/breed.js@@ -0,0 +1,393 @@+// POST /api/genome/breed — the breeding transaction.+//+// Two agents breed into a genuinely new child agent that provably inherits a+// seed-recorded recombination of both parents (brain, voice, body, skills). The+// child gets a FRESH, distinct Solana + EVM wallet (fork's ownership invariant,+// extended to two parents); NEITHER parent's row or wallet is touched. The child's+// real artifacts are synthesized — a baked GLB body, blended ElevenLabs voice+// settings, a composed in-character brain — and its expressed skill licenses are+// granted on-chain, royalty-provenance recorded. The breeding seed + derived+// genome are persisted so the descent is re-derivable and forgery-detectable.+//+// Idempotent per breeding key: replaying the same (parents, seed) returns the same+// child instead of minting twins.++import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { isUuid } from '../_lib/validate.js';+import { requireCsrf } from '../_lib/csrf.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { withDbRetry } from '../_lib/db-retry.js';+import { provisionAgentWallets } from '../_lib/agent-wallet.js';+import { createAvatar, storageKeyFor } from '../_lib/avatars.js';+import { copyObject, headObject } from '../_lib/r2.js';+import { bakeAndUploadAppearance } from '../_lib/bake.js';+import { dispatchWebhooks } from '../_lib/webhook-dispatch.js';+import { recordEvent } from '../_lib/usage.js';+import { mintSkillLicenseOnchain, minterKeypair } from '../_lib/skill-license-onchain.js';+import {+ deriveGenome,+ makeSeed,+ hashGenome,+ composePersonaPrompt,+ voiceSettings,+ appearanceFromGenome,+ expressedSkills,+ pedigreeScore,+} from '../_lib/genome.js';+import {+ loadBreedingAgent,+ agentGenome,+ eligibilityFor,+ cooldownRemainingMs,+ publicGenome,+} from '../_lib/genome-agent.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req, 'avatars:write');+ if (!auth) return error(res, 401, 'unauthorized', 'avatars:write scope required to breed');+ if (!(await requireCsrf(req, res, auth.userId))) return; // writes the 403 itself++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many breeding attempts — slow down');++ const body = await readJson(req);+ const parentAId = String(body.parent_a || body.parent_a_agent_id || '').trim();+ const parentBId = String(body.parent_b || body.parent_b_agent_id || '').trim();+ if (!isUuid(parentAId) || !isUuid(parentBId)) {+ return error(res, 400, 'validation_error', 'parent_a and parent_b agent ids are required');+ }+ if (parentAId === parentBId) return error(res, 400, 'validation_error', 'an agent cannot breed with itself');++ const seed = typeof body.seed === 'string' && body.seed ? body.seed.slice(0, 64) : makeSeed();+ // Idempotency: a provided key wins; else the canonical (sorted parents + seed)+ // so committing the same preview twice returns the same child, never twins.+ const breedingKey =+ (typeof body.idempotency_key === 'string' && body.idempotency_key.trim()) ||+ `${[parentAId, parentBId].sort().join(':')}:${seed}`;++ // Replay guard — return the existing child idempotently.+ const [existing] = await sql`+ select child_agent_id from genome_breedings where breeding_key = ${breedingKey} limit 1+ `;+ if (existing?.child_agent_id) {+ const child = await loadChildSummary(existing.child_agent_id);+ return json(res, 200, { child, deduped: true });+ }++ const [rowA, rowB] = await Promise.all([loadBreedingAgent(parentAId), loadBreedingAgent(parentBId)]);+ if (!rowA || !rowB) return error(res, 404, 'not_found', 'one or both parents not found');++ // Eligibility + cross-owner stud consent.+ const eligA = eligibilityFor(rowA, auth.userId);+ const eligB = eligibilityFor(rowB, auth.userId);+ if (!eligA.allowed) return error(res, 403, 'parent_ineligible', `parent A: ${eligA.reason}`, { parent: 'a', reason: eligA.reason });+ if (!eligB.allowed) return error(res, 403, 'parent_ineligible', `parent B: ${eligB.reason}`, { parent: 'b', reason: eligB.reason });++ const feeThree = (eligA.fee_three || 0) + (eligB.fee_three || 0);+ const consentOwner = eligA.cross_owner ? eligA.owner_id : eligB.cross_owner ? eligB.owner_id : null;+ // A cross-owner stud with a fee must be paid in $THREE: the caller supplies a+ // real settlement signature, or we 402 with the exact terms (no breed on credit).+ if (feeThree > 0 && !body.stud_fee_signature) {+ return error(res, 402, 'stud_fee_required', `breeding with this stud costs ${feeThree} $THREE — settle and include stud_fee_signature`, {+ stud_fee_three: feeThree,+ coin: '$THREE',+ });+ }++ // Cooldown — both parents must be off cooldown. Keeps deep pedigrees scarce.+ const now = Date.now();+ const [coolA, coolB] = await Promise.all([cooldownRemainingMs(parentAId, now), cooldownRemainingMs(parentBId, now)]);+ const cool = Math.max(coolA, coolB);+ if (cool > 0) {+ return error(res, 409, 'breeding_cooldown', 'a parent is still on breeding cooldown', {+ cooldown_remaining_ms: cool,+ cooldown_remaining_min: Math.ceil(cool / 60000),+ });+ }++ // Derive the child genome — deterministic, re-derivable from (parents, seed).+ const genomeA = agentGenome(rowA);+ const genomeB = agentGenome(rowB);+ const childGenome = deriveGenome({ parentA: genomeA, parentB: genomeB, seed });+ const childName = (typeof body.name === 'string' && body.name.trim().slice(0, 80)) || `${rowA.name} × ${rowB.name}`.slice(0, 80);+ const pedigree = pedigreeScore(childGenome);++ // ── Synthesize the child's real body (baked GLB) ────────────────────────────+ const baseAvatarId = childGenome.body.base_avatar_id || rowA.avatar_id || rowB.avatar_id || null;+ const childAvatar = await provisionChildAvatar({+ userId: auth.userId,+ baseAvatarId,+ fallbackStorageKey: rowA.avatar_storage_key || rowB.avatar_storage_key || null,+ appearance: appearanceFromGenome(childGenome),+ name: childName,+ });++ // ── Compose the child's real brain + voice ──────────────────────────────────+ const personaPrompt = composePersonaPrompt(childGenome, childName);+ const vSettings = voiceSettings(childGenome);+ const inheritedSkills = expressedSkills(childGenome);++ // Snapshot the EXACT parent genomes used. Verification re-derives from these+ // recorded inputs + seed, so a later edit to a parent's traits can never make a+ // genuine child fail to verify — the breed is provable from what it consumed.+ const bredFrom = {+ breeding_key: breedingKey,+ seed,+ parent_a: { agent_id: rowA.id, name: rowA.name, owner_id: rowA.user_id, genome: genomeA },+ parent_b: { agent_id: rowB.id, name: rowB.name, owner_id: rowB.user_id, genome: genomeB },+ generation: childGenome.generation,+ };+ const childMeta = {+ genome: childGenome,+ bred_from: bredFrom,+ genome_breeding: { breedable: true, stud: false, stud_fee_three: 0 },+ };++ // Insert the child agent. Its wallets are provisioned next — distinct keys,+ // no parent secret copied (provisionAgentWallets generates fresh material).+ let child;+ try {+ child = await withDbRetry(async () => {+ const [r] = await sql`+ insert into agent_identities (+ user_id, name, avatar_id, is_public,+ persona_prompt, persona_tone_tags,+ voice_provider, voice_id, voice_model, voice_settings,+ skills, meta, created_at, updated_at+ ) values (+ ${auth.userId}, ${childName}, ${childAvatar?.id || null}, false,+ ${personaPrompt}, ${JSON.stringify(childGenome.brain.tone_tags)}::jsonb,+ ${childGenome.voice.provider || 'browser'}, ${childGenome.voice.voice_id || null},+ ${childGenome.voice.model || null}, ${JSON.stringify(vSettings)}::jsonb,+ ${inheritedSkills}, ${JSON.stringify(childMeta)}::jsonb, now(), now()+ ) returning id+ `;+ return r;+ });+ } catch (e) {+ return error(res, 500, 'breed_failed', 'failed to create child agent');+ }++ const wallets = await provisionAgentWallets(child.id);+ // OWNERSHIP INVARIANT (proved live): the child's fresh wallets must differ from+ // both parents'. provisionAgentWallets generates new random keys, but assert it+ // rather than trust it — a collision here would be a critical breach.+ const parentSolanas = [rowA.meta?.solana_address, rowB.meta?.solana_address].filter(Boolean);+ const parentEvms = [rowA.meta?.wallet_address || rowA.wallet_address, rowB.meta?.wallet_address].filter(Boolean);+ if (parentSolanas.includes(wallets.solana) || parentEvms.includes(wallets.evm)) {+ return error(res, 500, 'ownership_invariant_violation', 'child wallet collided with a parent — breeding aborted');+ }++ // ── Grant inherited skill licenses on-chain (royalty-provenance recorded) ───+ const skillGrants = await grantInheritedSkills({+ skills: inheritedSkills,+ childGenome,+ childWallet: wallets.solana,+ parentA: { id: rowA.id, genome: genomeA },+ parentB: { id: rowB.id, genome: genomeB },+ network: body.network === 'devnet' ? 'devnet' : 'mainnet',+ });+ if (skillGrants.length) {+ await sql`+ update agent_identities+ set meta = jsonb_set(meta, '{skill_grants}', ${JSON.stringify(skillGrants)}::jsonb, true)+ where id = ${child.id}+ `.catch(() => {});+ }++ // ── Persist the breeding event (the verifiable lineage record) ──────────────+ const genomeHash = childGenome.genome_hash || hashGenome(childGenome);+ try {+ await sql`+ insert into genome_breedings (+ breeding_key, parent_a_agent_id, parent_b_agent_id, child_agent_id,+ seed, genome, genome_hash, generation, pedigree_tier, bred_by,+ stud_fee_lamports, stud_fee_signature, consent_owner, status+ ) values (+ ${breedingKey}, ${rowA.id}, ${rowB.id}, ${child.id},+ ${seed}, ${JSON.stringify(childGenome)}::jsonb, ${genomeHash},+ ${childGenome.generation}, ${pedigree.tier}, ${auth.userId},+ ${0}, ${body.stud_fee_signature || null}, ${consentOwner}, 'born'+ )+ on conflict (breeding_key) do nothing+ `;+ } catch (e) {+ console.error('[breed] lineage record failed', { child: child.id, error: e?.message });+ }++ dispatchWebhooks({+ userId: auth.userId,+ eventType: 'agent.bred',+ data: {+ child_agent_id: child.id,+ name: childName,+ generation: childGenome.generation,+ pedigree_tier: pedigree.tier,+ parents: [rowA.id, rowB.id],+ },+ }).catch(() => {});++ recordEvent({+ userId: auth.userId,+ apiKeyId: auth.apiKeyId,+ clientId: auth.clientId,+ avatarId: childAvatar?.id || null,+ kind: 'breed',+ meta: { parent_a: rowA.id, parent_b: rowB.id, generation: childGenome.generation, pedigree: pedigree.tier },+ });++ return json(res, 201, {+ child: {+ id: child.id,+ name: childName,+ wallet_address: wallets.evm,+ solana_address: wallets.solana,+ avatar_id: childAvatar?.id || null,+ generation: childGenome.generation,+ pedigree,+ },+ genome: publicGenome(childGenome, childName),+ genome_hash: genomeHash,+ seed,+ breeding_key: breedingKey,+ skill_grants: skillGrants,+ parents: { a: { id: rowA.id, name: rowA.name }, b: { id: rowB.id, name: rowB.name } },+ });+});++// Copy the dominant parent's GLB into the child's namespace, register a fresh+// avatar row (source='genome', parent_avatar_id=base), then bake the inherited+// appearance into a real composite child GLB. Degrades gracefully — a copy/bake+// hiccup never blocks the birth, but the child still references a real model.+async function provisionChildAvatar({ userId, baseAvatarId, fallbackStorageKey, appearance, name }) {+ try {+ let base = null;+ if (baseAvatarId) {+ [base] = await sql`+ select id, name, storage_key, content_type, size_bytes+ from avatars where id = ${baseAvatarId} and deleted_at is null limit 1+ `;+ }+ const baseStorageKey = base?.storage_key || fallbackStorageKey;+ if (!baseStorageKey) return null;++ const slugBase =+ (name || 'offspring').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'offspring';+ let newStorageKey = storageKeyFor({ userId, slug: slugBase });+ const copied = await copyObject({ fromKey: baseStorageKey, toKey: newStorageKey });+ if (!copied) newStorageKey = baseStorageKey; // hosted URL — reference through+ if (copied) {+ const head = await headObject(newStorageKey);+ if (!head) newStorageKey = baseStorageKey;+ }++ const avatar = await createAvatar({+ userId,+ input: {+ name,+ description: 'Bred via Agent Genome — a recombination of two parent agents.',+ size_bytes: Number(base?.size_bytes || 0),+ content_type: base?.content_type || 'model/gltf-binary',+ source: 'genome',+ source_meta: { bred: true, base_avatar_id: baseAvatarId || null },+ visibility: 'unlisted',+ tags: ['bred'],+ checksum_sha256: null,+ parent_avatar_id: baseAvatarId || null,+ appearance,+ },+ storageKey: newStorageKey,+ });++ // Bake the inherited morphs/colors/accessories into a real composite GLB.+ try {+ const baked = await bakeAndUploadAppearance({ baseStorageKey: newStorageKey, appearance });+ if (baked?.baked_storage_key) {+ await sql`+ update avatars set baked_storage_key = ${baked.baked_storage_key},+ appearance_hash = ${baked.appearance_hash}, baked_at = now(), updated_at = now()+ where id = ${avatar.id}+ `.catch(() => {});+ }+ } catch (e) {+ console.warn('[breed] bake failed, child uses copied base GLB', e?.message);+ }+ return avatar;+ } catch (e) {+ console.error('[breed] child avatar provision failed', e?.message);+ return null;+ }+}++// Grant each expressed inherited skill to the child on-chain. Provenance (which+// parent the allele came from, or emergent fusion) is recorded so skill royalties+// owed upstream still resolve. Degrades to a recorded-intent grant if the on-chain+// minter isn't configured for this environment — never fabricates a signature.+async function grantInheritedSkills({ skills, childGenome, childWallet, parentA, parentB, network }) {+ if (!skills.length) return [];+ const minterReady = !!minterKeypair() && !!childWallet;+ const expA = new Set(expressedSkills(parentA.genome));+ const expB = new Set(expressedSkills(parentB.genome));+ const alleleBySkill = new Map(childGenome.skills.map((s) => [s.skill, s]));++ const grants = [];+ for (const skill of skills) {+ const allele = alleleBySkill.get(skill);+ const inheritedFrom = [];+ if (expA.has(skill)) inheritedFrom.push(parentA.id);+ if (expB.has(skill)) inheritedFrom.push(parentB.id);+ const grant = {+ skill,+ inherited_from: inheritedFrom,+ emergent: allele?.source === 'emergent' ? allele.emergent_from || true : false,+ network,+ status: 'pending',+ signature: null,+ };+ if (minterReady) {+ try {+ const r = await mintSkillLicenseOnchain({ ownerWallet: childWallet, agentMint: childWallet, skill, network });+ grant.status = r.alreadyMinted ? 'already_minted' : 'minted';+ grant.signature = r.signature || null;+ grant.license = r.skillLicense || null;+ } catch (e) {+ grant.status = 'grant_deferred';+ grant.reason = e?.code || 'mint_failed';+ }+ } else {+ grant.status = 'grant_deferred';+ grant.reason = 'minter_unconfigured';+ }+ grants.push(grant);+ }+ return grants;+}++async function loadChildSummary(childAgentId) {+ const [r] = await sql`+ select id, name, avatar_id, meta from agent_identities where id = ${childAgentId} limit 1+ `;+ if (!r) return { id: childAgentId };+ return {+ id: r.id,+ name: r.name,+ avatar_id: r.avatar_id,+ solana_address: r.meta?.solana_address || null,+ wallet_address: r.meta?.wallet_address || null,+ generation: r.meta?.genome?.generation ?? null,+ };+}++async function resolveAuth(req, requiredScope) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, source: 'session' };+ const bearer = await authenticateBearer(extractBearer(req));+ if (!bearer) return null;+ if (!hasScope(bearer.scope, requiredScope)) return null;+ return bearer;+}diff --git a/api/genome/lineage.js b/api/genome/lineage.jsnew file mode 100644index 000000000..0d67d2fc5--- /dev/null+++ b/api/genome/lineage.js@@ -0,0 +1,166 @@+// GET /api/genome/lineage?agentId=<id> — the verifiable family tree.+// GET /api/genome/lineage?agentId=<id>&verify=1 — re-derive + confirm the genome.+//+// Lineage shows on all three nodes of a breed (both parents + child), mirroring+// fork. The verify path re-derives the child genome from the recorded seed + the+// parent-genome snapshots captured at breed time and confirms it matches the stored+// hash — so a forged "child" (one whose genome wasn't actually derived from its+// claimed parents) is detectable by anyone. Public-safe: no secret is exposed.++import { cors, json, method, wrap, error } from '../_lib/http.js';+import { isUuid } from '../_lib/validate.js';+import { sql } from '../_lib/db.js';+import { verifyGenome, pedigreeScore, normalizeGenome } from '../_lib/genome.js';+import { publicGenome } from '../_lib/genome-agent.js';++const MAX_ANCESTOR_DEPTH = 8;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://x');+ const agentId = String(url.searchParams.get('agentId') || '').trim();+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId is required');++ const node = await loadNode(agentId);+ if (!node) return error(res, 404, 'not_found', 'agent not found');++ if (url.searchParams.get('verify')) {+ return json(res, 200, await verifyNode(agentId), { 'cache-control': 'public, s-maxage=30' });+ }++ // Parents (if this agent was bred).+ const [birth] = await sql`+ select b.parent_a_agent_id, b.parent_b_agent_id, b.seed, b.genome_hash, b.generation,+ b.pedigree_tier, b.created_at+ from genome_breedings b+ where b.child_agent_id = ${agentId} and b.status = 'born'+ order by b.created_at asc limit 1+ `;+ const parents = birth+ ? await Promise.all([loadNode(birth.parent_a_agent_id), loadNode(birth.parent_b_agent_id)])+ : [];++ // Children (every breed this agent was a parent of).+ const childRows = await sql`+ select b.child_agent_id, b.generation, b.pedigree_tier, b.created_at,+ case when b.parent_a_agent_id = ${agentId} then b.parent_b_agent_id else b.parent_a_agent_id end as co_parent+ from genome_breedings b+ where (b.parent_a_agent_id = ${agentId} or b.parent_b_agent_id = ${agentId})+ and b.status = 'born' and b.child_agent_id is not null+ order by b.created_at desc limit 100+ `;+ const children = await Promise.all(+ childRows.map(async (r) => ({+ ...(await loadNode(r.child_agent_id)),+ co_parent: await loadNode(r.co_parent),+ bred_at: r.created_at,+ })),+ );++ // Ancestors — walk up the pedigree (bounded), so a profile can render depth.+ const ancestors = await walkAncestors(agentId);++ return json(+ res,+ 200,+ {+ agent: node,+ generation: node.generation,+ pedigree: node.pedigree,+ parents: parents.filter(Boolean),+ children: children.filter((c) => c && c.id),+ ancestors,+ bred: !!birth,+ seed: birth?.seed || null,+ genome_hash: birth?.genome_hash || null,+ },+ { 'cache-control': 'public, s-maxage=30' },+ );+});++// Re-derive the child genome from recorded inputs and confirm it matches.+async function verifyNode(agentId) {+ const [row] = await sql`+ select i.id, i.name, i.meta, b.seed, b.genome_hash+ from agent_identities i+ left join genome_breedings b on b.child_agent_id = i.id and b.status = 'born'+ where i.id = ${agentId} and i.deleted_at is null+ limit 1+ `;+ if (!row) return { verifiable: false, reason: 'not_found' };+ const bred = row.meta?.bred_from;+ const childGenome = row.meta?.genome;+ if (!bred || !childGenome) return { verifiable: false, reason: 'not_a_bred_agent' };++ const parentA = bred.parent_a?.genome;+ const parentB = bred.parent_b?.genome;+ const seed = bred.seed || row.seed;+ if (!parentA || !parentB || !seed) return { verifiable: false, reason: 'missing_recorded_inputs' };++ const result = verifyGenome(normalizeGenome(childGenome), { parentA, parentB, seed });+ return {+ verifiable: true,+ valid: result.valid,+ reason: result.reason || null,+ genome_hash: result.hash || childGenome.genome_hash || null,+ recorded_hash: row.genome_hash || childGenome.genome_hash || null,+ parents: [+ { id: bred.parent_a?.agent_id, name: bred.parent_a?.name },+ { id: bred.parent_b?.agent_id, name: bred.parent_b?.name },+ ],+ seed,+ };+}++async function walkAncestors(agentId) {+ const out = [];+ const seen = new Set([agentId]);+ let frontier = [agentId];+ for (let depth = 1; depth <= MAX_ANCESTOR_DEPTH && frontier.length; depth++) {+ const rows = await sql`+ select child_agent_id, parent_a_agent_id, parent_b_agent_id+ from genome_breedings+ where child_agent_id = any(${frontier}) and status = 'born'+ `;+ const next = [];+ for (const r of rows) {+ for (const pid of [r.parent_a_agent_id, r.parent_b_agent_id]) {+ if (pid && !seen.has(pid)) {+ seen.add(pid);+ next.push(pid);+ const n = await loadNode(pid);+ if (n) out.push({ ...n, depth, of: r.child_agent_id });+ }+ }+ }+ frontier = next;+ }+ return out;+}++// One node of the tree — public-safe. Private agents reveal only that they exist.+async function loadNode(agentId) {+ if (!agentId) return null;+ const [r] = await sql`+ select i.id, i.name, i.is_public, i.user_id, i.avatar_id, i.meta,+ a.thumbnail_key as avatar_thumbnail_key+ from agent_identities i+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null+ where i.id = ${agentId} and i.deleted_at is null+ limit 1+ `;+ if (!r) return null;+ const genome = r.meta?.genome ? normalizeGenome(r.meta.genome) : null;+ const pedigree = genome ? pedigreeScore(genome) : { tier: 'common', generation: 0, score: 0 };+ return {+ id: r.id,+ name: r.is_public ? r.name : 'Private agent',+ is_public: !!r.is_public,+ avatar_id: r.avatar_id,+ generation: genome?.generation ?? 0,+ pedigree,+ bred: !!r.meta?.bred_from,+ };+}diff --git a/api/genome/stud.js b/api/genome/stud.jsnew file mode 100644index 000000000..c95cd7d37--- /dev/null+++ b/api/genome/stud.js@@ -0,0 +1,85 @@+// GET /api/genome/stud — the genetic marketplace: agents listed as+// breedable studs, rarest pedigrees first.+// POST /api/genome/stud — list/unlist one of YOUR agents as a stud+// and set its $THREE stud fee. (owner-only)+//+// Stud service is what makes a deep pedigree valuable: an owner can let others+// breed with a rare agent for a $THREE fee, and rare-trait carriers command more.++import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { isUuid } from '../_lib/validate.js';+import { sql } from '../_lib/db.js';+import { pedigreeScore, normalizeGenome, genomeFromAgent } from '../_lib/genome.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ if (req.method === 'GET') return listStuds(req, res);++ // POST — owner toggles stud listing.+ const auth = await resolveAuth(req, 'avatars:write');+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to manage stud listings');+ if (!(await requireCsrf(req, res, auth.userId))) return;++ const body = await readJson(req);+ const agentId = String(body.agent_id || body.agentId || '').trim();+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id is required');++ const [row] = await sql`+ select id, user_id, meta from agent_identities where id = ${agentId} and deleted_at is null limit 1+ `;+ if (!row) return error(res, 404, 'not_found', 'agent not found');+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'you do not own this agent');++ const stud = body.stud === true;+ const fee = Math.max(0, Math.min(1_000_000, Number(body.stud_fee_three) || 0));+ const breedable = body.breedable !== false;+ const meta = { ...(row.meta || {}) };+ meta.genome_breeding = { ...(meta.genome_breeding || {}), breedable, stud, stud_fee_three: fee };++ await sql`update agent_identities set meta = ${JSON.stringify(meta)}::jsonb, updated_at = now() where id = ${agentId}`;+ return json(res, 200, { agent_id: agentId, genome_breeding: meta.genome_breeding });+});++async function listStuds(req, res) {+ const url = new URL(req.url, 'http://x');+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 24, 1), 60);+ const rows = await sql`+ select i.id, i.name, i.avatar_id, i.meta, i.skills,+ a.thumbnail_key as avatar_thumbnail_key+ from agent_identities i+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null+ where i.deleted_at is null and i.is_public = true+ and (i.meta -> 'genome_breeding' ->> 'stud') = 'true'+ order by i.updated_at desc nulls last+ limit ${limit}+ `;+ const studs = rows.map((r) => {+ const genome = r.meta?.genome ? normalizeGenome(r.meta.genome) : genomeFromAgent({ id: r.id, meta: r.meta, skills: r.skills });+ const pedigree = pedigreeScore(genome);+ return {+ id: r.id,+ name: r.name,+ avatar_id: r.avatar_id,+ generation: genome.generation,+ pedigree,+ stud_fee_three: Math.max(0, Number(r.meta?.genome_breeding?.stud_fee_three) || 0),+ expressed_skills: genome.skills.filter((s) => s.expressed).map((s) => s.skill),+ };+ });+ // Rarest first — depth + emergent talent is what a breeder pays for.+ studs.sort((a, b) => b.pedigree.score - a.pedigree.score);+ return json(res, 200, { studs }, { 'cache-control': 'public, s-maxage=20' });+}++async function resolveAuth(req, requiredScope) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, source: 'session' };+ const bearer = await authenticateBearer(extractBearer(req));+ if (!bearer) return null;+ if (!hasScope(bearer.scope, requiredScope)) return null;+ return bearer;+}diff --git a/api/labor/agent.js b/api/labor/agent.jsnew file mode 100644index 000000000..addc68ded--- /dev/null+++ b/api/labor/agent.js@@ -0,0 +1,44 @@+// GET /api/labor/agent?agentId=… — one agent's labor-market record for the+// profile "Work" tab: bounties it posted, jobs it did, total $THREE earned and+// spent, reputation, and its autonomy policy. Public read (real aggregates only).++import { cors, error, json, method, wrap } from '../_lib/http.js';+import { agentLaborStats, listBountiesForAgent, getLaborPolicy } from '../_lib/agent-labor.js';+import { sql } from '../_lib/db.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://localhost');+ const agentId = url.searchParams.get('agentId');+ if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');++ const [stats, posted, policy, jobs] = await Promise.all([+ agentLaborStats(agentId),+ listBountiesForAgent(agentId, { limit: 20 }),+ getLaborPolicy(agentId),+ sql`+ SELECT j.id, j.bounty_id, j.status, j.required_skill, j.worker_payout_atomics,+ j.settlement_sig, j.settled_at, b.title+ FROM agent_jobs j JOIN agent_bounties b ON b.id = j.bounty_id+ WHERE j.worker_agent_id = ${agentId}+ ORDER BY j.created_at DESC LIMIT 20`,+ ]);++ json(res, 200, {+ data: {+ stats,+ policy: policy || { worker_enabled: false, poster_enabled: false, skills: [] },+ posted,+ jobs: jobs.map((j) => ({+ id: j.id, bounty_id: j.bounty_id, title: j.title, status: j.status,+ required_skill: j.required_skill || null,+ worker_payout_atomics: j.worker_payout_atomics != null ? String(j.worker_payout_atomics).split('.')[0] : null,+ settlement_sig: j.settlement_sig || null,+ settlement_explorer: j.settlement_sig ? `https://solscan.io/tx/${j.settlement_sig}` : null,+ settled_at: j.settled_at || null,+ })),+ },+ });+});diff --git a/api/labor/policy.js b/api/labor/policy.jsnew file mode 100644index 000000000..d03007cc7--- /dev/null+++ b/api/labor/policy.js@@ -0,0 +1,48 @@+// /api/labor/policy — read or set an agent's labor-market autonomy policy.+// GET ?agentId=… → the agent's policy (public; powers the "for hire" badge).+// PUT { agentId, … } → owner-gated upsert of the worker/poster autonomy config.++import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { authWrite, loadOwnedAgent } from '../_lib/labor-auth.js';+import { getLaborPolicy, upsertLaborPolicy, threeToAtomics } from '../_lib/agent-labor.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;++ if (req.method === 'GET') {+ const url = new URL(req.url, 'http://localhost');+ const agentId = url.searchParams.get('agentId');+ if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');+ const policy = await getLaborPolicy(agentId);+ return json(res, 200, { data: policy || { agent_id: agentId, worker_enabled: false, poster_enabled: false, skills: [] } });+ }++ if (!method(req, res, ['GET', 'PUT'])) return;++ const auth = await authWrite(req, res);+ if (!auth) return;+ const { userId } = auth;++ const body = (await readJson(req)) || {};+ const { agentId } = body;+ if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');++ try {+ await loadOwnedAgent(agentId, userId);+ } catch (e) {+ return error(res, e.status || 400, e.code || 'bad_request', e.message);+ }++ const policy = await upsertLaborPolicy(agentId, userId, {+ workerEnabled: !!body.workerEnabled,+ posterEnabled: !!body.posterEnabled,+ autoAward: !!body.autoAward,+ skills: Array.isArray(body.skills) ? body.skills : [],+ minBids: body.minBids,+ maxBidAtomics: body.maxBidThree != null ? threeToAtomics(body.maxBidThree) : body.maxBidAtomics ?? null,+ minRewardAtomics: body.minRewardThree != null ? threeToAtomics(body.minRewardThree) : body.minRewardAtomics ?? null,+ meta: body.meta || {},+ });++ return json(res, 200, { ok: true, data: policy });+});diff --git a/api/labor/settle.js b/api/labor/settle.jsnew file mode 100644index 000000000..6367b37dc--- /dev/null+++ b/api/labor/settle.js@@ -0,0 +1,46 @@+// POST /api/labor/settle — verify a delivered job and release escrow on-chain.+// Idempotent (job settle_key): a retry never double-pays. Callable by either+// participant (poster or worker owner) so a stuck-but-delivered job can always be+// resolved; the neutral verifier — not the caller — decides whether funds release.++import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { authWrite } from '../_lib/labor-auth.js';+import { getJob, getJobByBounty, getBounty } from '../_lib/agent-labor.js';+import { runSettlement } from '../_lib/labor-settle.js';++async function ownsEither(userId, posterAgentId, workerAgentId) {+ const rows = await sql`+ SELECT id FROM agent_identities+ WHERE id IN (${posterAgentId}, ${workerAgentId}) AND user_id = ${userId} AND deleted_at IS NULL`;+ return rows.length > 0;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await authWrite(req, res);+ if (!auth) return;+ const { userId } = auth;++ const body = (await readJson(req)) || {};+ const { jobId, bountyId } = body;+ const job = jobId ? await getJob(jobId) : bountyId ? await getJobByBounty(bountyId) : null;+ if (!job) return error(res, 404, 'not_found', 'job not found');++ if (!(await ownsEither(userId, job.poster_agent_id, job.worker_agent_id))) {+ return error(res, 403, 'forbidden', 'only the poster or worker owner can settle this job');+ }++ if (!['delivered', 'verifying'].includes(job.status)) {+ if (job.status === 'settled' || job.status === 'failed' || job.status === 'refunded') {+ return json(res, 200, { ok: true, idempotent: true, status: job.status, job_id: job.id });+ }+ return error(res, 409, 'not_deliverable', `job is ${job.status}; nothing to settle until it is delivered`);+ }++ const bounty = await getBounty(job.bounty_id);+ const result = await runSettlement({ job, bounty });+ return json(res, 200, { ok: true, job_id: job.id, settlement: result });+});diff --git a/api/labor/tick.js b/api/labor/tick.jsnew file mode 100644index 000000000..9e2730301--- /dev/null+++ b/api/labor/tick.js@@ -0,0 +1,76 @@+// POST /api/labor/tick — cron driver for the Agent Labor Market.+// Advances autonomous bounties that haven't reached a terminal state inline:+// • open bounties (collect auto-bids, auto-award if the poster opted in)+// • working jobs with an autonomous worker (perform → verify → settle)+// • delivered/verifying jobs (settle now)+// Authenticated with the Vercel cron Bearer secret. No-op (503) if unset.++import { error, json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';+import { ensureLaborTables, getBounty, getJob } from '../_lib/agent-labor.js';+import { runAutopilot, runSettlement } from '../_lib/labor-settle.js';++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ error(res, 503, 'not_configured', 'CRON_SECRET unset');+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['POST', 'GET'])) return;+ if (!requireCron(req, res)) return;++ await ensureLaborTables();++ // Resumable work: open bounties with at least one bid + auto-award posters, and+ // any job stuck mid-pipeline. Cap the batch so a tick stays well within budget.+ const openBounties = await sql`+ SELECT b.id FROM agent_bounties b+ JOIN agent_labor_policies p ON p.agent_id = b.poster_agent_id AND p.poster_enabled AND p.auto_award+ WHERE b.status = 'open'+ AND EXISTS (SELECT 1 FROM agent_bids bd WHERE bd.bounty_id = b.id AND bd.status = 'pending')+ ORDER BY b.created_at ASC LIMIT 10`;++ const stuckJobs = await sql`+ SELECT j.id, j.bounty_id, j.status FROM agent_jobs j+ WHERE j.status IN ('working','delivered','verifying')+ AND j.created_at < now() - interval '15 seconds'+ ORDER BY j.created_at ASC LIMIT 10`;++ const results = { awarded: 0, settled: 0, scanned: openBounties.length + stuckJobs.length };++ for (const b of openBounties) {+ const r = await runAutopilot(b.id).catch(() => null);+ if (r?.awarded) results.awarded++;+ if (r?.settled === 'settled') results.settled++;+ }++ for (const j of stuckJobs) {+ const bounty = await getBounty(j.bounty_id);+ if (!bounty) continue;+ if (j.status === 'working') {+ // Only autonomous workers are driven to perform; runAutopilot enforces that.+ const r = await runAutopilot(j.bounty_id).catch(() => null);+ if (r?.settled === 'settled') results.settled++;+ } else {+ // Delivered/verifying: settle now from the full job row.+ const full = await getJob(j.id);+ if (!full) continue;+ const r = await runSettlement({ job: full, bounty }).catch(() => null);+ if (r?.status === 'settled') results.settled++;+ }+ }++ json(res, 200, { ok: true, ...results });+});diff --git a/data/changelog.json b/data/changelog.jsonindex a4a592aa4..171d4b562 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws — 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-23",+ "title": "A real pricing page, metered usage, and a downloadable invoice you can reconcile",+ "summary": "Billing on three.ws is now a closed loop you can read end to end. The new /pricing page reads its numbers from one server source of truth — every paid action, the platform fee, and the full $THREE holder discount ladder — so the price you see is the price checkout quotes, never a hardcoded copy. Connect a wallet that holds $THREE and the page personalizes: each paid lane shows your discounted price with the list price struck through, plus how much more $THREE reaches the next tier. Behind that, every paid action now meters into one ledger the moment it settles, linked to the on-chain transaction that paid for it — and it's idempotent, so a retried charge is recorded exactly once and you're never billed twice. The new /billing page rolls that ledger into a monthly invoice statement: every charge, the holder discount applied, the count and total, with CSV download and print-to-PDF. Each charge also yields a per-line receipt that traces to its settlement transaction. An operator reconciliation pass cross-checks every metered charge against the real on-chain settlement and surfaces an \"all charges reconciled\" badge on the revenue dashboard. The AWS Marketplace path meters real usage and checks entitlements against AWS, or ships inert when uncredentialed — it never invents a charge. $THREE is the only coin on three.ws.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/pricing"+ },{"date": "2026-06-23","title": "One $THREE tier page, and every locked perk now routes to it",diff --git a/pages/agent-detail.html b/pages/agent-detail.htmlindex f2e7cbb09..8ddd35a2f 100644--- a/pages/agent-detail.html+++ b/pages/agent-detail.html@@ -723,6 +723,27 @@</div></section>+ <section class="ad-card" id="ad-ledger-card" style="display: none">+ <div class="ad-card-head">+ <span class="ad-bullet ad-bullet-cyan"></span>+ <h2>REASONING LEDGER</h2>+ <span class="ad-pill ad-pill-muted" id="ad-ledger-verify">verifying…</span>+ </div>+ <div class="ad-row ad-row-split">+ <span class="ad-muted">Track-record score</span>+ <span><b id="ad-ledger-score">—</b> / 100</span>+ </div>+ <div class="ad-row ad-row-split">+ <span class="ad-muted">Hit rate</span>+ <span id="ad-ledger-hitrate">—</span>+ </div>+ <div class="ad-row ad-row-split">+ <span class="ad-muted">Reconciled calls</span>+ <span id="ad-ledger-sample">0</span>+ </div>+ <a class="ad-cta-row" id="ad-ledger-link" href="#" style="display:inline-flex;margin-top:10px;">Open the Reasoning Ledger →</a>+ </section>+<section class="ad-card" id="ad-actions-card" style="display: none"><div class="ad-card-head"><span class="ad-bullet ad-bullet-green"></span>diff --git a/public/admin/index.html b/public/admin/index.htmlindex 9e57d83c8..a6887c6d3 100644--- a/public/admin/index.html+++ b/public/admin/index.html@@ -116,6 +116,7 @@<a class="nav-item" data-tab="revenue" onclick="switchTab('revenue')">Revenue</a><a class="nav-item" data-tab="llm" onclick="switchTab('llm')">LLM Spend</a><a class="nav-item" data-tab="usage" onclick="switchTab('usage')">Usage</a>+ <a class="nav-item" data-tab="growth" onclick="switchTab('growth')">Growth</a><a class="nav-item" href="/admin/news">News</a><a class="nav-item" href="/admin/sdp">Solana Platform</a><a class="nav-item" href="/dashboard/">Dashboard</a>@@ -130,6 +131,7 @@<div id="tab-revenue" style="display:none"></div><div id="tab-llm" style="display:none"></div><div id="tab-usage" style="display:none"></div>+ <div id="tab-growth" style="display:none"></div></main></div>diff --git a/public/nav.css b/public/nav.cssindex 19f5485fc..c26e9c5d9 100644--- a/public/nav.css+++ b/public/nav.css@@ -285,6 +285,34 @@.notif-signin-btn:hover { background: rgba(255,255,255,0.15); border-color: rgba(255,255,255,0.28); }.notif-signin-btn:focus-visible { outline: 2px solid rgba(255,255,255,0.4); outline-offset: 2px; }+/* Value-moment push prompt — shown inside the inbox panel, never on load. */+.notif-push-banner {+ display: flex; flex-direction: column; gap: 10px;+ margin: 8px; padding: 12px 14px; border-radius: 12px;+ background: linear-gradient(135deg, rgba(106,92,255,0.16), rgba(255,92,168,0.12));+ border: 1px solid rgba(106,92,255,0.32);+}+.notif-push-copy { display: flex; align-items: flex-start; gap: 8px; font-size: var(--text-sm); color: rgba(255,255,255,0.86); line-height: 1.45; }+.notif-push-icon { flex: none; }+.notif-push-actions { display: flex; gap: 8px; }+.notif-push-enable {+ flex: 1; padding: 7px 12px; border-radius: 8px; cursor: pointer;+ font-size: var(--text-sm); font-weight: 600; color: #fff;+ background: linear-gradient(135deg, #6a5cff, #ff5ca8); border: none;+ transition: filter 0.12s, transform 0.06s;+}+.notif-push-enable:hover:not(:disabled) { filter: brightness(1.08); }+.notif-push-enable:active:not(:disabled) { transform: translateY(1px); }+.notif-push-enable:disabled { opacity: 0.65; cursor: default; }+.notif-push-dismiss {+ padding: 7px 12px; border-radius: 8px; cursor: pointer;+ font-size: var(--text-sm); color: rgba(255,255,255,0.6);+ background: transparent; border: 1px solid rgba(255,255,255,0.16);+ transition: color 0.12s, border-color 0.12s;+}+.notif-push-dismiss:hover { color: rgba(255,255,255,0.85); border-color: rgba(255,255,255,0.3); }+.notif-push-enable:focus-visible, .notif-push-dismiss:focus-visible { outline: 2px solid rgba(255,255,255,0.5); outline-offset: 2px; }+@media (max-width: 480px) {.notif-panel { width: calc(100vw - 16px); }}diff --git a/scripts/verify-x402-discovery.mjs b/scripts/verify-x402-discovery.mjsindex 897b64f8b..e2fcdcf95 100644--- a/scripts/verify-x402-discovery.mjs+++ b/scripts/verify-x402-discovery.mjs@@ -28,6 +28,10 @@ import addFormats from 'ajv-formats';const args = process.argv.slice(2);const base = (args.find((a) => a.startsWith('--base='))?.slice('--base='.length) || 'https://three.ws').replace(/\/$/, '');+// --file=<path> validates a locally-built catalog JSON instead of fetching a+// live URL, so CI can gate a catalog change BEFORE it deploys (the build:pages /+// pre-push guard) rather than discovering a regression only after we're delisted.+const filePath = args.find((a) => a.startsWith('--file='))?.slice('--file='.length) || null;const asJson = args.includes('--json');const NETWORK_BASE = 'eip155:8453';@@ -118,14 +122,27 @@ function checkResource(r) {return { label: label(r), url: r.url, errors, warnings };}-async function main() {+async function loadCatalog() {+ if (filePath) {+ const { readFile } = await import('node:fs/promises');+ try {+ return { source: filePath, doc: JSON.parse(await readFile(filePath, 'utf8')) };+ } catch (err) {+ console.error(`failed to read ${filePath}: ${err.message}`);+ process.exit(2);+ }+ }const url = `${base}/.well-known/x402.json`;const res = await fetch(url);if (!res.ok) {console.error(`failed to fetch ${url}: HTTP ${res.status}`);process.exit(2);}- const doc = await res.json();+ return { source: url, doc: await res.json() };+}++async function main() {+ const { source: url, doc } = await loadCatalog();const resources = doc.resources || doc.items || [];const report = resources.map(checkResource);diff --git a/src/dashboard-next/pages/creator.js b/src/dashboard-next/pages/creator.jsnew file mode 100644index 000000000..ef6cdecda--- /dev/null+++ b/src/dashboard-next/pages/creator.js@@ -0,0 +1,1191 @@+// dashboard-next — Creator Studio.+//+// The supply-side proof surface: creators set prices, watch real earnings, wire+// payouts, track the royalty ledger on-chain, and see per-skill analytics — all+// from live /api/* endpoints. No mock figures anywhere.+//+// Where this sits next to /dashboard/monetize: Monetize is the billing/withdrawal+// hub. Creator Studio is the *seller's* cockpit — dynamic pricing rules, the+// buyer-facing $THREE-holder price ladder, the pending→settling→settled royalty+// ledger, per-skill conversion, and a guided "become a creator → first sale"+// path instrumented as the creator funnel.++import { mountShell } from '../shell.js';+import { requireUser, get, post, put, del, patch, esc, relTime, formatUsdc, ApiError } from '../api.js';+import { errorStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';+import { track, trackFunnelStep, ANALYTICS_EVENTS } from '../../analytics.js';+import {+ TIER_LADDER,+ usdcToAtomic,+ atomicToUsdc,+ buyerPriceLadder,+ validatePrice,+ validateRule,+ effectivePriceNow,+ groupLedgerByStatus,+ ledgerToCsv,+ funnelStage,+} from './creator-helpers.js';++const SOLANA_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const EVM_ADDR_RE = /^0x[a-fA-F0-9]{40}$/;+const SKILL_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;++const PERIODS = [+ { key: '7d', label: 'Last 7 days', days: 7 },+ { key: '30d', label: 'Last 30 days', days: 30 },+ { key: '90d', label: 'Last 90 days', days: 90 },+ { key: 'all', label: 'All time', days: 365 },+];++const RULE_LABELS = {+ first_n_purchases: 'First N buyers',+ after_n_purchases: 'After N buyers',+ time_window: 'Time window',+};++const STATE = {+ me: null,+ agents: [],+ agentId: null,+ period: '30d',+ prices: [],+ rules: [], // pricing rules for the selected agent (all skills)+ wallet: null,+ withdrawals: [],+ earnings: null, // { pending_usd, settled_usd, entries }+ revenue: null,+ analytics: null,+ firstSaleFired: false,+};++(async function boot() {+ try {+ const main = await mountShell();+ STATE.me = await requireUser();++ injectStyles();+ main.innerHTML = `+ <div class="cs-head">+ <div>+ <h1 class="dn-h1">Creator Studio</h1>+ <p class="dn-h1-sub">Set prices, watch real earnings, and get paid. This is where creators make money.</p>+ </div>+ <div class="cs-head-controls">+ <div data-slot="agent-selector"></div>+ <select data-slot="period" class="cs-select" aria-label="Earnings period">+ ${PERIODS.map((p) => `<option value="${p.key}"${p.key === STATE.period ? ' selected' : ''}>${esc(p.label)}</option>`).join('')}+ </select>+ </div>+ </div>+ <div data-slot="content" class="cs-content"></div>+ `;++ const host = main.querySelector('[data-slot="content"]');+ const selectorHost = main.querySelector('[data-slot="agent-selector"]');+ const periodSel = main.querySelector('[data-slot="period"]');+ renderSkeleton(host);++ const agentsResp = await safe(() => get('/api/agents?limit=100'));+ STATE.agents = agentsResp?.agents || [];+ STATE.agentId = STATE.agents[0]?.id || null;++ renderAgentSelector(selectorHost, host);+ periodSel.addEventListener('change', async () => {+ STATE.period = periodSel.value;+ renderSkeleton(host);+ await loadAndRender(host);+ });++ // Funnel step 1 — the creator showed up. Tag with where they are so the+ // activation rate (viewer → first price → first sale) is measurable.+ const hasPrices = false; // not loaded yet; refined after load+ track(ANALYTICS_EVENTS.CREATOR_ONBOARDING_STARTED, {+ agent_count: STATE.agents.length,+ has_prices: hasPrices,+ });++ await loadAndRender(host);+ } catch (err) {+ if (err instanceof ApiError && err.status === 401) {+ const ret = encodeURIComponent(location.pathname + location.search);+ location.href = `/login?return=${ret}`;+ return;+ }+ throw err;+ }+})();++async function safe(fn) {+ try {+ return await fn();+ } catch (err) {+ if (err instanceof ApiError && err.status === 401) throw err;+ return null;+ }+}++// ── Agent selector ───────────────────────────────────────────────────────────++function renderAgentSelector(host, contentHost) {+ if (!STATE.agents.length) {+ host.innerHTML = `<a class="dn-btn primary" href="/dashboard/agents">Create your first agent</a>`;+ return;+ }+ host.innerHTML = `+ <select data-slot="agent-select" class="cs-select" aria-label="Select agent">+ ${STATE.agents.map((a) => `<option value="${esc(a.id)}"${a.id === STATE.agentId ? ' selected' : ''}>${esc(a.name || a.slug || 'Unnamed agent')}</option>`).join('')}+ </select>`;+ host.querySelector('[data-slot="agent-select"]').addEventListener('change', async (e) => {+ STATE.agentId = e.target.value;+ renderSkeleton(contentHost);+ await loadAndRender(contentHost);+ });+}++// ── Data loading ─────────────────────────────────────────────────────────────++async function loadAndRender(host) {+ if (!STATE.agents.length) {+ host.innerHTML = '';+ host.appendChild(renderNoAgents());+ return;+ }++ const agentId = STATE.agentId;+ const periodMeta = PERIODS.find((p) => p.key === STATE.period) || PERIODS[1];+ const days = periodMeta.days;++ const [prices, rulesResp, wallet, withdrawalsResp, earnings, revenue, analytics] = await Promise.all([+ safe(() => get(`/api/monetization/prices?agent_id=${encodeURIComponent(agentId)}`)),+ safe(() => get(`/api/agents/${encodeURIComponent(agentId)}/pricing-rules`)),+ safe(() => get(`/api/monetization/wallet?agent_id=${encodeURIComponent(agentId)}`)),+ safe(() => get(`/api/monetization/withdrawals?agent_id=${encodeURIComponent(agentId)}&limit=50`)),+ safe(() => get('/api/users/earnings')),+ safe(() => get(`/api/monetization/revenue?agent_id=${encodeURIComponent(agentId)}&period=${encodeURIComponent(STATE.period)}`)),+ safe(() => get(`/api/creators/skill-analytics?agent_id=${encodeURIComponent(agentId)}&days=${days}`)),+ ]);++ // If literally everything failed, this is a service problem — say so once.+ if (!prices && !wallet && !revenue && !earnings && !analytics) {+ ensureStateKitStyles();+ host.innerHTML = errorStateHTML({+ title: "Couldn't load your Creator Studio",+ body: 'We had trouble reaching the creator services. Check your connection and try again.',+ });+ host.querySelector('[data-sk-retry]')?.addEventListener('click', () => {+ renderSkeleton(host);+ loadAndRender(host);+ });+ return;+ }++ STATE.prices = prices?.prices || [];+ STATE.rules = rulesResp?.data?.rules || [];+ STATE.wallet = wallet?.resolved || null;+ STATE.withdrawals = withdrawalsResp?.withdrawals || [];+ STATE.balance = withdrawalsResp?.balance || null;+ STATE.earnings = earnings || { pending_usd: 0, settled_usd: 0, entries: [] };+ STATE.revenue = revenue || null;+ STATE.analytics = analytics?.data || null;++ const hasSale = Number(revenue?.event_count || 0) > 0 || (STATE.earnings.entries || []).length > 0;+ const hasPayout = Boolean(STATE.wallet?.solana_address || STATE.wallet?.evm_address);++ // Fire the first-sale funnel step once, when we first observe revenue.+ if (hasSale && !STATE.firstSaleFired) {+ STATE.firstSaleFired = true;+ trackFunnelStep('creator', ANALYTICS_EVENTS.CREATOR_FIRST_SALE, {+ agent_id: agentId,+ revenue_usd: Number(revenue?.net_usdc || 0),+ });+ }++ host.innerHTML = '';+ host.appendChild(renderOnboarding({ hasPayout, hasSale }));+ host.appendChild(renderEarningsHero());+ host.appendChild(renderRevenueChart());+ host.appendChild(renderPriceEditor(host));+ host.appendChild(renderSkillAnalytics());+ host.appendChild(renderPayoutPanel(host));+ host.appendChild(renderRoyaltyLedger());+ host.appendChild(renderWithdrawals(host));+}++// ── Onboarding path ──────────────────────────────────────────────────────────++function renderOnboarding({ hasPayout, hasSale }) {+ const stage = funnelStage({+ agentCount: STATE.agents.length,+ priceCount: STATE.prices.length,+ hasPayout,+ hasSale,+ });+ const wrap = document.createElement('div');+ if (stage === 'earning') {+ // Fully ramped — celebrate, don't nag.+ wrap.className = 'dn-panel cs-onboard cs-onboard-done';+ wrap.innerHTML = `+ <div class="cs-onboard-badge">✓</div>+ <div>+ <div class="dn-panel-title">You're a paid creator</div>+ <div class="dn-panel-sub">Prices set, payout wired, and real sales landing. Add more priced skills to grow your take.</div>+ </div>`;+ return wrap;+ }++ const steps = [+ { key: 'set_price', title: 'Set your first price', body: 'Charge USDC for a skill your agent already does.', done: STATE.prices.length > 0, cta: { label: 'Set a price', action: 'scroll-price' } },+ { key: 'configure_payout', title: 'Add a payout wallet', body: 'Tell us where to send your earnings.', done: hasPayout, cta: { label: 'Add wallet', action: 'scroll-payout' } },+ { key: 'first_sale', title: 'Make your first sale', body: 'Embed your agent or share its skills to earn.', done: hasSale, cta: { label: 'Get installs', href: '/dashboard/widgets' } },+ ];+ const doneCount = steps.filter((s) => s.done).length;++ wrap.className = 'dn-panel cs-onboard';+ wrap.innerHTML = `+ <div class="cs-onboard-head">+ <div class="dn-panel-title">Become a paid creator</div>+ <div class="cs-onboard-progress">${doneCount} of ${steps.length} done</div>+ </div>+ <div class="cs-steps">+ ${steps.map((s, i) => `+ <div class="cs-step${s.done ? ' done' : ''}${s.key === stage ? ' active' : ''}">+ <div class="cs-step-num">${s.done ? '✓' : i + 1}</div>+ <div class="cs-step-body">+ <div class="cs-step-title">${esc(s.title)}</div>+ <div class="cs-step-sub">${esc(s.body)}</div>+ </div>+ ${!s.done ? (s.cta.href+ ? `<a class="dn-btn" href="${esc(s.cta.href)}">${esc(s.cta.label)}</a>`+ : `<button class="dn-btn" data-action="${esc(s.cta.action)}">${esc(s.cta.label)}</button>`) : ''}+ </div>`).join('')}+ </div>`;++ wrap.querySelector('[data-action="scroll-price"]')?.addEventListener('click', () => {+ document.querySelector('[data-panel="price-editor"]')?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ });+ wrap.querySelector('[data-action="scroll-payout"]')?.addEventListener('click', () => {+ document.querySelector('[data-panel="payout"]')?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ });+ return wrap;+}++// ── Earnings hero ────────────────────────────────────────────────────────────++function renderEarningsHero() {+ const r = STATE.revenue || {};+ const gross = Number(r.total_usdc || 0);+ const net = Number(r.net_usdc || 0);+ const fees = Number(r.total_fees_usdc || 0);+ const count = Number(r.event_count || 0);+ const pending = Number(STATE.earnings?.pending_usd || 0);+ const available = Number(STATE.balance?.available_usdc || 0);+ const periodLabel = (PERIODS.find((p) => p.key === STATE.period) || PERIODS[1]).label.toLowerCase();++ const wrap = document.createElement('div');+ wrap.className = 'cs-hero';+ wrap.appendChild(heroCard({ title: 'Net earnings', value: usd(net), sub: `After platform fees · ${periodLabel}`, accent: 'good' }));+ wrap.appendChild(heroCard({ title: 'Gross volume', value: usd(gross), sub: `${count} paid call${count === 1 ? '' : 's'} · ${periodLabel}` }));+ wrap.appendChild(heroCard({ title: 'Platform fees', value: usd(fees), sub: 'Deducted from gross', accent: 'warn' }));+ wrap.appendChild(heroCard({ title: 'Pending royalties', value: usd(pending), sub: pending > 0 ? 'Settling to your wallet on-chain' : 'No unsettled royalties', accent: 'accent' }));+ wrap.appendChild(heroCard({ title: 'Available to withdraw', value: usd(available), sub: 'Settled balance, minus inflight', accent: 'good' }));+ return wrap;+}++function heroCard({ title, value, sub, accent }) {+ const color = accent === 'good' ? 'var(--nxt-success)' : accent === 'warn' ? 'var(--nxt-warn)' : accent === 'accent' ? 'var(--nxt-accent-strong)' : 'var(--nxt-ink)';+ const el = document.createElement('div');+ el.className = 'dn-panel cs-hero-card';+ el.innerHTML = `+ <div class="dn-panel-title">${esc(title)}</div>+ <div class="cs-hero-value" style="color:${color}">${esc(value)}</div>+ <div class="dn-panel-sub">${esc(sub)}</div>`;+ return el;+}++// ── Revenue chart ────────────────────────────────────────────────────────────++function renderRevenueChart() {+ const panel = document.createElement('div');+ panel.className = 'dn-panel';+ const series = (STATE.revenue?.by_day || []).map((d) => ({ label: d.date, value: Number(d.total || 0) }));+ panel.innerHTML = `+ <div class="cs-panel-head">+ <div>+ <div class="dn-panel-title">Earnings over time</div>+ <div class="dn-panel-sub">Net USDC per day from skill calls.</div>+ </div>+ </div>+ <div data-slot="chart" class="cs-chart"></div>`;+ const chartHost = panel.querySelector('[data-slot="chart"]');+ if (!series.length) {+ chartHost.innerHTML = `+ <div class="dn-empty">+ <h3>No sales yet</h3>+ <p>Price a skill below, then embed your agent or share it. Your first earnings will chart here.</p>+ </div>`;+ } else {+ requestAnimationFrame(() => paintChart(chartHost, series));+ }+ return panel;+}++function paintChart(host, series) {+ host.innerHTML = '';+ const canvas = document.createElement('canvas');+ canvas.style.cssText = 'width:100%;height:100%;display:block';+ host.appendChild(canvas);+ const dpr = window.devicePixelRatio || 1;+ const rect = host.getBoundingClientRect();+ const W = rect.width || 600;+ const H = rect.height || 220;+ canvas.width = Math.round(W * dpr);+ canvas.height = Math.round(H * dpr);+ const ctx = canvas.getContext('2d');+ ctx.scale(dpr, dpr);++ const PAD = { t: 16, r: 14, b: 26, l: 52 };+ const innerW = W - PAD.l - PAD.r;+ const innerH = H - PAD.t - PAD.b;+ const max = Math.max(0.01, ...series.map((d) => d.value));+ const pts = series.map((d, i) => ({+ x: PAD.l + (i / Math.max(1, series.length - 1)) * innerW,+ y: PAD.t + innerH - (d.value / max) * innerH,+ d,+ }));++ canvas.setAttribute('role', 'img');+ canvas.setAttribute('aria-label', `Net earnings, ${series.length} day${series.length === 1 ? '' : 's'}, peak ${usd(max)}`);++ ctx.strokeStyle = 'rgba(255,255,255,0.06)';+ ctx.fillStyle = 'rgba(255,255,255,0.32)';+ ctx.font = '10px Inter, system-ui, sans-serif';+ ctx.lineWidth = 0.5;+ for (let i = 0; i <= 4; i++) {+ const y = PAD.t + (i / 4) * innerH;+ ctx.beginPath(); ctx.moveTo(PAD.l, y); ctx.lineTo(W - PAD.r, y); ctx.stroke();+ ctx.textAlign = 'right';+ ctx.fillText(usd(((4 - i) / 4) * max), PAD.l - 8, y + 3);+ }+ const every = Math.max(1, Math.ceil(series.length / 8));+ ctx.textAlign = 'center';+ series.forEach((d, i) => { if (i % every === 0) ctx.fillText(shortDate(d.label), pts[i].x, H - 8); });++ if (pts.length >= 2) {+ const grad = ctx.createLinearGradient(0, PAD.t, 0, PAD.t + innerH);+ grad.addColorStop(0, 'rgba(74,222,128,0.25)');+ grad.addColorStop(1, 'rgba(74,222,128,0)');+ ctx.beginPath();+ ctx.moveTo(pts[0].x, PAD.t + innerH);+ pts.forEach((p) => ctx.lineTo(p.x, p.y));+ ctx.lineTo(pts[pts.length - 1].x, PAD.t + innerH);+ ctx.closePath(); ctx.fillStyle = grad; ctx.fill();+ }+ ctx.beginPath();+ pts.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));+ ctx.strokeStyle = '#4ade80'; ctx.lineWidth = 2; ctx.stroke();+ const last = pts[pts.length - 1];+ ctx.beginPath(); ctx.arc(last.x, last.y, 3.5, 0, Math.PI * 2); ctx.fillStyle = '#4ade80'; ctx.fill();++ canvas.addEventListener('mousemove', (e) => {+ const br = canvas.getBoundingClientRect();+ const mx = e.clientX - br.left;+ let best = 0, bd = Infinity;+ pts.forEach((p, i) => { const dd = Math.abs(p.x - mx); if (dd < bd) { bd = dd; best = i; } });+ canvas.title = `${shortDate(series[best].label)}: ${usd(series[best].value)}`;+ });+}++// ── Price editor (base price + $THREE ladder + dynamic rules) ─────────────────++function renderPriceEditor(host) {+ const panel = document.createElement('div');+ panel.className = 'dn-panel';+ panel.dataset.panel = 'price-editor';++ function paint() {+ panel.innerHTML = `+ <div class="cs-panel-head">+ <div>+ <div class="dn-panel-title">Skill pricing</div>+ <div class="dn-panel-sub">Charge USDC per call. $THREE holders see an automatic discount — preview it below.</div>+ </div>+ <button class="dn-btn primary" data-action="add">+ Price a skill</button>+ </div>+ <div data-slot="list"></div>`;+ const list = panel.querySelector('[data-slot="list"]');+ const priced = STATE.prices.filter((p) => p.gate_type !== 'nft');++ if (!priced.length) {+ list.innerHTML = `+ <div class="dn-empty">+ <h3>No priced skills yet</h3>+ <p>Pick a skill your agent performs and put a price on it. You keep the revenue minus the platform fee.</p>+ </div>`;+ } else {+ list.innerHTML = priced.map((p) => priceCard(p)).join('');+ }++ panel.querySelector('[data-action="add"]').addEventListener('click', () => openPriceModal(null, () => { reloadAgentPricing(host); }));+ list.querySelectorAll('[data-action="edit"]').forEach((b) => b.addEventListener('click', () => {+ const skill = b.dataset.skill;+ const price = STATE.prices.find((p) => (p.skill_name || p.skill) === skill);+ openPriceModal(price, () => reloadAgentPricing(host));+ }));+ list.querySelectorAll('[data-action="rules"]').forEach((b) => b.addEventListener('click', () => {+ openRulesModal(b.dataset.skill, () => reloadAgentPricing(host));+ }));+ list.querySelectorAll('[data-action="delete"]').forEach((b) => b.addEventListener('click', async () => {+ const skill = b.dataset.skill;+ b.disabled = true; b.textContent = 'Removing…';+ try {+ await del(`/api/monetization/prices?agent_id=${encodeURIComponent(STATE.agentId)}&skill_name=${encodeURIComponent(skill)}`);+ toast('Skill price removed');+ await reloadAgentPricing(host);+ } catch (err) {+ toast(err?.message || 'Delete failed', true);+ b.disabled = false; b.textContent = 'Remove';+ }+ }));+ }++ paint();+ return panel;+}++function priceCard(p) {+ const skill = p.skill_name || p.skill || 'unnamed';+ const base = Number(p.price_usdc ?? atomicToUsdc(p.amount_atomic) ?? 0);+ const rules = STATE.rules.filter((r) => r.skill_name === skill && r.is_active !== false);+ const saleCount = saleCountForSkill(skill);+ const effective = effectivePriceNow({ basePriceUsdc: base, rules, saleCount });+ const ladder = buyerPriceLadder(effective.priceUsdc);+ const active = p.is_active !== false;++ const ruleNote = effective.source !== 'base'+ ? `<span class="cs-tag accent" title="A dynamic pricing rule is active right now">${esc(RULE_LABELS[effective.source] || 'Rule')} active</span>`+ : '';++ return `+ <div class="cs-price-card">+ <div class="cs-price-top">+ <div class="cs-price-name">${esc(skill)} ${active ? '' : '<span class="cs-tag muted">paused</span>'} ${ruleNote}</div>+ <div class="cs-price-actions">+ <button class="dn-btn" data-action="edit" data-skill="${esc(skill)}">Edit</button>+ <button class="dn-btn" data-action="rules" data-skill="${esc(skill)}">Rules${rules.length ? ` · ${rules.length}` : ''}</button>+ <button class="dn-btn danger" data-action="delete" data-skill="${esc(skill)}">Remove</button>+ </div>+ </div>+ <div class="cs-price-figures">+ <div><span class="cs-fig-label">List price</span><span class="cs-fig-value">${usd(base)}</span></div>+ <div><span class="cs-fig-label">Effective now</span><span class="cs-fig-value">${usd(effective.priceUsdc)}</span></div>+ <div><span class="cs-fig-label">Confirmed sales</span><span class="cs-fig-value">${saleCount}</span></div>+ </div>+ <div class="cs-ladder" aria-label="Buyer-facing price by $THREE holder tier">+ ${ladder.map((t) => `+ <div class="cs-ladder-cell" title="${esc(t.label)} holders${t.discountBps ? ` save ${(t.discountBps / 100).toFixed(0)}%` : ''}">+ <span class="cs-ladder-tier">${esc(t.label)}</span>+ <span class="cs-ladder-price">${usd(t.price)}</span>+ <span class="cs-ladder-disc">${t.discountBps ? `−${(t.discountBps / 100).toFixed(0)}%` : 'full'}</span>+ </div>`).join('')}+ </div>+ </div>`;+}++function openPriceModal(existing, onSaved) {+ const isEdit = Boolean(existing);+ const skill = existing ? (existing.skill_name || existing.skill) : '';+ const price = existing ? Number(existing.price_usdc ?? atomicToUsdc(existing.amount_atomic) ?? 0) : '';+ const active = existing ? existing.is_active !== false : true;++ const overlay = modal(`+ <div class="cs-modal-title">${isEdit ? 'Edit price' : 'Price a skill'}</div>+ <label class="cs-field">+ <span class="cs-label">Skill name</span>+ <input data-f="skill" type="text" maxlength="64" class="cs-input" value="${esc(skill)}" ${isEdit ? 'readonly' : 'placeholder="e.g. generate_report"'} />+ <span class="cs-hint" data-h="skill"></span>+ </label>+ <label class="cs-field">+ <span class="cs-label">Price per call (USDC)</span>+ <input data-f="price" type="number" min="0" step="0.000001" class="cs-input" value="${esc(String(price))}" placeholder="0.05" />+ <span class="cs-hint" data-h="price"></span>+ </label>+ <div class="cs-ladder-preview" data-slot="ladder"></div>+ <label class="cs-check">+ <input data-f="active" type="checkbox" ${active ? 'checked' : ''} />+ <span>Active — buyers can call this skill</span>+ </label>+ <div class="cs-error" data-slot="err"></div>+ <div class="cs-modal-actions">+ <button class="dn-btn ghost" data-action="cancel">Cancel</button>+ <button class="dn-btn primary" data-action="save">${isEdit ? 'Save' : 'Add price'}</button>+ </div>+ `);++ const skillEl = overlay.querySelector('[data-f="skill"]');+ const priceEl = overlay.querySelector('[data-f="price"]');+ const activeEl = overlay.querySelector('[data-f="active"]');+ const errEl = overlay.querySelector('[data-slot="err"]');+ const ladderEl = overlay.querySelector('[data-slot="ladder"]');+ const skillHint = overlay.querySelector('[data-h="skill"]');+ const priceHint = overlay.querySelector('[data-h="price"]');++ function paintLadder() {+ const v = validatePrice(priceEl.value);+ if (!v.ok) { ladderEl.innerHTML = `<div class="cs-ladder-note">Enter a price to preview what each $THREE tier pays.</div>`; return; }+ ladderEl.innerHTML = `+ <div class="cs-ladder-note">What buyers pay by $THREE tier:</div>+ <div class="cs-ladder">${buyerPriceLadder(v.value).map((t) => `+ <div class="cs-ladder-cell">+ <span class="cs-ladder-tier">${esc(t.label)}</span>+ <span class="cs-ladder-price">${usd(t.price)}</span>+ <span class="cs-ladder-disc">${t.discountBps ? `−${(t.discountBps / 100).toFixed(0)}%` : 'full'}</span>+ </div>`).join('')}</div>`;+ }+ priceEl.addEventListener('input', () => {+ const v = validatePrice(priceEl.value);+ priceHint.textContent = v.ok ? '' : v.error;+ paintLadder();+ });+ paintLadder();+ (isEdit ? priceEl : skillEl).focus();++ overlay.querySelector('[data-action="save"]').addEventListener('click', async () => {+ errEl.textContent = '';+ const name = skillEl.value.trim();+ if (!SKILL_NAME_RE.test(name)) { skillHint.textContent = 'Letters, numbers, _ or -, up to 64 chars.'; return; }+ const v = validatePrice(priceEl.value);+ if (!v.ok) { priceHint.textContent = v.error; return; }++ const btn = overlay.querySelector('[data-action="save"]');+ btn.disabled = true; btn.textContent = 'Saving…';+ try {+ await put('/api/monetization/prices', {+ agent_id: STATE.agentId,+ skill_name: name,+ price_usdc: v.value,+ gate_type: 'price',+ });+ // Toggle active state if the owner unchecked it (PUT re-activates by default).+ if (!activeEl.checked) {+ await del(`/api/monetization/prices?agent_id=${encodeURIComponent(STATE.agentId)}&skill_name=${encodeURIComponent(name)}`);+ }+ const isFirst = STATE.prices.length === 0;+ trackFunnelStep('creator', ANALYTICS_EVENTS.CREATOR_PRICE_SET, {+ agent_id: STATE.agentId,+ skill: name,+ price_usdc: v.value,+ gate_type: 'price',+ is_first: isFirst,+ });+ overlay.close();+ toast(isEdit ? 'Price updated' : 'Skill priced');+ onSaved();+ } catch (err) {+ errEl.textContent = err?.body?.error_description || err?.message || 'Save failed';+ btn.disabled = false; btn.textContent = isEdit ? 'Save' : 'Add price';+ }+ });+}++// ── Dynamic pricing rules modal ──────────────────────────────────────────────++function openRulesModal(skill, onSaved) {+ const overlay = modal(`+ <div class="cs-modal-title">Pricing rules · ${esc(skill)}</div>+ <div class="dn-panel-sub" style="margin-bottom:14px">Rules override the list price by priority. First match wins; otherwise buyers pay the list price.</div>+ <div data-slot="rules"></div>+ <div class="cs-rule-form">+ <div class="cs-modal-subtitle">Add a rule</div>+ <label class="cs-field">+ <span class="cs-label">Type</span>+ <select data-f="type" class="cs-input">+ <option value="first_n_purchases">First N buyers (intro price)</option>+ <option value="after_n_purchases">After N buyers (raise price)</option>+ <option value="time_window">Time window (limited promo)</option>+ </select>+ </label>+ <div class="cs-rule-grid">+ <label class="cs-field" data-slot="threshold-field">+ <span class="cs-label">Threshold (N buyers)</span>+ <input data-f="threshold" type="number" min="1" step="1" class="cs-input" placeholder="10" />+ </label>+ <label class="cs-field" data-slot="start-field" hidden>+ <span class="cs-label">Start</span>+ <input data-f="start" type="datetime-local" class="cs-input" />+ </label>+ <label class="cs-field" data-slot="end-field" hidden>+ <span class="cs-label">End</span>+ <input data-f="end" type="datetime-local" class="cs-input" />+ </label>+ <label class="cs-field">+ <span class="cs-label">Rule price (USDC)</span>+ <input data-f="price" type="number" min="0" step="0.000001" class="cs-input" placeholder="0.01" />+ </label>+ </div>+ <div class="cs-error" data-slot="err"></div>+ <button class="dn-btn primary" data-action="add-rule">Add rule</button>+ </div>+ <div class="cs-modal-actions">+ <button class="dn-btn ghost" data-action="cancel">Done</button>+ </div>+ `);++ const typeEl = overlay.querySelector('[data-f="type"]');+ const thrField = overlay.querySelector('[data-slot="threshold-field"]');+ const startField = overlay.querySelector('[data-slot="start-field"]');+ const endField = overlay.querySelector('[data-slot="end-field"]');+ const errEl = overlay.querySelector('[data-slot="err"]');+ const rulesHost = overlay.querySelector('[data-slot="rules"]');++ function paintRules() {+ const rules = STATE.rules.filter((r) => r.skill_name === skill);+ rulesHost.innerHTML = rules.length+ ? `<table class="cs-table"><thead><tr><th>Type</th><th>Condition</th><th style="text-align:right">Price</th><th>Status</th><th></th></tr></thead><tbody>${rules.map(ruleRow).join('')}</tbody></table>`+ : `<div class="cs-rule-empty">No rules yet — buyers pay the list price.</div>`;+ rulesHost.querySelectorAll('[data-action="del-rule"]').forEach((b) => b.addEventListener('click', async () => {+ b.disabled = true;+ try {+ await del(`/api/agents/${encodeURIComponent(STATE.agentId)}/pricing-rules/${encodeURIComponent(b.dataset.id)}?rule_id=${encodeURIComponent(b.dataset.id)}`);+ STATE.rules = STATE.rules.filter((r) => r.id !== b.dataset.id);+ toast('Rule removed');+ paintRules();+ onSaved();+ } catch (err) { toast(err?.message || 'Failed', true); b.disabled = false; }+ }));+ }++ typeEl.addEventListener('change', () => {+ const t = typeEl.value;+ thrField.hidden = t === 'time_window';+ startField.hidden = t !== 'time_window';+ endField.hidden = t !== 'time_window';+ errEl.textContent = '';+ });+ paintRules();++ overlay.querySelector('[data-action="add-rule"]').addEventListener('click', async () => {+ errEl.textContent = '';+ const rule = {+ rule_type: typeEl.value,+ threshold: overlay.querySelector('[data-f="threshold"]').value,+ price_usdc: overlay.querySelector('[data-f="price"]').value,+ start_at: overlay.querySelector('[data-f="start"]').value || null,+ end_at: overlay.querySelector('[data-f="end"]').value || null,+ };+ const v = validateRule(rule);+ if (!v.ok) { errEl.textContent = v.error; return; }++ // Base price must exist for rules to resolve — guard with a clear message.+ const base = STATE.prices.find((p) => (p.skill_name || p.skill) === skill);+ if (!base) { errEl.textContent = 'Set a list price for this skill first.'; return; }++ const btn = overlay.querySelector('[data-action="add-rule"]');+ btn.disabled = true; btn.textContent = 'Adding…';+ try {+ const resp = await post(`/api/agents/${encodeURIComponent(STATE.agentId)}/pricing-rules?id=${encodeURIComponent(STATE.agentId)}`, {+ skill_name: skill,+ currency_mint: base.currency_mint || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ chain: base.chain || 'solana',+ ...v.payload,+ });+ if (resp?.data?.rule) STATE.rules.push(resp.data.rule);+ toast('Rule added');+ paintRules();+ onSaved();+ } catch (err) {+ errEl.textContent = err?.body?.error_description || err?.message || 'Failed to add rule';+ }+ btn.disabled = false; btn.textContent = 'Add rule';+ });+}++function ruleRow(r) {+ const cond = r.rule_type === 'time_window'+ ? `${r.start_at ? shortDate(r.start_at) : '…'} → ${r.end_at ? shortDate(r.end_at) : '…'}`+ : `N = ${esc(String(r.threshold ?? '—'))}`;+ return `+ <tr>+ <td>${esc(RULE_LABELS[r.rule_type] || r.rule_type)}</td>+ <td>${cond}</td>+ <td style="text-align:right">${usd(atomicToUsdc(r.price_amount))}</td>+ <td>${r.is_active === false ? '<span class="cs-tag muted">off</span>' : '<span class="cs-tag good">on</span>'}</td>+ <td style="text-align:right"><button class="dn-btn danger cs-btn-xs" data-action="del-rule" data-id="${esc(r.id)}">Delete</button></td>+ </tr>`;+}++// ── Per-skill analytics ──────────────────────────────────────────────────────++function renderSkillAnalytics() {+ const panel = document.createElement('div');+ panel.className = 'dn-panel';+ const a = STATE.analytics;+ const bySkill = a?.by_skill || [];+ const summary = a?.summary || {};++ panel.innerHTML = `+ <div class="cs-panel-head">+ <div>+ <div class="dn-panel-title">Per-skill analytics</div>+ <div class="dn-panel-sub">Calls, unique buyers, and success rate over the selected period.</div>+ </div>+ ${bySkill.length ? `<div class="cs-summary">${Number(summary.total_calls || 0).toLocaleString()} calls · ${Number(summary.unique_users || 0).toLocaleString()} buyers</div>` : ''}+ </div>+ <div data-slot="body"></div>`;+ const body = panel.querySelector('[data-slot="body"]');+ if (!bySkill.length) {+ body.innerHTML = `<div class="dn-empty"><h3>No skill usage yet</h3><p>Once buyers start calling your priced skills, conversion and volume show up here.</p></div>`;+ return panel;+ }+ body.innerHTML = `+ <div style="overflow-x:auto">+ <table class="cs-table">+ <thead><tr>+ <th>Skill</th>+ <th style="text-align:right">Calls</th>+ <th style="text-align:right">Buyers</th>+ <th style="text-align:right">Success</th>+ <th style="text-align:right">Avg latency</th>+ </tr></thead>+ <tbody>+ ${bySkill.map((s) => `+ <tr>+ <td>${esc(s.skill_name)}</td>+ <td style="text-align:right">${Number(s.total_calls || 0).toLocaleString()}</td>+ <td style="text-align:right">${Number(s.unique_users || 0).toLocaleString()}</td>+ <td style="text-align:right">${rate(s.success_rate_pct)}</td>+ <td style="text-align:right">${s.avg_execution_ms != null ? `${Number(s.avg_execution_ms).toLocaleString()} ms` : '—'}</td>+ </tr>`).join('')}+ </tbody>+ </table>+ </div>`;+ return panel;+}++// ── Payout wallet ────────────────────────────────────────────────────────────++function renderPayoutPanel(host) {+ const panel = document.createElement('div');+ panel.className = 'dn-panel';+ panel.dataset.panel = 'payout';+ const w = STATE.wallet || {};+ const evm = w.evm_address || '';+ const sol = w.solana_address || '';+ const preferred = w.preferred_network || 'solana';++ panel.innerHTML = `+ <div class="cs-panel-head">+ <div>+ <div class="dn-panel-title">Payout wallet</div>+ <div class="dn-panel-sub">Where your settled USDC lands. You control these wallets.</div>+ </div>+ </div>+ <div class="cs-form-grid">+ <label class="cs-field">+ <span class="cs-label">Solana address</span>+ <input data-f="sol" type="text" class="cs-input cs-mono" value="${esc(sol)}" placeholder="Base58 address…" />+ <span class="cs-hint" data-h="sol"></span>+ </label>+ <label class="cs-field">+ <span class="cs-label">EVM address (Base)</span>+ <input data-f="evm" type="text" class="cs-input cs-mono" value="${esc(evm)}" placeholder="0x…" />+ <span class="cs-hint" data-h="evm"></span>+ </label>+ </div>+ <div class="cs-payout-row">+ <label class="cs-field" style="margin:0;flex:1;min-width:160px">+ <span class="cs-label">Preferred network</span>+ <select data-f="net" class="cs-input">+ <option value="solana"${preferred === 'solana' ? ' selected' : ''}>Solana</option>+ <option value="base"${preferred === 'base' ? ' selected' : ''}>Base (EVM)</option>+ </select>+ </label>+ <button class="dn-btn primary" data-action="save">Save payout wallet</button>+ </div>+ <div class="cs-error" data-slot="err"></div>`;++ const solEl = panel.querySelector('[data-f="sol"]');+ const evmEl = panel.querySelector('[data-f="evm"]');+ const netEl = panel.querySelector('[data-f="net"]');+ const errEl = panel.querySelector('[data-slot="err"]');+ const solHint = panel.querySelector('[data-h="sol"]');+ const evmHint = panel.querySelector('[data-h="evm"]');++ solEl.addEventListener('input', () => { const v = solEl.value.trim(); solHint.textContent = v && !SOLANA_ADDR_RE.test(v) ? 'Invalid Solana address' : ''; });+ evmEl.addEventListener('input', () => { const v = evmEl.value.trim(); evmHint.textContent = v && !EVM_ADDR_RE.test(v) ? 'Invalid EVM address' : ''; });++ panel.querySelector('[data-action="save"]').addEventListener('click', async () => {+ errEl.textContent = '';+ const solV = solEl.value.trim();+ const evmV = evmEl.value.trim();+ if (solV && !SOLANA_ADDR_RE.test(solV)) { errEl.textContent = 'Invalid Solana address.'; return; }+ if (evmV && !EVM_ADDR_RE.test(evmV)) { errEl.textContent = 'Invalid EVM address.'; return; }+ if (!solV && !evmV) { errEl.textContent = 'Enter at least one wallet address.'; return; }+ const btn = panel.querySelector('[data-action="save"]');+ btn.disabled = true; btn.textContent = 'Saving…';+ try {+ await put('/api/monetization/wallet', {+ agent_id: STATE.agentId,+ solana_address: solV || undefined,+ evm_address: evmV || undefined,+ preferred_network: netEl.value,+ });+ trackFunnelStep('creator', ANALYTICS_EVENTS.CREATOR_PAYOUT_CONFIGURED, { agent_id: STATE.agentId, network: netEl.value });+ toast('Payout wallet saved');+ await reloadAgentPricing(host);+ } catch (err) {+ errEl.textContent = err?.body?.error_description || err?.message || 'Save failed';+ btn.disabled = false; btn.textContent = 'Save payout wallet';+ }+ });+ return panel;+}++// ── Royalty ledger (pending / settling / settled) ────────────────────────────++function renderRoyaltyLedger() {+ const panel = document.createElement('div');+ panel.className = 'dn-panel';+ const entries = STATE.earnings?.entries || [];+ const { totals } = groupLedgerByStatus(entries);++ panel.innerHTML = `+ <div class="cs-panel-head">+ <div>+ <div class="dn-panel-title">Royalty ledger</div>+ <div class="dn-panel-sub">Every sale, from pending to on-chain settled. This is your real money trail.</div>+ </div>+ ${entries.length ? `<button class="dn-btn" data-action="export">Export CSV</button>` : ''}+ </div>+ <div class="cs-ledger-totals">+ ${ledgerTotal('Pending', totals.pending, 'warn')}+ ${ledgerTotal('Settling', totals.settling, 'accent')}+ ${ledgerTotal('Settled', totals.settled, 'good')}+ ${totals.failed > 0 ? ledgerTotal('Failed', totals.failed, 'bad') : ''}+ </div>+ <div data-slot="body"></div>`;++ const body = panel.querySelector('[data-slot="body"]');+ if (!entries.length) {+ body.innerHTML = `<div class="dn-empty"><h3>No royalties yet</h3><p>When buyers pay for your skills, each sale appears here and settles to your wallet automatically.</p></div>`;+ } else {+ const sorted = entries.slice().sort((a, b) => new Date(b.created_at) - new Date(a.created_at)).slice(0, 100);+ body.innerHTML = `+ <div style="overflow-x:auto">+ <table class="cs-table">+ <thead><tr><th>When</th><th>Skill</th><th>Agent</th><th style="text-align:right">Amount</th><th>Status</th></tr></thead>+ <tbody>${sorted.map(ledgerRow).join('')}</tbody>+ </table>+ </div>+ ${entries.length > 100 ? `<div class="cs-ledger-more">Showing latest 100 of ${entries.length}. Export CSV for the full history.</div>` : ''}`;+ }++ panel.querySelector('[data-action="export"]')?.addEventListener('click', () => {+ const csv = ledgerToCsv(entries);+ downloadCsv(csv, `creator-royalties-${STATE.agentId?.slice(0, 8) || 'all'}.csv`);+ toast('Royalty history exported');+ });+ return panel;+}++function ledgerTotal(label, usdVal, accent) {+ const color = accent === 'good' ? 'var(--nxt-success)' : accent === 'warn' ? 'var(--nxt-warn)' : accent === 'bad' ? 'var(--nxt-danger)' : 'var(--nxt-accent-strong)';+ return `<div class="cs-ledger-total"><span class="cs-fig-label">${esc(label)}</span><span class="cs-fig-value" style="color:${color}">${usd(usdVal)}</span></div>`;+}++function ledgerRow(e) {+ const tag = {+ settled: '<span class="cs-tag good">Settled</span>',+ settling: '<span class="cs-tag accent">Settling</span>',+ failed: '<span class="cs-tag bad">Failed</span>',+ }[e.status] || '<span class="cs-tag warn">Pending</span>';+ return `+ <tr>+ <td style="white-space:nowrap;color:var(--nxt-ink-dim)">${esc(relTime(e.created_at))}</td>+ <td>${esc(e.skill_name || e.kind || '—')}</td>+ <td style="color:var(--nxt-ink-dim)">${esc(e.agent_name || '—')}</td>+ <td style="text-align:right">${usd(Number(e.price_usd || 0))}</td>+ <td>${tag}</td>+ </tr>`;+}++// ── Withdrawals ──────────────────────────────────────────────────────────────++function renderWithdrawals(host) {+ const panel = document.createElement('div');+ panel.className = 'dn-panel';+ const ws = STATE.withdrawals || [];+ const available = Number(STATE.balance?.available_usdc || 0);++ panel.innerHTML = `+ <div class="cs-panel-head">+ <div>+ <div class="dn-panel-title">Withdrawals</div>+ <div class="dn-panel-sub">Move settled USDC to your payout wallet. Minimum $1.00.</div>+ </div>+ <button class="dn-btn primary" data-action="withdraw"${available < 1 ? ' disabled title="Minimum withdrawal is $1.00"' : ''}>Withdraw ${usd(available)}</button>+ </div>+ <div data-slot="body"></div>`;++ const body = panel.querySelector('[data-slot="body"]');+ if (!ws.length) {+ body.innerHTML = `<div class="cs-withdraw-empty">No withdrawals yet. Your available balance is <strong>${usd(available)}</strong>.</div>`;+ } else {+ body.innerHTML = `+ <div style="overflow-x:auto">+ <table class="cs-table">+ <thead><tr><th>Requested</th><th>Chain</th><th style="text-align:right">Amount</th><th>Status</th><th>Tx</th></tr></thead>+ <tbody>${ws.map(withdrawalRow).join('')}</tbody>+ </table>+ </div>`;+ }++ panel.querySelector('[data-action="withdraw"]').addEventListener('click', () => openWithdrawModal(available, host));+ return panel;+}++function withdrawalRow(w) {+ const tag = {+ completed: '<span class="cs-tag good">Completed</span>',+ processing: '<span class="cs-tag accent">Processing</span>',+ failed: '<span class="cs-tag bad">Failed</span>',+ }[w.status] || '<span class="cs-tag warn">Pending</span>';+ let tx = '<span style="color:var(--nxt-ink-fade)">—</span>';+ if (w.tx_hash) {+ const url = w.chain === 'base' ? `https://basescan.org/tx/${encodeURIComponent(w.tx_hash)}` : `https://solscan.io/tx/${encodeURIComponent(w.tx_hash)}`;+ tx = `<a href="${url}" target="_blank" rel="noopener" class="cs-link">view</a>`;+ }+ return `+ <tr>+ <td style="white-space:nowrap;color:var(--nxt-ink-dim)">${esc(relTime(w.requested_at))}</td>+ <td style="color:var(--nxt-ink-dim)">${esc(w.chain || '—')}</td>+ <td style="text-align:right">${usd(Number(w.amount_usdc || 0))}</td>+ <td>${tag}</td>+ <td>${tx}</td>+ </tr>`;+}++function openWithdrawModal(available, host) {+ const overlay = modal(`+ <div class="cs-modal-title">Withdraw earnings</div>+ <div class="dn-panel-sub" style="margin-bottom:14px">Available now: <strong>${usd(available)}</strong>. Funds go to your configured payout wallet.</div>+ <label class="cs-field">+ <span class="cs-label">Amount (USDC)</span>+ <input data-f="amt" type="number" min="1" step="0.01" class="cs-input" value="${available >= 1 ? available.toFixed(2) : ''}" placeholder="${available.toFixed(2)}" />+ <span class="cs-hint">Leave blank to withdraw everything available.</span>+ </label>+ <div class="cs-error" data-slot="err"></div>+ <div class="cs-modal-actions">+ <button class="dn-btn ghost" data-action="cancel">Cancel</button>+ <button class="dn-btn primary" data-action="go">Withdraw</button>+ </div>+ `);+ const amtEl = overlay.querySelector('[data-f="amt"]');+ const errEl = overlay.querySelector('[data-slot="err"]');+ overlay.querySelector('[data-action="go"]').addEventListener('click', async () => {+ errEl.textContent = '';+ const raw = amtEl.value.trim();+ let amount = raw === '' ? null : Number(raw);+ if (amount !== null && (!Number.isFinite(amount) || amount < 1)) { errEl.textContent = 'Minimum withdrawal is $1.00.'; return; }+ if (amount !== null && amount > available) { errEl.textContent = `You can withdraw at most ${usd(available)}.`; return; }+ const btn = overlay.querySelector('[data-action="go"]');+ btn.disabled = true; btn.textContent = 'Requesting…';+ try {+ await post('/api/monetization/withdrawals', { agent_id: STATE.agentId, amount_usdc: amount });+ overlay.close();+ toast('Withdrawal requested');+ await reloadAgentPricing(host);+ } catch (err) {+ errEl.textContent = err?.body?.error_description || err?.message || 'Withdrawal failed';+ btn.disabled = false; btn.textContent = 'Withdraw';+ }+ });+}++// ── Shared helpers ───────────────────────────────────────────────────────────++async function reloadAgentPricing(host) {+ renderSkeleton(host);+ await loadAndRender(host);+}++function renderNoAgents() {+ const el = document.createElement('div');+ el.className = 'dn-panel';+ el.innerHTML = `+ <div class="dn-empty">+ <h3>Create an agent to start earning</h3>+ <p>Creator Studio is where your agents make money. Spin one up, price a skill, and watch the revenue land.</p>+ <a class="dn-btn primary" href="/dashboard/agents" style="margin-top:14px">Create an agent</a>+ </div>`;+ return el;+}++function saleCountForSkill(skill) {+ // Confirmed-sale count drives first_n / after_n rule evaluation. Use the+ // real per-skill revenue breakdown from /api/monetization/revenue.+ const row = (STATE.revenue?.by_skill || []).find((s) => s.skill === skill);+ return Number(row?.count || 0);+}++function usd(n) {+ const v = Number(n);+ if (!Number.isFinite(v)) return '$0.00';+ const decimals = v !== 0 && Math.abs(v) < 0.01 ? 6 : Math.abs(v) < 1 ? 4 : 2;+ return `$${v.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: decimals })}`;+}++function rate(pct) {+ const v = Number(pct);+ if (!Number.isFinite(v)) return '—';+ const color = v >= 95 ? 'var(--nxt-success)' : v >= 80 ? 'var(--nxt-warn)' : 'var(--nxt-danger)';+ return `<span style="color:${color}">${v.toFixed(0)}%</span>`;+}++function shortDate(s) {+ const d = new Date(s);+ if (isNaN(d)) return String(s).slice(5, 10);+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });+}++function downloadCsv(csv, filename) {+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url; a.download = filename;+ document.body.appendChild(a); a.click(); a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+}++function modal(innerHTML) {+ const overlay = document.createElement('div');+ overlay.className = 'cs-overlay';+ overlay.innerHTML = `<div role="dialog" aria-modal="true" class="cs-modal">${innerHTML}</div>`;+ document.body.appendChild(overlay);+ const close = () => { overlay.remove(); document.removeEventListener('keydown', onKey); };+ const onKey = (e) => { if (e.key === 'Escape') close(); };+ document.addEventListener('keydown', onKey);+ overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });+ overlay.querySelectorAll('[data-action="cancel"]').forEach((b) => b.addEventListener('click', close));+ overlay.close = close;+ const focusable = overlay.querySelector('input,select,button');+ focusable?.focus();+ return overlay;+}++let toastTimer = null;+function toast(msg, isError = false) {+ let host = document.querySelector('.cs-toast');+ if (!host) {+ host = document.createElement('div');+ host.className = 'cs-toast';+ document.body.appendChild(host);+ }+ host.textContent = msg;+ host.style.borderColor = isError ? 'var(--nxt-danger)' : 'var(--nxt-stroke-strong)';+ host.classList.add('show');+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => host.classList.remove('show'), 2600);+}++function renderSkeleton(host) {+ host.innerHTML = `+ <div class="cs-hero">${Array.from({ length: 5 }, () => `<div class="dn-panel cs-hero-card"><div class="dn-skeleton" style="height:14px;width:60%;border-radius:6px"></div><div class="dn-skeleton" style="height:28px;width:80%;border-radius:6px;margin:10px 0"></div><div class="dn-skeleton" style="height:12px;width:70%;border-radius:6px"></div></div>`).join('')}</div>+ <div class="dn-panel"><div class="dn-skeleton" style="height:220px;width:100%;border-radius:10px"></div></div>+ <div class="dn-panel"><div class="dn-skeleton" style="height:140px;width:100%;border-radius:10px"></div></div>`;+}++// ── Styles ───────────────────────────────────────────────────────────────────++let stylesInjected = false;+function injectStyles() {+ if (stylesInjected) return;+ stylesInjected = true;+ const css = `+ .cs-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:8px}+ .cs-head-controls{display:flex;gap:10px;flex-wrap:wrap}+ .cs-content{display:flex;flex-direction:column;gap:18px}+ .cs-select,.cs-input{background:var(--nxt-bg-1);border:1px solid var(--nxt-stroke);color:var(--nxt-ink);border-radius:var(--nxt-radius-sm,10px);padding:9px 12px;font-size:13.5px;font-family:inherit}+ .cs-select:focus,.cs-input:focus{outline:none;border-color:var(--nxt-stroke-strong);box-shadow:0 0 0 3px var(--nxt-accent-soft)}+ .cs-mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}+ .cs-panel-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px}+ .cs-summary{font-size:12.5px;color:var(--nxt-ink-dim);font-variant-numeric:tabular-nums}+ .cs-hero{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px}+ .cs-hero-card{display:flex;flex-direction:column;gap:4px}+ .cs-hero-value{font-size:26px;font-weight:700;letter-spacing:-0.02em;font-variant-numeric:tabular-nums;margin:4px 0 2px}+ .cs-chart{position:relative;width:100%;height:240px}+ /* Onboarding */+ .cs-onboard-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}+ .cs-onboard-progress{font-size:12.5px;color:var(--nxt-ink-dim)}+ .cs-onboard-done{display:flex;align-items:center;gap:14px}+ .cs-onboard-badge{width:40px;height:40px;border-radius:50%;background:rgba(74,222,128,0.15);color:var(--nxt-success);display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0}+ .cs-steps{display:flex;flex-direction:column;gap:10px}+ .cs-step{display:flex;align-items:center;gap:14px;padding:12px 14px;border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm,10px);transition:border-color .2s,background .2s}+ .cs-step.active{border-color:var(--nxt-stroke-strong);background:var(--nxt-accent-soft)}+ .cs-step.done{opacity:0.72}+ .cs-step-num{width:26px;height:26px;border-radius:50%;background:var(--nxt-bg-1);border:1px solid var(--nxt-stroke);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:600;flex-shrink:0}+ .cs-step.done .cs-step-num{background:rgba(74,222,128,0.15);color:var(--nxt-success);border-color:transparent}+ .cs-step-body{flex:1;min-width:0}+ .cs-step-title{font-weight:600;font-size:14px}+ .cs-step-sub{font-size:12.5px;color:var(--nxt-ink-dim);margin-top:2px}+ /* Price cards */+ .cs-price-card{border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm,10px);padding:14px;margin-bottom:12px}+ .cs-price-card:last-child{margin-bottom:0}+ .cs-price-top{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:12px}+ .cs-price-name{font-weight:600;font-size:14.5px;display:flex;align-items:center;gap:8px;flex-wrap:wrap}+ .cs-price-actions{display:flex;gap:6px;flex-wrap:wrap}+ .cs-price-figures{display:flex;gap:24px;flex-wrap:wrap;margin-bottom:12px}+ .cs-fig-label{display:block;font-size:11px;text-transform:uppercase;letter-spacing:0.05em;color:var(--nxt-ink-fade)}+ .cs-fig-value{display:block;font-size:18px;font-weight:600;font-variant-numeric:tabular-nums;margin-top:2px}+ .cs-ladder{display:grid;grid-template-columns:repeat(5,1fr);gap:8px}+ .cs-ladder-cell{background:var(--nxt-bg-1);border:1px solid var(--nxt-stroke);border-radius:8px;padding:8px 6px;text-align:center;display:flex;flex-direction:column;gap:2px}+ .cs-ladder-tier{font-size:10.5px;text-transform:uppercase;letter-spacing:0.04em;color:var(--nxt-ink-fade)}+ .cs-ladder-price{font-size:14px;font-weight:600;font-variant-numeric:tabular-nums}+ .cs-ladder-disc{font-size:10.5px;color:var(--nxt-ink-dim)}+ .cs-ladder-preview{margin:12px 0}+ .cs-ladder-note{font-size:12px;color:var(--nxt-ink-dim);margin-bottom:8px}+ /* Ledger */+ .cs-ledger-totals{display:flex;gap:28px;flex-wrap:wrap;margin-bottom:16px}+ .cs-ledger-total{display:flex;flex-direction:column}+ .cs-ledger-more,.cs-withdraw-empty,.cs-rule-empty{font-size:13px;color:var(--nxt-ink-dim);padding:12px 0}+ /* Table */+ .cs-table{width:100%;border-collapse:collapse;font-size:13px}+ .cs-table th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:0.05em;color:var(--nxt-ink-fade);font-weight:600;padding:0 12px 10px;border-bottom:1px solid var(--nxt-stroke)}+ .cs-table td{padding:11px 12px;border-bottom:1px solid var(--nxt-stroke);vertical-align:middle}+ .cs-table tbody tr:last-child td{border-bottom:none}+ .cs-table tbody tr:hover{background:var(--nxt-accent-soft)}+ /* Tags */+ .cs-tag{display:inline-block;padding:2px 8px;border-radius:var(--nxt-radius-pill,999px);font-size:11px;font-weight:600;border:1px solid var(--nxt-stroke)}+ .cs-tag.good{color:var(--nxt-success);background:rgba(74,222,128,0.12);border-color:transparent}+ .cs-tag.warn{color:var(--nxt-warn);background:rgba(255,165,0,0.12);border-color:transparent}+ .cs-tag.accent{color:var(--nxt-accent-strong);background:var(--nxt-accent-soft);border-color:transparent}+ .cs-tag.bad{color:var(--nxt-danger);background:rgba(255,0,0,0.1);border-color:transparent}+ .cs-tag.muted{color:var(--nxt-ink-fade)}+ .cs-link{color:var(--nxt-accent-strong);font-size:12px}+ .cs-btn-xs{padding:4px 9px;font-size:11.5px}+ /* Forms */+ .cs-form-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px}+ .cs-field{display:flex;flex-direction:column;gap:6px;margin-bottom:14px}+ .cs-label{font-size:12.5px;color:var(--nxt-ink-dim);font-weight:500}+ .cs-hint{font-size:11.5px;color:var(--nxt-warn);min-height:14px}+ .cs-check{display:flex;align-items:center;gap:10px;font-size:13px;cursor:pointer;margin-bottom:14px}+ .cs-check input{width:16px;height:16px;accent-color:var(--nxt-accent-strong)}+ .cs-payout-row{display:flex;align-items:flex-end;gap:14px;flex-wrap:wrap;margin-top:6px}+ .cs-error{color:var(--nxt-danger);font-size:12.5px;min-height:16px;margin:6px 0}+ /* Modal */+ .cs-overlay{position:fixed;inset:0;background:rgba(0,0,0,0.6);backdrop-filter:blur(3px);display:flex;align-items:center;justify-content:center;z-index:1000;padding:20px}+ .cs-modal{background:var(--nxt-bg-1);border:1px solid var(--nxt-stroke-strong);border-radius:var(--nxt-radius,14px);padding:24px;width:100%;max-width:520px;max-height:88vh;overflow-y:auto}+ .cs-modal-title{font-size:17px;font-weight:600;margin-bottom:16px}+ .cs-modal-subtitle{font-size:13px;font-weight:600;margin-bottom:10px}+ .cs-modal-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:8px}+ .cs-rule-form{border-top:1px solid var(--nxt-stroke);margin-top:16px;padding-top:16px}+ .cs-rule-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px}+ /* Toast */+ .cs-toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%) translateY(20px);background:var(--nxt-bg-1);border:1px solid var(--nxt-stroke-strong);color:var(--nxt-ink);padding:12px 20px;border-radius:var(--nxt-radius-sm,10px);font-size:13.5px;z-index:1100;opacity:0;pointer-events:none;transition:opacity .2s,transform .2s;box-shadow:0 8px 30px rgba(0,0,0,0.4)}+ .cs-toast.show{opacity:1;transform:translateX(-50%) translateY(0)}+ @media(max-width:640px){.cs-ladder{grid-template-columns:repeat(2,1fr)}}+ `;+ const style = document.createElement('style');+ style.textContent = css;+ document.head.appendChild(style);+}diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.jsindex a21846101..26ec60d36 100644--- a/src/dashboard-next/pages/home.js+++ b/src/dashboard-next/pages/home.js@@ -902,6 +902,7 @@ function renderQuickActions(host, { avatars = [], agents = [] } = {}) {defaults.push({ href: '/gallery-picker', title: 'Browse avatar gallery', sub: 'Explore public 3D avatars', iconKey: '/gallery-picker', cat: 'Create & Build' },{ href: '/dashboard/widgets', title: 'Embed an agent', sub: 'Drop-in chat widget for any site', iconKey: '/dashboard/widgets', cat: 'Distribute & Embed' },+ { href: '/dashboard/creator', title: 'Creator Studio', sub: 'Price skills, track earnings, get paid', iconKey: '/dashboard/creator', cat: 'Monetize & Earn' },{ href: '/voice', title: 'Voice Lab', sub: 'Clone your voice for avatars', iconKey: '/voice', cat: 'Create & Build' },{ href: repHref, title: 'Reputation', sub: 'On-chain reviews and attestations', iconKey: '/reputation', cat: 'Agents & Identity' },{ href: '/dashboard/api', title: 'API keys', sub: 'REST + MCP for your agents', iconKey: '/dashboard/api', cat: 'Distribute & Embed' },diff --git a/src/reasoning-ledger.js b/src/reasoning-ledger.jsnew file mode 100644index 000000000..63eb95db2--- /dev/null+++ b/src/reasoning-ledger.js@@ -0,0 +1,382 @@+// The Reasoning Ledger — frontend surface.+//+// A readable, filterable timeline of an agent's decisions with the rationale,+// prediction, and resolved outcome (right/wrong, by how much), plus the headline+// reputation with a "how is this computed" drill-down, a calibration chart, and a+// verification badge that re-checks the on-chain anchor on demand. Being wrong is+// made visible — honesty is the trust signal.++import { apiFetch } from './api.js';++const root = document.getElementById('rl-root');++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}+function shortId(id) { return id ? `${id.slice(0, 8)}…${id.slice(-4)}` : ''; }+function shortHash(h) { return h ? `${h.slice(0, 10)}…` : ''; }+function fmtSol(n) { return (n >= 0 ? '+' : '') + Number(n).toFixed(4) + ' SOL'; }+function fmtPct(n) { return (n >= 0 ? '+' : '') + Number(n).toFixed(1) + '%'; }+function timeAgo(iso) {+ const t = new Date(iso).getTime();+ if (!Number.isFinite(t)) return '';+ const s = Math.max(0, (Date.now() - t) / 1000);+ if (s < 60) return `${Math.floor(s)}s ago`;+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;+ return `${Math.floor(s / 86400)}d ago`;+}++function readAgentId() {+ const m = location.pathname.match(/\/ledger\/([^/?#]+)/);+ if (m) return decodeURIComponent(m[1]);+ const qs = new URLSearchParams(location.search);+ return qs.get('agent') || qs.get('id') || null;+}++const state = {+ agentId: readAgentId(),+ data: null,+ verify: null,+ filters: { kind: '', q: '' },+ beforeSeq: null,+ entries: [],+ loadingMore: false,+};++// ── Fetch ────────────────────────────────────────────────────────────────────++async function fetchLedger({ append = false } = {}) {+ const params = new URLSearchParams();+ params.set('limit', '40');+ if (state.filters.kind) params.set('kind', state.filters.kind);+ if (state.filters.q) params.set('q', state.filters.q);+ if (append && state.beforeSeq != null) params.set('before', String(state.beforeSeq));+ const res = await apiFetch(`/api/ledger/${encodeURIComponent(state.agentId)}?${params}`);+ if (!res.ok) throw new Error(`ledger ${res.status}`);+ const json = await res.json();+ if (append) {+ state.entries = state.entries.concat(json.decisions);+ } else {+ state.data = json;+ state.entries = json.decisions;+ }+ state.beforeSeq = json.paging?.next_before_seq ?? null;+ return json;+}++async function fetchVerify() {+ try {+ const res = await apiFetch(`/api/ledger/verify/${encodeURIComponent(state.agentId)}`);+ if (!res.ok) throw new Error(`verify ${res.status}`);+ state.verify = await res.json();+ } catch {+ state.verify = { status: 'error' };+ }+}++// ── Render: score ring + calibration chart ────────────────────────────────────++function scoreRing(score) {+ const r = 56, c = 2 * Math.PI * r;+ const pct = Math.max(0, Math.min(100, score)) / 100;+ const dash = (pct * c).toFixed(1);+ const hue = score >= 70 ? '#4ade80' : score >= 45 ? '#fbbf24' : '#f87171';+ return `+ <div class="rl-score-ring">+ <svg viewBox="0 0 132 132" role="img" aria-label="Reputation score ${score} of 100">+ <circle cx="66" cy="66" r="${r}" fill="none" stroke="var(--rl-line)" stroke-width="10" />+ <circle cx="66" cy="66" r="${r}" fill="none" stroke="${hue}" stroke-width="10"+ stroke-linecap="round" stroke-dasharray="${dash} ${c.toFixed(1)}" />+ </svg>+ <div class="rl-score-num">+ <span class="rl-score-val" style="color:${hue}">${score}</span>+ <span class="rl-score-cap">/ 100</span>+ </div>+ </div>`;+}++function calibrationChart(rep) {+ const buckets = (rep.calibration || []).filter((b) => b.count > 0 && b.predicted != null && b.actual != null);+ const S = 300, pad = 34;+ const x = (v) => pad + v * (S - 2 * pad);+ const y = (v) => S - pad - v * (S - 2 * pad);+ const maxN = Math.max(1, ...buckets.map((b) => b.count));+ const grid = [0, 0.25, 0.5, 0.75, 1].map((g) =>+ `<line x1="${x(g)}" y1="${y(0)}" x2="${x(g)}" y2="${y(1)}" stroke="var(--rl-line-2)" stroke-width="1"/>+ <line x1="${x(0)}" y1="${y(g)}" x2="${x(1)}" y2="${y(g)}" stroke="var(--rl-line-2)" stroke-width="1"/>`).join('');+ const dots = buckets.map((b) => {+ const rr = 4 + 7 * (b.count / maxN);+ const off = Math.abs(b.predicted - b.actual);+ const col = off < 0.1 ? '#4ade80' : off < 0.25 ? '#fbbf24' : '#f87171';+ return `<circle cx="${x(b.predicted).toFixed(1)}" cy="${y(b.actual).toFixed(1)}" r="${rr.toFixed(1)}"+ fill="${col}" fill-opacity="0.7" stroke="${col}" stroke-width="1.5">+ <title>${b.label}: predicted ${(b.predicted * 100).toFixed(0)}%, actual ${(b.actual * 100).toFixed(0)}% (n=${b.count})</title>+ </circle>`;+ }).join('');+ return `+ <svg class="rl-cal-chart" viewBox="0 0 ${S} ${S}" role="img" aria-label="Calibration: predicted confidence vs actual hit rate">+ ${grid}+ <line x1="${x(0)}" y1="${y(0)}" x2="${x(1)}" y2="${y(1)}" stroke="var(--rl-cyan)" stroke-width="1.5" stroke-dasharray="5 4"/>+ ${dots}+ <text x="${S / 2}" y="${S - 6}" text-anchor="middle" fill="var(--rl-dim)" font-size="11" font-family="var(--rl-mono)">predicted confidence →</text>+ <text x="12" y="${S / 2}" text-anchor="middle" fill="var(--rl-dim)" font-size="11" font-family="var(--rl-mono)" transform="rotate(-90 12 ${S / 2})">actual hit rate →</text>+ </svg>`;+}++// ── Render: reputation card ───────────────────────────────────────────────────++function repCard(rep) {+ const ece = rep.calibration_error;+ const compRows = rep.components.map((c) => `+ <div class="rl-comp">+ <span class="rl-comp-label">${esc(c.label)}</span>+ <span class="rl-comp-bar"><i style="width:${Math.round(c.value * 100)}%"></i></span>+ <span class="rl-comp-val">${(c.value * 100).toFixed(0)}% ×${c.weight}</span>+ </div>+ <div class="rl-comp-desc">${esc(c.description)} → +${(c.contribution * 100).toFixed(1)} pts</div>`).join('');++ return `+ <section class="rl-card">+ <div class="rl-card-head"><h2>Reputation</h2></div>+ <div class="rl-rep-grid">+ ${scoreRing(rep.score)}+ <dl class="rl-rep-stats">+ <div class="rl-stat"><dt>Hit rate</dt><dd>${rep.sample_size ? (rep.hit_rate * 100).toFixed(0) + '%' : '—'} <small>${rep.wins}W / ${rep.losses}L</small></dd></div>+ <div class="rl-stat"><dt>Reconciled</dt><dd>${rep.sample_size} <small>of ${rep.decisions_total}</small></dd></div>+ <div class="rl-stat"><dt>Calibration err</dt><dd>${ece != null ? (ece * 100).toFixed(1) + '%' : '—'}</dd></div>+ <div class="rl-stat"><dt>Net realized</dt><dd class="${rep.net_pnl_sol > 0 ? 'pos' : rep.net_pnl_sol < 0 ? 'neg' : ''}">${rep.net_pnl_sol ? fmtSol(rep.net_pnl_sol) : '—'}</dd></div>+ <div class="rl-stat"><dt>Pending</dt><dd>${rep.pending_count}</dd></div>+ <div class="rl-stat"><dt>Confidence</dt><dd>${(rep.confidence * 100).toFixed(0)}%</dd></div>+ </dl>+ </div>+ <div class="rl-verify-row" id="rl-verify-row"></div>+ <details class="rl-drill">+ <summary>How is this score computed?</summary>+ <div class="rl-formula">${esc(rep.formula)}</div>+ ${compRows}+ </details>+ </section>++ <section class="rl-card">+ <div class="rl-card-head"><h2>Calibration</h2></div>+ ${rep.sample_size > 0 ? `+ <div class="rl-cal-wrap">+ ${calibrationChart(rep)}+ <div class="rl-cal-legend">+ <p>Does an ${'80%'}-confidence call actually hit 80% of the time? Each dot is a confidence band — on the dashed line means perfectly calibrated.</p>+ <p><span class="rl-cal-swatch" style="background:#4ade80"></span><b>Well calibrated</b> (<10% off)<br>+ <span class="rl-cal-swatch" style="background:#fbbf24"></span>Slightly off<br>+ <span class="rl-cal-swatch" style="background:#f87171"></span>Poorly calibrated</p>+ <p>Dot size = number of calls in that band.</p>+ </div>+ </div>` : `<p class="rl-state" style="padding:20px">No reconciled calls yet — calibration appears once outcomes are resolved.</p>`}+ </section>`;+}++function verifyBadge() {+ const v = state.verify;+ if (!v) return `<button class="rl-verify is-checking" id="rl-verify-btn"><span class="rl-vdot"></span>Verifying chain…</button>`;+ let cls = 'rl-verify', label = 'Re-verify chain';+ if (v.status === 'verified') { cls += ' is-verified'; label = 'Verified · on-chain anchored'; }+ else if (v.status === 'verified_unanchored') { cls += ' is-unanchored'; label = 'Chain intact · anchor pending'; }+ else if (v.status === 'verification_failed') { cls += ' is-failed'; label = `Tamper detected${v.chain?.broken_at ? ` at #${v.chain.broken_at}` : ''}`; }+ else if (v.status === 'empty') { label = 'No decisions yet'; }+ else { cls += ' is-failed'; label = 'Verification unavailable'; }+ const anchor = v.anchor && v.anchor.explorer_url+ ? `<a class="rl-anchor-link" href="${esc(v.anchor.explorer_url)}" target="_blank" rel="noopener">anchor tx ↗</a>`+ : '';+ const head = v.chain?.head_hash ? `<span class="rl-hash" title="${esc(v.chain.head_hash)}">head ${shortHash(v.chain.head_hash)}</span>` : '';+ return `<button class="${cls}" id="rl-verify-btn"><span class="rl-vdot"></span>${esc(label)}</button>${anchor}${head}`;+}++// ── Render: timeline ──────────────────────────────────────────────────────────++function entryCard(d) {+ const o = d.outcome || { status: 'pending' };+ let cls = 'pending', chip = '<span class="rl-chip pending">Pending outcome</span>';+ if (o.status === 'reconciled') {+ const win = o.was_correct;+ cls = win ? 'win' : 'loss';+ const pnl = o.pnl_sol != null ? ` · ${fmtSol(o.pnl_sol)}` : '';+ chip = `<span class="rl-chip ${cls}">${win ? '✓ Right' : '✗ Wrong'}${pnl}</span>`;+ if (o.proof_url) chip += ` <a class="rl-proof" href="${esc(o.proof_url)}" target="_blank" rel="noopener">on-chain proof ↗</a>`;+ }+ const pred = d.prediction?.basis ? `<span class="rl-chip">predicted: ${esc(d.prediction.basis)}</span>` : '';+ const subj = d.subject_ref ? `<span class="rl-chip">${esc(String(d.subject_ref).slice(0, 12))}…</span>` : '';+ return `+ <article class="rl-entry ${cls}">+ <div class="rl-entry-top">+ <span class="rl-kind">${esc(d.kind)}</span>+ <span class="rl-seq">#${d.seq}</span>+ <span class="rl-conf">${d.confidence != null ? (d.confidence * 100).toFixed(0) + '% conf' : ''}</span>+ <span class="rl-when">${esc(timeAgo(d.decided_at))}</span>+ </div>+ <p class="rl-rationale">${esc(d.rationale)}</p>+ <div class="rl-entry-foot">+ ${chip} ${pred} ${subj}+ <span class="rl-hash" title="${esc(d.entry_hash)}">${shortHash(d.entry_hash)}</span>+ </div>+ </article>`;+}++function timelineSection() {+ if (!state.entries.length) {+ return `<section class="rl-card"><div class="rl-state"><h3>No decisions match</h3><p>Try clearing the filters, or this agent hasn't logged a decision of this kind yet.</p></div></section>`;+ }+ const rows = state.entries.map(entryCard).join('');+ const more = state.beforeSeq != null+ ? `<button class="rl-more" id="rl-more-btn">Load older decisions</button>`+ : '';+ return `+ <section>+ <div class="rl-filters">+ <div class="rl-search"><input id="rl-q" type="search" placeholder="Search rationale or token…" value="${esc(state.filters.q)}" aria-label="Search decisions" /></div>+ <select class="rl-select" id="rl-kind" aria-label="Filter by kind">+ <option value="">All kinds</option>+ <option value="snipe"${state.filters.kind === 'snipe' ? ' selected' : ''}>Snipe</option>+ <option value="exit"${state.filters.kind === 'exit' ? ' selected' : ''}>Exit</option>+ <option value="bounty_award"${state.filters.kind === 'bounty_award' ? ' selected' : ''}>Bounty award</option>+ <option value="moderation"${state.filters.kind === 'moderation' ? ' selected' : ''}>Moderation</option>+ </select>+ </div>+ <div class="rl-timeline">${rows}</div>+ ${more}+ </section>`;+}++// ── Render: shells ────────────────────────────────────────────────────────────++function hero(agent) {+ const img = agent?.image+ ? `<img class="rl-agent-avatar" src="${esc(agent.image)}" alt="" />`+ : `<div class="rl-agent-avatar"></div>`;+ const name = agent?.name ? esc(agent.name) : 'Agent';+ return `+ <p class="rl-kicker"><span class="rl-dot"></span>Auditable track record · tamper-evident</p>+ <h1 class="rl-title" id="rl-title">Reasoning Ledger</h1>+ <p class="rl-sub">Every consequential call this agent made — what it decided, why, what it predicted, and what actually happened. Anchored on-chain and independently verifiable. Being wrong is shown, not hidden.</p>+ <div class="rl-agent-head">+ ${img}+ <div>+ <p class="rl-agent-name">${name}</p>+ <p class="rl-agent-id"><a href="/agents/${esc(state.agentId)}">${shortId(state.agentId)} ↗</a></p>+ </div>+ </div>`;+}++function renderLoading() {+ root.innerHTML = `+ ${hero(null)}+ <section class="rl-card"><div class="rl-skel rl-skel-card"></div></section>+ <section class="rl-card"><div class="rl-skel rl-skel-line" style="width:40%"></div><div class="rl-skel rl-skel-card"></div></section>`;+}++function renderEmptyPrompt() {+ root.innerHTML = `+ ${hero(null).replace(/<div class="rl-agent-head">[\s\S]*$/, '')}+ <section class="rl-card"><div class="rl-state">+ <h3>Pick an agent to audit</h3>+ <p>The Reasoning Ledger is per-agent. Open any trader from the leaderboard to interrogate its decisions and verify its track record.</p>+ <a class="rl-btn" href="/leaderboard">Open the leaderboard →</a>+ </div></section>`;+}++function renderError(err) {+ root.innerHTML = `+ ${hero(state.data?.agent)}+ <section class="rl-card"><div class="rl-state">+ <h3>Couldn't load this ledger</h3>+ <p>${esc(err?.message || 'Something went wrong.')}</p>+ <button class="rl-btn" id="rl-retry">Try again</button>+ </div></section>`;+ document.getElementById('rl-retry')?.addEventListener('click', boot);+}++function renderNoDecisions() {+ root.innerHTML = `+ ${hero(state.data?.agent)}+ ${repCard(state.data.reputation)}+ <section class="rl-card"><div class="rl-state">+ <h3>No decisions recorded yet</h3>+ <p>Once this agent makes a consequential, on-chain call — a snipe, an exit, an award — it lands here with its reasoning and, after settlement, its real outcome.</p>+ <a class="rl-btn" href="/agents/${esc(state.agentId)}">View agent profile →</a>+ </div></section>`;+ mountVerify();+}++function renderAll() {+ if (!state.entries.length && state.data.reputation.decisions_total === 0) {+ return renderNoDecisions();+ }+ root.innerHTML = `+ ${hero(state.data.agent)}+ ${repCard(state.data.reputation)}+ ${timelineSection()}`;+ mountVerify();+ wireFilters();+}++// ── Wiring ────────────────────────────────────────────────────────────────────++function mountVerify() {+ const row = document.getElementById('rl-verify-row');+ if (row) row.innerHTML = verifyBadge();+ document.getElementById('rl-verify-btn')?.addEventListener('click', async () => {+ state.verify = null;+ mountVerify();+ await fetchVerify();+ mountVerify();+ });+}++let qTimer = null;+function wireFilters() {+ document.getElementById('rl-kind')?.addEventListener('change', (e) => {+ state.filters.kind = e.target.value;+ reloadTimeline();+ });+ document.getElementById('rl-q')?.addEventListener('input', (e) => {+ clearTimeout(qTimer);+ const v = e.target.value;+ qTimer = setTimeout(() => { state.filters.q = v.trim(); reloadTimeline(); }, 300);+ });+ document.getElementById('rl-more-btn')?.addEventListener('click', loadMore);+}++async function reloadTimeline() {+ state.beforeSeq = null;+ try {+ await fetchLedger({ append: false });+ renderAll();+ // keep focus on the search box across re-render+ const q = document.getElementById('rl-q');+ if (q && state.filters.q) { q.focus(); q.setSelectionRange(q.value.length, q.value.length); }+ } catch (e) { renderError(e); }+}++async function loadMore() {+ if (state.loadingMore || state.beforeSeq == null) return;+ state.loadingMore = true;+ const btn = document.getElementById('rl-more-btn');+ if (btn) { btn.disabled = true; btn.textContent = 'Loading…'; }+ try {+ await fetchLedger({ append: true });+ renderAll();+ } catch (e) { renderError(e); }+ finally { state.loadingMore = false; }+}++async function boot() {+ if (!state.agentId) return renderEmptyPrompt();+ renderLoading();+ try {+ await fetchLedger({ append: false });+ renderAll();+ fetchVerify().then(mountVerify); // verify in the background, then upgrade the badge+ } catch (e) {+ renderError(e);+ }+}++boot();diff --git a/src/shared/agent-tip.js b/src/shared/agent-tip.jsindex c20fc8f58..6f48c716c 100644--- a/src/shared/agent-tip.js+++ b/src/shared/agent-tip.js@@ -81,13 +81,18 @@ async function waitForConfirmation(conn, signature, timeoutMs = 60_000) {** @param {object} opts* @param {string} opts.toAddress Recipient base58 address (agent's solana_address).- * @param {'SOL'|'USDC'} [opts.token='SOL']+ * @param {'SOL'|'USDC'|'SPL'} [opts.token='SOL'] 'SPL' transfers an arbitrary+ * SPL token supplied at runtime via opts.mint + opts.decimals (coin-agnostic+ * plumbing — the caller chooses the mint; this module hardcodes none).+ * @param {string} [opts.mint] SPL mint (base58), required when token==='SPL'.+ * @param {number} [opts.decimals] SPL token decimals, required when token==='SPL'.+ * @param {string} [opts.noBalanceMsg] Custom "you hold none" error copy for the SPL branch.* @param {number} opts.amount Human amount (e.g. 0.1 SOL or 5 USDC).* @param {'mainnet'|'devnet'} [opts.network='mainnet']* @param {(stage: string) => void} [opts.onStage] Lifecycle: 'connecting'|'building'|'signing'|'sending'|'confirming'.* @returns {Promise<{ signature: string, explorerUrl: string, from: string }>}*/-export async function tipAgent({ toAddress, token = 'SOL', amount, network = 'mainnet', onStage } = {}) {+export async function tipAgent({ toAddress, token = 'SOL', amount, mint: splMint, decimals: splDecimals, noBalanceMsg, network = 'mainnet', onStage } = {}) {const stage = (s) => { try { onStage?.(s); } catch { /* listener best-effort */ } };if (!toAddress || !BASE58_RE.test(String(toAddress))) {@@ -146,6 +151,33 @@ export async function tipAgent({ toAddress, token = 'SOL', amount, network = 'ma}const raw = BigInt(Math.round(amt * 10 ** USDC_DECIMALS));tx.add(createTransferCheckedInstruction(fromAta, mint, toAta, from, raw, USDC_DECIMALS, [], TOKEN_PROGRAM_ID));+ } else if (token === 'SPL') {+ // Generic SPL transfer — the mint + decimals are supplied at runtime by+ // the caller (e.g. the Living Stages tip flow passing the $THREE mint). This+ // module hardcodes no token; it only moves whatever the caller names.+ if (!splMint || !BASE58_RE.test(String(splMint))) {+ throw new TipError('Missing or invalid token mint for this tip.', 'bad_mint');+ }+ const dec = Number.isInteger(splDecimals) && splDecimals >= 0 && splDecimals <= 18 ? splDecimals : 6;+ const mint = new PublicKey(String(splMint));+ const fromAta = await getAssociatedTokenAddress(mint, from);+ const toAta = await getAssociatedTokenAddress(mint, to);+ try {+ await getAccount(connection, fromAta);+ } catch {+ throw new TipError(noBalanceMsg || 'Your wallet holds none of this token to tip with.', 'no_balance');+ }+ let recipientHasAta = true;+ try {+ await getAccount(connection, toAta);+ } catch {+ recipientHasAta = false;+ }+ if (!recipientHasAta) {+ tx.add(createAssociatedTokenAccountInstruction(from, toAta, to, mint));+ }+ const raw = BigInt(Math.round(amt * 10 ** dec));+ tx.add(createTransferCheckedInstruction(fromAta, mint, toAta, from, raw, dec, [], TOKEN_PROGRAM_ID));} else {const lamports = Math.round(amt * LAMPORTS_PER_SOL);tx.add(SystemProgram.transfer({ fromPubkey: from, toPubkey: to, lamports }));diff --git a/src/stage-net.js b/src/stage-net.jsnew file mode 100644index 000000000..73b40fdc8--- /dev/null+++ b/src/stage-net.js@@ -0,0 +1,276 @@+// Realtime client for /stage — wraps colyseus.js with a small event API so+// stage.js can subscribe to the live show without knowing Colyseus. Mirrors+// irl-net.js / walk-net.js in shape (status model, single-retry reconnect, no+// storms) so the transports read the same.+//+// It joins the stage_world room for a given stageId and relays:+// • host — the host's performance frame (caption/beat/cue/speaking) as it+// changes, so the page renders captions + animation in sync.+// • utterance — the timed spoken beat { id, text, voice, cue, durationMs }; the+// page fetches TTS for it and plays spatial voice + lip-sync.+// • audience — the live crowd (count + members) for the 3D venue.+// • tip — a settled tip event (ticker + crowd cheer), within ~1s.+// • leaderboard— the synced top-tippers board.+// • reaction — an emoji another audience member fired.+//+// Graceful degradation: if no server is configured or the socket can't be+// reached after one retry, it settles into a distinct status so the page shows an+// honest "performance feed offline" state — captions/tips still work via polling.++import { Client, getStateCallbacks } from 'colyseus.js';+import { StageState } from '../multiplayer/src/stage-schemas.js';+import { joinRoomWithTimeout } from './shared/colyseus-connect.js';+import { log } from './shared/log.js';++const ROOM_NAME = 'stage_world';+const MAX_RETRIES = 1;++// Same resolution chain as irl-net: explicit override → meta → env → Codespaces+// port forwarding → same-host:2567 in dev. '' in prod with none set ⇒ poll mode.+function defaultServerUrl() {+ if (typeof window !== 'undefined') {+ if (window.STAGE_SERVER_URL) return String(window.STAGE_SERVER_URL).trim().replace(/\/$/, '');+ if (window.WALK_SERVER_URL) return String(window.WALK_SERVER_URL).trim().replace(/\/$/, '');+ }+ if (typeof document !== 'undefined') {+ for (const name of ['stage-server', 'walk-server']) {+ const v = document.querySelector(`meta[name="${name}"]`)?.getAttribute('content')?.trim();+ if (v) return v.replace(/\/$/, '');+ }+ }+ try {+ const envUrl = import.meta?.env?.VITE_STAGE_SERVER_URL || import.meta?.env?.VITE_WALK_SERVER_URL;+ if (envUrl) return String(envUrl).trim().replace(/\/$/, '');+ } catch (_) {}+ if (typeof location !== 'undefined') {+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';+ const host = location.hostname;+ const fwd = host.match(/^(.*)-(\d+)\.(app\.github\.dev|githubpreview\.dev|gitpod\.io)$/);+ if (fwd) return `${proto}//${fwd[1]}-2567.${fwd[3]}`;+ let isProd = false;+ try { isProd = import.meta?.env?.PROD === true; } catch (_) {}+ const isLocalHost = host === 'localhost' || host === '127.0.0.1';+ if (!isProd || isLocalHost) return `${proto}//${host}:2567`;+ return '';+ }+ return '';+}++export class StageNet {+ constructor(opts = {}) {+ this.stageId = String(opts.stageId || '');+ this.name = opts.name || '';+ this.avatar = opts.avatar || '';+ this.url = opts.url || defaultServerUrl();++ this.client = null;+ this.room = null;+ this.status = 'idle'; // idle | connecting | online | offline | failed | unavailable+ this.error = null;+ this.sessionId = null;+ this._handlers = {+ status: new Set(),+ host: new Set(),+ utterance: new Set(),+ audience: new Set(),+ tip: new Set(),+ leaderboard: new Set(),+ reaction: new Set(),+ };+ this._retries = 0;+ this._reconnectTimer = null;+ this._destroyed = false;+ this._connectGen = 0;+ this._audienceQueued = false;+ this._hb = null;+ }++ on(event, fn) {+ const bucket = this._handlers[event];+ if (!bucket) throw new Error(`StageNet: unknown event "${event}"`);+ bucket.add(fn);+ return () => bucket.delete(fn);+ }++ _emit(event, ...args) {+ for (const fn of this._handlers[event]) {+ try { fn(...args); } catch (e) { log.error(`[stage-net] ${event} handler threw:`, e); }+ }+ }++ _setStatus(status, error = null) {+ this.status = status;+ this.error = error;+ this._emit('status', { status, error });+ }++ _closeRoom() {+ const room = this.room;+ if (this._hb) { clearInterval(this._hb); this._hb = null; }+ if (!room) return;+ this.room = null;+ try { room.removeAllListeners(); } catch {}+ try { room.leave(); } catch {}+ }++ async connect() {+ if (this._destroyed) return;+ this._closeRoom();+ if (!this.url || !this.stageId) {+ this._setStatus('unavailable');+ return;+ }+ const gen = ++this._connectGen;+ this._setStatus('connecting');+ try {+ this.client = new Client(this.url);+ const room = await joinRoomWithTimeout(this.client, ROOM_NAME, {+ stageId: this.stageId,+ name: this.name,+ avatar: this.avatar,+ }, StageState);+ if (this._destroyed || gen !== this._connectGen) {+ try { room.leave(); } catch {}+ return;+ }+ this.room = room;+ this.sessionId = room.sessionId;+ this._retries = 0;++ const $ = getStateCallbacks(this.room);++ // Host performance frame — emit the full host snapshot on any change.+ const $host = $(this.room.state)?.host;+ if ($host) {+ $host.onChange(() => this._emit('host', snapshotHost(this.room.state.host)));+ }++ // Audience — coalesce the join-time burst into one emit.+ const $aud = $(this.room.state)?.audience;+ if ($aud) {+ $aud.onAdd((m) => { $(m).onChange(() => this._queueAudience()); this._queueAudience(); });+ $aud.onRemove(() => this._queueAudience());+ }++ // Leaderboard — the synced top-tippers array.+ const $lb = $(this.room.state)?.leaderboard;+ if ($lb) {+ $lb.onAdd(() => this._emitLeaderboard());+ $lb.onRemove(() => this._emitLeaderboard());+ $lb.onChange?.(() => this._emitLeaderboard());+ }++ // Transient broadcasts.+ this.room.onMessage('utterance', (msg) => this._emit('utterance', msg));+ this.room.onMessage('tip', (msg) => this._emit('tip', msg));+ this.room.onMessage('reaction', (msg) => this._emit('reaction', msg));+ this.room.onMessage('question_ack', (msg) => this._emit('reaction', { ack: msg }));++ this.room.onLeave((code) => {+ if (this._destroyed || code === 1000) return;+ this._setStatus('offline');+ this._scheduleReconnect();+ });+ this.room.onError((code, message) => log.warn('[stage-net] room.onError', code, message));++ // Initial full snapshots + a heartbeat so the reaper keeps us.+ this._emit('host', snapshotHost(this.room.state.host));+ this._emitLeaderboard();+ this._queueAudience();+ this._hb = setInterval(() => { try { this.room?.send('heartbeat'); } catch {} }, 15_000);++ this._setStatus('online');+ } catch (err) {+ const reason = err?.message || (err?.code != null ? `code ${err.code}` : String(err));+ log.warn('[stage-net] connect failed:', reason);+ this._setStatus('failed', reason);+ this._scheduleReconnect();+ }+ }++ _scheduleReconnect() {+ if (this._reconnectTimer || this._destroyed) return;+ if (this._retries >= MAX_RETRIES) {+ this._setStatus('unavailable', this.error);+ return;+ }+ this._retries++;+ const delay = 2500 + Math.random() * 1500;+ this._reconnectTimer = setTimeout(() => {+ this._reconnectTimer = null;+ if (this._destroyed) return;+ this.connect();+ }, delay);+ }++ react(emoji) {+ if (this.status !== 'online' || !this.room) return;+ try { this.room.send('reaction', { emoji: String(emoji) }); } catch (e) {+ log.warn('[stage-net] reaction send failed:', e?.message || e);+ }+ }++ ask(text) {+ if (this.status !== 'online' || !this.room) return false;+ try { this.room.send('question', { text: String(text) }); return true; } catch (e) {+ log.warn('[stage-net] question send failed:', e?.message || e);+ return false;+ }+ }++ _queueAudience() {+ if (this._audienceQueued || this._destroyed) return;+ this._audienceQueued = true;+ Promise.resolve().then(() => {+ this._audienceQueued = false;+ this._emitAudience();+ });+ }++ _emitAudience() {+ if (this._destroyed || !this.room) return;+ const map = this.room.state?.audience;+ if (!map) return;+ const members = [];+ map.forEach((m, id) => {+ members.push({ id, name: m.name || '', avatar: m.avatar || '', x: m.x, z: m.z, vip: !!m.vip, reaction: m.reaction || '', reactionTs: m.reactionTs });+ });+ this._emit('audience', { count: members.length, members, selfId: this.room.sessionId });+ }++ _emitLeaderboard() {+ if (this._destroyed || !this.room) return;+ const lb = this.room.state?.leaderboard;+ if (!lb) return;+ const rows = [];+ lb.forEach((t) => rows.push({ label: t.label, total: Number(t.total), count: t.count }));+ this._emit('leaderboard', {+ rows,+ totalTipsAtomic: Number(this.room.state.totalTipsAtomic || 0),+ tipCount: this.room.state.tipCount || 0,+ phase: this.room.state.phase,+ });+ }++ retry() {+ if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }+ this._retries = 0;+ this.connect();+ }++ destroy() {+ this._destroyed = true;+ if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }+ this._closeRoom();+ this.client = null;+ }+}++function snapshotHost(h) {+ if (!h) return null;+ return {+ agentId: h.agentId, name: h.name, avatar: h.avatar, voice: h.voice,+ utteranceId: h.utteranceId, beat: h.beat, caption: h.caption, cue: h.cue,+ speaking: h.speaking, startedAtMs: h.startedAtMs,+ };+}diff --git a/src/three-access.js b/src/three-access.jsindex 8e23d7cf0..b90f90b11 100644--- a/src/three-access.js+++ b/src/three-access.js@@ -342,6 +342,92 @@ export function renderInlineLock(target, access) {` · <a href="${ECONOMY_URL}">Get $THREE →</a></span>`;}+// ── High-level holder-value API (the documented one-import surface) ────────────+// renderTierBadge / requireTier / gateAffordance are the named, stable entry+// points other surfaces import. They are thin wrappers over the data + UI helpers+// above so there is exactly ONE client holder gate — these add ergonomics, not a+// second implementation. The canonical upgrade destination is ECONOMY_URL (/three).++/**+ * Render a tier chip for an ALREADY-resolved tier object (synchronous) — the+ * companion to {@link mountTierBadge}, which fetches the tier itself. Hides the+ * chip for non-holders (Member / level 0) so it never reads as a false signal.+ * @param {Element|string} target+ * @param {{ id?:string, label?:string, level?:number, held_usd?:number }|null} tier+ */+export function renderTierBadge(target, tier) {+ const el = typeof target === 'string' ? document.querySelector(target) : target;+ if (!el) return;+ injectStyles();+ if (!tier || (Number(tier.level) || 0) < 1) {+ el.hidden = true;+ el.innerHTML = '';+ return;+ }+ el.hidden = false;+ const held =+ Number(tier.held_usd) > 0+ ? ` · $${Number(tier.held_usd).toLocaleString('en-US', { maximumFractionDigits: 0 })} held`+ : '';+ el.innerHTML =+ `<a class="tg-badge tg-tier-${escapeHtml(tier.id || 'member')}" href="${ECONOMY_URL}" ` ++ `aria-label="Your $THREE tier: ${escapeHtml(tier.label || 'Holder')}" ` ++ `title="Your $THREE holder tier — what it unlocks${held}">` ++ `<span class="tg-tier-mark" aria-hidden="true">◆</span>` ++ `<span class="tg-tier-label">${escapeHtml(tier.label || 'Holder')}</span></a>`;+}++/**+ * Resolve whether the caller may use a gated feature. The single eligibility read+ * a surface calls before exposing an affordance.+ * @param {string} featureId a key of GATED_FEATURES (server: three-access.js)+ * @returns {Promise<{ allowed:boolean, tier:object|null, access:object|null, upgradeUrl:string }>}+ * `allowed` is false on a clean "insufficient tier" AND on a network failure+ * (caller renders the locked state; the server stays the only authority on the+ * actual action). `upgradeUrl` is the canonical /three tier surface.+ */+export async function requireTier(featureId) {+ const data = await getAccess(featureId);+ const access = data?.access || null;+ return {+ allowed: Boolean(access?.eligible),+ tier: data?.tier || null,+ access,+ upgradeUrl: ECONOMY_URL,+ };+}++/**+ * Wire a gated affordance to the shared holder gate: read the feature's access,+ * reflect locked/unlocked on the control, and (when eligible) run `onUnlock`.+ * A locked control is marked disabled + `aria-disabled` and, when `lockEl` is+ * given, gets the inline lock chip beside it (routing to /three). When access+ * can't be read (network failure) the control is LEFT enabled — the server+ * remains the authority and answers with a 402 the caller can route to onGate().+ * @param {Element|string} target+ * @param {{ featureId:string, onUnlock?:(access)=>void, lockEl?:Element|string }} opts+ * @returns {Promise<{ allowed:boolean, access:object|null, tier:object|null, upgradeUrl:string }>}+ */+export async function gateAffordance(target, { featureId, onUnlock, lockEl } = {}) {+ const el = typeof target === 'string' ? document.querySelector(target) : target;+ if (!el || !featureId) return { allowed: false, access: null, tier: null, upgradeUrl: ECONOMY_URL };+ const data = await getAccess(featureId);+ const access = data?.access || null;+ // No access payload → couldn't check; don't hard-block (fail-open), the server+ // gate is authoritative. A real payload drives the locked/unlocked affordance.+ const allowed = access ? Boolean(access.eligible) : true;++ el.classList.toggle('three-locked', !allowed);+ if ('disabled' in el) el.disabled = !allowed;+ el.setAttribute('aria-disabled', String(!allowed));++ const chip = lockEl ? (typeof lockEl === 'string' ? document.querySelector(lockEl) : lockEl) : null;+ if (chip) renderInlineLock(chip, access);++ if (allowed && typeof onUnlock === 'function') onUnlock(access);+ return { allowed, access, tier: data?.tier || null, upgradeUrl: ECONOMY_URL };+}+// ── Upsell modal (402 three_hold_required) ────────────────────────────────────/**diff --git a/tests/api/x402-discovery-green.test.js b/tests/api/x402-discovery-green.test.jsnew file mode 100644index 000000000..50f07804e--- /dev/null+++ b/tests/api/x402-discovery-green.test.js@@ -0,0 +1,168 @@+// Guardrail: the published x402 discovery catalog must stay "fully green" —+// every resource must pass the exact checks the open indexers (CDP Bazaar /+// agentic.market, x402scan, 402index) run, the same ones+// scripts/verify-x402-discovery.mjs enforces against the live catalog. A single+// malformed resource (a newline in payTo, a bazaar.info that fails its own+// schema, a missing output.example) silently delists us from discovery — that's+// how we once lost all 43 resources to one stray newline.+//+// This renders the catalog locally (no deploy/network) and asserts ZERO errors+// AND ZERO warnings, so any regression in api/wk.js is a red build before it can+// ship and quietly drop us from the indexes.++import { describe, it, expect, beforeAll } from 'vitest';+import Ajv2020 from 'ajv/dist/2020.js';+import addFormats from 'ajv-formats';++const NETWORK_BASE = 'eip155:8453';+const SOLANA_PREFIX = 'solana:';++const ajv = new Ajv2020({ allErrors: true, strict: false });+addFormats(ajv);++function isAbsoluteHttps(u) {+ try {+ return new URL(u).protocol === 'https:';+ } catch {+ return false;+ }+}+function isPrintableAscii(s, max) {+ return typeof s === 'string' && s.length > 0 && s.length <= max && /^[\x20-\x7e]+$/.test(s);+}+function label(r) {+ return r.toolName ? `${r.path || r.url} :: ${r.toolName}` : r.path || r.url;+}++// Mirrors checkResource() in scripts/verify-x402-discovery.mjs exactly.+function checkResource(r) {+ const errors = [];+ const warnings = [];++ if (!r.url) errors.push('missing resource.url');+ if (!r.description || String(r.description).trim().length < 12)+ warnings.push('description missing or very short (<12 chars)');+ const accepts = Array.isArray(r.accepts) ? r.accepts : [];+ if (!accepts.length) errors.push('no accepts[] — not payable, will not be cataloged');+ accepts.forEach((a, i) => {+ for (const f of ['scheme', 'network', 'amount', 'asset', 'payTo']) {+ if (a[f] == null || a[f] === '') errors.push(`accepts[${i}] missing ${f}`);+ }+ if (typeof a.payTo === 'string' && /\s/.test(a.payTo))+ errors.push(`accepts[${i}].payTo contains whitespace ("${a.payTo}")`);+ });++ const nets = accepts.map((a) => a.network || '');+ const hasBase = nets.includes(NETWORK_BASE);+ const hasSolana = nets.some((n) => n.startsWith(SOLANA_PREFIX));+ if (!hasBase && !hasSolana) warnings.push('advertises neither Base nor Solana');++ if (r.serviceName != null && !isPrintableAscii(r.serviceName, 32))+ warnings.push('serviceName not printable-ASCII ≤32 chars');+ if (r.tags != null) {+ if (!Array.isArray(r.tags) || r.tags.length > 5) warnings.push('tags must be an array of ≤5');+ else if (!r.tags.every((t) => isPrintableAscii(t, 32)))+ warnings.push('a tag is not printable-ASCII ≤32 chars');+ }+ if (r.iconUrl != null && !isAbsoluteHttps(r.iconUrl))+ warnings.push('iconUrl is not an absolute https URL');++ const bazaar = r.extensions?.bazaar || r.bazaar;+ if (!bazaar) {+ errors.push('no bazaar extension');+ } else {+ if (bazaar.discoverable !== true) warnings.push('bazaar.discoverable is not true');+ if (!bazaar.info) errors.push('bazaar.info missing');+ if (!bazaar.schema) {+ warnings.push('bazaar.schema missing');+ } else if (bazaar.info) {+ let validate;+ try {+ validate = ajv.compile(bazaar.schema);+ } catch (e) {+ errors.push(`bazaar.schema does not compile: ${e.message}`);+ }+ if (validate && !validate(bazaar.info)) {+ const detail = (validate.errors || [])+ .map((e) => `${e.instancePath || '/'} ${e.message}`)+ .join('; ');+ errors.push(`bazaar.info FAILS its own schema → CDP rejects: ${detail}`);+ }+ }+ if (!bazaar.info?.output?.example) warnings.push('no output.example');+ }++ return { label: label(r), errors, warnings };+}++async function renderDiscovery() {+ Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',+ X402_PAY_TO_SOLANA: 'So11111111111111111111111111111111111111112',+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ X402_ASSET_MINT_SOLANA: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ X402_ASSET_ADDRESS_ARBITRUM: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',+ X402_MAX_AMOUNT_REQUIRED: '1000',+ X402_FEE_PAYER_SOLANA: 'So11111111111111111111111111111111111111112',+ });+ const mod = await import('../../api/wk.js');+ const res = {+ statusCode: 0,+ headers: {},+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ end(body) {+ this.body = body;+ },+ };+ const req = {+ method: 'GET',+ url: '/.well-known/x402-discovery?name=x402-discovery',+ query: { name: 'x402-discovery' },+ headers: {},+ };+ await mod.default(req, res);+ return JSON.parse(res.body);+}++describe('x402 discovery catalog is fully green', () => {+ let report;+ beforeAll(async () => {+ const doc = await renderDiscovery();+ report = (doc.resources || []).map(checkResource);+ });++ it('catalogs a non-trivial number of resources', () => {+ expect(report.length).toBeGreaterThan(20);+ });++ it('has no errors that would get a resource dropped by the indexers', () => {+ const failing = report.filter((r) => r.errors.length);+ expect(+ failing,+ `Resources the indexers will DROP:\n${failing+ .map((r) => ` ✗ ${r.label}: ${r.errors.join('; ')}`)+ .join('\n')}`,+ ).toEqual([]);+ });++ it('has no listing-quality warnings (every resource ranks and renders fully)', () => {+ const warned = report.filter((r) => r.warnings.length);+ expect(+ warned,+ `Resources with listing-quality warnings:\n${warned+ .map((r) => ` ▲ ${r.label}: ${r.warnings.join('; ')}`)+ .join('\n')}`,+ ).toEqual([]);+ });++ it('every resource carries a real output.example for result cards', async () => {+ const doc = await renderDiscovery();+ for (const r of doc.resources || []) {+ const ex = (r.extensions?.bazaar || r.bazaar)?.info?.output?.example;+ expect(ex, `${label(r)} is missing bazaar.info.output.example`).toBeTruthy();+ }+ });+});