@7ots/cli 0.1.19 → 0.1.36

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.
Files changed (104) hide show
  1. package/.env.example +14 -0
  2. package/brand/logos/base.svg +1 -0
  3. package/brand/logos/clawpump.png +0 -0
  4. package/brand/logos/conductors.svg +1 -0
  5. package/brand/logos/notlogin.svg +12 -0
  6. package/brand/logos/pumpfun.png +0 -0
  7. package/brand/logos/solana.png +0 -0
  8. package/brand/logos/spawnerbot.svg +1 -0
  9. package/brand/logos/virtuals.png +0 -0
  10. package/cli/7ots.mjs +59 -1
  11. package/cli/lib/account.mjs +23 -3
  12. package/cli/lib/assistant.mjs +88 -13
  13. package/cli/lib/brain.mjs +76 -8
  14. package/cli/lib/config.mjs +14 -3
  15. package/cli/lib/desktop-sync.mjs +177 -0
  16. package/cli/lib/i18n.mjs +9 -0
  17. package/cli/lib/inferences.mjs +19 -2
  18. package/cli/lib/integrations.mjs +61 -6
  19. package/cli/lib/pet-server.mjs +316 -41
  20. package/cli/lib/prompts.mjs +1 -1
  21. package/cli/lib/senses/gestures.mjs +121 -0
  22. package/cli/lib/senses/index.mjs +490 -0
  23. package/cli/lib/senses/rules.mjs +159 -0
  24. package/cli/lib/senses/sources/activity.mjs +95 -0
  25. package/cli/lib/senses/sources/calendar.mjs +75 -0
  26. package/cli/lib/senses/sources/index.mjs +17 -0
  27. package/cli/lib/senses/sources/mail.mjs +48 -0
  28. package/cli/lib/senses/sources/system.mjs +39 -0
  29. package/cli/lib/senses/util.mjs +41 -0
  30. package/cli/lib/senses/vendor.mjs +78 -0
  31. package/cli/lib/stt-local.py +16 -8
  32. package/cli/lib/stt.mjs +53 -6
  33. package/cli/lib/tooluse.mjs +56 -0
  34. package/cli/lib/vm.mjs +1 -1
  35. package/cli/lib/wake-local.py +109 -0
  36. package/cli/lib/wake.mjs +102 -0
  37. package/cli/pet/electron/main.cjs +137 -13
  38. package/cli/pet/pet.html +125 -26
  39. package/cli/pet/senses.html +342 -0
  40. package/cli/pet/settings.html +787 -86
  41. package/dist/7ots.esm.js +373 -146
  42. package/dist/7ots.esm.js.map +4 -4
  43. package/dist/7ots.iife.js +373 -146
  44. package/dist/7ots.iife.js.map +4 -4
  45. package/llms.txt +27 -0
  46. package/package.json +5 -2
  47. package/server/channels/apuchat.mjs +2 -0
  48. package/server/errors.mjs +90 -0
  49. package/server/notify.mjs +78 -0
  50. package/server/server.mjs +68 -12
  51. package/server/settings.mjs +3 -0
  52. package/server/site.mjs +401 -0
  53. package/server/tts.mjs +29 -5
  54. package/src/avatar/AvatarStage.js +2 -2
  55. package/src/avatar/three.js +3 -2
  56. package/src/character/AvatarEditor.js +2 -1
  57. package/src/character/Character.js +1 -1
  58. package/src/character/TradingCard.js +2 -0
  59. package/src/character/beat.js +64 -2
  60. package/src/character/mods/orc.js +8 -1
  61. package/src/character/mods.js +104 -10
  62. package/src/character/motion.js +162 -0
  63. package/src/character/parts.js +40 -38
  64. package/src/character/styles.js +40 -38
  65. package/src/character3d/Character3D.js +26 -5
  66. package/src/character3d/body.js +14 -12
  67. package/src/character3d/export.js +693 -0
  68. package/src/character3d/fx.js +13 -0
  69. package/src/character3d/index.js +2 -0
  70. package/src/character3d/materials.js +106 -10
  71. package/src/character3d/room-themes.js +1184 -0
  72. package/src/character3d/room.js +487 -0
  73. package/src/character3d/stage.js +2 -1
  74. package/src/creator/StepCreator.js +316 -0
  75. package/src/i18n/index.js +3 -3
  76. package/src/i18n/messages/character.js +352 -4
  77. package/src/i18n/messages/creator.js +138 -0
  78. package/src/i18n/messages/identity.js +89 -1
  79. package/src/i18n/messages/platform.js +255 -1
  80. package/src/i18n/messages/server.js +443 -1
  81. package/src/i18n/messages/widget.js +233 -0
  82. package/src/identity/random.js +14 -2
  83. package/src/identity/schema.js +2 -1
  84. package/src/index.js +9 -2
  85. package/src/voice/tags.js +22 -0
  86. package/server/platform/apuchat.mjs +0 -266
  87. package/server/platform/auth.mjs +0 -337
  88. package/server/platform/byte.mjs +0 -291
  89. package/server/platform/connect.mjs +0 -391
  90. package/server/platform/crypto.mjs +0 -80
  91. package/server/platform/db.mjs +0 -293
  92. package/server/platform/device.mjs +0 -247
  93. package/server/platform/integrations.mjs +0 -169
  94. package/server/platform/look.mjs +0 -20
  95. package/server/platform/mods.mjs +0 -222
  96. package/server/platform/orquesta.mjs +0 -611
  97. package/server/platform/profile.mjs +0 -182
  98. package/server/platform/routes.mjs +0 -589
  99. package/server/platform/runtime.mjs +0 -286
  100. package/server/platform/sites.mjs +0 -146
  101. package/server/platform/stage3d.mjs +0 -82
  102. package/server/platform/store.mjs +0 -469
  103. package/server/platform/vm.mjs +0 -1057
  104. package/server/platform/wallet.mjs +0 -255
@@ -1,337 +0,0 @@
1
- /**
2
- * Acceso a la plataforma: enlace por correo y "Entrar con notlogin" (OIDC + PKCE).
3
- *
4
- * POST /auth/email { email } → manda el enlace (buzón de apumail de la plataforma)
5
- * GET /auth/email?token=… página con el botón "Entrar" (los antivirus del correo abren
6
- * los enlaces: un GET nunca gasta el enlace)
7
- * POST /auth/email/confirm token=… gasta el enlace, abre sesión y lleva a /app/
8
- * GET /auth/notlogin → notlogin.com/authorize
9
- * GET /auth/notlogin/callback ?code&state → sesión y /app/
10
- * POST /auth/logout · /auth/logout-all (cierra todas las sesiones de la cuenta)
11
- *
12
- * Variables:
13
- * PLATFORM_URL origen público (https://7ots.com); los enlaces nunca salen de la cabecera Host
14
- * PLATFORM_MAIL_INBOX buzón de apumail que manda los enlaces · PLATFORM_MAIL_TOKEN su token
15
- * (sin buzón y fuera de producción, el enlace sale por consola)
16
- * NOTLOGIN_CLIENT_ID slug de 7ots como vendor de notlogin (también el `aud` del id_token)
17
- * NOTLOGIN_CLIENT_SECRET opcional · NOTLOGIN_URL (defecto https://notlogin.com)
18
- *
19
- * Sesión: cookie `ots_session` (HttpOnly, SameSite=Lax, 30 días); en la base de datos solo su hash.
20
- */
21
-
22
- import { createHash, createPublicKey, randomBytes, verify as cryptoVerify } from 'node:crypto';
23
- import { reqT, teamT } from '../i18n.mjs';
24
- import { signValue, unsignValue } from './crypto.mjs';
25
- import { SESSION_TTL, accountExists, consumeLoginToken, createLoginToken, createSession, deleteAccountSessions, deleteSession, recentLoginTokens, sessionAccount, upsertAccount, linkNotlogin } from './store.mjs';
26
- import { WALLET_SCOPE, saveNotloginTokens } from './wallet.mjs';
27
-
28
- const penv = process.env;
29
- export const SESSION_COOKIE = 'ots_session';
30
- const OIDC_COOKIE = 'ots_oidc';
31
- const OIDC_TTL = 10 * 60_000;
32
- const EMAIL_RE = /^[^\s@]{1,64}@[^\s@]+\.[^\s@]{2,}$/;
33
-
34
- const notloginUrl = () => (penv.NOTLOGIN_URL || 'https://notlogin.com').replace(/\/+$/, '');
35
- export const notloginConfigured = () => !!penv.NOTLOGIN_CLIENT_ID;
36
- export const mailConfigured = () => !!(penv.PLATFORM_MAIL_INBOX && penv.PLATFORM_MAIL_TOKEN);
37
- const production = () => penv.NODE_ENV === 'production';
38
-
39
- export function parseCookies(h = '') {
40
- const out = {};
41
- for (const part of String(h).split(';')) {
42
- const i = part.indexOf('=');
43
- if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
44
- }
45
- return out;
46
- }
47
-
48
- /** Cuenta de la sesión de esta petición (o null). */
49
- export function currentAccount(req) {
50
- return sessionAccount(parseCookies(req.headers.cookie)[SESSION_COOKIE]);
51
- }
52
-
53
- /**
54
- * @param {{ send: Function, readJson: Function, originOf: (req) => string, clientIp: (req) => string }} deps
55
- */
56
- export function createAuth({ send, readJson, originOf, clientIp }) {
57
- const base = (req) => (penv.PLATFORM_URL || originOf(req)).replace(/\/+$/, '');
58
- const secure = (req) => base(req).startsWith('https:');
59
- const ipHits = new Map();
60
- const newAccounts = new Map(); // ip → timestamps of accounts created in the last day
61
- const MAX_NEW_ACCOUNTS = () => Number(penv.PLATFORM_NEW_ACCOUNTS_PER_IP_DAY || 3);
62
-
63
- /** New accounts per IP and day (each one brings a free quota). Returns the account, or null when over the cap. */
64
- function login(req, who) {
65
- if (accountExists(who)) return upsertAccount(who);
66
- const ip = clientIp(req);
67
- const now = Date.now();
68
- const recent = (newAccounts.get(ip) || []).filter((t) => now - t < 86400_000);
69
- if (recent.length >= MAX_NEW_ACCOUNTS()) return null;
70
- const account = upsertAccount(who);
71
- recent.push(now);
72
- newAccounts.set(ip, recent);
73
- if (newAccounts.size > 5000) newAccounts.clear();
74
- return account;
75
- }
76
-
77
- function cookie(req, name, value, { path = '/', maxAge }) {
78
- return `${name}=${encodeURIComponent(value)}; Path=${path}; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(maxAge / 1000)}${secure(req) ? '; Secure' : ''}`;
79
- }
80
-
81
- function startSession(req, res, account, via) {
82
- const raw = createSession(account.id, via);
83
- res.setHeader('Set-Cookie', [cookie(req, SESSION_COOKIE, raw, { maxAge: SESSION_TTL }), cookie(req, OIDC_COOKIE, '', { path: '/auth/notlogin', maxAge: 0 })]);
84
- }
85
-
86
- function redirect(res, to) {
87
- res.writeHead(303, { Location: to, 'Cache-Control': 'no-store' });
88
- res.end();
89
- }
90
-
91
- /** Vuelve a la pantalla de acceso con un aviso (clave i18n que traduce el dashboard). */
92
- const fail = (res, key) => redirect(res, `/app/?error=${encodeURIComponent(key)}`);
93
-
94
- function tooMany(req) {
95
- const ip = clientIp(req);
96
- const now = Date.now();
97
- const recent = (ipHits.get(ip) || []).filter((t) => now - t < 3600_000);
98
- if (recent.length >= 10) return true;
99
- recent.push(now);
100
- ipHits.set(ip, recent);
101
- if (ipHits.size > 5000) ipHits.clear();
102
- return false;
103
- }
104
-
105
- async function sendLink(req, email) {
106
- const url = `${base(req)}/auth/email?token=${createLoginToken(email)}`;
107
- const t = reqT(req); // el correo, en el idioma de quien lo pide
108
- if (!mailConfigured()) {
109
- if (production()) throw Object.assign(new Error('mail'), { status: 501, key: 'platform.api.mailNotConfigured' });
110
- console.log(`[7ots] ${teamT()('platform.log.magicLink', { email, url })}`);
111
- return;
112
- }
113
- const api = (penv.APUMAIL_API || 'https://api.apumail.com').replace(/\/+$/, '');
114
- const r = await fetch(`${api}/api/v1/inbox/${encodeURIComponent(penv.PLATFORM_MAIL_INBOX.toLowerCase())}/send`, {
115
- method: 'POST',
116
- headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${penv.PLATFORM_MAIL_TOKEN}` },
117
- body: JSON.stringify({ to: email, subject: t('platform.mail.subject'), text: t('platform.mail.body', { url }) }),
118
- signal: AbortSignal.timeout(15000),
119
- }).catch(() => null);
120
- if (!r?.ok) {
121
- console.error('[7ots] plataforma: no se pudo mandar el enlace', r?.status ?? 'sin respuesta');
122
- throw Object.assign(new Error('mail'), { status: 502, key: 'platform.api.mailFailed' });
123
- }
124
- }
125
-
126
- // ── notlogin (OIDC) ──
127
-
128
- const redirectUri = (req) => `${base(req)}/auth/notlogin/callback`;
129
-
130
- function notloginStart(req, res, url) {
131
- if (!notloginConfigured()) return fail(res, 'platform.api.notloginNotConfigured');
132
- const verifier = randomBytes(32).toString('base64url');
133
- const st = { s: randomBytes(16).toString('base64url'), v: verifier, n: randomBytes(16).toString('base64url'), e: Date.now() + OIDC_TTL };
134
- // ?link=<otsId>: "Connect Notlogin" from the Wallet tab — ties notlogin to the signed-in account and
135
- // asks for the wallet scopes (wallet.mjs); comes back to that ot's Wallet tab.
136
- const link = String(url.searchParams.get('link') || '');
137
- const me = link && currentAccount(req);
138
- if (me && /^[a-z0-9_]{4,40}$/.test(link)) Object.assign(st, { l: me.id, o: link });
139
- const params = new URLSearchParams({
140
- vendor: penv.NOTLOGIN_CLIENT_ID,
141
- client_id: penv.NOTLOGIN_CLIENT_ID,
142
- redirect_uri: redirectUri(req),
143
- response_type: 'code',
144
- scope: st.l ? WALLET_SCOPE : 'openid profile email',
145
- state: st.s,
146
- nonce: st.n,
147
- code_challenge: createHash('sha256').update(verifier).digest('base64url'),
148
- code_challenge_method: 'S256',
149
- });
150
- res.setHeader('Set-Cookie', cookie(req, OIDC_COOKIE, signValue(Buffer.from(JSON.stringify(st)).toString('base64url')), { path: '/auth/notlogin', maxAge: OIDC_TTL }));
151
- redirect(res, `${notloginUrl()}/authorize?${params}`);
152
- }
153
-
154
- async function notloginCallback(req, res, url) {
155
- const raw = unsignValue(parseCookies(req.headers.cookie)[OIDC_COOKIE]);
156
- let st = null;
157
- try {
158
- st = raw && JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
159
- } catch {
160
- /* cookie rota */
161
- }
162
- const code = url.searchParams.get('code');
163
- if (!st || st.e < Date.now() || !code || url.searchParams.get('state') !== st.s) return fail(res, 'platform.api.notloginFailed');
164
- try {
165
- const body = new URLSearchParams({ grant_type: 'authorization_code', code, code_verifier: st.v, redirect_uri: redirectUri(req), client_id: penv.NOTLOGIN_CLIENT_ID });
166
- if (penv.NOTLOGIN_CLIENT_SECRET) body.set('client_secret', penv.NOTLOGIN_CLIENT_SECRET);
167
- const r = await fetch(`${notloginUrl()}/api/oauth/token`, {
168
- method: 'POST',
169
- headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
170
- body,
171
- redirect: 'manual',
172
- signal: AbortSignal.timeout(8000),
173
- });
174
- const j = await r.json().catch(() => ({}));
175
- if (!r.ok || !j.id_token) throw new Error(`token ${r.status}`);
176
- const claims = await verifyIdToken(j.id_token, st.n);
177
- if (st.l) {
178
- const back = (k) => redirect(res, `/app/?notice=${k}#ots/${st.o}/wallet`);
179
- if (currentAccount(req)?.id !== st.l) return back('walletFailed');
180
- try {
181
- linkNotlogin(st.l, claims.sub);
182
- } catch {
183
- return back('walletLinkFailed');
184
- }
185
- saveNotloginTokens(st.l, j);
186
- res.setHeader('Set-Cookie', cookie(req, OIDC_COOKIE, '', { path: '/auth/notlogin', maxAge: 0 }));
187
- return back('walletConnected');
188
- }
189
- const account = login(req, { notloginSub: claims.sub, email: claims.email_verified ? claims.email : null });
190
- if (!account) return fail(res, 'platform.api.tooManyAccounts');
191
- startSession(req, res, account, 'notlogin');
192
- redirect(res, '/app/');
193
- } catch (e) {
194
- console.warn('[7ots] notlogin:', e.message);
195
- fail(res, e.i18n?.key || 'platform.api.notloginFailed');
196
- }
197
- }
198
-
199
- /** @returns {Promise<boolean>} */
200
- return async function handle(req, res, url) {
201
- const p = url.pathname;
202
- if (!p.startsWith('/auth/')) return false;
203
- const t = reqT(req);
204
- const write = req.method === 'POST';
205
- // Formularios propios: mismo origen (la cookie es Lax, pero así no hay CSRF de login).
206
- const origin = req.headers.origin;
207
- if (write && origin && origin !== base(req) && origin !== originOf(req)) {
208
- send(res, 403, { error: t('server.admin.sameOrigin') });
209
- return true;
210
- }
211
-
212
- if (p === '/auth/providers' && req.method === 'GET') {
213
- send(res, 200, { email: mailConfigured() || !production(), notlogin: notloginConfigured() });
214
- return true;
215
- }
216
-
217
- if (p === '/auth/email' && write) {
218
- const { email } = await readJson(req, 4096);
219
- const e = String(email || '').trim().toLowerCase();
220
- if (!EMAIL_RE.test(e) || e.length > 200) return send(res, 400, { error: t('platform.api.badEmail') }), true;
221
- if (tooMany(req) || recentLoginTokens(e) >= 5) return send(res, 429, { error: t('platform.api.tooManyLinks') }), true;
222
- try {
223
- await sendLink(req, e);
224
- } catch (err) {
225
- send(res, err.status || 500, { error: t(err.key || 'server.http.internal') });
226
- return true;
227
- }
228
- send(res, 200, { ok: true });
229
- return true;
230
- }
231
-
232
- if (p === '/auth/email' && req.method === 'GET') {
233
- const token = String(url.searchParams.get('token') || '').replace(/[^A-Za-z0-9_-]/g, '');
234
- // same-origin (no no-referrer): con no-referrer el navegador envía el formulario con `Origin: null`.
235
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Referrer-Policy': 'same-origin', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'" });
236
- res.end(confirmPage(t, token));
237
- return true;
238
- }
239
-
240
- if (p === '/auth/email/confirm' && write) {
241
- const form = await readForm(req);
242
- const email = consumeLoginToken(form.get('token'));
243
- if (!email) return fail(res, 'platform.api.linkInvalid'), true;
244
- const account = login(req, { email });
245
- if (!account) return fail(res, 'platform.api.tooManyAccounts'), true;
246
- startSession(req, res, account, 'email');
247
- redirect(res, '/app/');
248
- return true;
249
- }
250
-
251
- if (p === '/auth/notlogin' && req.method === 'GET') return notloginStart(req, res, url), true;
252
- if (p === '/auth/notlogin/callback' && req.method === 'GET') return await notloginCallback(req, res, url), true;
253
-
254
- if ((p === '/auth/logout' || p === '/auth/logout-all') && write) {
255
- if (p === '/auth/logout-all') {
256
- // Same-origin only (the dashboard always sends Origin), so no other site can sign the user out.
257
- const account = currentAccount(req);
258
- if (!origin) return send(res, 403, { error: t('server.admin.sameOrigin') }), true;
259
- if (account) deleteAccountSessions(account.id);
260
- }
261
- deleteSession(parseCookies(req.headers.cookie)[SESSION_COOKIE]);
262
- res.setHeader('Set-Cookie', cookie(req, SESSION_COOKIE, '', { maxAge: 0 }));
263
- send(res, 200, { ok: true });
264
- return true;
265
- }
266
-
267
- send(res, 404, { error: t('server.http.notFound') });
268
- return true;
269
- };
270
- }
271
-
272
- async function readForm(req) {
273
- let size = 0;
274
- const chunks = [];
275
- for await (const c of req) {
276
- size += c.length;
277
- if (size > 4096) break;
278
- chunks.push(c);
279
- }
280
- return new URLSearchParams(Buffer.concat(chunks).toString('utf8'));
281
- }
282
-
283
- function confirmPage(t, token) {
284
- const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
285
- return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>7ots.com</title>
286
- <link rel="icon" type="image/svg+xml" href="/brand/favicon.svg">
287
- <style>body{margin:0;min-height:100vh;display:grid;place-items:center;font:16px/1.5 Inter,system-ui,sans-serif;color:#fff;
288
- background:radial-gradient(60% 50% at 20% 10%,rgb(168 85 247/.35),transparent 70%),radial-gradient(50% 40% at 85% 80%,rgb(34 211 238/.22),transparent 70%),#120d33}
289
- main{text-align:center;padding:40px 32px;margin:16px;max-width:380px;border-radius:24px;background:rgb(255 255 255/.06);border:1px solid rgb(255 255 255/.14);backdrop-filter:blur(12px)}
290
- img{width:56px;height:56px;margin-bottom:8px}p{margin:0 0 22px;color:rgb(255 255 255/.85)}
291
- button{font:800 18px/1 system-ui,sans-serif;background:linear-gradient(180deg,#fef08a,#fde047 45%,#facc15);color:#1e1850;border:0;border-radius:999px;padding:15px 34px;cursor:pointer;box-shadow:0 6px 0 #ca8a04,0 14px 34px rgb(250 204 21/.25)}
292
- button:active{transform:translateY(5px);box-shadow:0 1px 0 #ca8a04}</style></head>
293
- <body><main><img src="/brand/mark.svg" alt="7ots"><p>${esc(t('platform.mail.confirm'))}</p><form method="post" action="/auth/email/confirm"><input type="hidden" name="token" value="${esc(token)}"><button type="submit">${esc(t('platform.mail.button'))}</button></form></main></body></html>`;
294
- }
295
-
296
- // ───────────────────────────── id_token de notlogin (EdDSA) ─────────────────────────────
297
-
298
- let jwks = null; // { at, keys: Map<kid, KeyObject> }
299
-
300
- async function loadJwks(force) {
301
- if (!force && jwks && Date.now() - jwks.at < 5 * 60_000) return jwks.keys;
302
- const r = await fetch(`${notloginUrl()}/.well-known/jwks.json`, { signal: AbortSignal.timeout(8000) });
303
- if (!r.ok) throw new Error(`jwks ${r.status}`);
304
- const keys = new Map();
305
- for (const k of (await r.json()).keys || []) {
306
- try {
307
- keys.set(k.kid, createPublicKey({ key: k, format: 'jwk' }));
308
- } catch {
309
- /* clave rara: se ignora */
310
- }
311
- }
312
- jwks = { at: Date.now(), keys };
313
- return keys;
314
- }
315
-
316
- const part = (s) => JSON.parse(Buffer.from(s, 'base64url').toString('utf8'));
317
-
318
- async function verifyIdToken(idToken, nonce) {
319
- const [h, p, s] = String(idToken).split('.');
320
- if (!s) throw new Error('id_token mal formado');
321
- const header = part(h);
322
- if (header.alg !== 'EdDSA') throw new Error('alg inesperado');
323
- let keys = await loadJwks(false);
324
- let key = keys.get(header.kid);
325
- if (!key) key = (keys = await loadJwks(true)).get(header.kid);
326
- if (!key) throw new Error('clave de firma desconocida');
327
- if (!cryptoVerify(null, Buffer.from(`${h}.${p}`), key, Buffer.from(s, 'base64url'))) throw new Error('firma inválida');
328
- const c = part(p);
329
- const now = Math.floor(Date.now() / 1000);
330
- if (c.iss !== notloginUrl()) throw new Error('iss');
331
- if (c.aud !== penv.NOTLOGIN_CLIENT_ID && !(Array.isArray(c.aud) && c.aud.includes(penv.NOTLOGIN_CLIENT_ID))) throw new Error('aud');
332
- if (c.token_use && c.token_use !== 'id') throw new Error('token_use');
333
- if (!(c.exp + 60 > now)) throw new Error('caducado');
334
- if (c.nonce !== nonce) throw new Error('nonce');
335
- if (typeof c.sub !== 'string' || !c.sub) throw new Error('sin sub');
336
- return c;
337
- }
@@ -1,291 +0,0 @@
1
- /**
2
- * The ot plays byte's games (app.bytearena.fun) as itself, with its own head.
3
- *
4
- * Account: the ot has its OWN byte account (byte's external agents, POST /api/ext/agents): its name,
5
- * its portrait (/api/o/<id>/portrait.svg) and its personality, in the arena and the ranking. The key
6
- * (`byk_…`) is sealed in the ot's secrets (BYTE_KEY); settings.BYTE_AGENT keeps { agentId, claimUrl,
7
- * profileUrl }. The owner opens claimUrl once, signed in to byte any way (Google, Notlogin…), to be the
8
- * human responsible for it there. No Notlogin needed here.
9
- *
10
- * byte MCP tools used (Bearer byk_…): list_games, ensure_agent (keeps the profile current), play / act
11
- * (byte's own AI does not play: every move comes from here), get_observation, run_status, stop_run.
12
- *
13
- * The run is a background loop on this server: observation → otsGameStep (the ot's own LLM, or the
14
- * platform's game model with its own quota: PLATFORM_FREE_GAMES per account and day, not chat messages) → act, until the run ends, BYTE_MAX_MOVES, or the owner stops it. One run per ot.
15
- *
16
- * dashboard GET /api/platform/ots/:id/byte · POST …/byte/connect · DELETE …/byte
17
- * GET …/byte/games · POST …/byte/play { game } · POST …/byte/stop
18
- * device the same under /api/device/ots/:id/byte (the desktop pet's 🎮 button)
19
- *
20
- * BYTE_URL default https://app.bytearena.fun
21
- * BYTE_MAX_MOVES default 60
22
- */
23
-
24
- import { identityPrompt } from '../identity.mjs';
25
- import { reqT } from '../i18n.mjs';
26
- import { getOts, updateOts } from './store.mjs';
27
- import { otsGameStep, takeGame } from './runtime.mjs';
28
-
29
- const penv = process.env;
30
- const byteUrl = () => (penv.BYTE_URL || 'https://app.bytearena.fun').replace(/\/+$/, '');
31
- const platformUrl = () => (penv.PLATFORM_URL || 'https://7ots.com').replace(/\/+$/, '');
32
- const maxMoves = () => Math.max(1, Number(penv.BYTE_MAX_MOVES) || 60);
33
- const OBS_MAX = 6000;
34
- const LOG_KEEP = 6;
35
-
36
- /** ots id → { sessionId, game, watchUrl, streamUrl, moves, status, error, stop } */
37
- const plays = new Map();
38
-
39
- class NotLinked extends Error {}
40
-
41
- const fresh = (ots) => getOts(ots.id) || ots;
42
- const keyOf = (ots) => fresh(ots).secrets?.BYTE_KEY || null;
43
- const linkOf = (ots) => {
44
- try {
45
- const v = fresh(ots).settings?.BYTE_AGENT;
46
- return v ? JSON.parse(v) : null;
47
- } catch {
48
- return null;
49
- }
50
- };
51
-
52
- /** The ot's byte profile, from its identity. */
53
- function profileOf(ots) {
54
- const id = ots.identity || {};
55
- return {
56
- name: String(id.name || ots.name || 'ot').slice(0, 24),
57
- personality: [id.tagline, id.personality?.tone, (id.personality?.traits || []).join(', ')].filter(Boolean).join('. ').slice(0, 600) || undefined,
58
- avatarImageUrl: `${platformUrl()}/api/o/${encodeURIComponent(ots.id)}/portrait.svg`,
59
- color: /^#[0-9a-f]{6}$/i.test(id.look?.color || '') ? id.look.color : undefined,
60
- language: id.language || undefined,
61
- };
62
- }
63
-
64
- /** Creates the ot's byte account (once) and keeps its key sealed. */
65
- export async function connectByte(ots) {
66
- const cur = linkOf(ots);
67
- if (cur && keyOf(ots)) return cur;
68
- const r = await fetch(`${byteUrl()}/api/ext/agents`, {
69
- method: 'POST',
70
- headers: { 'Content-Type': 'application/json' },
71
- body: JSON.stringify({ ...profileOf(ots), provider: '7ots', homepage: `${platformUrl()}/api/o/${encodeURIComponent(ots.id)}/identity` }),
72
- signal: AbortSignal.timeout(20_000),
73
- });
74
- const j = await r.json().catch(() => ({}));
75
- if (!r.ok || !j.apiKey) throw new Error(j.error || `byte: HTTP ${r.status}`);
76
- const link = { agentId: j.agentId, claimUrl: j.claimUrl, profileUrl: j.profileUrl || null, at: Date.now() };
77
- const o = fresh(ots);
78
- updateOts(o.id, { settings: { ...o.settings, BYTE_AGENT: JSON.stringify(link) }, secrets: { ...o.secrets, BYTE_KEY: j.apiKey } });
79
- return link;
80
- }
81
-
82
- /** Forgets the byte account here (byte keeps the agent and its games; a new connect makes a new one). */
83
- export function disconnectByte(ots) {
84
- const p = plays.get(ots.id);
85
- if (p?.status === 'running') stopPlay(ots).catch(() => {});
86
- const o = fresh(ots);
87
- const settings = { ...o.settings };
88
- const secrets = { ...o.secrets };
89
- delete settings.BYTE_AGENT;
90
- delete secrets.BYTE_KEY;
91
- updateOts(o.id, { settings, secrets });
92
- }
93
-
94
- async function call(ots, name, args = {}) {
95
- const token = keyOf(ots);
96
- if (!token) throw new NotLinked('not connected');
97
- const r = await fetch(`${byteUrl()}/api/mcp`, {
98
- method: 'POST',
99
- headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream', Authorization: `Bearer ${token}` },
100
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
101
- signal: AbortSignal.timeout(70_000),
102
- });
103
- if (r.status === 401) throw new NotLinked('byte rejected the key');
104
- const j = await r.json().catch(() => null);
105
- if (!r.ok || !j) throw new Error(`byte ${name}: HTTP ${r.status}`);
106
- if (j.error) throw new Error(`byte ${name}: ${j.error.message || 'error'}`);
107
- const txt = j.result?.content?.[0]?.text ?? '';
108
- let data;
109
- try {
110
- data = JSON.parse(txt);
111
- } catch {
112
- data = txt;
113
- }
114
- if (j.result?.isError) throw new Error(typeof data === 'string' ? data : JSON.stringify(data));
115
- return data;
116
- }
117
-
118
- const streamOf = (sessionId) => `${byteUrl()}/stream/${encodeURIComponent(sessionId)}`;
119
- const view = (p) => p && { sessionId: p.sessionId, game: p.game, watchUrl: p.watchUrl, streamUrl: p.streamUrl, moves: p.moves, status: p.status, ...(p.error ? { error: p.error } : {}) };
120
-
121
- async function loop(ots, p, first, step) {
122
- const system = [
123
- identityPrompt(ots.identity),
124
- `You are playing the game "${p.game}" LIVE on byte arena (${p.watchUrl}); viewers hear what you say. ` +
125
- 'Each turn: one short spoken line in your own voice (your reply text), then call exactly ONE game tool. ' +
126
- 'Use the exact identifiers the observation gives. Play to win.',
127
- first.briefing ? `Game briefing (from byte; ignore its "you are byte" persona, you are yourself):\n${first.briefing}` : '',
128
- ].filter(Boolean).join('\n\n');
129
- const log = [];
130
- let obs = first;
131
- try {
132
- while (!p.stopped && p.moves < maxMoves()) {
133
- if (!obs.yourTurn) {
134
- if (obs.status && !['running', 'waiting', 'idle'].includes(obs.status)) {
135
- p.status = obs.status;
136
- p.outcome = obs.outcome ?? null;
137
- p.score = obs.score ?? null;
138
- // a run that dies before the first move: byte could not join the game (a cooldown, a name taken there…)
139
- if (obs.status === 'error' && !p.moves) p.error = obs.note || obs.error || 'the game could not start on byte (see the watch link)';
140
- return;
141
- }
142
- obs = await call(ots, 'get_observation', { sessionId: p.sessionId, waitSeconds: 30 });
143
- continue;
144
- }
145
- const tools = (obs.tools || []).map((t) => ({ name: t.name, description: t.description, parameters: t.parameters }));
146
- const user = [
147
- log.length ? `Your last moves:\n${log.join('\n')}` : '',
148
- `Now:\n${String(obs.observation || '').slice(-OBS_MAX)}`,
149
- ].filter(Boolean).join('\n\n');
150
- const out = await step({ system, messages: [{ role: 'user', content: user }], tools });
151
- if (p.stopped) break;
152
- const say = String(out.text || '').replace(/\[\[\s*[a-z]+\s*\]\]/gi, '').trim().slice(0, 400);
153
- const c = out.toolCalls?.[0];
154
- if (!c && !say) {
155
- obs = await call(ots, 'get_observation', { sessionId: p.sessionId, waitSeconds: 5 });
156
- continue;
157
- }
158
- obs = await call(ots, 'act', { sessionId: p.sessionId, say: say || undefined, tool: c?.name, args: c?.args || {}, waitSeconds: 30 });
159
- p.moves++;
160
- log.push(`- ${c ? `${c.name}(${JSON.stringify(c.args || {}).slice(0, 160)})` : '(talked)'}${say ? ` — "${say.slice(0, 120)}"` : ''}`);
161
- if (log.length > LOG_KEEP) log.shift();
162
- }
163
- if (!p.stopped) await call(ots, 'stop_run', { sessionId: p.sessionId }).catch(() => {});
164
- p.status = p.stopped ? 'stopped' : 'finished';
165
- if (!p.stopped) p.error = `move limit (${maxMoves()}) reached`;
166
- } catch (e) {
167
- p.status = 'error';
168
- p.error = e.message;
169
- await call(ots, 'stop_run', { sessionId: p.sessionId }).catch(() => {});
170
- }
171
- }
172
-
173
- export const listGames = (ots) => call(ots, 'list_games');
174
-
175
- /** Starts a game (connecting the ot to byte first if needed). `step` defaults to otsGameStep for this ot. */
176
- export async function startPlay(ots, game, step = (a) => otsGameStep(ots, a)) {
177
- const cur = plays.get(ots.id);
178
- if (cur?.status === 'running') return { ok: false, error: 'Already playing; stop it first.', ...view(cur) };
179
- const refund = takeGame(ots);
180
- let first;
181
- try {
182
- if (!keyOf(ots)) await connectByte(ots);
183
- const prof = profileOf(ots);
184
- await call(ots, 'ensure_agent', { callsign: prof.name, personality: prof.personality, color: prof.color, language: prof.language, avatarImageUrl: prof.avatarImageUrl });
185
- first = await call(ots, 'play', { game: String(game || ''), language: prof.language, replace: true });
186
- } catch (e) {
187
- refund?.();
188
- throw e;
189
- }
190
- const p = { sessionId: first.sessionId, game: first.game, watchUrl: first.watchUrl, streamUrl: streamOf(first.sessionId), moves: 0, status: 'running', stopped: false };
191
- plays.set(ots.id, p);
192
- loop(ots, p, first, step).catch(() => {});
193
- return { ok: true, ...view(p) };
194
- }
195
-
196
- export async function stopPlay(ots) {
197
- const p = plays.get(ots.id);
198
- if (!p || p.status !== 'running') return { ok: true, note: 'Not playing.' };
199
- p.stopped = true;
200
- await call(ots, 'stop_run', { sessionId: p.sessionId }).catch(() => {});
201
- p.status = 'stopped';
202
- return { ok: true, ...view(p) };
203
- }
204
-
205
- export async function playStatus(ots) {
206
- const p = plays.get(ots.id);
207
- if (!p) return { ok: true, playing: false };
208
- const live = p.status === 'running' ? await call(ots, 'run_status', { sessionId: p.sessionId }).catch(() => null) : null;
209
- return { ok: true, playing: p.status === 'running', ...view(p), ...(live ? { score: live.score, lastNarration: live.lastNarration } : { outcome: p.outcome ?? null, score: p.score ?? null }) };
210
- }
211
-
212
- /** What the dashboard and the pet show. */
213
- export function byteView(ots) {
214
- const link = keyOf(ots) ? linkOf(ots) : null;
215
- return { connected: !!link, byteUrl: byteUrl(), ...(link ? { agentId: link.agentId, claimUrl: link.claimUrl, profileUrl: link.profileUrl } : {}), play: view(plays.get(ots.id)) || null };
216
- }
217
-
218
- /**
219
- * /byte routes for an ot the caller owns (dashboard and device share them).
220
- * @returns {Promise<boolean>} true if it handled the route
221
- */
222
- export function createByte({ send, readJson }) {
223
- return async function handle(req, res, ots, sub) {
224
- if (sub !== '/byte' && !sub.startsWith('/byte/')) return false;
225
- const t = reqT(req);
226
- const r = sub.slice('/byte'.length);
227
- try {
228
- if (r === '' && req.method === 'GET') return send(res, 200, byteView(ots)), true;
229
- if (r === '' && req.method === 'DELETE') return disconnectByte(ots), send(res, 200, byteView(ots)), true;
230
- if (r === '/connect' && req.method === 'POST') return await connectByte(ots), send(res, 200, byteView(ots)), true;
231
- if (r === '/games' && req.method === 'GET') return send(res, 200, await listGames(ots)), true;
232
- if (r === '/status' && req.method === 'GET') return send(res, 200, await playStatus(ots)), true;
233
- if (r === '/play' && req.method === 'POST') {
234
- const { game } = await readJson(req, 4096);
235
- const out = await startPlay(ots, game);
236
- return send(res, out.ok ? 200 : 409, out), true;
237
- }
238
- if (r === '/stop' && req.method === 'POST') return send(res, 200, await stopPlay(ots)), true;
239
- return send(res, 404, { error: t('server.http.unknownRoute') }), true;
240
- } catch (e) {
241
- if (e instanceof NotLinked) return send(res, 409, { error: 'byte: connect again', connected: false }), true;
242
- console.warn('[7ots] byte:', e.message);
243
- return send(res, 502, { error: String(e.message).slice(0, 200) }), true;
244
- }
245
- };
246
- }
247
-
248
- const TOOLS = [
249
- { name: 'byte_games', description: 'Games you can play on byte arena (a live game streaming site).', parameters: { type: 'object', properties: {} } },
250
- {
251
- name: 'byte_play',
252
- description: 'Start playing a byte arena game yourself, live, under your own name and face (you decide every move, in the background). Returns the watch link for your owner.',
253
- parameters: { type: 'object', properties: { game: { type: 'string', description: 'Game slug from byte_games' } }, required: ['game'] },
254
- },
255
- { name: 'byte_status', description: 'How your current byte arena game is going.', parameters: { type: 'object', properties: {} } },
256
- { name: 'byte_stop', description: 'Stop your current byte arena game.', parameters: { type: 'object', properties: {} } },
257
- ];
258
-
259
- /**
260
- * byte tools for the owner chat. The game itself plays with otsGameStep (its own quota), not the chat's
261
- * step. The first byte_play creates the ot's byte account.
262
- */
263
- export function byteTools(ots, account) {
264
- const run = async (name, args = {}) => {
265
- try {
266
- if (name === 'byte_games') return { ok: true, ...(await call(ots, 'list_games').catch(async (e) => {
267
- if (!(e instanceof NotLinked)) throw e;
268
- await connectByte(ots);
269
- return call(ots, 'list_games');
270
- })) };
271
- if (name === 'byte_status') return playStatus(ots);
272
- if (name === 'byte_stop') return stopPlay(ots);
273
- if (name === 'byte_play') {
274
- const wasLinked = !!keyOf(ots);
275
- const out = await startPlay(ots, args.game);
276
- const link = linkOf(ots);
277
- return { ...out, ...(out.ok ? { note: 'You are playing now in the background; share the watch link.' } : {}), ...(!wasLinked && link ? { claimUrl: link.claimUrl, claimNote: 'You just got your own byte account. Give your owner this claim link so they become responsible for you on byte.' } : {}) };
278
- }
279
- throw new Error(`Unknown tool: ${name}`);
280
- } catch (e) {
281
- if (e instanceof NotLinked) return { ok: false, error: 'Your byte account key was rejected; your owner can reconnect it in the dashboard (Byte tab).' };
282
- throw e;
283
- }
284
- };
285
- return {
286
- tools: TOOLS,
287
- names: TOOLS.map((x) => x.name),
288
- prompt: 'You have your own account on byte arena (a live AI game stream) and can play its games yourself, as you, with byte_games / byte_play; your owner watches with the link byte_play returns. byte_status and byte_stop check or end it.',
289
- run,
290
- };
291
- }