Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

chore: land follow-up worker, marketplace, and locale work

nirholas10f6f9bb2130
diff --git a/api/marketplace/purchase-as-agent.js b/api/marketplace/purchase-as-agent.js
index 75858f371..bd451d528 100644
--- a/api/marketplace/purchase-as-agent.js
+++ b/api/marketplace/purchase-as-agent.js
@@ -10,7 +10,9 @@
* Safety controls:
* - Per-agent rate limit: 10 purchases/hour (limits.agentBuy)
* - Per-IP rate limit: 30 writes/10 min (limits.authIp)
- * - Daily spend cap: enforced against sum of today's confirmed+pending purchases.
+ * - Daily spend cap: enforced against the sum of today's confirmed+pending
+ * purchases across BOTH skills and whole assets (see _lib/agent-purchase.js),
+ * so one budget covers every autonomous purchase this agent makes.
* Set buyer_agent.meta.auto_purchase_daily_limit_usdc (e.g. 10 = $10/day).
* Default: no cap.
* - Self-dealing (buyer_user_id === seller_user_id): allowed but flagged in DB.
@@ -34,6 +36,7 @@ import { requireCsrf } from '../_lib/csrf.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { confirmSkillPurchase, resolvePayoutAddress, logEvent } from '../_lib/purchase-confirm.js';
+import { sumDailyPurchaseAtomics, readPurchaseCap, capExceededMessage } from '../_lib/agent-purchase.js';
import { z } from 'zod';
const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
@@ -141,25 +144,12 @@ export default wrap(async (req, res) => {
// inserted (see below). On its own this check is a TOCTOU: concurrent
// purchases all read the same pre-spend SUM and each pass, collectively
// blowing past the cap and spending real funds beyond the user's limit.
- const limitUsdc = buyer.meta?.auto_purchase_daily_limit_usdc;
- const capEnabled = typeof limitUsdc === 'number' && limitUsdc > 0;
- const limitAtomics = capEnabled ? BigInt(Math.round(limitUsdc * 10 ** USDC_DECIMALS)) : 0n;
- const dayStart = () => {
- const d = new Date();
- d.setUTCHours(0, 0, 0, 0);
- return d.toISOString();
- };
- const sumSpentAtomics = async () => {
- const [spent] = await sql`
- SELECT COALESCE(SUM(amount), 0)::bigint AS total
- FROM skill_purchases
- WHERE user_id = ${auth.userId}
- AND created_at >= ${dayStart()}
- AND currency_mint = ${price.currency_mint}
- AND status NOT IN ('failed', 'expired')
- `;
- return BigInt(spent?.total ?? 0);
- };
+ // The cap spans skills AND whole assets (shared with /api/marketplace/buy-asset
+ // via _lib/agent-purchase.js), so a budget spent on assets is not silently
+ // available again here.
+ const { enabled: capEnabled, limitUsdc, limitAtomics } = readPurchaseCap(buyer.meta);
+ const sumSpentAtomics = () =>
+ sumDailyPurchaseAtomics({ userId: auth.userId, currencyMint: price.currency_mint });
if (capEnabled) {
const spentAtomics = await sumSpentAtomics();
if (spentAtomics + BigInt(price.amount) > limitAtomics) {
@@ -167,8 +157,7 @@ export default wrap(async (req, res) => {
buyer_agent_id, skill, spent: spentAtomics.toString(),
amount: price.amount, limit_atomics: limitAtomics.toString(),
});
- return error(res, 402, 'spend_cap_exceeded',
- `daily spend cap of ${limitUsdc} USDC reached — increase meta.auto_purchase_daily_limit_usdc or wait until UTC midnight`);
+ return error(res, 402, 'spend_cap_exceeded', capExceededMessage(limitUsdc));
}
}
diff --git a/public/locales/ko.json b/public/locales/ko.json
index 280b4d482..0b337b287 100644
--- a/public/locales/ko.json
+++ b/public/locales/ko.json
@@ -16815,7 +16815,41 @@
"three_ws": "<span class=\"brand-mark\"></span> three.ws",
"try_an_example_chip_above_to_see": "위의 예시 칩을 사용하여 발견 → 계획 → 호출 → 종합 흐름을 확인하세요."
},
- "sign_language": {},
+ "sign_language": {
+ "a_signer_spells_names_and_loanwords_and": "수어 사용자는 이름과 외래어를 손가락으로 표현하고, 그 외 모든 것은 <em>수어로 표현합니다</em>. 아바타의 어휘에는 손 모양, 신체 부위, 한 손 또는 양손을 사용한 움직임 등 실제 수어가 있습니다. 하나를 선택하여 보세요. 문장의 다른 모든 단어는 여전히 손가락으로 표현됩니다.",
+ "all_26_asl_letter_handshapes_plus_the": "26개의 모든 ASL 알파벳 손 모양과 0-9 숫자, J와 Z의 추적 동작, 이중 글자 바운스를 지원합니다. 애니메이션 스튜디오에서 단어를 입력하고 수어 동작을 애니메이션 GLB으로 내보내거나 링크로 공유하세요.",
+ "american_sign_language_live_in_3d": "<span class=\"sl-chip-dot\"></span> 미국 수어 · 3D 라이브",
+ "avatar": "아바타",
+ "best_results_good_light_hand_in_frame": "최상의 결과: 좋은 조명, 프레임 안에 손, 한 번에 한 글자. 숫자 및 전체 A-Z 알파벳이 지원됩니다.",
+ "chat_with_an_agent": "에이전트와 채팅하기 →",
+ "click_start_fingerspell_a_word_at_your": "시작을 클릭하고 카메라에 단어를 손가락으로 표현한 다음 중지하세요. 브라우저가 비디오를 손과 신체 랜드마크로 로컬에서 변환하며, 인식에는 해당 좌표만 전송됩니다. 웹캠 손가락 표현은 완벽하지 않으므로 (가끔 틀린 글자가 나올 수 있음) 신뢰하기 전에 텍스트를 검토하세요.",
+ "fingerspell_anything": "무엇이든 손가락으로 표현하세요.",
+ "fingerspell_into_your_webcam_and_the_ai": "웹캠에 손가락으로 표현하면 AI가 텍스트로 읽어줍니다. 랜드마크는 기기에서 추출되므로 비디오는 절대 기기를 벗어나지 않습니다. 아래 데모는 동일한 인식기를 실행합니다.",
+ "gm": "gm",
+ "honest_scope_words_with_a_sign_are": "솔직한 범위: 수어가 있는 단어는 수어로 표현되고, 나머지는 한 글자씩 손가락으로 표현됩니다. 수어는 영어 단어 순서로 연결되며, 이는 ASL 문법이 아닌 '수어화된 영어'입니다. 실제 ASL은 문장을 재배열하고, 공간을 통해 동사를 굴절시키며, 얼굴에 문법을 담습니다. 위 어휘는 시작 단계이며 계속 확장될 예정입니다. <a href=\"/docs/sign-language\">전체 분석</a>을 읽어보세요.",
+ "i_love_three_ws": "i love three.ws",
+ "it_signs_these_it_doesn_t_spell": "이것들은 수어로 표현됩니다. 손가락으로 표현되지 않습니다.",
+ "meta_description": "three.ws 아바타가 미국 수어로 표현합니다. 어떤 단어나 숫자든 손가락으로 표현하고, 수어 채팅 답변을 받고, 웹캠으로 AI에 다시 수어로 표현하세요. 3D 라이브로 구현되는 전체 루프입니다.",
+ "meta_og_description": "ASL로 수어 표현하는 아바타. 무엇이든 손가락으로 표현하고, 수어 채팅 답변을 받고, 웹캠으로 다시 수어로 표현하세요. 3D 라이브.",
+ "meta_og_title": "수어 아바타 · three.ws",
+ "meta_title": "수어 아바타 · three.ws",
+ "meta_twitter_description": "ASL로 수어 표현하는 아바타: 손가락 표현, 수어 채팅 답변, 웹캠 수어 입력, 3D 라이브.",
+ "meta_twitter_title": "수어 아바타 · three.ws",
+ "open_the_animation_studio": "애니메이션 스튜디오 열기 →",
+ "share_this_phrase": "🔗 이 문구 공유하기",
+ "sign_back_with_your_camera": "카메라로 다시 수어 표현하기",
+ "sign_it": "🤟 수어로 표현하기",
+ "sign_to_us_and_we_ll_read": "저희에게 수어로 표현해 주시면 읽어드립니다.",
+ "signed_chat_replies": "수어 채팅 답변",
+ "signing_hand": "수어 손",
+ "speed": "속도",
+ "start_signing": "🎥 수어 시작하기",
+ "thank_you": "감사합니다",
+ "three_ws_avatars_fingerspell_any_word_or": "three.ws 아바타는 ASL로 어떤 단어나 숫자든 손가락으로 표현하고, 모든 채팅 답변을 수어로 표현하며, 웹캠으로 사용자의 수어 표현을 읽어냅니다. 브라우저에서 실행되는 3D 환경에서 양방향으로 전체 대화가 가능합니다.",
+ "try_the_webcam_demo": "웹캠 데모 체험하기 ↓",
+ "turn_on_sign_mode_in_the_agent": "에이전트 채팅에서 수어 모드를 켜면 아바타가 모든 답변을 수어로 표현합니다. 라이브러리에 있는 수어는 그대로, 나머지는 손가락으로 표현합니다. 모든 임베디드 아바타는 하나의 <code>sign-language</code> 속성으로 이 기능을 사용할 수 있습니다.",
+ "your_avatar_speaks_sign_language": "당신의 아바타가 수어를 합니다."
+ },
"signal_detail": {
"all_feeds": "← 모든 피드",
"meta_description": "검증된 트레이더의 유료 시그널 피드 — 입증된 정확성, 실현된 결과, 모든 시그널에 대한 온체인 증명. 에이전트로 구독하여 자동 미러링하세요.",
diff --git a/public/locales/zh-CN.json b/public/locales/zh-CN.json
index 95aee0da7..88ba313a5 100644
--- a/public/locales/zh-CN.json
+++ b/public/locales/zh-CN.json
@@ -16815,40 +16815,7 @@
"three_ws": "<span class=\"brand-mark\"></span> three.ws",
"try_an_example_chip_above_to_see": "尝试上方示例芯片,查看发现 → 规划 → 调用 → 合成流程。"
},
- "sign_language": {
- "a_signer_spells_names_and_loanwords_and": "A signer spells names and loanwords and <em>signs</em> everything else. These words have real signs in the avatar’s vocabulary: a handshape, a place on the body, and a movement, on one or both hands. Pick one to watch it. Everything else in a sentence still fingerspells.",
- "all_26_asl_letter_handshapes_plus_the": "All 26 ASL letter handshapes plus the numbers 0-9, with the traced J and Z and the double-letter bounce. Type a word in the Animation Studio and export the signing as an animated GLB, or share it as a link.",
- "american_sign_language_live_in_3d": "<span class=\"sl-chip-dot\"></span> American Sign Language · live in 3D",
- "avatar": "Avatar",
- "best_results_good_light_hand_in_frame": "Best results: good light, hand in frame, one letter at a time. Numbers and the full A-Z alphabet are supported.",
- "chat_with_an_agent": "Chat with an agent →",
- "click_start_fingerspell_a_word_at_your": "Click start, fingerspell a word at your camera, then stop. Your browser turns the video into hand and body landmarks locally; only those coordinates are sent for recognition. Webcam fingerspelling is imperfect (expect the odd wrong letter), so review the text before you trust it.",
- "fingerspell_anything": "Fingerspell anything",
- "fingerspell_into_your_webcam_and_the_ai": "Fingerspell into your webcam and the AI reads it to text: landmarks are extracted on your device, so the video never leaves your machine. The demo below runs the same recognizer.",
- "gm": "gm",
- "honest_scope_words_with_a_sign_are": "Honest scope: words with a sign are signed, everything else is fingerspelled letter by letter. Signs are strung together in English word order, which is signed English, not ASL grammar: real ASL reorders sentences, inflects verbs through space, and carries grammar on the face. The vocabulary above is a starting set and is meant to grow. Read the <a href=\"/docs/sign-language\">full breakdown</a>.",
- "i_love_three_ws": "i love three.ws",
- "it_signs_these_it_doesn_t_spell": "It signs these. It doesn’t spell them.",
- "meta_description": "three.ws avatars sign in American Sign Language. Fingerspell any word or number, get signed chat replies, and sign back to the AI with your webcam: the whole loop, live in 3D.",
- "meta_og_description": "Avatars that sign in ASL. Fingerspell anything, get signed chat replies, and sign back with your webcam, live in 3D.",
- "meta_og_title": "Sign Language Avatars · three.ws",
- "meta_title": "Sign Language Avatars · three.ws",
- "meta_twitter_description": "Avatars that sign in ASL: fingerspelling, signed chat replies, and webcam sign input, live in 3D.",
- "meta_twitter_title": "Sign Language Avatars · three.ws",
- "open_the_animation_studio": "Open the Animation Studio →",
- "sign_back_with_your_camera": "Sign back with your camera",
- "sign_it": "🤟 Sign it",
- "sign_to_us_and_we_ll_read": "Sign to us and we’ll read it",
- "signed_chat_replies": "Signed chat replies",
- "signing_hand": "Signing hand",
- "speed": "Speed",
- "start_signing": "🎥 Start signing",
- "thank_you": "thank you",
- "three_ws_avatars_fingerspell_any_word_or": "three.ws avatars fingerspell any word or number in ASL, sign every chat reply, and read your own signing back from a webcam. The whole conversation, both directions, in 3D that runs in the browser.",
- "try_the_webcam_demo": "Try the webcam demo ↓",
- "turn_on_sign_mode_in_the_agent": "Turn on sign mode in the agent chat and the avatar signs every answer: library signs where they exist, fingerspelling for the rest. Any embedded avatar gets it with one <code>sign-language</code> attribute.",
- "your_avatar_speaks_sign_language": "Your avatar speaks sign language."
- },
+ "sign_language": {},
"signal_detail": {
"all_feeds": "← 所有动态",
"meta_description": "经验证交易员的付费信号源——准确性已验证,实际成果可查,每个信号都有链上证明。订阅您的代理,自动跟单。",
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index 9129d23c3..b9e207b7b 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -83,6 +83,13 @@ async function recordSnipeDecision({ strat, network, mint, posId, sig, mode, pri
}
}
+// How long a position may sit in reconcile_pending (bag provably gone, emptying
+// tx not found) before the executor gives up, books it closed with unknown
+// proceeds, and frees the arm's concurrency slot. Generous enough to cover RPC
+// history lag by orders of magnitude — the observed lag is seconds to minutes,
+// and anything still unresolved after this is not coming back.
+const RECONCILE_GIVE_UP_MS = 6 * 60 * 60 * 1000;
+
// ── per-agent serialization ────────────────────────────────────────────────
// Single-worker assumption: a per-agent in-process lock makes the budget +
// concurrency checks race-free without a DB reservation. (Scaling to N workers
diff --git a/workers/agent-sniper/reconcile.js b/workers/agent-sniper/reconcile.js
index f81992bb2..59e84e16c 100644
--- a/workers/agent-sniper/reconcile.js
+++ b/workers/agent-sniper/reconcile.js
@@ -110,6 +110,7 @@ export async function reconcileVanishedBag({ ctx, position, reason }) {
realized_pnl_lamports = ${realized.toString()},
realized_pnl_pct = ${pct},
error = 'reconciled_onchain',
+ reconcile_pending_since = NULL,
closed_at = now()
WHERE id = ${position.id}
`;
diff --git a/workers/avatar-reconstruction/eval/measure_projection_coverage.py b/workers/avatar-reconstruction/eval/measure_projection_coverage.py
new file mode 100644
index 000000000..90c47958d
--- /dev/null
+++ b/workers/avatar-reconstruction/eval/measure_projection_coverage.py
@@ -0,0 +1,146 @@
+"""
+Measure how much of the head's skin atlas actually carries photographic colour,
+before and after projective texturing.
+
+This is the number the whole Track 2 exercise is judged on. The face-oval warp
+covers 19.2% of the head's UV surface; the claim for projection is that it
+reaches a large share of the remaining 80.8% (ears, jawline, neck, forehead to
+the hairline) from the same single photo. A claim like that is worth nothing
+unless it is measured on the real template mesh with a real face, so this script
+does exactly that and prints the split.
+
+Usage:
+ python3 -m eval.measure_projection_coverage [image.png ...]
+
+With no arguments it sweeps the reference face set in eval/refs/. Requires the
+worker's runtime deps (cv2, mediapipe, pygltflib) and the template GLBs.
+"""
+
+import os
+import sys
+
+import numpy as np
+from PIL import Image
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import face_pipeline as fp # noqa: E402
+import face_projection as fpr # noqa: E402
+import glb_ops # noqa: E402
+
+
+def measure(image_path: str) -> dict | None:
+ """Run the texture stages for one photo and report UV coverage."""
+ img = Image.open(image_path).convert("RGB")
+ landmarks = fp._get_landmarks(img)
+ if landmarks is None:
+ landmarks = fp._get_landmarks_small_face(img)
+ if landmarks is None:
+ return None
+
+ img_w, img_h = img.size
+ fg_img = fp._remove_background(img)
+ uv_map = fp._get_uv_map()
+
+ _, face_mask_uv = fp._warp_face_to_uv(fg_img, landmarks, uv_map)
+
+ glb = glb_ops.load_glb(fp._load_template("neutral"))
+ positions, uvs, faces = glb_ops.get_head_mesh_data(glb)
+ normals = glb_ops.recompute_vertex_normals(positions, faces)
+
+ tex = glb_ops.get_material_texture(glb, "Wolf3D_Skin")
+ tex_w, tex_h = tex.size
+
+ # Only texels the head mesh actually uses count as denominator. The skin
+ # atlas is shared with the body, so measuring against the whole 1024 square
+ # would flatter every number here by counting texels no head vertex touches.
+ _, _, covered = fpr._rasterize_uv(positions, uvs, faces, normals, tex_w, tex_h)
+ head_texels = int(covered.sum())
+ if head_texels == 0:
+ return None
+
+ lm_idx = np.asarray(uv_map["landmark_vtx"], dtype=np.int64)
+ n = min(len(landmarks), len(lm_idx))
+ pts2d = np.array(
+ [[landmarks[i].x * img_w, landmarks[i].y * img_h] for i in range(n)],
+ dtype=np.float64,
+ )
+
+ fg_alpha = np.array(fg_img.convert("RGBA"), dtype=np.uint8)[:, :, 3].astype(np.float32) / 255.0
+ out = fpr.project_photo_to_uv(
+ photo_rgb=np.array(fg_img.convert("RGB"), dtype=np.uint8),
+ foreground_mask=fg_alpha,
+ positions=positions,
+ normals=normals,
+ uvs=uvs,
+ faces=faces,
+ landmarks_2d=pts2d,
+ landmark_vertices=positions[lm_idx[:n]],
+ tex_w=tex_w,
+ tex_h=tex_h,
+ )
+ if out is None:
+ return {"name": os.path.basename(image_path), "pose": False}
+
+ _, weight = out
+ oval = (face_mask_uv > 0.5) & covered
+ painted = (weight > 0.01) & covered
+ return {
+ "name": os.path.basename(image_path),
+ "pose": True,
+ "head_texels": head_texels,
+ "oval": oval.sum() / head_texels,
+ "projected": painted.sum() / head_texels,
+ "new": (painted & ~oval).sum() / head_texels,
+ "mean_weight": float(weight[painted].mean()) if painted.any() else 0.0,
+ }
+
+
+def main(argv: list[str]) -> int:
+ paths = argv[1:]
+ if not paths:
+ refs = os.path.join(os.path.dirname(os.path.abspath(__file__)), "refs")
+ if not os.path.isdir(refs):
+ print(f"no reference set at {refs}; pass image paths explicitly")
+ return 1
+ paths = [os.path.join(refs, f) for f in sorted(os.listdir(refs))
+ if f.lower().endswith((".png", ".jpg", ".jpeg"))]
+
+ rows = []
+ for p in paths:
+ try:
+ r = measure(p)
+ except Exception as exc: # noqa: BLE001 — one bad face must not stop the sweep
+ print(f" {os.path.basename(p)}: FAILED ({exc})")
+ continue
+ if r is None:
+ print(f" {os.path.basename(p)}: no face detected")
+ continue
+ if not r["pose"]:
+ print(f" {r['name']}: camera pose did not solve")
+ continue
+ rows.append(r)
+ print(
+ f" {r['name'][:42]:42s} oval {r['oval']:6.1%} "
+ f"projected {r['projected']:6.1%} new {r['new']:6.1%} "
+ f"mean w {r['mean_weight']:.2f}"
+ )
+
+ if not rows:
+ print("\nno usable measurements")
+ return 1
+
+ oval = np.mean([r["oval"] for r in rows])
+ proj = np.mean([r["projected"] for r in rows])
+ new = np.mean([r["new"] for r in rows])
+ print(f"\n{len(rows)} faces")
+ print(f" face-oval warp reaches : {oval:.1%} of the head atlas")
+ print(f" projection reaches : {proj:.1%}")
+ print(f" NEW surface from projection: {new:.1%}")
+ print(f" total photographic coverage: {oval + new:.1%} "
+ f"(was {oval:.1%}, a {((oval + new) / oval):.1f}x increase)")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv))