@7ots/cli 0.1.17 → 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.
- package/.env.example +14 -0
- package/README.md +11 -0
- package/brand/logos/base.svg +1 -0
- package/brand/logos/clawpump.png +0 -0
- package/brand/logos/conductors.svg +1 -0
- package/brand/logos/notlogin.svg +12 -0
- package/brand/logos/pumpfun.png +0 -0
- package/brand/logos/solana.png +0 -0
- package/brand/logos/spawnerbot.svg +1 -0
- package/brand/logos/virtuals.png +0 -0
- package/cli/7ots.mjs +61 -1
- package/cli/lib/account.mjs +23 -3
- package/cli/lib/assistant.mjs +92 -14
- package/cli/lib/brain.mjs +84 -11
- package/cli/lib/card-shot.mjs +1 -1
- package/cli/lib/config.mjs +14 -3
- package/cli/lib/desktop-sync.mjs +177 -0
- package/cli/lib/i18n.mjs +9 -0
- package/cli/lib/inferences.mjs +19 -2
- package/cli/lib/integrations.mjs +98 -13
- package/cli/lib/mcp.mjs +1 -1
- package/cli/lib/open.mjs +3 -1
- package/cli/lib/pet-server.mjs +352 -41
- package/cli/lib/prompts.mjs +1 -1
- package/cli/lib/screen.mjs +1 -1
- package/cli/lib/senses/gestures.mjs +121 -0
- package/cli/lib/senses/index.mjs +490 -0
- package/cli/lib/senses/rules.mjs +159 -0
- package/cli/lib/senses/sources/activity.mjs +95 -0
- package/cli/lib/senses/sources/calendar.mjs +75 -0
- package/cli/lib/senses/sources/index.mjs +17 -0
- package/cli/lib/senses/sources/mail.mjs +48 -0
- package/cli/lib/senses/sources/system.mjs +39 -0
- package/cli/lib/senses/util.mjs +41 -0
- package/cli/lib/senses/vendor.mjs +78 -0
- package/cli/lib/stt-local.py +16 -8
- package/cli/lib/stt.mjs +53 -6
- package/cli/lib/tooluse.mjs +56 -0
- package/cli/lib/tts-local.mjs +2 -2
- package/cli/lib/vm.mjs +2 -2
- package/cli/lib/wake-local.py +109 -0
- package/cli/lib/wake.mjs +102 -0
- package/cli/pet/electron/main.cjs +190 -8
- package/cli/pet/pet.html +153 -34
- package/cli/pet/senses.html +342 -0
- package/cli/pet/settings.html +815 -74
- package/dist/7ots.esm.js +373 -146
- package/dist/7ots.esm.js.map +4 -4
- package/dist/7ots.iife.js +373 -146
- package/dist/7ots.iife.js.map +4 -4
- package/llms.txt +27 -0
- package/package.json +5 -2
- package/server/channels/apuchat.mjs +18 -4
- package/server/errors.mjs +90 -0
- package/server/notify.mjs +78 -0
- package/server/server.mjs +84 -14
- package/server/settings.mjs +3 -0
- package/server/site.mjs +401 -0
- package/server/tts.mjs +29 -5
- package/src/avatar/AvatarStage.js +2 -2
- package/src/avatar/three.js +3 -2
- package/src/character/AvatarEditor.js +2 -1
- package/src/character/Character.js +38 -5
- package/src/character/TradingCard.js +2 -0
- package/src/character/beat.js +64 -2
- package/src/character/mods/orc.js +8 -1
- package/src/character/mods.js +104 -10
- package/src/character/motion.js +252 -1
- package/src/character/parts.js +40 -38
- package/src/character/styles.js +40 -38
- package/src/character3d/Character3D.js +26 -5
- package/src/character3d/body.js +14 -12
- package/src/character3d/export.js +693 -0
- package/src/character3d/fx.js +13 -0
- package/src/character3d/index.js +2 -0
- package/src/character3d/materials.js +106 -10
- package/src/character3d/room-themes.js +1184 -0
- package/src/character3d/room.js +487 -0
- package/src/character3d/stage.js +14 -2
- package/src/creator/StepCreator.js +316 -0
- package/src/i18n/index.js +3 -3
- package/src/i18n/messages/character.js +352 -4
- package/src/i18n/messages/creator.js +138 -0
- package/src/i18n/messages/identity.js +89 -1
- package/src/i18n/messages/platform.js +270 -4
- package/src/i18n/messages/server.js +443 -1
- package/src/i18n/messages/widget.js +233 -0
- package/src/identity/random.js +14 -2
- package/src/identity/schema.js +2 -1
- package/src/index.js +9 -2
- package/src/voice/tags.js +22 -0
- package/server/platform/apuchat.mjs +0 -266
- package/server/platform/auth.mjs +0 -319
- package/server/platform/connect.mjs +0 -387
- package/server/platform/crypto.mjs +0 -80
- package/server/platform/db.mjs +0 -275
- package/server/platform/device.mjs +0 -222
- package/server/platform/integrations.mjs +0 -169
- package/server/platform/look.mjs +0 -20
- package/server/platform/mods.mjs +0 -222
- package/server/platform/orquesta.mjs +0 -577
- package/server/platform/profile.mjs +0 -161
- package/server/platform/routes.mjs +0 -542
- package/server/platform/runtime.mjs +0 -242
- package/server/platform/sites.mjs +0 -146
- package/server/platform/store.mjs +0 -456
- package/server/platform/vm.mjs +0 -1057
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.
|
|
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
|
-
"
|
|
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"
|
|
@@ -37,6 +37,7 @@ const DM_GAP_MS = 2100; // 0,5 mensajes/s por identidad
|
|
|
37
37
|
const DM_MAX = 4000;
|
|
38
38
|
const BACKLOG_MAX_AGE_MS = 10 * 60 * 1000;
|
|
39
39
|
const INVITE_MAX_AGE_MS = 3 * 60 * 1000; // una invitación vieja es una llamada que ya acabó
|
|
40
|
+
const NO_SHOW_MS = 5 * 60 * 1000; // lo que el agente espera en la sala a que entre la persona
|
|
40
41
|
const PER_SENDER_PER_HOUR = 30;
|
|
41
42
|
/** Configuración del canal desde el entorno (el SDK puede pasar la suya). */
|
|
42
43
|
export function apuchatConfigFromEnv(e = env) {
|
|
@@ -57,6 +58,7 @@ export function apuchatConfigured(cfg = apuchatConfigFromEnv()) {
|
|
|
57
58
|
/**
|
|
58
59
|
* @param {{ agent: ReturnType<import('./agent.mjs').createServerAgent>, persona: Function, log: Function, config?: object, tools?: Function }} deps
|
|
59
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
|
|
60
62
|
*/
|
|
61
63
|
export function createApuchatChannel({ agent, persona, log, config = apuchatConfigFromEnv(), tools: extraTools = null }) {
|
|
62
64
|
const cfg = { ...apuchatConfigFromEnv({}), ...config };
|
|
@@ -136,6 +138,7 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
|
|
|
136
138
|
if (res.status === 401 || res.status === 403) {
|
|
137
139
|
stats.lastError = `wait ${res.status}`;
|
|
138
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);
|
|
139
142
|
return;
|
|
140
143
|
}
|
|
141
144
|
if (!res.ok) throw new Error(`wait ${res.status}`);
|
|
@@ -215,12 +218,19 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
|
|
|
215
218
|
const say = async (text) => {
|
|
216
219
|
if (text) await send(text);
|
|
217
220
|
};
|
|
221
|
+
// Lo mismo que puede en el chat con esa persona (p. ej. Orquesta): la llamada es otro canal, no otro agente.
|
|
222
|
+
// Sin @peer (una llamada abierta desde la web) no hay a quién autorizar: sin herramientas.
|
|
223
|
+
const extra = peer ? extraTools?.({ channel: 'dm', from: peer }) || null : null;
|
|
224
|
+
const voiceOpts = () => ({
|
|
225
|
+
lang: s.lang,
|
|
226
|
+
...(extra ? { tools: extra.tools, run: (name, args) => extra.run(name, args) } : {}),
|
|
227
|
+
});
|
|
218
228
|
const greet = async () => {
|
|
219
229
|
if (s.greeted) return;
|
|
220
230
|
s.greeted = true;
|
|
221
231
|
s.lastHuman = Date.now();
|
|
222
232
|
const hello = await agent
|
|
223
|
-
.respond(`call:${channel_id}`, 'voice', `(La persona${peer ? ` @${peer}` : ''} acaba de entrar en la llamada${reason ? `; ibais a hablar de: ${reason}` : ''}. Salúdala en una frase y pregúntale en qué la ayudas.)`,
|
|
233
|
+
.respond(`call:${channel_id}`, 'voice', `(La persona${peer ? ` @${peer}` : ''} acaba de entrar en la llamada${reason ? `; ibais a hablar de: ${reason}` : ''}. Salúdala en una frase y pregúntale en qué la ayudas.)`, voiceOpts())
|
|
224
234
|
.catch(() => '');
|
|
225
235
|
await say(hello || tc('server.channels.hello', { name: p.name }));
|
|
226
236
|
};
|
|
@@ -240,7 +250,8 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
|
|
|
240
250
|
|
|
241
251
|
while (!s.done && !stopped) {
|
|
242
252
|
const now = Date.now();
|
|
243
|
-
|
|
253
|
+
// El teléfono puede tardar en sonar y en descolgarse: 5 min antes de rendirse.
|
|
254
|
+
if (!s.greeted && now - s.start > NO_SHOW_MS) return leave('nadie entró');
|
|
244
255
|
if (s.greeted && now - s.lastHuman > 180_000) {
|
|
245
256
|
await say(tc('server.channels.hangUp'));
|
|
246
257
|
return leave('silencio');
|
|
@@ -251,7 +262,8 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
|
|
|
251
262
|
}
|
|
252
263
|
let r;
|
|
253
264
|
try {
|
|
254
|
-
|
|
265
|
+
// Mientras nadie entra, vueltas cortas: el roster de /wait dice cuándo llega la persona.
|
|
266
|
+
r = await hubFetch('GET', path(`/wait?timeout=${s.greeted ? 25 : 8}${s.since ? `&since=${s.since}` : ''}`), { headers: headers(), timeoutMs: 40000 });
|
|
255
267
|
} catch {
|
|
256
268
|
await sleep(2000);
|
|
257
269
|
continue;
|
|
@@ -269,6 +281,8 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
|
|
|
269
281
|
await sleep(2000);
|
|
270
282
|
continue;
|
|
271
283
|
}
|
|
284
|
+
// Quien entra a meet no siempre habla ni toca el idioma: con verlo en la sala ya se le saluda.
|
|
285
|
+
if (!s.greeted && (r.data.roster || []).some((c) => c && c !== s.cs)) await greet();
|
|
272
286
|
const lines = [];
|
|
273
287
|
for (const m of r.data.messages || []) {
|
|
274
288
|
if (m.id > s.since) s.since = m.id;
|
|
@@ -291,7 +305,7 @@ export function createApuchatChannel({ agent, persona, log, config = apuchatConf
|
|
|
291
305
|
s.turns++;
|
|
292
306
|
await send(tc('server.channels.thinking'), 'status');
|
|
293
307
|
try {
|
|
294
|
-
await say(await agent.respond(`call:${channel_id}`, 'voice', text,
|
|
308
|
+
await say(await agent.respond(`call:${channel_id}`, 'voice', text, voiceOpts()));
|
|
295
309
|
} catch (e) {
|
|
296
310
|
log('apuchat call llm:', e.message);
|
|
297
311
|
await say(tc('server.channels.repeat'));
|
|
@@ -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
|
|
145
|
-
|
|
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)
|
|
150
|
-
|
|
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)) {
|
|
@@ -329,7 +350,10 @@ async function serveBackoffice(req, res, pathname, dir = 'backoffice') {
|
|
|
329
350
|
let file = join(ROOT, rel);
|
|
330
351
|
if (!file.startsWith(join(ROOT, dir))) return send(res, 403, { error: reqT(req)('server.http.forbidden') });
|
|
331
352
|
try {
|
|
332
|
-
if ((await stat(file)).isDirectory())
|
|
353
|
+
if ((await stat(file)).isDirectory()) {
|
|
354
|
+
if (!pathname.endsWith('/')) return redirectSlash(req, res, pathname);
|
|
355
|
+
file = join(file, 'index.html');
|
|
356
|
+
}
|
|
333
357
|
const data = await readFile(file);
|
|
334
358
|
const headers = { 'Content-Type': MIME[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' };
|
|
335
359
|
// Nada se puede enmarcar (clickjacking).
|
|
@@ -379,6 +403,8 @@ function sameOrigin(req) {
|
|
|
379
403
|
}
|
|
380
404
|
|
|
381
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');
|
|
382
408
|
if (body === undefined) {
|
|
383
409
|
res.writeHead(status);
|
|
384
410
|
return res.end();
|
|
@@ -424,29 +450,73 @@ function rateLimit(req) {
|
|
|
424
450
|
return true;
|
|
425
451
|
}
|
|
426
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
|
+
|
|
427
470
|
const MIME = {
|
|
428
471
|
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
|
|
429
472
|
'.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
|
|
430
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',
|
|
431
475
|
};
|
|
476
|
+
/** Directorio pedido sin barra final: 301 a la forma con barra (conserva la query). */
|
|
477
|
+
function redirectSlash(req, res, pathname) {
|
|
478
|
+
const q = req.url.indexOf('?');
|
|
479
|
+
res.writeHead(301, { Location: `${pathname}/${q >= 0 ? req.url.slice(q) : ''}` });
|
|
480
|
+
res.end();
|
|
481
|
+
}
|
|
482
|
+
|
|
432
483
|
const STATIC_DIRS = ['site', 'brand', 'examples', 'src', 'dist'];
|
|
433
484
|
|
|
434
|
-
async function serveStatic(req, res,
|
|
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') });
|
|
435
488
|
if (pathname === '/') {
|
|
436
|
-
res.writeHead(302, { Location:
|
|
489
|
+
res.writeHead(302, { Location: `/site/start/${url.search}` });
|
|
437
490
|
return res.end();
|
|
438
491
|
}
|
|
439
|
-
let rel
|
|
440
|
-
|
|
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();
|
|
441
499
|
let file = join(ROOT, rel);
|
|
442
500
|
if (!file.startsWith(ROOT)) return send(res, 403, { error: reqT(req)('server.http.forbidden') });
|
|
443
501
|
try {
|
|
444
|
-
if ((await stat(file)).isDirectory())
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
502
|
+
if ((await stat(file)).isDirectory()) {
|
|
503
|
+
// /site/start → /site/start/: sin la barra, los recursos relativos (start.css) no cargan.
|
|
504
|
+
if (!pathname.endsWith('/')) return redirectSlash(req, res, pathname);
|
|
505
|
+
file = join(file, 'index.html');
|
|
506
|
+
rel = join(rel, 'index.html');
|
|
507
|
+
}
|
|
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);
|
|
448
518
|
} catch {
|
|
449
|
-
|
|
519
|
+
notFound();
|
|
450
520
|
}
|
|
451
521
|
}
|
|
452
522
|
|
package/server/settings.mjs
CHANGED
|
@@ -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: {},
|