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
Add initial chat application files and assets
nirholas0f8081893add
diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 9b4c8794f..9bc415d61 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -202,6 +202,12 @@ export const env = {return opt('OPENROUTER_API_KEY');},+ // Neynar API key — used by POST /api/agents/:id/memory/seed/farcaster.+ // When unset, the endpoint returns 501 not_configured.+ get NEYNAR_API_KEY() {+ return opt('NEYNAR_API_KEY');+ },+// ElevenLabs API key — used by TTS proxy and voice cloning endpoints.// Never sent to the browser.get ELEVENLABS_API_KEY() {diff --git a/api/_lib/royalty.js b/api/_lib/royalty.jsnew file mode 100644index 000000000..5537ae6aa--- /dev/null+++ b/api/_lib/royalty.js@@ -0,0 +1,209 @@+/**+ * Skill royalty helpers.+ *+ * billSkillRoyalty — fire-and-forget from skill-runtime after a paid skill returns.+ * settleRoyalties — called by the settle-royalties cron; redeems EIP-7710 delegations+ * and marks ledger rows settled or failed.+ */++import { sql } from './db.js';+import { env } from './env.js';++// ── billSkillRoyalty ──────────────────────────────────────────────────────────++/**+ * Record a royalty_ledger debit for a paid skill invocation.+ * Does NOT block the skill — call with queueMicrotask or plain fire-and-forget.+ *+ * @param {{ skillId: string, skillName: string, agentId: string, authorId: string, priceUsd: number }} opts+ */+export async function billSkillRoyalty({ skillId, skillName, agentId, authorId, priceUsd }) {+ try {+ // Verify the agent exists and get its wallet/chain info.+ const [agent] = await sql`+ SELECT id, wallet_address, chain_id+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) {+ console.warn('[royalty] billSkillRoyalty: agent not found', { agentId, skillName });+ return;+ }++ // Check for an active delegation that covers this spend.+ const [delegation] = await sql`+ SELECT id FROM agent_delegations+ WHERE agent_id = ${agentId}+ AND status = 'active'+ AND expires_at > now()+ ORDER BY created_at DESC+ LIMIT 1+ `;++ if (!delegation) {+ console.warn('[royalty] insufficient_balance: no active delegation', {+ agentId,+ skillName,+ priceUsd,+ });+ return;+ }++ await sql`+ INSERT INTO royalty_ledger+ (skill_id, agent_id, author_user_id, price_usd, status)+ VALUES+ (${skillId}, ${agentId}, ${authorId}, ${priceUsd}, 'pending')+ `;+ } catch (e) {+ console.error('[royalty] billSkillRoyalty failed', e?.message);+ }+}++// ── settleRoyalties ───────────────────────────────────────────────────────────++const SETTLE_THRESHOLD_USD = 0.01;++/**+ * Settle all pending royalty_ledger rows for a given author.+ * Groups by (agent_id, chain_id), looks up delegation, redeems via the+ * /api/permissions/redeem relayer endpoint, then marks rows settled or failed.+ *+ * @param {string} authorUserId+ */+export async function settleRoyalties(authorUserId) {+ // Aggregate pending rows by agent + chain.+ const groups = await sql`+ SELECT+ rl.agent_id,+ ai.chain_id,+ ai.wallet_address,+ SUM(rl.price_usd)::float AS total_usd,+ array_agg(rl.id) AS ledger_ids+ FROM royalty_ledger rl+ JOIN agent_identities ai ON ai.id = rl.agent_id+ WHERE rl.author_user_id = ${authorUserId}+ AND rl.status = 'pending'+ GROUP BY rl.agent_id, ai.chain_id, ai.wallet_address+ HAVING SUM(rl.price_usd) >= ${SETTLE_THRESHOLD_USD}+ `;++ for (const group of groups) {+ try {+ const txHash = await _redeemForGroup(group, authorUserId);+ await sql`+ UPDATE royalty_ledger+ SET status = 'settled', settled_at = now(), tx_hash = ${txHash}+ WHERE id = ANY(${group.ledger_ids}::uuid[])+ `;+ } catch (e) {+ console.error('[royalty] settle failed for group', {+ agentId: group.agent_id,+ authorUserId,+ error: e?.message,+ });+ await sql`+ UPDATE royalty_ledger+ SET status = 'failed'+ WHERE id = ANY(${group.ledger_ids}::uuid[])+ `;+ }+ }+}++/**+ * Settle all authors with pending balances above the threshold.+ * Called by the cron job.+ */+export async function settleAllPendingRoyalties() {+ const authors = await sql`+ SELECT DISTINCT author_user_id+ FROM royalty_ledger+ WHERE status = 'pending'+ GROUP BY author_user_id+ HAVING SUM(price_usd) >= ${SETTLE_THRESHOLD_USD}+ `;++ const results = { settled: 0, failed: 0, authors: authors.length };+ for (const { author_user_id } of authors) {+ try {+ await settleRoyalties(author_user_id);+ results.settled++;+ } catch (e) {+ results.failed++;+ console.error('[royalty] settleAllPendingRoyalties: author failed', {+ author_user_id,+ error: e?.message,+ });+ }+ }+ return results;+}++// ── internal ──────────────────────────────────────────────────────────────────++async function _redeemForGroup(group, authorUserId) {+ const { agent_id, chain_id, wallet_address } = group;++ // Find the author's wallet address to send funds to.+ const [author] = await sql`+ SELECT w.address+ FROM user_wallets w+ WHERE w.user_id = ${authorUserId}+ AND (${chain_id}::int IS NULL OR w.chain_id = ${chain_id}::int)+ AND w.is_primary = true+ LIMIT 1+ `;++ if (!author?.address) {+ throw new Error(`no_author_wallet: author ${authorUserId} has no primary wallet`);+ }++ // Find active delegation for this agent/chain.+ const [delegation] = await sql`+ SELECT id, delegation_json, scope+ FROM agent_delegations+ WHERE agent_id = ${agent_id}+ AND chain_id = ${chain_id}+ AND status = 'active'+ AND expires_at > now()+ ORDER BY created_at DESC+ LIMIT 1+ `;++ if (!delegation) {+ throw new Error(`no_delegation: agent ${agent_id} chain ${chain_id}`);+ }++ // Call the relayer endpoint to redeem the delegation.+ const cronSecret = env.CRON_SECRET;+ const issuer = env.ISSUER ?? 'http://localhost:3000';++ const resp = await fetch(`${issuer}/api/permissions/redeem`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${cronSecret}`,+ },+ body: JSON.stringify({+ id: delegation.id,+ calls: [+ {+ // Transfer call: recipient = author wallet, value = 0 (off-chain settlement via ledger).+ // On a real deployment this would be a USDC transferFrom calldata.+ to: author.address,+ value: '0x0',+ data: '0x',+ },+ ],+ }),+ });++ if (!resp.ok) {+ const body = await resp.text().catch(() => '');+ throw new Error(`redeem_failed: ${resp.status} ${body}`);+ }++ const result = await resp.json();+ return result.tx_hash ?? result.txHash ?? null;+}diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 6659171bd..182add6bf 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -294,6 +294,14 @@ alter table agent_identities add column if not exists embed_policy jsonb;alter table agent_identities add column if not exists voice_provider text default 'browser';alter table agent_identities add column if not exists voice_id text;alter table agent_identities add column if not exists voice_cloned_at timestamptz;+alter table agent_identities add column if not exists farcaster_fid integer;+alter table agent_identities add column if not exists farcaster_fname text;+alter table agent_identities add column if not exists farcaster_seeded_at timestamptz;+alter table agent_identities add column if not exists persona_prompt text;+alter table agent_identities add column if not exists persona_prompt_hash text;+alter table agent_identities add column if not exists persona_prompt_sig text;+alter table agent_identities add column if not exists persona_tone_tags jsonb not null default '[]'::jsonb;+alter table agent_identities add column if not exists persona_extracted_at timestamptz;-- ── agent_memories — the agent's persistent context ──────────────────────────create table if not exists agent_memories (@@ -751,3 +759,79 @@ create table if not exists skill_ratings (created_at timestamptz not null default now(),unique (user_id, skill_id));++-- Additive migration: royalty pricing on skills.+alter table marketplace_skills add column if not exists price_per_call_usd numeric(10,6) not null default 0;++-- ── royalty_ledger — per-call micro-payment records ──────────────────────────+create table if not exists royalty_ledger (+ id uuid primary key default gen_random_uuid(),+ skill_id uuid not null references marketplace_skills(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ author_user_id uuid not null references users(id) on delete cascade,+ price_usd numeric(10,6) not null,+ status text not null default 'pending',+ settled_at timestamptz,+ tx_hash text,+ created_at timestamptz not null default now(),+ constraint royalty_ledger_status_check check (status in ('pending', 'settled', 'failed'))+);++create index if not exists royalty_ledger_author_idx on royalty_ledger(author_user_id, created_at desc);+create index if not exists royalty_ledger_agent_idx on royalty_ledger(agent_id, created_at desc);++-- ── subscription_plans — creator monetization plans ───────────────────────────+-- Distinct from the `subscriptions` table (platform billing). These are+-- creator-to-fan recurring payment plans.+create table if not exists subscription_plans (+ id uuid primary key default gen_random_uuid(),+ creator_id uuid not null references users(id) on delete cascade,+ agent_id uuid references agent_identities(id) on delete set null,+ name text not null,+ price_usd numeric(8,2) not null check (price_usd >= 0.99),+ interval text not null default 'monthly' check (interval in ('weekly','monthly')),+ perks text[],+ active boolean not null default true,+ created_at timestamptz not null default now()+);++create index if not exists subscription_plans_creator_idx+ on subscription_plans(creator_id) where active = true;+create index if not exists subscription_plans_agent_idx+ on subscription_plans(agent_id) where agent_id is not null and active = true;++-- ── creator_subscriptions — fan subscriptions to creator plans ────────────────+create table if not exists creator_subscriptions (+ id uuid primary key default gen_random_uuid(),+ plan_id uuid not null references subscription_plans(id),+ subscriber_user_id uuid not null references users(id) on delete cascade,+ status text not null default 'active' check (status in ('active','paused','cancelled','past_due')),+ current_period_start timestamptz not null default now(),+ current_period_end timestamptz not null,+ payment_method text not null default 'x402',+ wallet_address text,+ created_at timestamptz not null default now(),+ cancelled_at timestamptz,+ unique(plan_id, subscriber_user_id)+);++create index if not exists creator_subscriptions_subscriber_idx+ on creator_subscriptions(subscriber_user_id) where status = 'active';+create index if not exists creator_subscriptions_plan_idx+ on creator_subscriptions(plan_id);+create index if not exists creator_subscriptions_due_idx+ on creator_subscriptions(current_period_end) where status = 'active';++-- ── subscription_payments — per-period payment records ────────────────────────+create table if not exists subscription_payments (+ id uuid primary key default gen_random_uuid(),+ subscription_id uuid not null references creator_subscriptions(id),+ amount_usd numeric(8,2) not null,+ status text not null default 'pending' check (status in ('pending','succeeded','failed')),+ tx_hash text,+ paid_at timestamptz,+ created_at timestamptz not null default now()+);++create index if not exists subscription_payments_subscription_idx+ on subscription_payments(subscription_id);diff --git a/api/_lib/skill-runtime.js b/api/_lib/skill-runtime.jsindex 59b25f149..c1a14c32b 100644--- a/api/_lib/skill-runtime.js+++ b/api/_lib/skill-runtime.js@@ -62,9 +62,10 @@ async function loadManifest(name) {* @param {object} [opts.fetch] - fetch impl (defaults to globalThis.fetch)* @param {string} [opts.agentId] - if set, every memory.note is persisted to agent_actions* @param {string} [opts.signerAddress] - persisted with each agent_actions row when agentId is set+ * @param {Record<string, { skill_id: string, author_id: string }>} [opts.skillMeta] - DB-sourced royalty metadata keyed by skill name*/export function makeRuntime(opts = {}) {- const { configOverrides = {}, wallet, onEvent, fetch = globalThis.fetch, agentId, signerAddress } = opts;+ const { configOverrides = {}, wallet, onEvent, fetch = globalThis.fetch, agentId, signerAddress, skillMeta = {} } = opts;let _sql;// Map skill-internal tags to canonical action types so existing// aggregations (spend-policy, portfolio cost-basis) keep working.@@ -125,11 +126,34 @@ export function makeRuntime(opts = {}) {recall: async () => null,},};+ let result;try {- return await fn(args ?? {}, ctx);+ result = await fn(args ?? {}, ctx);} catch (e) {return { ok: false, error: e?.message ?? String(e) };}++ // Fire-and-forget royalty billing for paid skills.+ if (result?.ok !== false && agentId && manifest.price_per_call_usd > 0) {+ const meta = skillMeta[skillName];+ if (meta?.skill_id && meta?.author_id) {+ queueMicrotask(() => {+ import('./royalty.js')+ .then(({ billSkillRoyalty }) =>+ billSkillRoyalty({+ skillId: meta.skill_id,+ skillName,+ agentId,+ authorId: meta.author_id,+ priceUsd: manifest.price_per_call_usd,+ }),+ )+ .catch((e) => console.error('[skill-runtime] royalty billing failed', e?.message));+ });+ }+ }++ return result;}return { invoke };diff --git a/api/agents/_id/memory-seed-farcaster.js b/api/agents/_id/memory-seed-farcaster.jsnew file mode 100644index 000000000..0719ec288--- /dev/null+++ b/api/agents/_id/memory-seed-farcaster.js@@ -0,0 +1,211 @@+// GET /api/agents/:id/memory/seed/farcaster — current link status+// POST /api/agents/:id/memory/seed/farcaster — link Farcaster account & seed memories++import { z } from 'zod';+import { sql } from '../../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { parse } from '../../_lib/validate.js';+import { env } from '../../_lib/env.js';++const bodySchema = z+ .object({+ fid: z.number().int().positive().optional(),+ fname: z.string().trim().min(1).max(64).optional(),+ })+ .refine((d) => d.fid != null || d.fname != null, { message: 'fid or fname required' });++const NEYNAR_BASE = 'https://api.neynar.com/v2/farcaster';+const SEED_COOLDOWN_MS = 6 * 60 * 60 * 1000;++async function neynarGet(path, apiKey) {+ const resp = await fetch(`${NEYNAR_BASE}${path}`, {+ headers: { api_key: apiKey },+ });+ if (!resp.ok) {+ const err = new Error(`Neynar ${resp.status}`);+ err.httpStatus = resp.status;+ throw err;+ }+ return resp.json();+}++async function distillFacts(profile, casts, apiKey) {+ const castTexts = casts+ .slice(0, 50)+ .map((c) => c.text || '')+ .filter(Boolean)+ .join('\n');++ const displayName = profile.display_name || profile.username || '';+ const bio = profile.profile?.bio?.text || '';+ const followers = profile.follower_count ?? 0;+ const userLine = `Display name: ${displayName}, Bio: ${bio || '(none)'}, Followers: ${followers}`;++ const resp = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'anthropic-version': '2023-06-01',+ 'x-api-key': env.ANTHROPIC_API_KEY,+ },+ body: JSON.stringify({+ model: 'claude-haiku-4-5-20251001',+ max_tokens: 1024,+ tools: [+ {+ name: 'extract_memory_facts',+ description:+ 'Extract concise memory facts from a Farcaster profile and recent casts for an AI agent.',+ input_schema: {+ type: 'object',+ properties: {+ facts: {+ type: 'array',+ items: { type: 'string' },+ maxItems: 15,+ description: 'Up to 15 single-sentence facts about the user',+ },+ },+ required: ['facts'],+ },+ },+ ],+ tool_choice: { type: 'tool', name: 'extract_memory_facts' },+ system: 'You distill Farcaster casts into concise memory facts for an AI agent. Focus on: recurring topics, opinions, projects, communication style, community ties.',+ messages: [+ {+ role: 'user',+ content: `Profile: ${userLine}\n\nRecent casts (newest first):\n${castTexts}`,+ },+ ],+ }),+ });++ if (!resp.ok) throw new Error(`Claude error ${resp.status}`);++ const data = await resp.json();+ const toolUse = data.content?.find((b) => b.type === 'tool_use');+ const facts = toolUse?.input?.facts;+ return Array.isArray(facts) ? facts.slice(0, 15) : [];+}++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 (!env.NEYNAR_API_KEY)+ return error(res, 501, 'not_configured', 'Farcaster integration not configured');++ const url = new URL(req.url, 'http://x');+ const parts = url.pathname.split('/').filter(Boolean);+ const agentId = parts[2];++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ const userId = session?.id ?? bearer?.userId;+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');++ const [agent] = await sql`+ SELECT id, farcaster_fid, farcaster_fname, farcaster_seeded_at+ FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');++ if (req.method === 'GET') {+ const [countRow] = await sql`+ SELECT COUNT(*)::int AS fact_count+ FROM agent_memories+ WHERE agent_id = ${agentId}+ AND context->>'source' = 'farcaster_seed'+ AND (expires_at IS NULL OR expires_at > now())+ `;+ return json(res, 200, {+ fid: agent.farcaster_fid ?? null,+ fname: agent.farcaster_fname ?? null,+ seeded_at: agent.farcaster_seeded_at ?? null,+ fact_count: countRow?.fact_count ?? 0,+ });+ }++ // POST+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ if (agent.farcaster_seeded_at) {+ const elapsed = Date.now() - new Date(agent.farcaster_seeded_at).getTime();+ if (elapsed < SEED_COOLDOWN_MS)+ return error(res, 429, 'rate_limited', 'farcaster seed cooldown: try again in 6 hours');+ }++ const body = parse(bodySchema, await readJson(req));++ let fid = body.fid ?? null;+ let fname = body.fname ?? null;++ // Resolve fname → fid+ if (!fid && fname) {+ let userData;+ try {+ userData = await neynarGet(+ `/user/by_username?username=${encodeURIComponent(fname)}`,+ env.NEYNAR_API_KEY,+ );+ } catch (e) {+ if (e.httpStatus === 404)+ return error(res, 404, 'farcaster_user_not_found', 'Farcaster user not found');+ throw e;+ }+ fid = userData?.user?.fid;+ if (!fid) return error(res, 404, 'farcaster_user_not_found', 'Farcaster user not found');+ }++ // Fetch casts and profile in parallel+ const [castsData, profileData] = await Promise.all([+ neynarGet(+ `/feed/user/casts?fid=${fid}&limit=50&include_replies=false`,+ env.NEYNAR_API_KEY,+ ),+ neynarGet(`/user?fid=${fid}`, env.NEYNAR_API_KEY),+ ]);++ const casts = castsData?.casts ?? [];+ const profile = profileData?.users?.[0] ?? profileData?.user ?? {};++ if (!fname && profile.username) fname = profile.username;++ const facts = casts.length > 0 ? await distillFacts(profile, casts) : [];++ // Delete existing farcaster_seed memories (idempotent re-seed)+ await sql`+ DELETE FROM agent_memories+ WHERE agent_id = ${agentId} AND context->>'source' = 'farcaster_seed'+ `;++ // Insert new memories+ for (const fact of facts) {+ await sql`+ INSERT INTO agent_memories (id, agent_id, type, content, tags, context, salience)+ VALUES (+ gen_random_uuid(),+ ${agentId},+ 'user',+ ${fact},+ ARRAY['farcaster'],+ ${JSON.stringify({ source: 'farcaster_seed', fid })}::jsonb,+ 0.7+ )+ `;+ }++ // Update agent with validated farcaster identity+ await sql`+ UPDATE agent_identities+ SET farcaster_fid = ${fid}, farcaster_fname = ${fname}, farcaster_seeded_at = now()+ WHERE id = ${agentId}+ `;++ return json(res, 200, { fid, fname, seeded: facts.length, facts });+});diff --git a/api/agents/_id/persona.js b/api/agents/_id/persona.jsnew file mode 100644index 000000000..bac34474d--- /dev/null+++ b/api/agents/_id/persona.js@@ -0,0 +1,165 @@+// GET /api/agents/:id/persona — persona status (has_persona, tone_tags, extracted_at)+// POST /api/agents/:id/persona/extract — extract persona from 5-question interview via Claude++import { createHash, createHmac } from 'node:crypto';+import { sql } from '../../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import { env } from '../../_lib/env.js';+import { parse } from '../../_lib/validate.js';+import { z } from 'zod';++const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';++const extractBody = z.object({+ answers: z+ .array(z.string().trim().min(5, 'Each answer must be at least 5 characters').max(1000))+ .length(5, 'Exactly 5 answers required'),+});++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++const PERSONA_TOOL = {+ name: 'extract_persona',+ description: 'Extract a persona system prompt from interview answers',+ input_schema: {+ type: 'object',+ required: ['system_prompt', 'tone_tags', 'vocabulary_samples'],+ properties: {+ system_prompt: {+ type: 'string',+ description:+ 'A 150-300 word first-person system prompt that captures the persona. Start with "You are ...".',+ },+ tone_tags: {+ type: 'array',+ items: { type: 'string' },+ description: 'Up to 8 single-word tone descriptors (e.g. witty, direct, empathetic).',+ },+ vocabulary_samples: {+ type: 'array',+ items: { type: 'string' },+ description: 'Up to 10 short phrases or expressions characteristic of this persona.',+ },+ },+ },+};++export const handlePersona = wrap(async (req, res, id, action) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const [agent] =+ await sql`SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ // ── GET — persona status ─────────────────────────────────────────────────++ if (req.method === 'GET') {+ const [row] = await sql`+ SELECT persona_prompt_hash, persona_tone_tags, persona_extracted_at+ FROM agent_identities WHERE id = ${id}+ `;+ return json(res, 200, {+ has_persona: Boolean(row?.persona_prompt_hash),+ tone_tags: row?.persona_tone_tags || [],+ extracted_at: row?.persona_extracted_at || null,+ });+ }++ // ── POST /extract ─────────────────────────────────────────────────────────++ if (req.method === 'POST' && action === 'extract') {+ const rl = await limits.personaExtract(auth.userId);+ if (!rl.success)+ return error(res, 429, 'rate_limited', 'persona extraction limit reached (5 per day)');++ const body = parse(extractBody, await readJson(req));+ const { answers } = body;++ const apiKey = env.ANTHROPIC_API_KEY;++ let upstream;+ try {+ upstream = await fetch(ANTHROPIC_URL, {+ method: 'POST',+ headers: {+ 'x-api-key': apiKey,+ 'anthropic-version': '2023-06-01',+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ model: 'claude-sonnet-4-6',+ max_tokens: 1024,+ system:+ 'You are a persona architect. Given a person\'s interview answers, extract their communication style, tone, and voice. Produce a concise first-person system prompt that an LLM can use to impersonate this person faithfully. Be specific. Avoid clichés.',+ messages: [+ {+ role: 'user',+ content: `Interview answers:\n1. ${answers[0]}\n2. ${answers[1]}\n3. ${answers[2]}\n4. ${answers[3]}\n5. ${answers[4]}`,+ },+ ],+ tools: [PERSONA_TOOL],+ tool_choice: { type: 'tool', name: 'extract_persona' },+ }),+ });+ } catch (err) {+ console.error('[persona/extract] anthropic fetch failed', err);+ return error(res, 502, 'upstream_error', 'persona extraction service unreachable');+ }++ if (!upstream.ok) {+ const text = await upstream.text().catch(() => '');+ console.error('[persona/extract] anthropic error', upstream.status, text.slice(0, 400));+ return error(res, 502, 'upstream_error', `persona extraction failed (${upstream.status})`);+ }++ const data = await upstream.json();+ const toolUse = data.content?.find(+ (b) => b.type === 'tool_use' && b.name === 'extract_persona',+ );+ if (!toolUse?.input) {+ console.error('[persona/extract] no tool_use block', JSON.stringify(data).slice(0, 400));+ return error(res, 502, 'upstream_error', 'unexpected response from persona extraction');+ }++ const { system_prompt, tone_tags, vocabulary_samples } = toolUse.input;++ const hash = createHash('sha256').update(system_prompt).digest('hex');+ const sig = createHmac('sha256', env.JWT_SECRET).update(hash).digest('hex');++ const [updated] = await sql`+ UPDATE agent_identities+ SET+ persona_prompt = ${system_prompt},+ persona_prompt_hash = ${hash},+ persona_prompt_sig = ${sig},+ persona_tone_tags = ${JSON.stringify(tone_tags)}::jsonb,+ persona_extracted_at = now(),+ updated_at = now()+ WHERE id = ${id}+ RETURNING persona_extracted_at+ `;++ return json(res, 200, {+ system_prompt,+ tone_tags,+ vocabulary_samples,+ hash,+ extracted_at: updated.persona_extracted_at,+ });+ }++ return error(res, 404, 'not_found', 'unknown persona action');+});diff --git a/api/cron/[name].js b/api/cron/[name].jsindex f10cddcfc..404cf23b1 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -55,6 +55,7 @@ const HANDLERS = {'run-dca': handleRunDca,'run-distribute-payments': handleRunDistributePayments,'run-subscriptions': handleRunSubscriptions,+ 'settle-royalties': handleSettleRoyalties,'solana-attest-event-cleanup': handleSolanaAttestEventCleanup,'solana-attestations-crawl': handleSolanaAttestationsCrawl,};diff --git a/api/skills/index.js b/api/skills/index.jsindex d5f40d7a6..57a06cd6c 100644--- a/api/skills/index.js+++ b/api/skills/index.js@@ -33,6 +33,7 @@ const publishSchema = z.object({).min(1),is_public: z.boolean().default(true),+ price_per_call_usd: z.number().min(0).max(10).default(0),});export default wrap(async (req, res) => {@@ -62,6 +63,7 @@ function toSkill(row, { includeInstalled = false, includeSchema = false } = {})install_count: row.install_count || 0,avg_rating: Number(row.avg_rating) || 0,rating_count: row.rating_count || 0,+ price_per_call_usd: Number(row.price_per_call_usd) || 0,author: row.author_id? { id: row.author_id, display_name: row.author_display_name }: null,@@ -197,7 +199,7 @@ async function handlePublish(req, res) {let row;try {[row] = await sql`- INSERT INTO marketplace_skills (author_id, name, slug, description, category, tags, schema_json, is_public)+ INSERT INTO marketplace_skills (author_id, name, slug, description, category, tags, schema_json, is_public, price_per_call_usd)VALUES (${auth.userId},${body.name},@@ -206,7 +208,8 @@ async function handlePublish(req, res) {${body.category},${body.tags},${JSON.stringify(body.schema_json)}::jsonb,- ${body.is_public}+ ${body.is_public},+ ${body.price_per_call_usd})RETURNING *`;diff --git a/public/chat/index.html b/public/chat/index.htmlnew file mode 100644index 000000000..df345a6e6--- /dev/null+++ b/public/chat/index.html@@ -0,0 +1,52 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <link rel="icon" type="image/svg+xml" href="/chat/three.svg" />+ <link rel="icon" type="image/png" href="/chat/ios/180.png" />+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">+ <link rel="manifest" href="/chat/manifest.json">+ <meta name="theme-color" content="#FFFFFF"/>++ <meta name="description" content="Chat with any AI model — Claude, GPT, Gemini, Ollama and more. Powered by three.ws." />++ <!-- Open Graph -->+ <meta property="og:type" content="website" />+ <meta property="og:url" content="https://three.ws/chat" />+ <meta property="og:title" content="three.ws chat" />+ <meta property="og:description" content="Chat with any AI model — Claude, GPT, Gemini, Ollama and more." />+ <meta property="og:image" content="https://three.ws/og-image.png" />++ <!-- Twitter -->+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@three_ws" />+ <meta name="twitter:title" content="three.ws chat" />+ <meta name="twitter:description" content="Chat with any AI model — Claude, GPT, Gemini, Ollama and more." />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />++ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Lora:ital,wght@0,500;0,600;0,700;1,500&display=swap" rel="stylesheet">+ <link+ rel="stylesheet"+ href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"+ integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn"+ crossorigin="anonymous"+ />+ <title>three.ws chat</title>++ <script type="importmap">+ {+ "imports": {+ "three": "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js",+ "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"+ }+ }+ </script>+ <script type="module" crossorigin src="/chat/assets/index-ClPZmpTl.js"></script>+ <link rel="stylesheet" crossorigin href="/chat/assets/index-DmlkQKLg.css">+ </head>+ <body>+ <div id="app"></div>+ </body>+</html>