@7ots/cli 0.1.17 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,255 @@
1
+ /**
2
+ * The ot's wallet: a managed subwallet in the owner's Notlogin account (agentId = the ot's id).
3
+ *
4
+ * Money never moves without the owner. The ot can only PROPOSE a payment (tool `request_payment`, owner
5
+ * chat only); the owner approves it in the dashboard's Wallet tab, which turns it into a Notlogin
6
+ * `withdraw` intent that they confirm on notlogin.com with a fresh sign-in. 7ots holds no keys.
7
+ *
8
+ * NOTLOGIN_SERVICE_TOKEN provisions/reads the agent wallets (GET /api/x402/wallet?userId&agentId)
9
+ * account integration 'notlogin' { access, refresh, exp } scopes wallet:read intents:create, from
10
+ * "Connect Notlogin" (/auth/notlogin?link=<otsId>, auth.mjs)
11
+ *
12
+ * Dashboard (connect.mjs-style, mounted from routes.mjs):
13
+ * GET …/ots/:id/wallet addresses, balances, payments
14
+ * POST …/ots/:id/wallet/payments/:pid/approve → { url } of the Notlogin confirm page
15
+ * POST …/ots/:id/wallet/payments/:pid/decline
16
+ * POST …/ots/:id/wallet/payments/:pid/refresh reads the intent's outcome
17
+ */
18
+
19
+ import { randomBytes } from 'node:crypto';
20
+ import { reqT } from '../i18n.mjs';
21
+ import { getDb } from './db.mjs';
22
+ import { getIntegration, setIntegration } from './store.mjs';
23
+
24
+ const penv = process.env;
25
+ const notloginUrl = () => (penv.NOTLOGIN_URL || 'https://notlogin.com').replace(/\/+$/, '');
26
+ export const WALLET_SCOPE = 'openid profile email wallet:read intents:create';
27
+ export const walletConfigured = () => !!(penv.NOTLOGIN_CLIENT_ID && penv.NOTLOGIN_SERVICE_TOKEN);
28
+
29
+ const NETWORKS = ['base', 'solana'];
30
+ const ADDR = { base: /^0x[0-9a-fA-F]{40}$/, solana: /^[1-9A-HJ-NP-Za-km-z]{32,44}$/ };
31
+ const MAX_OPEN = 10;
32
+
33
+ // ───────────────────────────── Notlogin tokens ─────────────────────────────
34
+
35
+ /** Saves the tokens from the token endpoint (the link callback or a refresh). */
36
+ export function saveNotloginTokens(accountId, j) {
37
+ if (!j?.access_token) return;
38
+ const prev = getIntegration(accountId, 'notlogin') || {};
39
+ setIntegration(accountId, 'notlogin', {
40
+ access: j.access_token,
41
+ refresh: j.refresh_token || prev.refresh || null,
42
+ exp: Date.now() + (Number(j.expires_in) || 900) * 1000,
43
+ scope: j.scope || prev.scope || '',
44
+ });
45
+ }
46
+
47
+ /** A valid access token with the wallet scopes, refreshing it when needed. null = connect again. */
48
+ export async function accessToken(accountId) {
49
+ const it = getIntegration(accountId, 'notlogin');
50
+ if (!it) return null;
51
+ if (it.access && it.exp > Date.now() + 30_000) return it.access;
52
+ if (!it.refresh) return null;
53
+ const body = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: it.refresh, client_id: penv.NOTLOGIN_CLIENT_ID });
54
+ if (penv.NOTLOGIN_CLIENT_SECRET) body.set('client_secret', penv.NOTLOGIN_CLIENT_SECRET);
55
+ const r = await fetch(`${notloginUrl()}/api/oauth/token`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, body, signal: AbortSignal.timeout(10000) }).catch(() => null);
56
+ const j = r ? await r.json().catch(() => ({})) : {};
57
+ if (!r?.ok || !j.access_token) {
58
+ // single-use refresh: a rejected one is gone for good
59
+ if (r && r.status >= 400 && r.status < 500) setIntegration(accountId, 'notlogin', null);
60
+ return null;
61
+ }
62
+ saveNotloginTokens(accountId, j);
63
+ return j.access_token;
64
+ }
65
+
66
+ // ───────────────────────────── Notlogin calls ─────────────────────────────
67
+
68
+ /** The ot's wallets (created on first call) with balances. */
69
+ async function agentWallets(sub, otsId) {
70
+ const q = new URLSearchParams({ userId: sub, agentId: otsId, vendorSlug: penv.NOTLOGIN_CLIENT_ID });
71
+ const r = await fetch(`${notloginUrl()}/api/x402/wallet?${q}`, { headers: { Authorization: `Bearer ${penv.NOTLOGIN_SERVICE_TOKEN}`, Accept: 'application/json' }, signal: AbortSignal.timeout(15000) });
72
+ const j = await r.json().catch(() => ({}));
73
+ if (!r.ok) throw new Error(`notlogin wallet ${r.status}${j.error ? `: ${String(j.error).slice(0, 120)}` : ''}`);
74
+ return (j.wallets || [])
75
+ .filter((w) => w.namespace === 'evm' || w.namespace === 'solana')
76
+ .map((w) => ({ namespace: w.namespace, network: w.network, address: w.address, balances: w.balances || null, balanceError: w.balanceError || null }));
77
+ }
78
+
79
+ async function intentCall(accountId, path, init = {}) {
80
+ const tok = await accessToken(accountId);
81
+ if (!tok) throw Object.assign(new Error('relink'), { relink: true });
82
+ const r = await fetch(`${notloginUrl()}/api/v1/account/intents${path}`, {
83
+ ...init,
84
+ headers: { Authorization: `Bearer ${tok}`, Accept: 'application/json', ...(init.body ? { 'Content-Type': 'application/json' } : {}) },
85
+ signal: AbortSignal.timeout(10000),
86
+ });
87
+ const j = await r.json().catch(() => ({}));
88
+ if (r.status === 401 || r.status === 403) throw Object.assign(new Error('relink'), { relink: true });
89
+ if (!r.ok) throw new Error(j.error || `notlogin ${r.status}`);
90
+ return j;
91
+ }
92
+
93
+ // ───────────────────────────── payments ─────────────────────────────
94
+
95
+ // public block explorers: an address page lists everything that came in and went out
96
+ const EXPLORER = { base: ['https://basescan.org/address/', 'https://basescan.org/tx/'], solana: ['https://solscan.io/account/', 'https://solscan.io/tx/'] };
97
+ const walletNetwork = (w) => (w.namespace === 'solana' ? 'solana' : w.network);
98
+ export const addressUrl = (network, address) => (EXPLORER[network] && address ? EXPLORER[network][0] + encodeURIComponent(address) : null);
99
+ const txUrl = (network, hash) => (EXPLORER[network] && hash ? EXPLORER[network][1] + encodeURIComponent(hash) : null);
100
+
101
+ const payOf = (r) =>
102
+ r && { id: r.id, network: r.network, to: r.to_addr, amount: r.amount, asset: r.asset, reason: r.reason, who: r.who, status: r.status, intentId: r.intent_id || null, txHash: r.tx_hash || null, txUrl: txUrl(r.network, r.tx_hash), error: r.error || null, createdAt: r.created_at, updatedAt: r.updated_at };
103
+
104
+ export function listPayments(otsId, limit = 30) {
105
+ return getDb().prepare('SELECT * FROM ots_payments WHERE ots_id = ? ORDER BY created_at DESC LIMIT ?').all(otsId, limit).map(payOf);
106
+ }
107
+
108
+ function getPayment(otsId, id) {
109
+ return payOf(getDb().prepare('SELECT * FROM ots_payments WHERE id = ? AND ots_id = ?').get(String(id || ''), otsId));
110
+ }
111
+
112
+ function setPayment(id, patch) {
113
+ const cols = { status: 'status', intentId: 'intent_id', txHash: 'tx_hash', error: 'error' };
114
+ const keys = Object.keys(patch).filter((k) => cols[k]);
115
+ if (!keys.length) return;
116
+ getDb()
117
+ .prepare(`UPDATE ots_payments SET ${keys.map((k) => `${cols[k]} = ?`).join(', ')}, updated_at = ? WHERE id = ?`)
118
+ .run(...keys.map((k) => (patch[k] == null ? null : String(patch[k]).slice(0, 300))), Date.now(), id);
119
+ }
120
+
121
+ /** A payment the ot proposes. It stays 'pending' until the owner approves it. */
122
+ export function requestPayment(ots, { network, to, amount, asset, reason }, who = 'owner') {
123
+ network = String(network || 'base').toLowerCase();
124
+ if (!NETWORKS.includes(network)) throw new Error(`network must be one of ${NETWORKS.join(', ')}`);
125
+ to = String(to || '').trim();
126
+ if (!ADDR[network].test(to)) throw new Error(`"to" is not a valid ${network} address`);
127
+ amount = String(amount ?? '').trim();
128
+ if (!/^\d+(\.\d{1,9})?$/.test(amount) || Number(amount) <= 0) throw new Error('amount must be a positive decimal, e.g. "2.5"');
129
+ asset = String(asset || 'USDC').trim().slice(0, 60) || 'USDC';
130
+ const open = getDb().prepare("SELECT COUNT(*) n FROM ots_payments WHERE ots_id = ? AND status IN ('pending', 'confirming')").get(ots.id).n;
131
+ if (open >= MAX_OPEN) throw new Error('Too many payments waiting for approval; ask your owner to review them first');
132
+ const id = `pay_${randomBytes(8).toString('hex')}`;
133
+ const now = Date.now();
134
+ getDb()
135
+ .prepare('INSERT INTO ots_payments (id, ots_id, account_id, network, to_addr, amount, asset, reason, who, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
136
+ .run(id, ots.id, ots.accountId, network, to, amount, asset, String(reason || '').slice(0, 300), String(who).slice(0, 120), 'pending', now, now);
137
+ return getPayment(ots.id, id);
138
+ }
139
+
140
+ /** Notlogin withdraw params: USDC is Notlogin's default stable; anything else goes as the asset ref. */
141
+ const withdrawParams = (otsId, p) => ({ network: p.network, to: p.to, amount: p.amount, agentId: otsId, ...(p.asset && p.asset.toUpperCase() !== 'USDC' ? { asset: p.asset } : {}) });
142
+
143
+ async function syncPayment(accountId, p) {
144
+ if (p.status !== 'confirming' || !p.intentId) return p;
145
+ const i = await intentCall(accountId, `/${encodeURIComponent(p.intentId)}`);
146
+ if (i.status === 'done') setPayment(p.id, { status: 'paid', txHash: i.result?.txHash || i.result?.hash || i.result?.signature || null });
147
+ else if (i.status === 'cancelled') setPayment(p.id, { status: 'cancelled' });
148
+ else if (i.expiresAt && Date.parse(i.expiresAt) < Date.now()) setPayment(p.id, { status: 'pending', intentId: null });
149
+ return { ...p, ...payOf(getDb().prepare('SELECT * FROM ots_payments WHERE id = ?').get(p.id)) };
150
+ }
151
+
152
+ // ───────────────────────────── views ─────────────────────────────
153
+
154
+ export async function walletView(account, ots) {
155
+ const linked = !!account.notlogin_sub;
156
+ const scoped = linked && !!getIntegration(account.id, 'notlogin');
157
+ const v = { configured: walletConfigured(), linked, scoped, wallets: [], error: null, payments: listPayments(ots.id), connectUrl: `/auth/notlogin?link=${encodeURIComponent(ots.id)}`, notloginUrl: notloginUrl() };
158
+ if (!v.configured || !linked) return v;
159
+ try {
160
+ v.wallets = (await agentWallets(account.notlogin_sub, ots.id)).map((w) => ({ ...w, explorerUrl: addressUrl(walletNetwork(w), w.address) }));
161
+ } catch (e) {
162
+ v.error = e.message;
163
+ }
164
+ return v;
165
+ }
166
+
167
+ // ───────────────────────────── dashboard routes ─────────────────────────────
168
+
169
+ export function createWallet({ send, readJson }) {
170
+ /** @returns {Promise<boolean>} */
171
+ return async function dashboard(req, res, account, ots, sub) {
172
+ if (sub !== '/wallet' && !sub.startsWith('/wallet/')) return false;
173
+ const t = reqT(req);
174
+ if (sub === '/wallet' && req.method === 'GET') {
175
+ const v = await walletView(account, ots);
176
+ // payments waiting on Notlogin: pick up their outcome while the tab is open
177
+ if (v.scoped) for (const p of v.payments.filter((x) => x.status === 'confirming').slice(0, 3)) await syncPayment(account.id, p).catch(() => null);
178
+ return send(res, 200, { ...v, payments: listPayments(ots.id) }), true;
179
+ }
180
+ const m = sub.match(/^\/wallet\/payments\/(pay_[a-f0-9]{16})\/(approve|decline|refresh)$/);
181
+ if (!m || req.method !== 'POST') return send(res, 404, { error: t('server.http.unknownRoute') }), true;
182
+ const p = getPayment(ots.id, m[1]);
183
+ if (!p) return send(res, 404, { error: t('server.http.notFound') }), true;
184
+ try {
185
+ if (m[2] === 'decline') {
186
+ if (!['pending', 'confirming'].includes(p.status)) return send(res, 409, { error: t('platform.wallet.notPending') }), true;
187
+ setPayment(p.id, { status: 'declined' });
188
+ return send(res, 200, { payment: getPayment(ots.id, p.id) }), true;
189
+ }
190
+ if (m[2] === 'refresh') return send(res, 200, { payment: await syncPayment(account.id, p) }), true;
191
+ // approve → a Notlogin withdraw intent, confirmed by the owner on notlogin.com
192
+ if (!['pending', 'confirming'].includes(p.status)) return send(res, 409, { error: t('platform.wallet.notPending') }), true;
193
+ if (!account.notlogin_sub) return send(res, 409, { error: t('platform.wallet.relink'), relink: true }), true;
194
+ const base = (penv.PLATFORM_URL || '').replace(/\/+$/, '');
195
+ const intent = await intentCall(account.id, '', {
196
+ method: 'POST',
197
+ body: JSON.stringify({ type: 'withdraw', params: withdrawParams(ots.id, p), ...(base ? { returnTo: `${base}/app/#ots/${ots.id}/wallet` } : {}) }),
198
+ });
199
+ setPayment(p.id, { status: 'confirming', intentId: intent.id, error: null });
200
+ return send(res, 200, { url: intent.url, payment: getPayment(ots.id, p.id) }), true;
201
+ } catch (e) {
202
+ if (e.relink) return send(res, 409, { error: t('platform.wallet.relink'), relink: true }), true;
203
+ console.warn('[7ots] wallet:', e.message);
204
+ return send(res, 502, { error: String(e.message).slice(0, 200) }), true;
205
+ }
206
+ };
207
+ }
208
+
209
+ // ───────────────────────────── the ot's tools (owner chat) ─────────────────────────────
210
+
211
+ const TOOLS = [
212
+ {
213
+ name: 'wallet_info',
214
+ description: 'Shows your own wallet: your addresses (Base and Solana) and balances, and the payments you proposed with their status.',
215
+ parameters: { type: 'object', properties: {} },
216
+ },
217
+ {
218
+ name: 'request_payment',
219
+ description:
220
+ 'Proposes a payment from your wallet. It does NOT pay by itself: your owner must approve it in the Wallet tab and confirm it on Notlogin. ' +
221
+ 'Only use it when your owner asked you to pay something, with the exact address and amount.',
222
+ parameters: {
223
+ type: 'object',
224
+ properties: {
225
+ network: { type: 'string', enum: NETWORKS, description: 'base (default) or solana' },
226
+ to: { type: 'string', description: 'Destination address' },
227
+ amount: { type: 'string', description: 'Decimal amount, e.g. "2.5"' },
228
+ asset: { type: 'string', description: 'USDC (default) or a token address' },
229
+ reason: { type: 'string', description: 'What it is for, in a few words' },
230
+ },
231
+ required: ['to', 'amount'],
232
+ },
233
+ },
234
+ ];
235
+
236
+ /** Wallet tools for the owner chat, or null when the account has no Notlogin wallet. */
237
+ export function walletTools(ots, account) {
238
+ if (!walletConfigured() || !account?.notlogin_sub) return null;
239
+ return {
240
+ tools: TOOLS,
241
+ names: TOOLS.map((x) => x.name),
242
+ prompt: 'You have your own crypto wallet (Notlogin). You can check it with wallet_info and propose payments with request_payment; your owner approves every payment in the Wallet tab, so say so after proposing one.',
243
+ run: async (name, args = {}) => {
244
+ if (name === 'wallet_info') {
245
+ const wallets = await agentWallets(account.notlogin_sub, ots.id).catch((e) => ({ error: e.message }));
246
+ return { ok: true, wallets, payments: listPayments(ots.id, 10).map(({ id, network, to, amount, asset, reason, status, txHash }) => ({ id, network, to, amount, asset, reason, status, txHash })) };
247
+ }
248
+ if (name === 'request_payment') {
249
+ const p = requestPayment(ots, args, 'owner chat');
250
+ return { ok: true, id: p.id, status: p.status, note: 'Waiting for your owner to approve it in the Wallet tab.' };
251
+ }
252
+ throw new Error(`Unknown tool: ${name}`);
253
+ },
254
+ };
255
+ }
package/server/server.mjs CHANGED
@@ -329,7 +329,10 @@ async function serveBackoffice(req, res, pathname, dir = 'backoffice') {
329
329
  let file = join(ROOT, rel);
330
330
  if (!file.startsWith(join(ROOT, dir))) return send(res, 403, { error: reqT(req)('server.http.forbidden') });
331
331
  try {
332
- if ((await stat(file)).isDirectory()) file = join(file, 'index.html');
332
+ if ((await stat(file)).isDirectory()) {
333
+ if (!pathname.endsWith('/')) return redirectSlash(req, res, pathname);
334
+ file = join(file, 'index.html');
335
+ }
333
336
  const data = await readFile(file);
334
337
  const headers = { 'Content-Type': MIME[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' };
335
338
  // Nada se puede enmarcar (clickjacking).
@@ -429,6 +432,13 @@ const MIME = {
429
432
  '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
430
433
  '.jpg': 'image/jpeg', '.glb': 'model/gltf-binary', '.md': 'text/markdown; charset=utf-8', '.ico': 'image/x-icon',
431
434
  };
435
+ /** Directorio pedido sin barra final: 301 a la forma con barra (conserva la query). */
436
+ function redirectSlash(req, res, pathname) {
437
+ const q = req.url.indexOf('?');
438
+ res.writeHead(301, { Location: `${pathname}/${q >= 0 ? req.url.slice(q) : ''}` });
439
+ res.end();
440
+ }
441
+
432
442
  const STATIC_DIRS = ['site', 'brand', 'examples', 'src', 'dist'];
433
443
 
434
444
  async function serveStatic(req, res, pathname) {
@@ -441,7 +451,11 @@ async function serveStatic(req, res, pathname) {
441
451
  let file = join(ROOT, rel);
442
452
  if (!file.startsWith(ROOT)) return send(res, 403, { error: reqT(req)('server.http.forbidden') });
443
453
  try {
444
- if ((await stat(file)).isDirectory()) file = join(file, 'index.html');
454
+ if ((await stat(file)).isDirectory()) {
455
+ // /site/start → /site/start/: sin la barra, los recursos relativos (start.css) no cargan.
456
+ if (!pathname.endsWith('/')) return redirectSlash(req, res, pathname);
457
+ file = join(file, 'index.html');
458
+ }
445
459
  const data = await readFile(file);
446
460
  res.writeHead(200, { 'Content-Type': MIME[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
447
461
  res.end(data);
@@ -36,7 +36,7 @@ import { STYLE_IDS, stylizeSpec, styleLayers, styleSeed, backdropIn, backdropCSS
36
36
  import { translator } from '../i18n/index.js';
37
37
  import {
38
38
  GESTURES, GESTURE_ALIAS, MORPHS, EFFECTS, VISEMES, POSE0, EASE, clamp, lerp, approach, seeded,
39
- shapePoints, ptsBox, textToVisemes, babbleVisemes,
39
+ shapePoints, ptsBox, textToVisemes, babbleVisemes, drawLegs,
40
40
  } from './motion.js';
41
41
 
42
42
  export const CHARACTER_MOODS = ['neutral', 'happy', 'angry', 'sad', 'fear', 'disgust', 'love', 'sleep', 'surprised'];
@@ -714,6 +714,7 @@ export function createCharacter(container, spec, opts = {}) {
714
714
  const mo = { open: 0, target: 0, msx: 1, tmsx: 1 };
715
715
  let blinkAt = -1e9;
716
716
  let gest = null;
717
+ let legs = null; // patas de los bailes: { pose, dir, k, on, start }
717
718
  let pose = { ...POSE0 };
718
719
  const morphs = new Map();
719
720
  let fxs = [];
@@ -724,7 +725,7 @@ export function createCharacter(container, spec, opts = {}) {
724
725
  let accMask = '';
725
726
  let morphMask = '';
726
727
  let px = 240;
727
- const keys = { body: '', eyes: '', brows: '', mouth: '', rig: '', mback: '', mfront: '', fx: '', fxface: '', mask: '', detail: '' };
728
+ const keys = { body: '', eyes: '', brows: '', mouth: '', rig: '', legs: '', mback: '', mfront: '', fx: '', fxface: '', mask: '', detail: '' };
728
729
 
729
730
  /**
730
731
  * Nivel de detalle de la piel: sin textura si se ve diminuto; sin filtros mientras el contorno
@@ -738,7 +739,7 @@ export function createCharacter(container, spec, opts = {}) {
738
739
 
739
740
  function build() {
740
741
  pal = palette(s);
741
- svg.innerHTML = `<style>${STYLE}</style><defs data-p="defs"></defs><defs data-p="mask"></defs><g data-p="styled"><g class="otsc-rig"><g data-p="fxback"></g><g class="otsc-sway"><g class="otsc-breathe"><g data-p="mback"></g><g data-p="back"></g><g data-p="body"></g><g data-p="cheeks"></g><g data-p="fxface"></g><g data-p="eyes"></g><g data-p="brows"></g><g data-p="mouth"></g><g data-p="front"></g><g data-p="mfront"></g></g></g><g data-p="fx"></g></g></g>`;
742
+ svg.innerHTML = `<style>${STYLE}</style><defs data-p="defs"></defs><defs data-p="mask"></defs><g data-p="styled"><g data-p="legs"></g><g class="otsc-rig"><g data-p="fxback"></g><g class="otsc-sway"><g class="otsc-breathe"><g data-p="mback"></g><g data-p="back"></g><g data-p="body"></g><g data-p="cheeks"></g><g data-p="fxface"></g><g data-p="eyes"></g><g data-p="brows"></g><g data-p="mouth"></g><g data-p="front"></g><g data-p="mfront"></g></g></g><g data-p="fx"></g></g></g>`;
742
743
  g = { rig: svg.querySelector('.otsc-rig') };
743
744
  for (const el of svg.querySelectorAll('[data-p]')) g[el.dataset.p] = el;
744
745
  if (!idle) {
@@ -1025,6 +1026,35 @@ export function createCharacter(container, spec, opts = {}) {
1025
1026
  if (fxFront !== keys.fx) { g.fx.innerHTML = fxFront; keys.fx = fxFront; }
1026
1027
  if (fxFace !== keys.fxface) { g.fxface.innerHTML = fxFace; keys.fxface = fxFace; }
1027
1028
 
1029
+ // 8b) patas de los bailes: el cuerpo sube sobre ellas y los pies se quedan en el suelo
1030
+ let legLift = 0;
1031
+ let legSVG = '';
1032
+ if (legs) {
1033
+ busy = true;
1034
+ const lt = legs.on ? 1 : 0;
1035
+ legs.k = rm ? lt : approach(legs.k, lt, dt, 150);
1036
+ if (!legs.on && legs.k < 0.01) legs = null;
1037
+ else {
1038
+ const W = L0.box.w;
1039
+ const H = L0.box.h;
1040
+ const LL = H * 0.36;
1041
+ legLift = LL * legs.k;
1042
+ room = Math.max(room, 1 + 0.42 * legs.k);
1043
+ const ox = L0.cx;
1044
+ const oy = L0.box.y + H;
1045
+ const rr = ((pose.r + (rm ? 0 : look.x * 2)) * Math.PI) / 180;
1046
+ const hips = [-1, 1].map((sd) => {
1047
+ const lx = sd * W * 0.2 * pose.sx;
1048
+ const ly = -H * 0.1 * pose.sy;
1049
+ return { x: ox + pose.x * W + lx * Math.cos(rr) - ly * Math.sin(rr), y: oy + pose.y * H - legLift + lx * Math.sin(rr) + ly * Math.cos(rr) };
1050
+ });
1051
+ const ol = outlineOf(s, pal);
1052
+ const hr = Math.max(6, W * 0.1);
1053
+ legSVG = drawLegs({ hips, floor: oy, cx: ox, W, LL, hr, aw: hr * 0.55, fill: skin?.solid || s.body.color, line: ol ? ol.color : pal.line, lw: ol ? R(Math.min(ol.w, 3.2)) : 1.8 }, legs.k, rm ? 0 : t - legs.start, legs);
1054
+ }
1055
+ }
1056
+ if (legSVG !== keys.legs) { g.legs.innerHTML = legSVG; keys.legs = legSVG; }
1057
+
1028
1058
  // 9) zoom del encuadre para que quepan alas, manos, pinchos…
1029
1059
  const zt = canZoom ? room : 1;
1030
1060
  if (zoom !== zt) {
@@ -1042,7 +1072,7 @@ export function createCharacter(container, spec, opts = {}) {
1042
1072
  const r = pose.r + (rm ? 0 : look.x * 2);
1043
1073
  const ox = L0.cx;
1044
1074
  const oy = L0.box.y + L0.box.h;
1045
- const tf = `translate(${R(ox + pose.x * L0.box.w)} ${R(oy + pose.y * L0.box.h)}) rotate(${R(r)}) scale(${R(sx * 1000) / 1000} ${R(sy * 1000) / 1000}) translate(${R(-ox)} ${R(-oy)})`;
1075
+ const tf = `translate(${R(ox + pose.x * L0.box.w)} ${R(oy + pose.y * L0.box.h - legLift)}) rotate(${R(r)}) scale(${R(sx * 1000) / 1000} ${R(sy * 1000) / 1000}) translate(${R(-ox)} ${R(-oy)})`;
1046
1076
  if (tf !== keys.rig) { g.rig.setAttribute('transform', tf); keys.rig = tf; }
1047
1077
 
1048
1078
  if (busy) raf = requestAnimationFrame(frame);
@@ -1079,6 +1109,7 @@ export function createCharacter(container, spec, opts = {}) {
1079
1109
  const old = gest;
1080
1110
  gest = null;
1081
1111
  g.rig?.setAttribute('class', 'otsc-rig');
1112
+ if (legs) legs.on = false;
1082
1113
  const hands = morphs.get('hands');
1083
1114
  if (old.def.hands && hands && !hands.byGesture && hands.userPose !== undefined) setPose(hands, hands.userPose);
1084
1115
  const wings = morphs.get('wings');
@@ -1097,6 +1128,8 @@ export function createCharacter(container, spec, opts = {}) {
1097
1128
  if (gest) endGesture();
1098
1129
  gest = { name: gname, def, start: t, ms, dir, from, fired: new Set() };
1099
1130
  g.rig.setAttribute('class', `otsc-rig otsc-g-${gname}`);
1131
+ // patas: los bailes las sacan (si ya estaban, solo cambian de paso)
1132
+ if (def.legs && opts.legs !== false) legs = { pose: def.legs, dir, k: legs?.k || 0, on: true, start: legs?.start ?? t };
1100
1133
  // manos y alas que necesita el gesto (si ya estaban, solo cambian de postura)
1101
1134
  const hands = morphs.get('hands');
1102
1135
  if (def.hands) {
@@ -92,7 +92,7 @@ function keys(list) {
92
92
 
93
93
  /**
94
94
  * Gestos. { ms (duración por defecto), pose(t, ageMs) → pose, hands?: postura de manos,
95
- * wings?: 'slow'|'fast', fx?: [[t, efecto|metamorfosis, opts?]], hold?: se puede alargar con {ms} }.
95
+ * legs?: postura de patas (LEG_POSES), wings?: 'slow'|'fast', fx?: [[t, efecto|metamorfosis, opts?]], hold?: se puede alargar con {ms} }.
96
96
  * Se diseñan mirando a la derecha; con { dir: -1 } se reflejan x, r, lx y la mano activa.
97
97
  */
98
98
  const DAB = keys([[0, {}], [0.15, { sy: 0.9, sx: 1.06, y: 0.01, r: 4 }], [0.25, { r: -14, x: -0.03, sy: 1.02, ly: 0.7, lx: -0.5, blink: 0.4, curve: 0.5 }, 'out'], [0.85, { r: -14, x: -0.03, sy: 1.01, ly: 0.7, lx: -0.5, blink: 0.4, curve: 0.5 }], [1, {}]]);
@@ -199,6 +199,7 @@ export const GESTURES = {
199
199
  ms: 2600,
200
200
  hold: true,
201
201
  dance: 'funk',
202
+ legs: 'stomp',
202
203
  hands: 'dance',
203
204
  fx: [[0.05, 'notes']],
204
205
  pose: (t, age) => {
@@ -213,6 +214,7 @@ export const GESTURES = {
213
214
  ms: 6000,
214
215
  hold: true,
215
216
  dance: 'hype',
217
+ legs: 'floss',
216
218
  hands: 'floss',
217
219
  fx: [[0.04, 'notes']],
218
220
  pose: (t, age) => {
@@ -226,6 +228,7 @@ export const GESTURES = {
226
228
  ms: 6000,
227
229
  hold: true,
228
230
  dance: 'chip',
231
+ legs: 'robot',
229
232
  hands: 'robot',
230
233
  fx: [[0.04, 'notes']],
231
234
  pose: (t, age) => {
@@ -242,6 +245,7 @@ export const GESTURES = {
242
245
  ms: 6000,
243
246
  hold: true,
244
247
  dance: 'hype',
248
+ legs: 'shuffle',
245
249
  hands: 'pump',
246
250
  fx: [[0.04, 'notes']],
247
251
  pose: (t, age) => {
@@ -256,6 +260,7 @@ export const GESTURES = {
256
260
  ms: 4000,
257
261
  hold: true,
258
262
  dance: 'trap',
263
+ legs: 'wide',
259
264
  hands: 'dab',
260
265
  fx: [[0.08, 'sparkles']],
261
266
  // un golpe cada dos segundos (4 tiempos): se prepara, clava el dab y lo sostiene
@@ -271,6 +276,7 @@ export const GESTURES = {
271
276
  ms: 6000,
272
277
  hold: true,
273
278
  dance: 'funk',
279
+ legs: 'kick',
274
280
  hands: 'groove',
275
281
  fx: [[0.04, 'notes']],
276
282
  pose: (t, age) => {
@@ -284,6 +290,7 @@ export const GESTURES = {
284
290
  ms: 6000,
285
291
  hold: true,
286
292
  dance: 'chip',
293
+ legs: 'stomp',
287
294
  hands: 'armwave',
288
295
  fx: [[0.04, 'notes']],
289
296
  pose: (t, age) => {
@@ -296,6 +303,7 @@ export const GESTURES = {
296
303
  ms: 6000,
297
304
  hold: true,
298
305
  dance: 'funk',
306
+ legs: 'disco',
299
307
  hands: 'disco',
300
308
  fx: [[0.04, 'notes'], [0.04, 'sparkles']],
301
309
  pose: (t, age) => {
@@ -310,6 +318,7 @@ export const GESTURES = {
310
318
  ms: 6000,
311
319
  hold: true,
312
320
  dance: 'funk',
321
+ legs: 'moonwalk',
313
322
  hands: 'swing',
314
323
  fx: [[0.04, 'notes']],
315
324
  pose: (t, age) => {
@@ -324,6 +333,7 @@ export const GESTURES = {
324
333
  ms: 8000,
325
334
  hold: true,
326
335
  dance: 'hype',
336
+ legs: 'stomp',
327
337
  hands: 'routine',
328
338
  fx: [[0.04, 'notes']],
329
339
  pose: (t, age) => {
@@ -580,6 +590,85 @@ function drawHands(c, k, age, o) {
580
590
  return [back, front, mask];
581
591
  }
582
592
 
593
+ // ───────────────────────────── patas ─────────────────────────────
594
+
595
+ /**
596
+ * Patas de los bailes: le salen por debajo, el cuerpo sube y los pies se quedan en el suelo,
597
+ * así cada salto, giro o vaivén las estira y dobla (de goma). (side, ageMs, dir) → { dx en
598
+ * anchos de cuerpo desde su sitio, lift en largos de pata, ang de la punta en grados }.
599
+ */
600
+ const FOOT_REST = { dx: 0, lift: 0, ang: 0 };
601
+ const tap = (a, hz, ph) => Math.max(0, S(a, hz, ph)) ** 1.5;
602
+ export const LEG_POSES = {
603
+ rest: () => FOOT_REST,
604
+ // pisa al compás, un pie y el otro
605
+ stomp: (s, a) => ({ dx: 0, lift: 0.38 * tap(a, BEAT / 2, s > 0 ? 0 : Math.PI), ang: -12 * tap(a, BEAT / 2, s > 0 ? 0 : Math.PI) }),
606
+ // running man: un pie adelante y el otro atrás, levantando la rodilla
607
+ shuffle: (s, a) => {
608
+ const ph = s > 0 ? 0 : Math.PI;
609
+ return { dx: 0.14 * S(a, BEAT / 2, ph), lift: 0.45 * tap(a, BEAT / 2, ph + Math.PI / 2), ang: -18 * tap(a, BEAT / 2, ph + Math.PI / 2) };
610
+ },
611
+ // a golpes: levanta un pie recto y lo planta
612
+ robot: (s, a) => {
613
+ const [i, k] = beatStep(a);
614
+ const up = (n) => ((n + (s > 0 ? 0 : 1)) % 2 ? 1 : 0);
615
+ const q = lerp(up(i - 1), up(i), k);
616
+ return { dx: 0.04 * q * s, lift: 0.3 * q, ang: 0 };
617
+ },
618
+ // las caderas van y vienen, los pies quietos y juntos: las patas se cruzan
619
+ floss: (s) => ({ dx: -s * 0.06, lift: 0, ang: 0 }),
620
+ // patada al costado cada cuatro tiempos
621
+ kick: (s, a, dir) => {
622
+ const b = ((a / 1000) * BEAT) % 4;
623
+ const kick = s === dir && b >= 2 && b < 3 ? Math.sin((b - 2) * Math.PI) : 0;
624
+ const bob = s !== dir ? 0 : 0.12 * tap(a, BEAT, 0) * (b < 2 ? 1 : 0);
625
+ return { dx: 0.3 * kick, lift: 0.9 * kick + bob, ang: -40 * kick };
626
+ },
627
+ // se desliza hacia atrás con un talón arriba (alternando)
628
+ moonwalk: (s, a) => {
629
+ const f = ((a / 1000) * (BEAT / 2)) % 1;
630
+ const which = Math.floor((a / 1000) * BEAT) % 2 ? 1 : -1;
631
+ const heel = s === which ? 0.22 : 0;
632
+ return { dx: -0.06 * Math.sin(f * TAU), lift: heel, ang: s === which ? 35 : 0 };
633
+ },
634
+ // marca el tiempo con la punta del pie de adelante
635
+ disco: (s, a, dir) => (s === dir ? { dx: 0.12, lift: 0.22 * tap(a, BEAT, 0), ang: -25 * tap(a, BEAT, 0) } : { dx: -0.03, lift: 0, ang: 0 }),
636
+ // bien abiertas y firmes
637
+ wide: (s) => ({ dx: s * 0.1, lift: 0, ang: 0 }),
638
+ };
639
+
640
+ /**
641
+ * Patas en coordenadas del mundo (no del cuerpo: los pies no siguen al cuerpo, se quedan en el
642
+ * suelo). c: { hips: [{x,y} izq, der], floor, cx, W, LL (largo), hr, aw, fill, line, lw }.
643
+ */
644
+ export function drawLegs(c, k, age, o = {}) {
645
+ if (k <= 0.01) return '';
646
+ const dir = o.dir || 1;
647
+ const fn = LEG_POSES[o.pose] || LEG_POSES.stomp;
648
+ let out = '';
649
+ for (const s of [-1, 1]) {
650
+ const p = fn(s, age, dir);
651
+ const hip = c.hips[s > 0 ? 1 : 0];
652
+ const fr = c.hr * 0.62;
653
+ const ax = c.cx + s * c.W * 0.17 + p.dx * c.W;
654
+ const ay = c.floor - fr * 0.9 - p.lift * c.LL;
655
+ const dx = ax - hip.x;
656
+ const dy = ay - hip.y;
657
+ const d = Math.hypot(dx, dy) || 1;
658
+ // rodilla de goma: cuanto más corta queda la pata, más se dobla hacia fuera
659
+ const bend = Math.sqrt(Math.max(0, c.LL * c.LL - d * d)) * 0.55 + d * 0.06;
660
+ const kx = (hip.x + ax) / 2 + s * bend;
661
+ const ky = (hip.y + ay) / 2;
662
+ const path = `M${R(hip.x)} ${R(hip.y)}Q${R(kx)} ${R(ky)} ${R(ax)} ${R(ay)}`;
663
+ const w = c.aw * 1.15 * Math.min(1, k);
664
+ out += `<path d="${path}" stroke="${c.line}" stroke-width="${R(w + c.lw * 2)}" fill="none" stroke-linecap="round"/><path d="${path}" stroke="${c.fill}" stroke-width="${R(w)}" fill="none" stroke-linecap="round"/>`;
665
+ // pie: zapatito redondo con la punta hacia fuera
666
+ const sc = Math.max(0.01, Math.min(1, k));
667
+ out += `<g transform="translate(${R(ax)} ${R(ay)}) scale(${R(s * sc)} ${R(sc)}) rotate(${R(p.ang)})"><ellipse cx="${R(c.hr * 0.45)}" cy="${R(fr * 0.35)}" rx="${R(c.hr * 1.05)}" ry="${R(fr)}" fill="${c.fill}" stroke="${c.line}" stroke-width="${c.lw}"/><path d="M${R(-c.hr * 0.45)} ${R(fr * 0.95)}H${R(c.hr * 1.3)}" stroke="${c.line}" stroke-width="${R(c.lw * 0.9)}" stroke-linecap="round" opacity=".5"/><ellipse cx="${R(c.hr * 0.85)}" cy="${R(-fr * 0.05)}" rx="${R(c.hr * 0.28)}" ry="${R(fr * 0.28)}" fill="#fff" opacity=".35"/></g>`;
668
+ }
669
+ return out;
670
+ }
671
+
583
672
  // ───────────────────────────── alas, pinchos, cuernos ─────────────────────────────
584
673
 
585
674
  const WING = 'M0 0C18 -36 64 -56 96 -44C88 -32 82 -28 72 -25C74 -14 66 -8 54 -8C54 3 42 8 30 6C20 11 7 9 0 0Z';
@@ -117,6 +117,14 @@ class Stage {
117
117
  this.visible.delete(view);
118
118
  this.io.unobserve(view.el);
119
119
  delete view.el.__ots3dView;
120
+ if (!this.visible.size) this.clear();
121
+ }
122
+
123
+ /** Borra el canvas: sin vistas el bucle se duerme, y el último cuadro quedaría pegado encima de la página. */
124
+ clear() {
125
+ this.sleep();
126
+ this.renderer.setScissorTest(false);
127
+ this.renderer.clear();
120
128
  }
121
129
 
122
130
  wake() {
@@ -144,7 +152,10 @@ class Stage {
144
152
 
145
153
  frame(t) {
146
154
  this.raf = 0;
147
- if (document.hidden || !this.visible.size) return;
155
+ if (document.hidden) return;
156
+ // una vista cuyo elemento salió del DOM sin destroy() (la vista cambió por innerHTML) no se dibuja más
157
+ for (const v of this.visible) if (!v.el.isConnected) this.visible.delete(v);
158
+ if (!this.visible.size) return this.clear();
148
159
  const dt = Math.min(64, Math.max(0, t - this.last));
149
160
  this.last = t;
150
161
  const t0 = performance.now();