@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,469 +0,0 @@
1
- /**
2
- * Datos de la plataforma: cuentas, sesiones, ots, conversaciones y uso.
3
- * Todo pasa por aquí; las rutas nunca escriben SQL.
4
- */
5
-
6
- import { defineIdentity } from '../../src/identity/schema.js';
7
- import { getDb, monthOf, tx } from './db.mjs';
8
- import { lookPrint } from './look.mjs';
9
- import { randomIdentity, newSeed } from '../../src/identity/random.js';
10
- import { i18nError } from '../i18n.mjs';
11
- import { newId, open, seal, sha256, token } from './crypto.mjs';
12
-
13
- const now = () => Date.now();
14
- const parse = (s, fallback) => {
15
- try {
16
- return JSON.parse(s);
17
- } catch {
18
- return fallback;
19
- }
20
- };
21
-
22
- export const SESSION_TTL = 30 * 24 * 3600_000;
23
- export const MAX_OTS_PER_ACCOUNT = () => Number(process.env.PLATFORM_MAX_OTS || 7);
24
-
25
- /**
26
- * Ajustes que cada ots puede cambiar. Lo que no está aquí lo fija la plataforma
27
- * (hub de apuchat, API de apumail, URL de la voz de apuchat, puertos…): así nadie puede
28
- * apuntar el servidor a direcciones internas.
29
- * secret: se guarda cifrado y nunca se devuelve.
30
- * max: tope numérico.
31
- * channels: al cambiar, se reinician los canales de ese ots.
32
- * managed: only the dashboard's own routes write it (apuchat identity, Orquesta panel);
33
- * the backoffice's /server PUT ignores it and a duplicate doesn't copy it.
34
- */
35
- export const OTS_KEYS = {
36
- LLM_PROVIDER: {}, LLM_MODEL: {}, LLM_EFFORT: {}, LLM_MAX_TOKENS: { max: 16000 },
37
- ANTHROPIC_API_KEY: { secret: true }, OPENAI_API_KEY: { secret: true },
38
- SERVER_INSTRUCTIONS: {},
39
- TTS_PROVIDER: {}, OPENAI_TTS_MODEL: {}, OPENAI_TTS_VOICE: {},
40
- ELEVENLABS_API_KEY: { secret: true }, ELEVENLABS_VOICE_ID: {}, ELEVENLABS_MODEL: {},
41
- APUCHAT_VOICE_TOKEN: { secret: true }, APUCHAT_VOICE_ID: {}, APUCHAT_VOICE_PROVIDER: {},
42
- XAI_API_KEY: { secret: true }, XAI_TTS_VOICE: {},
43
- FISH_API_KEY: { secret: true }, FISH_VOICE_ID: {}, FISH_MODEL: {},
44
- APUMAIL_INBOX: {}, APUMAIL_INBOX_TOKEN: { secret: true }, APUMAIL_TO: {},
45
- APUCHAT_NOTIFIER_IDENTITY_KEY: { secret: true }, APUCHAT_OPERATOR_HANDLE: {}, APUCHAT_TRANSCRIBE: {},
46
- APUMAIL_AGENT_INBOX: { channels: true }, APUMAIL_AGENT_TOKEN: { secret: true, channels: true },
47
- APUMAIL_AGENT_DAILY: { channels: true, max: 100 },
48
- APUCHAT_AGENT_IDENTITY_KEY: { secret: true, channels: true }, APUCHAT_AGENT_ALLOW: { channels: true },
49
- AGENT_MAX_CALLS: { channels: true, max: 3 }, AGENT_CALL_MAX_MINUTES: { channels: true, max: 30 }, AGENT_CALL_MAX_TURNS: { channels: true, max: 60 },
50
- // apuchat identity made from the dashboard: its @callsign, '1' while it is a free one, and who holds it
51
- // ('managed' = the platform's anonymous apuchat account for this 7ots account, 'linked' = the user's own).
52
- APUCHAT_AGENT_CALLSIGN: { managed: true }, APUCHAT_AGENT_FREE: { managed: true }, APUCHAT_AGENT_OWNER: { managed: true },
53
- // Orquesta tasks: project, on/off, who may ask outside the dashboard (explicit list, empty = nobody), daily cap.
54
- // Read on every message, so changing them never restarts the channels.
55
- ORQUESTA_PROJECT: { managed: true }, ORQUESTA_PROJECT_NAME: { managed: true }, ORQUESTA_TASKS: { managed: true },
56
- ORQUESTA_ALLOW: { managed: true }, ORQUESTA_DAILY: { managed: true, max: 200 },
57
- // The ot's own MCP servers and APIs (integrations.mjs): JSON list; their tokens live in secrets as INTEG_<id>.
58
- INTEGRATIONS: { managed: true },
59
- // Cloud VM (vm.mjs): which job kinds the desktop may send to this ot's worker (csv; default research,browse,long).
60
- VM_JOB_KINDS: {},
61
- };
62
-
63
- // ───────────────────────────── cuentas ─────────────────────────────
64
-
65
- export function accountById(id) {
66
- return getDb().prepare('SELECT * FROM accounts WHERE id = ?').get(id) || null;
67
- }
68
-
69
- /**
70
- * Cuenta para un login. Con notlogin se busca por `sub`; si no existe y trae un email
71
- * verificado que ya tiene cuenta, se vincula a esa. Si no, se crea.
72
- */
73
- export function upsertAccount({ email = null, notloginSub = null, name = '' }) {
74
- email = email ? String(email).trim().toLowerCase() : null;
75
- return tx((d) => {
76
- let acc = notloginSub ? d.prepare('SELECT * FROM accounts WHERE notlogin_sub = ?').get(notloginSub) : null;
77
- if (!acc && email) acc = d.prepare('SELECT * FROM accounts WHERE email = ?').get(email);
78
- // An email account already tied to a different notlogin identity is not taken over.
79
- if (acc && notloginSub && acc.notlogin_sub && acc.notlogin_sub !== notloginSub) throw i18nError(409, 'platform.api.accountLinked');
80
- if (acc) {
81
- if (notloginSub && !acc.notlogin_sub) d.prepare('UPDATE accounts SET notlogin_sub = ? WHERE id = ?').run(notloginSub, acc.id);
82
- if (email && !acc.email && !d.prepare('SELECT 1 FROM accounts WHERE email = ?').get(email)) d.prepare('UPDATE accounts SET email = ? WHERE id = ?').run(email, acc.id);
83
- d.prepare('UPDATE accounts SET last_login_at = ? WHERE id = ?').run(now(), acc.id);
84
- return d.prepare('SELECT * FROM accounts WHERE id = ?').get(acc.id);
85
- }
86
- const id = newId('acc');
87
- d.prepare('INSERT INTO accounts (id, email, notlogin_sub, name, created_at, last_login_at) VALUES (?, ?, ?, ?, ?, ?)').run(id, email, notloginSub, String(name || '').slice(0, 80), now(), now());
88
- return d.prepare('SELECT * FROM accounts WHERE id = ?').get(id);
89
- });
90
- }
91
-
92
- /** Ties a notlogin identity to an account that signed in another way ("Connect Notlogin"). */
93
- export function linkNotlogin(accountId, notloginSub) {
94
- return tx((d) => {
95
- const acc = d.prepare('SELECT * FROM accounts WHERE id = ?').get(accountId);
96
- if (!acc) throw i18nError(404, 'platform.api.notFound');
97
- if (acc.notlogin_sub === notloginSub) return acc;
98
- if (acc.notlogin_sub || d.prepare('SELECT 1 FROM accounts WHERE notlogin_sub = ?').get(notloginSub)) throw i18nError(409, 'platform.api.accountLinked');
99
- d.prepare('UPDATE accounts SET notlogin_sub = ? WHERE id = ?').run(notloginSub, accountId);
100
- return d.prepare('SELECT * FROM accounts WHERE id = ?').get(accountId);
101
- });
102
- }
103
-
104
- export function publicAccount(acc) {
105
- return { id: acc.id, email: acc.email, name: acc.name, plan: acc.plan, notlogin: !!acc.notlogin_sub, vmEnabled: acc.vm_enabled === 1, createdAt: acc.created_at };
106
- }
107
-
108
- // ───────────────────────────── sesiones ─────────────────────────────
109
-
110
- /** Crea una sesión y devuelve el token en claro (solo va en la cookie). */
111
- export function createSession(accountId, via) {
112
- const raw = token();
113
- getDb().prepare('INSERT INTO sessions (id, account_id, created_at, expires_at, via) VALUES (?, ?, ?, ?, ?)').run(sha256(raw), accountId, now(), now() + SESSION_TTL, via);
114
- return raw;
115
- }
116
-
117
- export function sessionAccount(raw) {
118
- if (!raw) return null;
119
- const row = getDb().prepare('SELECT a.* FROM sessions s JOIN accounts a ON a.id = s.account_id WHERE s.id = ? AND s.expires_at > ?').get(sha256(raw), now());
120
- return row || null;
121
- }
122
-
123
- export function deleteSession(raw) {
124
- if (raw) getDb().prepare('DELETE FROM sessions WHERE id = ?').run(sha256(raw));
125
- }
126
-
127
- /** Closes every session of the account (sign out everywhere). */
128
- export function deleteAccountSessions(accountId) {
129
- getDb().prepare('DELETE FROM sessions WHERE account_id = ?').run(accountId);
130
- }
131
-
132
- /** Does a login (email or notlogin sub) already have an account? */
133
- export function accountExists({ email = null, notloginSub = null }) {
134
- const d = getDb();
135
- return !!((notloginSub && d.prepare('SELECT 1 FROM accounts WHERE notlogin_sub = ?').get(notloginSub)) || (email && d.prepare('SELECT 1 FROM accounts WHERE email = ?').get(String(email).trim().toLowerCase())));
136
- }
137
-
138
- // ───────────────────────────── enlaces por email ─────────────────────────────
139
-
140
- export const LOGIN_TOKEN_TTL = 15 * 60_000;
141
-
142
- export function createLoginToken(email) {
143
- const raw = token();
144
- const d = getDb();
145
- d.prepare('DELETE FROM login_tokens WHERE expires_at < ?').run(now() - 24 * 3600_000);
146
- d.prepare('INSERT INTO login_tokens (hash, email, expires_at) VALUES (?, ?, ?)').run(sha256(raw), email, now() + LOGIN_TOKEN_TTL);
147
- return raw;
148
- }
149
-
150
- /** Enlaces pedidos para ese email en la última hora (límite anti-abuso). */
151
- export function recentLoginTokens(email) {
152
- return getDb().prepare('SELECT COUNT(*) n FROM login_tokens WHERE email = ? AND expires_at > ?').get(email, now() + LOGIN_TOKEN_TTL - 3600_000).n;
153
- }
154
-
155
- /** Gasta un enlace: devuelve el email si era válido (una sola vez). */
156
- export function consumeLoginToken(raw) {
157
- if (!raw) return null;
158
- return tx((d) => {
159
- const row = d.prepare('SELECT * FROM login_tokens WHERE hash = ?').get(sha256(raw));
160
- if (!row || row.used_at || row.expires_at < now()) return null;
161
- d.prepare('UPDATE login_tokens SET used_at = ? WHERE hash = ?').run(now(), row.hash);
162
- return row.email;
163
- });
164
- }
165
-
166
- // ───────────────────────────── ots ─────────────────────────────
167
-
168
- function hydrate(row) {
169
- if (!row) return null;
170
- return {
171
- id: row.id,
172
- accountId: row.account_id,
173
- name: row.name,
174
- status: row.status,
175
- domains: parse(row.domains, []),
176
- identity: defineIdentity(parse(row.identity, {})),
177
- widget: parse(row.widget, {}),
178
- settings: parse(row.settings, {}),
179
- secrets: open(row.secrets),
180
- lookPrint: row.look_print || null,
181
- createdAt: row.created_at,
182
- updatedAt: row.updated_at,
183
- };
184
- }
185
-
186
- export function getOts(id) {
187
- return hydrate(getDb().prepare('SELECT * FROM ots WHERE id = ?').get(String(id || '')));
188
- }
189
-
190
- /** El ots solo si es de esa cuenta (si no, null: la ruta responde 404, no 403). */
191
- export function getOwnOts(accountId, id) {
192
- const o = getOts(id);
193
- return o && o.accountId === accountId ? o : null;
194
- }
195
-
196
- export function listOts(accountId) {
197
- return getDb().prepare('SELECT * FROM ots WHERE account_id = ? ORDER BY created_at').all(accountId).map(hydrate);
198
- }
199
-
200
- export function countOts(accountId) {
201
- return getDb().prepare('SELECT COUNT(*) n FROM ots WHERE account_id = ?').get(accountId).n;
202
- }
203
-
204
- // Cada ot es único (ver look.mjs): la base rechaza una cara repetida con este error.
205
- const isLookClash = (e) => /UNIQUE/i.test(e?.message || '') && /look_print/.test(e.message);
206
- const lookTakenError = () => i18nError(409, 'platform.api.lookTaken');
207
-
208
- /** ¿Esa cara ya la tiene otro ot? (`exceptId`: el propio, al guardarlo). */
209
- export function lookTaken(identity, exceptId = '') {
210
- const p = lookPrint(defineIdentity(identity));
211
- return !!p && !!getDb().prepare('SELECT 1 FROM ots WHERE look_print = ? AND id != ?').get(p, String(exceptId));
212
- }
213
-
214
- /**
215
- * La misma identidad con una cara nueva que nadie tenga: la de la semilla `seed` si está libre y si no,
216
- * semillas al azar. Lo usan crear (un ot sin cara elegida) y duplicar.
217
- */
218
- export function withFreeLook(identity, seed = null) {
219
- for (let i = 0; i < 40; i++) {
220
- const look = randomIdentity(i === 0 && seed ? seed : newSeed()).look;
221
- const next = { ...identity, look: { ...identity.look, kind: 'character', character: look.character } };
222
- if (!lookTaken(next)) return next;
223
- }
224
- throw lookTakenError();
225
- }
226
-
227
- export function createOts(accountId, { name, identity = {}, widget = {}, settings = {}, secrets = {}, domains = [] } = {}) {
228
- const id = newId('ots');
229
- const nm = cleanName(name) || 'Ots';
230
- const ident = defineIdentity({ ...identity, name: identity.name || nm });
231
- try {
232
- getDb()
233
- .prepare('INSERT INTO ots (id, account_id, name, status, domains, identity, widget, settings, secrets, look_print, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
234
- .run(id, accountId, nm, 'on', JSON.stringify(cleanDomains(domains)), JSON.stringify(ident), JSON.stringify(widget), JSON.stringify(settings), seal(secrets), lookPrint(ident), now(), now());
235
- } catch (e) {
236
- throw isLookClash(e) ? lookTakenError() : e;
237
- }
238
- return getOts(id);
239
- }
240
-
241
- /** Copia un ots (sin sus claves ni canales propios: un @handle no puede estar en dos ots) con otra cara: no hay dos iguales. */
242
- export function duplicateOts(accountId, src) {
243
- const settings = { ...src.settings };
244
- for (const k of Object.keys(settings)) if (OTS_KEYS[k]?.channels || OTS_KEYS[k]?.managed) delete settings[k];
245
- return createOts(accountId, { name: `${src.name} (copia)`, identity: withFreeLook(src.identity), widget: src.widget, settings, domains: src.domains });
246
- }
247
-
248
- export function updateOts(id, patch) {
249
- const cur = getOts(id);
250
- if (!cur) return null;
251
- const next = { ...cur, ...patch };
252
- // Un ot viejo que ya repetía cara (sin huella) se puede seguir guardando mientras no la cambie.
253
- let print = lookPrint(next.identity);
254
- if (!cur.lookPrint && print === lookPrint(cur.identity) && lookTaken(next.identity, id)) print = null;
255
- try {
256
- getDb()
257
- .prepare('UPDATE ots SET name = ?, status = ?, domains = ?, identity = ?, widget = ?, settings = ?, secrets = ?, look_print = ?, updated_at = ? WHERE id = ?')
258
- .run(cleanName(next.name) || cur.name, next.status === 'off' ? 'off' : 'on', JSON.stringify(cleanDomains(next.domains)), JSON.stringify(next.identity), JSON.stringify(next.widget), JSON.stringify(next.settings), seal(next.secrets), print, now(), id);
259
- } catch (e) {
260
- throw isLookClash(e) ? lookTakenError() : e;
261
- }
262
- return getOts(id);
263
- }
264
-
265
- export function deleteOts(id) {
266
- getDb().prepare('DELETE FROM ots WHERE id = ?').run(id);
267
- }
268
-
269
- /** Todos los ots encendidos (para arrancar sus canales). */
270
- export function allLiveOts() {
271
- return getDb().prepare("SELECT * FROM ots WHERE status = 'on'").all().map(hydrate);
272
- }
273
-
274
- function cleanName(s) {
275
- return String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, 60);
276
- }
277
-
278
- /**
279
- * Dominios donde puede ir el widget: "tienda.com", "*.tienda.com" o "http://localhost:3000".
280
- * Se guardan como orígenes o comodines normalizados.
281
- */
282
- export function cleanDomains(list) {
283
- const out = new Set();
284
- for (const raw of Array.isArray(list) ? list : String(list || '').split(/[\s,]+/)) {
285
- let s = String(raw || '').trim().toLowerCase().replace(/\/+$/, '');
286
- if (!s) continue;
287
- const wildcard = s.startsWith('*.');
288
- if (wildcard) s = s.slice(2);
289
- if (!/^https?:\/\//.test(s)) s = `https://${s}`;
290
- let u;
291
- try {
292
- u = new URL(s);
293
- } catch {
294
- continue;
295
- }
296
- if (!/^[a-z0-9.-]+$/.test(u.hostname) || u.pathname !== '/' || u.search || u.username) continue;
297
- out.add(wildcard ? `*.${u.hostname}` : u.origin);
298
- if (out.size >= 20) break;
299
- }
300
- return [...out];
301
- }
302
-
303
- /** ¿Puede este origen usar el ots? */
304
- export function originAllowed(ots, origin) {
305
- let u;
306
- try {
307
- u = new URL(origin);
308
- } catch {
309
- return false;
310
- }
311
- return ots.domains.some((d) => {
312
- if (d.startsWith('*.')) {
313
- const base = d.slice(2);
314
- return u.protocol === 'https:' && (u.hostname === base || u.hostname.endsWith(`.${base}`));
315
- }
316
- // "https://tienda.com" también admite www.tienda.com
317
- const a = new URL(d);
318
- return u.protocol === a.protocol && u.port === a.port && (u.hostname === a.hostname || u.hostname === `www.${a.hostname}`);
319
- });
320
- }
321
-
322
- // ───────────────────────────── conversaciones ─────────────────────────────
323
-
324
- /**
325
- * Apunta un turno en la conversación (se crea la primera vez).
326
- * `key` la elige quien llama (sesión del widget, contacto del canal); el id se deriva de ella.
327
- * @returns {{ created: boolean }}
328
- */
329
- /** `page`: URL concreta (actualiza la conversación); `origin`: solo si aún no hay página. */
330
- export function logTurn(ots, { key, channel = 'web', visitor = '', page = '', origin = '', user = '', reply = '' }) {
331
- if (!key || (!user && !reply)) return { created: false };
332
- const id = `c_${sha256(`${ots.id}:${channel}:${key}`).slice(0, 22)}`;
333
- const t = now();
334
- return tx((d) => {
335
- const cur = d.prepare('SELECT id FROM conversations WHERE id = ?').get(id);
336
- if (!cur) {
337
- d.prepare('INSERT INTO conversations (id, ots_id, channel, visitor, page, title, messages, started_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)').run(id, ots.id, channel, String(visitor).slice(0, 120), String(page || origin).slice(0, 500), String(user || reply).replace(/\s+/g, ' ').slice(0, 80), t, t);
338
- }
339
- let n = 0;
340
- if (user) {
341
- d.prepare('INSERT INTO messages (conversation_id, role, content, at) VALUES (?, ?, ?, ?)').run(id, 'user', String(user).slice(0, 8000), t);
342
- n++;
343
- }
344
- if (reply) {
345
- d.prepare('INSERT INTO messages (conversation_id, role, content, at) VALUES (?, ?, ?, ?)').run(id, 'assistant', String(reply).slice(0, 8000), t);
346
- n++;
347
- }
348
- d.prepare('UPDATE conversations SET messages = messages + ?, updated_at = ?, page = CASE WHEN ? != \'\' THEN ? ELSE page END WHERE id = ?').run(n, t, page, String(page).slice(0, 500), id);
349
- return { created: !cur };
350
- });
351
- }
352
-
353
- export function listConversations(otsId, { limit = 50, before = null } = {}) {
354
- const lim = Math.min(200, Math.max(1, Number(limit) || 50));
355
- const rows = before
356
- ? getDb().prepare('SELECT * FROM conversations WHERE ots_id = ? AND updated_at < ? ORDER BY updated_at DESC LIMIT ?').all(otsId, Number(before), lim)
357
- : getDb().prepare('SELECT * FROM conversations WHERE ots_id = ? ORDER BY updated_at DESC LIMIT ?').all(otsId, lim);
358
- return rows.map((r) => ({ id: r.id, channel: r.channel, visitor: r.visitor, page: r.page, title: r.title, messages: r.messages, startedAt: r.started_at, updatedAt: r.updated_at }));
359
- }
360
-
361
- export function getConversation(otsId, id) {
362
- const c = getDb().prepare('SELECT * FROM conversations WHERE id = ? AND ots_id = ?').get(id, otsId);
363
- if (!c) return null;
364
- const messages = getDb().prepare('SELECT role, content, at FROM messages WHERE conversation_id = ? ORDER BY id LIMIT 2000').all(id);
365
- return { id: c.id, channel: c.channel, visitor: c.visitor, page: c.page, title: c.title, startedAt: c.started_at, updatedAt: c.updated_at, messages };
366
- }
367
-
368
- export function deleteConversation(otsId, id) {
369
- return getDb().prepare('DELETE FROM conversations WHERE id = ? AND ots_id = ?').run(id, otsId).changes > 0;
370
- }
371
-
372
- // ───────────────────────────── uso ─────────────────────────────
373
-
374
- /**
375
- * Tipos: llm (respuestas de IA), llm_platform (las pagadas por la plataforma),
376
- * tts / tts_platform (audios), call (videollamadas), conversation (conversaciones nuevas).
377
- */
378
- export function addUsage(ots, kind, n = 1, period = monthOf()) {
379
- getDb()
380
- .prepare('INSERT INTO usage (account_id, ots_id, month, kind, count) VALUES (?, ?, ?, ?, ?) ON CONFLICT(ots_id, month, kind) DO UPDATE SET count = count + excluded.count')
381
- .run(ots.accountId, ots.id, period, kind, n);
382
- }
383
-
384
- /** Uso del mes de toda la cuenta de un tipo (para el cupo gratis). */
385
- export function accountUsage(accountId, kind, month = monthOf()) {
386
- return getDb().prepare('SELECT COALESCE(SUM(count), 0) n FROM usage WHERE account_id = ? AND month = ? AND kind = ?').get(accountId, month, kind).n;
387
- }
388
-
389
- /** Uso del mes por ots: { [otsId]: { llm, llm_platform, … } } */
390
- export function usageByOts(accountId, month = monthOf()) {
391
- const out = {};
392
- for (const r of getDb().prepare('SELECT ots_id, kind, count FROM usage WHERE account_id = ? AND month = ?').all(accountId, month)) {
393
- (out[r.ots_id] ||= {})[r.kind] = r.count;
394
- }
395
- return out;
396
- }
397
-
398
- /** Últimos meses de un ots: [{ month, llm, … }] */
399
- export function usageHistory(otsId, months = 6) {
400
- // `month` también guarda días (YYYY-MM-DD, el cupo diario de byte): el historial es sólo de meses
401
- const rows = getDb().prepare('SELECT month, kind, count FROM usage WHERE ots_id = ? AND length(month) = 7 ORDER BY month DESC').all(otsId);
402
- const by = new Map();
403
- for (const r of rows) {
404
- if (!by.has(r.month)) by.set(r.month, { month: r.month });
405
- by.get(r.month)[r.kind] = r.count;
406
- }
407
- return [...by.values()].slice(0, months);
408
- }
409
-
410
- // ───────────────────────────── integraciones ─────────────────────────────
411
-
412
- /** Connected service of an account ('apuchat' | 'orquesta'): its tokens, decrypted. null if none. */
413
- export function getIntegration(accountId, kind) {
414
- const row = getDb().prepare('SELECT data FROM integrations WHERE account_id = ? AND kind = ?').get(accountId, kind);
415
- return row ? open(row.data) : null;
416
- }
417
-
418
- /** Saves (sealed) or, with null, forgets an account's integration. */
419
- export function setIntegration(accountId, kind, data) {
420
- if (data == null) return void getDb().prepare('DELETE FROM integrations WHERE account_id = ? AND kind = ?').run(accountId, kind);
421
- getDb()
422
- .prepare('INSERT INTO integrations (account_id, kind, data, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(account_id, kind) DO UPDATE SET data = excluded.data, updated_at = excluded.updated_at')
423
- .run(accountId, kind, seal(data), now());
424
- }
425
-
426
- export function getPlatformState(key) {
427
- return getDb().prepare('SELECT value FROM platform_state WHERE key = ?').get(key)?.value ?? null;
428
- }
429
-
430
- export function setPlatformState(key, value) {
431
- getDb().prepare('INSERT INTO platform_state (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at').run(key, String(value), now());
432
- }
433
-
434
- // ───────────────────────────── tareas de Orquesta ─────────────────────────────
435
-
436
- const taskOf = (r) => r && { id: r.id, otsId: r.ots_id, projectId: r.project_id, who: r.who, channel: r.channel, task: r.task, status: r.status, result: r.result, error: r.error, createdAt: r.created_at, updatedAt: r.updated_at };
437
- export const TASK_FINAL = ['completed', 'failed', 'cancelled'];
438
-
439
- export function addTask(ots, { id, projectId, who, channel, task, status = 'pending' }) {
440
- getDb()
441
- .prepare('INSERT INTO ots_tasks (id, ots_id, account_id, project_id, who, channel, task, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
442
- .run(String(id), ots.id, ots.accountId, String(projectId || ''), String(who).slice(0, 200), String(channel).slice(0, 20), String(task).slice(0, 8000), status, now(), now());
443
- return getTask(ots.id, id);
444
- }
445
-
446
- export function updateTask(id, { status, result, error }) {
447
- getDb()
448
- .prepare('UPDATE ots_tasks SET status = COALESCE(?, status), result = COALESCE(?, result), error = COALESCE(?, error), updated_at = ? WHERE id = ?')
449
- .run(status ?? null, result == null ? null : String(result).slice(0, 20000), error == null ? null : String(error).slice(0, 2000), now(), String(id));
450
- }
451
-
452
- /** The task only if it belongs to that ot. */
453
- export function getTask(otsId, id) {
454
- return taskOf(getDb().prepare('SELECT * FROM ots_tasks WHERE id = ? AND ots_id = ?').get(String(id || ''), otsId)) || null;
455
- }
456
-
457
- export function listTasks(otsId, limit = 20) {
458
- return getDb().prepare('SELECT * FROM ots_tasks WHERE ots_id = ? ORDER BY created_at DESC LIMIT ?').all(otsId, Math.min(100, Math.max(1, Number(limit) || 20))).map(taskOf);
459
- }
460
-
461
- /** Tasks the ot sent in the last 24 h (its daily cap). */
462
- export function tasksLastDay(otsId) {
463
- return getDb().prepare('SELECT COUNT(*) n FROM ots_tasks WHERE ots_id = ? AND created_at > ?').get(otsId, now() - 24 * 3600_000).n;
464
- }
465
-
466
- /** Tasks not finished yet (newest first). */
467
- export function openTasks(otsId) {
468
- return getDb().prepare(`SELECT * FROM ots_tasks WHERE ots_id = ? AND status NOT IN (${TASK_FINAL.map(() => '?').join(', ')}) ORDER BY created_at DESC LIMIT 5`).all(otsId, ...TASK_FINAL).map(taskOf);
469
- }