@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
package/llms.txt CHANGED
@@ -251,6 +251,33 @@ comments on what happens and has needs (food, energy, fun, levels).
251
251
  `--shell` (bash/zsh). Remove with `npx -y @7ots/cli hooks remove`.
252
252
  4. Care: `7ots feed`, `7ots play`, `7ots sleep`, `7ots status`, `7ots say "<text>"`, `7ots stop`.
253
253
 
254
+ ## Make a mod (a look for any ot: "make my ot look like an orc / a pirate / <someone>")
255
+ A mod is a JSON file the user imports in the pet (Settings → Mods → Import .json) or shares on 7ots.com.
256
+ Full format and limits: src/character/mods.js (header). Shape:
257
+ `{ id, name, character: {…patch}, face: {…}, replaces: [slots], parts: [{ id, slot, anchor, layer, svg, view, color, x, y, scale }] }`
258
+ - It REPLACES, it doesn't stack: each slot it fills (head, eyes, face, neck, back, body, extra) loses whatever the ot
259
+ wore there. Give every part a `slot`; catalog accessories in `character.accessories` take their group's slot;
260
+ `replaces: ['eyes']` (or 'all') also empties slots the mod leaves bare. `slot: 'none'` adds on top without removing.
261
+ - Resemble the person or creature physically before adding props: skin tone (`character.body.color`), body shape
262
+ (`character.body.shape`), eyes/brows/mouth type and colors, and relative `face` tweaks from -1 to 1:
263
+ width, height, jaw, chin, forehead, cheekbones, eyeSize, eyeSpacing, eyeHeight, mouthSize, mouthHeight.
264
+ - Hair is a head-slot item: a catalog one (hair, curls, mohawk, hairbun, pigtails…) with its `color`, or your own SVG part.
265
+ - Catalog ids: `SHAPES`, `EYES`, `BROWS`, `MOUTHS`, `CHEEKS`, `ACCESSORIES` (with `group`) in src/character/parts.js.
266
+ - Check it renders: `renderCharacter({ …anOt, mods: [mod] })` from src/character/Character.js returns the SVG.
267
+
268
+ ## Tokenize an ot (launch its token with SpawnerBot)
269
+ The dashboard's Tokenize tab has "Tokenize with SpawnerBot". It sends the ot's kit to SpawnerBot as a partner draft:
270
+ name, ticker, description, `/api/o/<id>/portrait.png` (a 512 px PNG of the portrait) and `/api/o/<id>/identity`.
271
+ The owner opens the link, signs in with the same Notlogin and confirms once, and the token launches from their
272
+ Notlogin wallet. 7ots never signs and never holds funds.
273
+ - Dashboard API (session, `X-7ots-Admin: 1`):
274
+ - `GET /api/platform/ots/<id>/spawnerbot` returns `{ configured, pads, nftPads, draft, nftDraft }`.
275
+ - `POST` with `{ pad, symbol, description }` returns `{ url }`.
276
+ - NFT collection instead of a token: `POST` with `{ kind: "nft", pad: "zora1155"|"mplcore", symbol, price?, supply?, royaltyBps? }`.
277
+ The portrait is the collection image; once live, `nftDraft` has `collection`, `collectionUrl` and `explorer`.
278
+ - Server env: `SPAWNERBOT_PARTNER_KEY` (`sbp_…`), optional `SPAWNERBOT_URL`.
279
+ - SpawnerBot's own agent API (campaigns, satellites, waves, write keys): https://spawnerbot.com/llms.txt.
280
+
254
281
  ## Join an apuchat meet video call with this identity
255
282
  The ot joins meet.apuchat.com with its own meet avatar, scene and personality, and talks using the configured brain.
256
283
  - New call: `npx -y @7ots/cli meet --new` prints a private link for the user (it carries keys and PIN: give it only to them),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@7ots/cli",
3
- "version": "0.1.19",
3
+ "version": "0.1.36",
4
4
  "description": "7ots.com — your AI companion with a face of its own: a desktop pet that watches over your coding agent (Claude Code and shell hooks), a personal assistant (reminders, alerts, notes, opens sites, sees your screen if allowed) and a reproducible identity (face, personality, voice) for any agent — in apuchat meet calls, Orquesta projects or your own server.",
5
5
  "homepage": "https://7ots.com",
6
6
  "repository": {
@@ -24,6 +24,7 @@
24
24
  "dist",
25
25
  "src",
26
26
  "server",
27
+ "!server/platform",
27
28
  "cli",
28
29
  "skills",
29
30
  "brand",
@@ -67,7 +68,9 @@
67
68
  ],
68
69
  "dependencies": {
69
70
  "@anthropic-ai/sdk": "^0.129.0",
70
- "openai": "^7.25.0"
71
+ "@resvg/resvg-wasm": "2.6.2",
72
+ "openai": "^7.25.0",
73
+ "three": "0.170.0"
71
74
  },
72
75
  "devDependencies": {
73
76
  "esbuild": "^0.28.2"
@@ -58,6 +58,7 @@ export function apuchatConfigured(cfg = apuchatConfigFromEnv()) {
58
58
  /**
59
59
  * @param {{ agent: ReturnType<import('./agent.mjs').createServerAgent>, persona: Function, log: Function, config?: object, tools?: Function }} deps
60
60
  * tools: extra tools for a DM, decided by sender ({ channel:'dm', from } → { tools, run } | null)
61
+ * config.onInvalidKey: called once when the hub rejects the identity key (401/403), e.g. to replace an expired free one
61
62
  */
62
63
  export function createApuchatChannel({ agent, persona, log, config = apuchatConfigFromEnv(), tools: extraTools = null }) {
63
64
  const cfg = { ...apuchatConfigFromEnv({}), ...config };
@@ -137,6 +138,7 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
137
138
  if (res.status === 401 || res.status === 403) {
138
139
  stats.lastError = `wait ${res.status}`;
139
140
  log(`apuchat: la identidad del agente no es válida (${res.status}); se deja de escuchar. ¿Caducó? Revisa APUCHAT_AGENT_IDENTITY_KEY.`);
141
+ cfg.onInvalidKey?.(res.status);
140
142
  return;
141
143
  }
142
144
  if (!res.ok) throw new Error(`wait ${res.status}`);
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Monitoreo de errores propio (P10, "Sentry o similar"), sin dependencias ni terceros:
3
+ * - back: errores 5xx del servidor, uncaughtException y unhandledRejection;
4
+ * - front: window.onerror / unhandledrejection de 7ots.com y del panel → POST /api/site/error.
5
+ * Cada error va al log (journald) y, agrupado por firma, se avisa por correo a ERROR_ALERT_EMAIL
6
+ * (defecto maestro@apumail.com) con el mismo buzón de envío que el resto de avisos (server/notify.mjs).
7
+ * Una misma firma avisa como mucho una vez por hora; tope global ERROR_ALERT_MAX_PER_HOUR (defecto 12).
8
+ * Nunca se mandan cuerpos de request, cookies ni cabeceras: sólo mensaje, pila, ruta y navegador.
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+ import { notifyConfigured, sendNotify } from './notify.mjs';
12
+
13
+ const env = process.env;
14
+ const HOUR = 3600_000;
15
+ const seen = new Map(); // firma → { at, n }
16
+ let sentHour = 0;
17
+ let sentCount = 0;
18
+
19
+ const clip = (v, n) => String(v ?? '').slice(0, n);
20
+ const sigOf = (kind, msg, where) => createHash('sha1').update(`${kind}|${msg}|${where}`).digest('hex').slice(0, 12);
21
+
22
+ /** Registra un error y avisa (best-effort, nunca lanza). */
23
+ export function reportError({ kind = 'server', message, stack, where = '', ua = '', page = '' }) {
24
+ try {
25
+ const msg = clip(message, 300) || 'Error';
26
+ const sig = sigOf(kind, msg, clip(where, 200));
27
+ const now = Date.now();
28
+ const e = seen.get(sig);
29
+ console.error(`[7ots][error:${kind}] ${sig} ${msg}${where ? ` @ ${clip(where, 200)}` : ''}`);
30
+ if (e && now - e.at < HOUR) { e.n++; return; }
31
+ const repeats = e?.n || 0;
32
+ seen.set(sig, { at: now, n: 0 });
33
+ if (seen.size > 2000) seen.clear();
34
+ const hour = Math.floor(now / HOUR);
35
+ if (hour !== sentHour) { sentHour = hour; sentCount = 0; }
36
+ if (sentCount >= Number(env.ERROR_ALERT_MAX_PER_HOUR || 12) || !notifyConfigured()) return;
37
+ sentCount++;
38
+ const text = [
39
+ `Producto: 7ots.com`,
40
+ `Tipo: ${kind}`,
41
+ `Firma: ${sig}${repeats ? ` (se repitió ${repeats} veces en la hora anterior)` : ''}`,
42
+ `Mensaje: ${msg}`,
43
+ where && `Dónde: ${clip(where, 300)}`,
44
+ page && `Página: ${clip(page, 300)}`,
45
+ ua && `Navegador: ${clip(ua, 200)}`,
46
+ `Fecha: ${new Date(now).toISOString()}`,
47
+ env.REVISION && `Versión: ${env.REVISION}`,
48
+ '',
49
+ clip(stack, 3000),
50
+ ].filter((x) => x !== '' && x != null && x !== false).join('\n');
51
+ sendNotify({ to: env.ERROR_ALERT_EMAIL || 'maestro@apumail.com', subject: `[7ots error] ${kind}: ${msg.slice(0, 120)}`, text }).catch(() => {});
52
+ } catch { /* el monitor nunca rompe nada */ }
53
+ }
54
+
55
+ /** Errores del proceso que no pasan por un request. */
56
+ export function watchProcess() {
57
+ process.on('uncaughtException', (err) => reportError({ kind: 'uncaught', message: err?.message || String(err), stack: err?.stack }));
58
+ process.on('unhandledRejection', (err) => reportError({ kind: 'unhandledRejection', message: err?.message || String(err), stack: err?.stack }));
59
+ }
60
+
61
+ /** POST /api/site/error: errores del navegador. Responde 204 siempre que el formato sea válido. */
62
+ export function createErrorIntake({ send, clientIp, originOf }) {
63
+ const perIp = new Map();
64
+ return async function handle(req, res, url) {
65
+ if (url.pathname !== '/api/site/error') return false;
66
+ if (req.method !== 'POST') { send(res, 405, { error: 'POST only' }); return true; }
67
+ const origin = req.headers.origin;
68
+ if (origin && origin !== originOf(req) && origin !== 'https://7ots.com') { send(res, 403, { error: 'origin' }); return true; }
69
+ const ip = clientIp(req);
70
+ const now = Date.now();
71
+ const b = perIp.get(ip);
72
+ const cur = b && now - b.at < 600_000 ? b : { at: now, n: 0 };
73
+ cur.n++;
74
+ perIp.set(ip, cur);
75
+ if (perIp.size > 5000) perIp.clear();
76
+ if (cur.n > 20) { res.setHeader('Retry-After', '600'); send(res, 429, { error: 'rate' }); return true; }
77
+ let raw = '';
78
+ for await (const chunk of req) {
79
+ raw += chunk;
80
+ if (raw.length > 16_384) { send(res, 413, { error: 'too large' }); return true; }
81
+ }
82
+ let d;
83
+ try { d = JSON.parse(raw || '{}'); } catch { send(res, 400, { error: 'json' }); return true; }
84
+ if (!d || typeof d.message !== 'string' || !d.message.trim()) { send(res, 400, { error: 'message' }); return true; }
85
+ reportError({ kind: 'browser', message: d.message, stack: d.stack, where: d.source ? `${clip(d.source, 200)}:${d.line || 0}:${d.col || 0}` : '', page: d.page, ua: req.headers['user-agent'] });
86
+ res.writeHead(204);
87
+ res.end();
88
+ return true;
89
+ };
90
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Correos internos de 7ots.com (al equipo, nunca a terceros elegidos por el visitante):
3
+ * formulario de contacto/feedback del sitio y aviso de alta de cuentas nuevas.
4
+ *
5
+ * Salen por la API de envío de un buzón permanente de apumail.com:
6
+ * NOTIFY_MAIL_INBOX buzón remitente (p. ej. 7ots@apumail.com) · NOTIFY_MAIL_TOKEN su token
7
+ * CONTACT_TO destino del formulario de contacto/feedback (defecto maestro@apumail.com)
8
+ * SIGNUP_NOTIFY_EMAIL destino del aviso de alta (defecto maestro@apumail.com)
9
+ * APUMAIL_API defecto https://api.apumail.com
10
+ *
11
+ * Es independiente de PLATFORM_MAIL_* (enlace mágico de acceso), que sigue apagado mientras no se configure.
12
+ */
13
+
14
+ const env = process.env;
15
+ export const notifyConfigured = () => !!(env.NOTIFY_MAIL_INBOX && env.NOTIFY_MAIL_TOKEN);
16
+ const clip = (s, n) => String(s ?? '').replace(/\r/g, '').slice(0, n).trim();
17
+
18
+ /** Envía un correo de texto plano desde el buzón de avisos. Lanza si falla. */
19
+ export async function sendNotify({ to, subject, text, replyTo }) {
20
+ if (!notifyConfigured()) {
21
+ const e = new Error('notify mail not configured');
22
+ e.status = 501;
23
+ throw e;
24
+ }
25
+ const api = (env.APUMAIL_API || 'https://api.apumail.com').replace(/\/$/, '');
26
+ const body = { to, subject: clip(subject, 256), text: clip(text, 100000) };
27
+ if (replyTo) body.reply_to = replyTo;
28
+ const res = await fetch(`${api}/api/v1/inbox/${encodeURIComponent(env.NOTIFY_MAIL_INBOX.toLowerCase())}/send`, {
29
+ method: 'POST',
30
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${env.NOTIFY_MAIL_TOKEN}` },
31
+ body: JSON.stringify(body),
32
+ signal: AbortSignal.timeout(15000),
33
+ });
34
+ if (!res.ok) {
35
+ const out = await res.json().catch(() => ({}));
36
+ const e = new Error(`apumail ${res.status} ${out.code || ''}`.trim());
37
+ e.status = res.status === 429 ? 429 : 502;
38
+ throw e;
39
+ }
40
+ return true;
41
+ }
42
+
43
+ // ───────────────────────────── aviso de alta (P15) ─────────────────────────────
44
+
45
+ const signupHits = [];
46
+ /**
47
+ * Avisa al dueño de una cuenta nueva. Best-effort: nunca lanza ni bloquea el alta.
48
+ * Solo producto, email (si lo hay), método y fecha; nada de tokens ni ids de sesión.
49
+ */
50
+ export function notifySignup({ email, via, id }) {
51
+ try {
52
+ const now = Date.now();
53
+ while (signupHits.length && now - signupHits[0] > 3600_000) signupHits.shift();
54
+ if (signupHits.length >= Number(env.SIGNUP_NOTIFY_MAX_PER_HOUR || 60)) return Promise.resolve(false);
55
+ signupHits.push(now);
56
+ const to = env.SIGNUP_NOTIFY_EMAIL || 'maestro@apumail.com';
57
+ const when = new Date(now).toISOString();
58
+ const who = email || '(sin email: cuenta notlogin)';
59
+ const text = [
60
+ 'Nueva cuenta en 7ots.com',
61
+ '',
62
+ `Producto: 7ots (https://7ots.com)`,
63
+ `Usuario: ${who}`,
64
+ `Método de alta: ${via || 'desconocido'}`,
65
+ `Cuenta: ${id ?? "?"}`,
66
+ `Fecha: ${when}`,
67
+ ].join('\n');
68
+ return sendNotify({ to, subject: `[7ots] Nueva cuenta: ${who}`, text })
69
+ .then(() => true)
70
+ .catch((e) => {
71
+ console.warn('[7ots] aviso de alta no enviado:', e.message);
72
+ return false;
73
+ });
74
+ } catch (e) {
75
+ console.warn('[7ots] aviso de alta:', e.message);
76
+ return Promise.resolve(false);
77
+ }
78
+ }
package/server/server.mjs CHANGED
@@ -54,6 +54,11 @@ const { getIdentity, identityConfigured, identityPrompt, publicIdentity, toVCard
54
54
  const { createAdmin } = await import('./admin.mjs');
55
55
  // Idioma: respuestas al cliente según Accept-Language; consola y equipo según LOCALE (ver server/i18n.mjs).
56
56
  const { reqT, requestLocale, teamT, i18nError, errorText } = await import('./i18n.mjs');
57
+ // Capa pública del sitio: idioma servido, hreflang, pie común, legales, contacto, robots/sitemap, 404 (server/site.mjs).
58
+ const { createSite, renderSitePage } = await import('./site.mjs');
59
+ // P10: monitoreo de errores propio (back + front → log + aviso por correo agrupado).
60
+ const { reportError, watchProcess, createErrorIntake } = await import('./errors.mjs');
61
+ watchProcess();
57
62
 
58
63
  const env = process.env;
59
64
  const PORT = Number(env.PORT || 8787);
@@ -111,6 +116,9 @@ const REVISION = (() => {
111
116
  try { return JSON.parse(readFileSync(join(ROOT, 'REVISION'), 'utf8')); } catch { return null; }
112
117
  })();
113
118
 
119
+ const site = createSite({ send, clientIp, originOf });
120
+ const errorIntake = createErrorIntake({ send, clientIp, originOf });
121
+
114
122
  const server = createServer(async (req, res) => {
115
123
  const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
116
124
  const t = reqT(req);
@@ -120,6 +128,8 @@ const server = createServer(async (req, res) => {
120
128
  res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', 'Access-Control-Allow-Origin': '*' });
121
129
  return res.end(req.method === 'HEAD' ? undefined : JSON.stringify(REVISION || { commit: null }));
122
130
  }
131
+ if (await errorIntake(req, res, url)) return;
132
+ if (await site.handle(req, res, url)) return;
123
133
  if (platform && ((await platform(req, res, url)) || (await auth(req, res, url)))) return;
124
134
  if (PLATFORM && (url.pathname === '/app' || url.pathname.startsWith('/app/'))) return await serveApp(req, res, url.pathname);
125
135
  if (url.pathname === '/llms.txt' && (req.method === 'GET' || req.method === 'HEAD')) {
@@ -141,13 +151,18 @@ const server = createServer(async (req, res) => {
141
151
 
142
152
  if (url.pathname.startsWith(PREFIX)) return await api(req, res, url.pathname.slice(PREFIX.length));
143
153
  if (DEMO && (await handleDemo(req, res, url, { readJson, send }))) return;
144
- if (SERVE_STATIC && req.method === 'GET') return await serveStatic(req, res, url.pathname);
145
- send(res, 404, { error: t('server.http.notFound') });
154
+ if (SERVE_STATIC && (req.method === 'GET' || req.method === 'HEAD')) return await serveStatic(req, res, url);
155
+ site.notFound(req, res, url, { error: t('server.http.notFound') });
146
156
  } catch (err) {
147
157
  // Only our own (i18n) errors reach the visitor as text; provider/SDK errors can echo keys or bodies.
148
158
  const status = err.i18n ? err.status || 500 : err.status ? 502 : 500;
149
- if (status >= 500 && status !== 501) console.error('[7ots]', req.method, url.pathname, err);
150
- if (!res.headersSent) send(res, status, { error: status >= 500 && status !== 501 ? t('server.http.internal') : errorText(err, t) });
159
+ if (status >= 500 && status !== 501) {
160
+ console.error('[7ots]', req.method, url.pathname, err);
161
+ reportError({ kind: `http ${status}`, message: err?.message || String(err), stack: err?.stack, where: `${req.method} ${url.pathname}` });
162
+ }
163
+ // An i18n error is our own sentence (a provider's reason trimmed and scrubbed, e.g. "ElevenLabs rejected the
164
+ // key"), so it is shown even on a 5xx; anything else on a 5xx stays the generic text (QA BUG-013).
165
+ if (!res.headersSent) send(res, status, { error: status >= 500 && status !== 501 && !err.i18n ? t('server.http.internal') : errorText(err, t) });
151
166
  }
152
167
  });
153
168
 
@@ -162,6 +177,12 @@ async function api(req, res, path) {
162
177
  if (!rateLimit(req)) return send(res, 429, { error: t('server.http.rateLimited') });
163
178
 
164
179
  if (path === '/chat') {
180
+ // Cupo diario por IP: el chat del sitio gasta la clave del operador.
181
+ const wait = chatDailyWait(req);
182
+ if (wait) {
183
+ res.setHeader('Retry-After', String(wait));
184
+ return send(res, 429, { error: t('server.http.rateLimited') });
185
+ }
165
186
  const body = await readJson(req, 1024 * 1024);
166
187
  const { system, messages, tools = [] } = body;
167
188
  if (typeof system !== 'string' || !Array.isArray(messages) || !messages.length || !Array.isArray(tools)) {
@@ -382,6 +403,8 @@ function sameOrigin(req) {
382
403
  }
383
404
 
384
405
  function send(res, status, body) {
406
+ // R7: todo 429 dice cuándo reintentar (los límites con su propio plazo ya lo pusieron).
407
+ if (status === 429 && !res.getHeader('Retry-After')) res.setHeader('Retry-After', '60');
385
408
  if (body === undefined) {
386
409
  res.writeHead(status);
387
410
  return res.end();
@@ -427,10 +450,28 @@ function rateLimit(req) {
427
450
  return true;
428
451
  }
429
452
 
453
+ // Cupo diario de /api/agent/chat por IP (CHAT_DAILY_PER_IP, defecto 300). Devuelve segundos de espera o 0.
454
+ const chatDay = new Map();
455
+ function chatDailyWait(req) {
456
+ const max = Number(env.CHAT_DAILY_PER_IP || 300);
457
+ if (!max) return 0;
458
+ const ip = clientIp(req);
459
+ const now = Date.now();
460
+ const day = Math.floor(now / 86400_000);
461
+ const e = chatDay.get(ip);
462
+ const cur = e && e.day === day ? e : { day, n: 0 };
463
+ if (cur.n >= max) return Math.ceil(((day + 1) * 86400_000 - now) / 1000);
464
+ cur.n++;
465
+ chatDay.set(ip, cur);
466
+ if (chatDay.size > 20000) chatDay.clear();
467
+ return 0;
468
+ }
469
+
430
470
  const MIME = {
431
471
  '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
432
472
  '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
433
473
  '.jpg': 'image/jpeg', '.glb': 'model/gltf-binary', '.md': 'text/markdown; charset=utf-8', '.ico': 'image/x-icon',
474
+ '.webp': 'image/webp', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8',
434
475
  };
435
476
  /** Directorio pedido sin barra final: 301 a la forma con barra (conserva la query). */
436
477
  function redirectSlash(req, res, pathname) {
@@ -441,13 +482,20 @@ function redirectSlash(req, res, pathname) {
441
482
 
442
483
  const STATIC_DIRS = ['site', 'brand', 'examples', 'src', 'dist'];
443
484
 
444
- async function serveStatic(req, res, pathname) {
485
+ async function serveStatic(req, res, url) {
486
+ const pathname = url.pathname;
487
+ const notFound = () => site.notFound(req, res, url, { error: reqT(req)('server.http.notFound') });
445
488
  if (pathname === '/') {
446
- res.writeHead(302, { Location: '/site/start/' });
489
+ res.writeHead(302, { Location: `/site/start/${url.search}` });
447
490
  return res.end();
448
491
  }
449
- let rel = normalize(decodeURIComponent(pathname)).replace(/^([/\\])+/, '');
450
- if (!STATIC_DIRS.some((d) => rel === d || rel.startsWith(`${d}/`))) return send(res, 404, { error: reqT(req)('server.http.notFound') });
492
+ let rel;
493
+ try {
494
+ rel = normalize(decodeURIComponent(pathname)).replace(/^([/\\])+/, '');
495
+ } catch {
496
+ return notFound();
497
+ }
498
+ if (!STATIC_DIRS.some((d) => rel === d || rel.startsWith(`${d}/`))) return notFound();
451
499
  let file = join(ROOT, rel);
452
500
  if (!file.startsWith(ROOT)) return send(res, 403, { error: reqT(req)('server.http.forbidden') });
453
501
  try {
@@ -455,12 +503,20 @@ async function serveStatic(req, res, pathname) {
455
503
  // /site/start → /site/start/: sin la barra, los recursos relativos (start.css) no cargan.
456
504
  if (!pathname.endsWith('/')) return redirectSlash(req, res, pathname);
457
505
  file = join(file, 'index.html');
506
+ rel = join(rel, 'index.html');
458
507
  }
459
- const data = await readFile(file);
460
- res.writeHead(200, { 'Content-Type': MIME[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
461
- res.end(data);
508
+ let data = await readFile(file);
509
+ const headers = { 'Content-Type': MIME[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' };
510
+ // Páginas del sitio: idioma, hreflang, OG y pie se resuelven en el servidor.
511
+ if (rel.startsWith('site/') && extname(file) === '.html') {
512
+ data = Buffer.from(renderSitePage(req, url, rel.replace(/\\/g, '/'), data.toString('utf8')));
513
+ headers.Vary = 'Accept-Language, Cookie';
514
+ }
515
+ headers['Content-Length'] = data.length;
516
+ res.writeHead(200, headers);
517
+ res.end(req.method === 'HEAD' ? undefined : data);
462
518
  } catch {
463
- send(res, 404, { error: reqT(req)('server.http.notFound') });
519
+ notFound();
464
520
  }
465
521
  }
466
522
 
@@ -36,6 +36,9 @@ export const SERVER_KEYS = {
36
36
  APUCHAT_VOICE_URL: {}, APUCHAT_VOICE_TOKEN: { secret: true }, APUCHAT_VOICE_ID: {}, APUCHAT_VOICE_PROVIDER: {},
37
37
  XAI_API_KEY: { secret: true }, XAI_TTS_VOICE: {},
38
38
  FISH_API_KEY: { secret: true }, FISH_VOICE_ID: {}, FISH_MODEL: {},
39
+ // Fotos con IA de la plaza (server/platform/imagegen.mjs)
40
+ PLAZA_IMAGE_PROVIDER: {}, PLAZA_IMAGE_MODEL: {}, PLAZA_IMAGE_REGION: {}, PLAZA_IMAGE_QUALITY: {}, PLAZA_IMAGINE_DAILY: {},
41
+ AWS_BEARER_TOKEN_BEDROCK: { secret: true }, AWS_ACCESS_KEY_ID: {}, AWS_SECRET_ACCESS_KEY: { secret: true },
39
42
  // Contacto desde el widget
40
43
  APUMAIL_API: {}, APUMAIL_INBOX: {}, APUMAIL_INBOX_TOKEN: { secret: true }, APUMAIL_TO: {},
41
44
  APUCHAT_HUB: { channels: true }, APUCHAT_NOTIFIER_IDENTITY_KEY: { secret: true }, APUCHAT_OPERATOR_HANDLE: {}, APUCHAT_TRANSCRIBE: {},