@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.
Files changed (107) hide show
  1. package/.env.example +14 -0
  2. package/README.md +11 -0
  3. package/brand/logos/base.svg +1 -0
  4. package/brand/logos/clawpump.png +0 -0
  5. package/brand/logos/conductors.svg +1 -0
  6. package/brand/logos/notlogin.svg +12 -0
  7. package/brand/logos/pumpfun.png +0 -0
  8. package/brand/logos/solana.png +0 -0
  9. package/brand/logos/spawnerbot.svg +1 -0
  10. package/brand/logos/virtuals.png +0 -0
  11. package/cli/7ots.mjs +61 -1
  12. package/cli/lib/account.mjs +23 -3
  13. package/cli/lib/assistant.mjs +92 -14
  14. package/cli/lib/brain.mjs +84 -11
  15. package/cli/lib/card-shot.mjs +1 -1
  16. package/cli/lib/config.mjs +14 -3
  17. package/cli/lib/desktop-sync.mjs +177 -0
  18. package/cli/lib/i18n.mjs +9 -0
  19. package/cli/lib/inferences.mjs +19 -2
  20. package/cli/lib/integrations.mjs +98 -13
  21. package/cli/lib/mcp.mjs +1 -1
  22. package/cli/lib/open.mjs +3 -1
  23. package/cli/lib/pet-server.mjs +352 -41
  24. package/cli/lib/prompts.mjs +1 -1
  25. package/cli/lib/screen.mjs +1 -1
  26. package/cli/lib/senses/gestures.mjs +121 -0
  27. package/cli/lib/senses/index.mjs +490 -0
  28. package/cli/lib/senses/rules.mjs +159 -0
  29. package/cli/lib/senses/sources/activity.mjs +95 -0
  30. package/cli/lib/senses/sources/calendar.mjs +75 -0
  31. package/cli/lib/senses/sources/index.mjs +17 -0
  32. package/cli/lib/senses/sources/mail.mjs +48 -0
  33. package/cli/lib/senses/sources/system.mjs +39 -0
  34. package/cli/lib/senses/util.mjs +41 -0
  35. package/cli/lib/senses/vendor.mjs +78 -0
  36. package/cli/lib/stt-local.py +16 -8
  37. package/cli/lib/stt.mjs +53 -6
  38. package/cli/lib/tooluse.mjs +56 -0
  39. package/cli/lib/tts-local.mjs +2 -2
  40. package/cli/lib/vm.mjs +2 -2
  41. package/cli/lib/wake-local.py +109 -0
  42. package/cli/lib/wake.mjs +102 -0
  43. package/cli/pet/electron/main.cjs +190 -8
  44. package/cli/pet/pet.html +153 -34
  45. package/cli/pet/senses.html +342 -0
  46. package/cli/pet/settings.html +815 -74
  47. package/dist/7ots.esm.js +373 -146
  48. package/dist/7ots.esm.js.map +4 -4
  49. package/dist/7ots.iife.js +373 -146
  50. package/dist/7ots.iife.js.map +4 -4
  51. package/llms.txt +27 -0
  52. package/package.json +5 -2
  53. package/server/channels/apuchat.mjs +18 -4
  54. package/server/errors.mjs +90 -0
  55. package/server/notify.mjs +78 -0
  56. package/server/server.mjs +84 -14
  57. package/server/settings.mjs +3 -0
  58. package/server/site.mjs +401 -0
  59. package/server/tts.mjs +29 -5
  60. package/src/avatar/AvatarStage.js +2 -2
  61. package/src/avatar/three.js +3 -2
  62. package/src/character/AvatarEditor.js +2 -1
  63. package/src/character/Character.js +38 -5
  64. package/src/character/TradingCard.js +2 -0
  65. package/src/character/beat.js +64 -2
  66. package/src/character/mods/orc.js +8 -1
  67. package/src/character/mods.js +104 -10
  68. package/src/character/motion.js +252 -1
  69. package/src/character/parts.js +40 -38
  70. package/src/character/styles.js +40 -38
  71. package/src/character3d/Character3D.js +26 -5
  72. package/src/character3d/body.js +14 -12
  73. package/src/character3d/export.js +693 -0
  74. package/src/character3d/fx.js +13 -0
  75. package/src/character3d/index.js +2 -0
  76. package/src/character3d/materials.js +106 -10
  77. package/src/character3d/room-themes.js +1184 -0
  78. package/src/character3d/room.js +487 -0
  79. package/src/character3d/stage.js +14 -2
  80. package/src/creator/StepCreator.js +316 -0
  81. package/src/i18n/index.js +3 -3
  82. package/src/i18n/messages/character.js +352 -4
  83. package/src/i18n/messages/creator.js +138 -0
  84. package/src/i18n/messages/identity.js +89 -1
  85. package/src/i18n/messages/platform.js +270 -4
  86. package/src/i18n/messages/server.js +443 -1
  87. package/src/i18n/messages/widget.js +233 -0
  88. package/src/identity/random.js +14 -2
  89. package/src/identity/schema.js +2 -1
  90. package/src/index.js +9 -2
  91. package/src/voice/tags.js +22 -0
  92. package/server/platform/apuchat.mjs +0 -266
  93. package/server/platform/auth.mjs +0 -319
  94. package/server/platform/connect.mjs +0 -387
  95. package/server/platform/crypto.mjs +0 -80
  96. package/server/platform/db.mjs +0 -275
  97. package/server/platform/device.mjs +0 -222
  98. package/server/platform/integrations.mjs +0 -169
  99. package/server/platform/look.mjs +0 -20
  100. package/server/platform/mods.mjs +0 -222
  101. package/server/platform/orquesta.mjs +0 -577
  102. package/server/platform/profile.mjs +0 -161
  103. package/server/platform/routes.mjs +0 -542
  104. package/server/platform/runtime.mjs +0 -242
  105. package/server/platform/sites.mjs +0 -146
  106. package/server/platform/store.mjs +0 -456
  107. package/server/platform/vm.mjs +0 -1057
@@ -1,275 +0,0 @@
1
- /**
2
- * Base de datos de la plataforma 7ots.com (solo con PLATFORM=true).
3
- *
4
- * SQLite de Node (node:sqlite): sin dependencias ni servidor aparte. Un fichero,
5
- * PLATFORM_DB (defecto data/platform.db), en modo WAL.
6
- *
7
- * accounts cuentas (email y/o notlogin_sub)
8
- * sessions sesiones del dashboard (se guarda el hash del token, nunca el token)
9
- * login_tokens enlaces de acceso por email (hash, 15 min, un solo uso)
10
- * ots los agentes: identidad, widget y ajustes en JSON; claves cifradas aparte
11
- * conversations una por visitante y sesión del widget (o contacto de un canal)
12
- * messages lo que dijo cada uno (texto, sin el `raw` del proveedor)
13
- * usage contadores por ots, mes y tipo
14
- * integrations cuentas conectadas de cada cuenta (apuchat, Orquesta), cifradas
15
- * platform_state valores de la plataforma (p. ej. el client_id de OAuth registrado en Orquesta)
16
- * ots_tasks tareas que un ots mandó a Orquesta: quién la pidió, por dónde y cómo acabó
17
- * sites sites/APIs/MCPs enrolled in Prowl.world so ots know how to use them (sites.mjs)
18
- * devices computers signed in with `7ots login` (the desktop pet): a bearer token, hashed
19
- * ots_vms the machine where an ot's assistant worker runs (one per ot; vm.mjs, docs/VM-PLAN.md):
20
- * provider 'byo' (the owner's own server, enrolled by hand), 'orquesta' (in the account's Orquesta
21
- * child org, paid through Orquesta's checkout) or 'orquesta_user' (in the owner's own Orquesta org)
22
- * vm_jobs work the desktop sends to that VM, and how it ended
23
- * vm_job_events what the worker reported while doing it (seq per job, for long-polls)
24
- */
25
-
26
- import { lookPrint } from './look.mjs';
27
- import { DatabaseSync } from 'node:sqlite';
28
- import { mkdirSync } from 'node:fs';
29
- import { dirname, join, resolve } from 'node:path';
30
- import { fileURLToPath } from 'node:url';
31
-
32
- const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
33
-
34
- const SCHEMA = `
35
- CREATE TABLE IF NOT EXISTS accounts (
36
- id TEXT PRIMARY KEY,
37
- email TEXT UNIQUE,
38
- notlogin_sub TEXT UNIQUE,
39
- name TEXT NOT NULL DEFAULT '',
40
- plan TEXT NOT NULL DEFAULT 'free',
41
- created_at INTEGER NOT NULL,
42
- last_login_at INTEGER
43
- );
44
- CREATE TABLE IF NOT EXISTS sessions (
45
- id TEXT PRIMARY KEY,
46
- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
47
- created_at INTEGER NOT NULL,
48
- expires_at INTEGER NOT NULL,
49
- via TEXT NOT NULL DEFAULT ''
50
- );
51
- CREATE INDEX IF NOT EXISTS sessions_account ON sessions(account_id);
52
- CREATE TABLE IF NOT EXISTS login_tokens (
53
- hash TEXT PRIMARY KEY,
54
- email TEXT NOT NULL,
55
- expires_at INTEGER NOT NULL,
56
- used_at INTEGER
57
- );
58
- CREATE TABLE IF NOT EXISTS ots (
59
- id TEXT PRIMARY KEY,
60
- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
61
- name TEXT NOT NULL,
62
- status TEXT NOT NULL DEFAULT 'on',
63
- domains TEXT NOT NULL DEFAULT '[]',
64
- identity TEXT NOT NULL DEFAULT '{}',
65
- widget TEXT NOT NULL DEFAULT '{}',
66
- settings TEXT NOT NULL DEFAULT '{}',
67
- secrets TEXT NOT NULL DEFAULT '',
68
- created_at INTEGER NOT NULL,
69
- updated_at INTEGER NOT NULL
70
- );
71
- CREATE INDEX IF NOT EXISTS ots_account ON ots(account_id);
72
- CREATE TABLE IF NOT EXISTS conversations (
73
- id TEXT PRIMARY KEY,
74
- ots_id TEXT NOT NULL REFERENCES ots(id) ON DELETE CASCADE,
75
- channel TEXT NOT NULL DEFAULT 'web',
76
- visitor TEXT NOT NULL DEFAULT '',
77
- page TEXT NOT NULL DEFAULT '',
78
- title TEXT NOT NULL DEFAULT '',
79
- messages INTEGER NOT NULL DEFAULT 0,
80
- started_at INTEGER NOT NULL,
81
- updated_at INTEGER NOT NULL
82
- );
83
- CREATE INDEX IF NOT EXISTS conversations_ots ON conversations(ots_id, updated_at DESC);
84
- CREATE TABLE IF NOT EXISTS messages (
85
- id INTEGER PRIMARY KEY AUTOINCREMENT,
86
- conversation_id TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
87
- role TEXT NOT NULL,
88
- content TEXT NOT NULL,
89
- at INTEGER NOT NULL
90
- );
91
- CREATE INDEX IF NOT EXISTS messages_conversation ON messages(conversation_id, id);
92
- CREATE TABLE IF NOT EXISTS usage (
93
- account_id TEXT NOT NULL,
94
- ots_id TEXT NOT NULL,
95
- month TEXT NOT NULL,
96
- kind TEXT NOT NULL,
97
- count INTEGER NOT NULL DEFAULT 0,
98
- PRIMARY KEY (ots_id, month, kind)
99
- );
100
- CREATE INDEX IF NOT EXISTS usage_account ON usage(account_id, month);
101
- CREATE TABLE IF NOT EXISTS integrations (
102
- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
103
- kind TEXT NOT NULL,
104
- data TEXT NOT NULL DEFAULT '',
105
- updated_at INTEGER NOT NULL,
106
- PRIMARY KEY (account_id, kind)
107
- );
108
- CREATE TABLE IF NOT EXISTS platform_state (
109
- key TEXT PRIMARY KEY,
110
- value TEXT NOT NULL,
111
- updated_at INTEGER NOT NULL
112
- );
113
- CREATE TABLE IF NOT EXISTS devices (
114
- id TEXT PRIMARY KEY,
115
- hash TEXT NOT NULL UNIQUE,
116
- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
117
- name TEXT NOT NULL DEFAULT '',
118
- created_at INTEGER NOT NULL,
119
- last_used_at INTEGER NOT NULL
120
- );
121
- CREATE INDEX IF NOT EXISTS devices_account ON devices(account_id);
122
- CREATE TABLE IF NOT EXISTS sites (
123
- id TEXT PRIMARY KEY,
124
- account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
125
- kind TEXT NOT NULL DEFAULT 'site',
126
- url TEXT NOT NULL,
127
- domain TEXT NOT NULL,
128
- name TEXT NOT NULL DEFAULT '',
129
- guide TEXT NOT NULL DEFAULT '',
130
- service_id TEXT NOT NULL,
131
- status TEXT NOT NULL DEFAULT 'pending',
132
- proof TEXT,
133
- created_at INTEGER NOT NULL,
134
- verified_at INTEGER
135
- );
136
- CREATE INDEX IF NOT EXISTS sites_account ON sites(account_id);
137
- CREATE TABLE IF NOT EXISTS ots_tasks (
138
- id TEXT PRIMARY KEY,
139
- ots_id TEXT NOT NULL REFERENCES ots(id) ON DELETE CASCADE,
140
- account_id TEXT NOT NULL,
141
- project_id TEXT NOT NULL DEFAULT '',
142
- who TEXT NOT NULL DEFAULT '',
143
- channel TEXT NOT NULL DEFAULT '',
144
- task TEXT NOT NULL DEFAULT '',
145
- status TEXT NOT NULL DEFAULT 'pending',
146
- result TEXT NOT NULL DEFAULT '',
147
- error TEXT NOT NULL DEFAULT '',
148
- created_at INTEGER NOT NULL,
149
- updated_at INTEGER NOT NULL
150
- );
151
- CREATE INDEX IF NOT EXISTS ots_tasks_ots ON ots_tasks(ots_id, created_at DESC);
152
- CREATE TABLE IF NOT EXISTS ots_vms (
153
- ots_id TEXT PRIMARY KEY REFERENCES ots(id) ON DELETE CASCADE,
154
- account_id TEXT NOT NULL,
155
- provider TEXT NOT NULL DEFAULT 'byo',
156
- orq_project_id TEXT NOT NULL DEFAULT '',
157
- orq_vm_id TEXT NOT NULL DEFAULT '',
158
- status TEXT NOT NULL DEFAULT 'pending',
159
- size TEXT NOT NULL DEFAULT '',
160
- region TEXT NOT NULL DEFAULT '',
161
- ip TEXT NOT NULL DEFAULT '',
162
- error TEXT NOT NULL DEFAULT '',
163
- enroll_hash TEXT UNIQUE,
164
- enroll_exp INTEGER,
165
- agent_hash TEXT UNIQUE,
166
- agent_seen_at INTEGER,
167
- worker_version TEXT NOT NULL DEFAULT '',
168
- worker_info TEXT NOT NULL DEFAULT '{}',
169
- created_at INTEGER NOT NULL,
170
- updated_at INTEGER NOT NULL
171
- );
172
- CREATE TABLE IF NOT EXISTS vm_jobs (
173
- id TEXT PRIMARY KEY,
174
- ots_id TEXT NOT NULL REFERENCES ots(id) ON DELETE CASCADE,
175
- account_id TEXT NOT NULL,
176
- device_id TEXT NOT NULL DEFAULT '',
177
- kind TEXT NOT NULL,
178
- input TEXT NOT NULL DEFAULT '',
179
- context TEXT NOT NULL DEFAULT '',
180
- status TEXT NOT NULL DEFAULT 'queued',
181
- result TEXT NOT NULL DEFAULT '',
182
- error TEXT NOT NULL DEFAULT '',
183
- created_at INTEGER NOT NULL,
184
- claimed_at INTEGER,
185
- finished_at INTEGER,
186
- updated_at INTEGER NOT NULL
187
- );
188
- CREATE INDEX IF NOT EXISTS vm_jobs_ots ON vm_jobs(ots_id, created_at DESC);
189
- CREATE TABLE IF NOT EXISTS vm_job_events (
190
- job_id TEXT NOT NULL REFERENCES vm_jobs(id) ON DELETE CASCADE,
191
- seq INTEGER NOT NULL,
192
- kind TEXT NOT NULL,
193
- text TEXT NOT NULL DEFAULT '',
194
- at INTEGER NOT NULL,
195
- PRIMARY KEY (job_id, seq)
196
- );
197
- `;
198
-
199
- let db = null;
200
-
201
- /** Carpeta de datos de la plataforma (junto a PLATFORM_DB): ahí van también los archivos subidos. */
202
- export const dataDir = () => (process.env.PLATFORM_DB === ':memory:' ? resolve(ROOT, 'data') : dirname(resolve(ROOT, process.env.PLATFORM_DB || join('data', 'platform.db'))));
203
-
204
- /** Abre (y crea si hace falta) la base de datos. Idempotente. */
205
- export function openDb(path = process.env.PLATFORM_DB) {
206
- if (db) return db;
207
- const file = path === ':memory:' ? path : resolve(ROOT, path || join('data', 'platform.db'));
208
- if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true });
209
- db = new DatabaseSync(file);
210
- db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 3000;');
211
- db.exec(SCHEMA);
212
- migrateLookPrints(db);
213
- // VMs paid by 7ots (provider 'orquesta') are opt-in per account; your own server never needs it (vm.mjs).
214
- if (!db.prepare('PRAGMA table_info(accounts)').all().some((c) => c.name === 'vm_enabled')) db.exec('ALTER TABLE accounts ADD COLUMN vm_enabled INTEGER NOT NULL DEFAULT 0');
215
- // VMs created through Orquesta: its last-seen VM status, when it was checked and the monthly price it quoted.
216
- const vmCols = db.prepare('PRAGMA table_info(ots_vms)').all().map((c) => c.name);
217
- if (!vmCols.includes('orq_status')) db.exec("ALTER TABLE ots_vms ADD COLUMN orq_status TEXT NOT NULL DEFAULT ''");
218
- if (!vmCols.includes('orq_checked_at')) db.exec('ALTER TABLE ots_vms ADD COLUMN orq_checked_at INTEGER');
219
- if (!vmCols.includes('price_cents')) db.exec('ALTER TABLE ots_vms ADD COLUMN price_cents INTEGER');
220
- // One Orquesta child org per 7ots account (partner orgs): the account's org id, and the org each VM lives in
221
- // ('' = the partner's own org, VMs made before child orgs). Provider 'orquesta_user' VMs live in the owner's org.
222
- if (!db.prepare('PRAGMA table_info(accounts)').all().some((c) => c.name === 'orq_org_id')) db.exec("ALTER TABLE accounts ADD COLUMN orq_org_id TEXT NOT NULL DEFAULT ''");
223
- if (!vmCols.includes('orq_org_id')) db.exec("ALTER TABLE ots_vms ADD COLUMN orq_org_id TEXT NOT NULL DEFAULT ''");
224
- return db;
225
- }
226
-
227
- export function getDb() {
228
- return db || openDb();
229
- }
230
-
231
- /**
232
- * Cada ot es único: huella del aspecto (ver look.mjs) con índice UNIQUE. Las bases viejas ganan la
233
- * columna y se rellenan; si ya había repetidos, el más antiguo se queda la huella y los demás quedan
234
- * sin ella (y se avisa) hasta que se les cambie la cara: guardarlos de nuevo exige una libre.
235
- */
236
- function migrateLookPrints(d) {
237
- if (!d.prepare('PRAGMA table_info(ots)').all().some((c) => c.name === 'look_print')) d.exec('ALTER TABLE ots ADD COLUMN look_print TEXT');
238
- d.exec('CREATE UNIQUE INDEX IF NOT EXISTS ots_look ON ots(look_print)');
239
- const seen = new Set(d.prepare('SELECT look_print p FROM ots WHERE look_print IS NOT NULL').all().map((r) => r.p));
240
- const set = d.prepare('UPDATE ots SET look_print = ? WHERE id = ?');
241
- for (const row of d.prepare('SELECT id, identity FROM ots WHERE look_print IS NULL ORDER BY created_at').all()) {
242
- let p = null;
243
- try {
244
- p = lookPrint(JSON.parse(row.identity));
245
- } catch {
246
- /* identidad rota: sin huella */
247
- }
248
- if (!p) continue;
249
- if (seen.has(p)) console.warn(`[7ots] plataforma: ${row.id} repite la cara de otro ot; queda sin huella hasta que se le cambie`);
250
- else set.run(p, row.id), seen.add(p);
251
- }
252
- }
253
-
254
- /** Cierra la base de datos (tests). */
255
- export function closeDb() {
256
- db?.close();
257
- db = null;
258
- }
259
-
260
- /** Varias escrituras como una sola. */
261
- export function tx(fn) {
262
- const d = getDb();
263
- d.exec('BEGIN');
264
- try {
265
- const out = fn(d);
266
- d.exec('COMMIT');
267
- return out;
268
- } catch (e) {
269
- d.exec('ROLLBACK');
270
- throw e;
271
- }
272
- }
273
-
274
- /** Mes en curso (UTC) para los contadores: "2026-09". */
275
- export const monthOf = (t = Date.now()) => new Date(t).toISOString().slice(0, 7);
@@ -1,222 +0,0 @@
1
- /**
2
- * Signing a computer in to 7ots.com (`7ots login`, or "Connect" in the pet's settings), so the
3
- * desktop pet can list the account's ots, switch to another one and bring its settings home.
4
- *
5
- * Device flow, like a TV app: the computer asks for a code, opens /app/#device/<code>, the
6
- * person (signed in to the dashboard) approves it, and the computer picks up a bearer token.
7
- *
8
- * POST /api/device/start { name } → { code, url, expiresIn } (no auth, rate-limited)
9
- * POST /api/device/poll { code } → 202 pending · 200 { token } once · 410 expired/denied
10
- * GET /api/device/me → { account, ots: [summary] } (Authorization: Bearer)
11
- * GET /api/device/ots/:id → { ots: summary, identity } (the owner's full identity)
12
- * DELETE /api/device/token → signs this computer out
13
- * GET /api/device/ots/:id/orquesta → { connected, project, projectName, projects }
14
- * POST /api/device/ots/:id/orquesta/tasks { text, projectId? } · GET …/tasks/:tid
15
- * The desktop ot uses the account's Orquesta connection through here: the Orquesta token
16
- * stays sealed on 7ots.com and never reaches the computer. The device is the owner's (it
17
- * was approved from the dashboard), so it may pick any project the connection can reach.
18
- * GET /api/device/ots/:id/inbox → { apuchat, email, conversations: [{ channel, who, at, messages }] }
19
- * what people wrote to the ot on apuchat and email lately, and what it answered (read only;
20
- * the channels' keys stay on 7ots.com)
21
- *
22
- * From the dashboard (session cookie, X-7ots-Admin: 1, same origin; see routes.mjs):
23
- * GET /api/platform/device/:code → { name, expiresIn } what is asking
24
- * POST /api/platform/device/:code { approve: bool }
25
- * GET /api/platform/devices DELETE /api/platform/devices/:id
26
- *
27
- * Tokens are only stored hashed. Pending codes live in memory (10 min): a restart just means
28
- * running `7ots login` again.
29
- */
30
-
31
- import { defineIdentity } from '../../src/identity/schema.js';
32
- import { createHash } from 'node:crypto';
33
- import { mkdirSync, writeFileSync } from 'node:fs';
34
- import { join } from 'node:path';
35
- import { dataDir, getDb } from './db.mjs';
36
- import { newId, sha256, token } from './crypto.mjs';
37
- import { getConversation, getOwnOts, listConversations, listOts, publicAccount } from './store.mjs';
38
- import { listProjects, orquestaAccountView, otsOrquesta, runTask, taskStatus } from './orquesta.mjs';
39
-
40
- const CODE_TTL = 10 * 60_000;
41
- const PREFIX = '7d_'; // so a leaked token is recognizable
42
-
43
- const pending = new Map(); // code → { name, at, accountId?, token?, denied? }
44
-
45
- function sweep() {
46
- const t = Date.now();
47
- for (const [c, v] of pending) if (t - v.at > CODE_TTL) pending.delete(c);
48
- }
49
-
50
- export function deviceFromBearer(req) {
51
- const m = /^Bearer\s+(7d_[A-Za-z0-9_-]{20,200})$/.exec(String(req.headers.authorization || ''));
52
- if (!m) return null;
53
- const d = getDb();
54
- const row = d.prepare('SELECT d.id AS device_id, a.* FROM devices d JOIN accounts a ON a.id = d.account_id WHERE d.hash = ?').get(sha256(m[1]));
55
- if (!row) return null;
56
- d.prepare('UPDATE devices SET last_used_at = ? WHERE id = ?').run(Date.now(), row.device_id);
57
- return { deviceId: row.device_id, account: row };
58
- }
59
-
60
- export function listDevices(accountId) {
61
- return getDb().prepare('SELECT id, name, created_at AS createdAt, last_used_at AS lastUsedAt FROM devices WHERE account_id = ? ORDER BY last_used_at DESC').all(accountId);
62
- }
63
-
64
- /**
65
- * @param {{ send: Function, readJson: Function, base: (req) => string, rateLimit: (req) => boolean, summary: (ots) => object }} deps
66
- */
67
- /** What the pet and 7ots.com keep in sync (the look goes only as look.character). */
68
- const SYNCED = ['name', 'role', 'tagline', 'bio', 'language', 'languages', 'personality'];
69
- const MAX_MODEL = 60 * 1024 * 1024;
70
-
71
- export function createDevice({ send, readJson, base, rateLimit, summary, save }) {
72
- /** Public half (/api/device/*). @returns {Promise<boolean>} */
73
- async function api(req, res, path) {
74
- res.setHeader('Cache-Control', 'no-store');
75
- if (path === '/start' && req.method === 'POST') {
76
- if (!rateLimit(req)) return send(res, 429, { error: 'rate' }), true;
77
- const { name } = await readJson(req, 4096);
78
- sweep();
79
- if (pending.size > 2000) return send(res, 503, { error: 'busy' }), true;
80
- const code = token().replace(/[^A-Za-z0-9]/g, '').slice(0, 24);
81
- pending.set(code, { name: String(name || '').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 60) || 'computer', at: Date.now() });
82
- return send(res, 200, { code, url: `${base(req)}/app/#device/${code}`, expiresIn: CODE_TTL / 1000 }), true;
83
- }
84
- if (path === '/poll' && req.method === 'POST') {
85
- const { code } = await readJson(req, 4096);
86
- sweep();
87
- const p = pending.get(String(code || ''));
88
- if (!p || p.denied) return pending.delete(String(code || '')), send(res, 410, { error: p?.denied ? 'denied' : 'expired' }), true;
89
- if (!p.token) return send(res, 202, { status: 'pending' }), true;
90
- pending.delete(code); // handed out once
91
- return send(res, 200, { token: p.token }), true;
92
- }
93
- const who = deviceFromBearer(req);
94
- if (path === '/me' || path === '/token' || path.startsWith('/ots/')) {
95
- if (!who) return send(res, 401, { error: 'login' }), true;
96
- const { account } = who;
97
- if (path === '/me' && req.method === 'GET') return send(res, 200, { account: publicAccount(account), ots: listOts(account.id).map(summary) }), true;
98
- if (path === '/token' && req.method === 'DELETE') {
99
- getDb().prepare('DELETE FROM devices WHERE id = ?').run(who.deviceId);
100
- return send(res, 200, { ok: true }), true;
101
- }
102
- const m = /^\/ots\/([a-z0-9_]{4,40})$/.exec(path);
103
- if (m && req.method === 'GET') {
104
- const ots = getOwnOts(account.id, m[1]);
105
- if (!ots) return send(res, 404, { error: 'not found' }), true;
106
- return send(res, 200, { ots: summary(ots), identity: defineIdentity(ots.identity), updatedAt: ots.updatedAt }), true;
107
- }
108
- // sync with the desktop pet: the same look, personality and character sheet on both sides
109
- const sm = /^\/ots\/([a-z0-9_]{4,40})\/identity$/.exec(path);
110
- if (sm && req.method === 'PUT') {
111
- const ots = getOwnOts(account.id, sm[1]);
112
- if (!ots) return send(res, 404, { error: 'not found' }), true;
113
- const inc = (await readJson(req, 512 * 1024))?.identity;
114
- if (!inc || typeof inc !== 'object') return send(res, 400, { error: 'identity' }), true;
115
- const patch = Object.fromEntries(SYNCED.filter((k) => k in inc).map((k) => [k, inc[k]]));
116
- if (inc.look?.character) patch.look = { character: inc.look.character }; // the rest of the look (image, avatar) is the web's
117
- try {
118
- const next = await save(ots, { identity: defineIdentity(patch, ots.identity) });
119
- return send(res, 200, { identity: defineIdentity(next.identity), updatedAt: next.updatedAt }), true;
120
- } catch (e) {
121
- return send(res, e.status || 500, { error: e.message }), true;
122
- }
123
- }
124
- // a full-body model (.glb/.vrm) of a mod: content-addressed, served at /mods/<sha16>.<ext> like on the pet
125
- const fm = /^\/ots\/([a-z0-9_]{4,40})\/files$/.exec(path);
126
- if (fm && req.method === 'POST') {
127
- if (!getOwnOts(account.id, fm[1])) return send(res, 404, { error: 'not found' }), true;
128
- const ext = new URL(req.url, 'http://x').searchParams.get('ext');
129
- if (!['glb', 'vrm'].includes(ext)) return send(res, 400, { error: 'ext' }), true;
130
- const chunks = [];
131
- let size = 0;
132
- for await (const c of req) {
133
- size += c.length;
134
- if (size > MAX_MODEL) return send(res, 413, { error: 'too big' }), true;
135
- chunks.push(c);
136
- }
137
- const buf = Buffer.concat(chunks);
138
- if (buf.length < 20 || buf.toString('latin1', 0, 4) !== 'glTF') return send(res, 400, { error: 'not a glTF binary' }), true;
139
- const h = createHash('sha256').update(buf).digest('hex').slice(0, 16);
140
- mkdirSync(join(dataDir(), 'mods'), { recursive: true });
141
- writeFileSync(join(dataDir(), 'mods', `${h}.${ext}`), buf);
142
- return send(res, 200, { url: `/mods/${h}.${ext}` }), true;
143
- }
144
- const im = /^\/ots\/([a-z0-9_]{4,40})\/inbox$/.exec(path);
145
- if (im && req.method === 'GET') {
146
- const ots = getOwnOts(account.id, im[1]);
147
- if (!ots) return send(res, 404, { error: 'not found' }), true;
148
- const conversations = listConversations(ots.id, { limit: 60 })
149
- .filter((c) => c.channel === 'apuchat' || c.channel === 'apumail')
150
- .slice(0, 10)
151
- .map((c) => ({ channel: c.channel, who: c.visitor, at: c.updatedAt, messages: (getConversation(ots.id, c.id)?.messages || []).slice(-6).map((m) => ({ role: m.role, text: m.content.slice(0, 1200), at: m.at })) }));
152
- const s = ots.settings;
153
- return send(res, 200, { apuchat: s.APUCHAT_AGENT_CALLSIGN || null, email: s.APUMAIL_AGENT_INBOX || null, conversations }), true;
154
- }
155
- const om = /^\/ots\/([a-z0-9_]{4,40})\/orquesta(\/tasks(?:\/([A-Za-z0-9_-]{4,100}))?)?$/.exec(path);
156
- if (om) {
157
- const ots = getOwnOts(account.id, om[1]);
158
- if (!ots) return send(res, 404, { error: 'not found' }), true;
159
- return orquesta(req, res, account, ots, !!om[2], om[3]);
160
- }
161
- }
162
- return false;
163
- }
164
-
165
- /** The ot's Orquesta, used by the desktop ot with the account's connection. */
166
- async function orquesta(req, res, account, ots, tasks, tid) {
167
- const view = orquestaAccountView(account.id);
168
- if (!tasks && req.method === 'GET') {
169
- const cfg = otsOrquesta(ots);
170
- let projects = [];
171
- let error = view.error;
172
- if (view.connected) projects = await listProjects(account.id).catch((e) => ((error = e.message), []));
173
- return send(res, 200, { connected: view.connected, error, project: cfg.project, projectName: cfg.projectName, projects }), true;
174
- }
175
- if (!view.connected) return send(res, 409, { error: 'Orquesta is not connected on 7ots.com' }), true;
176
- if (tasks && !tid && req.method === 'POST') {
177
- const { text, projectId } = await readJson(req, 64 * 1024);
178
- let project = otsOrquesta(ots).project;
179
- if (projectId) {
180
- const p = (await listProjects(account.id)).find((x) => x.id === String(projectId));
181
- if (!p) return send(res, 404, { error: 'that project is not shared with 7ots' }), true;
182
- project = p.id;
183
- }
184
- if (!project) return send(res, 400, { error: 'pick a project' }), true;
185
- // the owner, from their own computer: tasks on for this one, the chosen project
186
- const out = await runTask({ ...ots, settings: { ...ots.settings, ORQUESTA_TASKS: '1', ORQUESTA_PROJECT: project } }, { task: text, who: `owner ${account.email || account.id}`, channel: 'desktop' });
187
- return send(res, out.ok === false && !out.id ? 400 : 200, out), true;
188
- }
189
- if (tid && req.method === 'GET') return send(res, 200, await taskStatus(ots, tid)), true;
190
- return send(res, 405, { error: 'method' }), true;
191
- }
192
-
193
- /** Dashboard half, already behind the session + same-origin checks. @returns {boolean} */
194
- async function dashboard(req, res, account, path) {
195
- const m = /^\/device\/([A-Za-z0-9]{8,40})$/.exec(path);
196
- if (m) {
197
- sweep();
198
- const p = pending.get(m[1]);
199
- if (!p || p.token || p.denied) return send(res, 410, { error: 'expired' }), true;
200
- if (req.method === 'GET') return send(res, 200, { name: p.name, expiresIn: Math.max(0, Math.round((CODE_TTL - (Date.now() - p.at)) / 1000)) }), true;
201
- if (req.method === 'POST') {
202
- const { approve } = await readJson(req, 4096);
203
- if (approve !== true) return (p.denied = true), send(res, 200, { ok: true }), true;
204
- const raw = PREFIX + token();
205
- const t = Date.now();
206
- getDb().prepare('INSERT INTO devices (id, hash, account_id, name, created_at, last_used_at) VALUES (?, ?, ?, ?, ?, ?)').run(newId('dev'), sha256(raw), account.id, p.name, t, t);
207
- p.token = raw;
208
- p.accountId = account.id;
209
- return send(res, 200, { ok: true }), true;
210
- }
211
- }
212
- if (path === '/devices' && req.method === 'GET') return send(res, 200, { devices: listDevices(account.id) }), true;
213
- const d = /^\/devices\/([\w-]{4,60})$/.exec(path);
214
- if (d && req.method === 'DELETE') {
215
- getDb().prepare('DELETE FROM devices WHERE id = ? AND account_id = ?').run(d[1], account.id);
216
- return send(res, 200, { ok: true }), true;
217
- }
218
- return false;
219
- }
220
-
221
- return { api, dashboard };
222
- }
@@ -1,169 +0,0 @@
1
- /**
2
- * An ot's own integrations on 7ots.com (dashboard → Assistant → Integrations): MCP servers and APIs it
3
- * can use when its owner asks it something in the dashboard ("Ask your ot").
4
- *
5
- * settings.INTEGRATIONS JSON [{ id, kind: 'mcp'|'api'|'note', name, instructions, url?, on }] (managed, ≤ 10)
6
- * secrets.INTEG_<id> its token (Bearer), sealed like the other keys and never returned
7
- *
8
- * The server reaches these URLs itself, so only public https hosts: every address the name resolves to
9
- * must be public (no loopback, private, link-local or metadata ranges) and redirects are not followed.
10
- * Commands are desktop-only (the pet runs them on the user's own computer).
11
- */
12
-
13
- import { lookup } from 'node:dns/promises';
14
- import { isIP } from 'node:net';
15
- import { randomBytes } from 'node:crypto';
16
- import { mcpCall, mcpTools } from '../../cli/lib/mcp.mjs';
17
-
18
- export const MAX_INTEGRATIONS = 10;
19
- const KINDS = ['mcp', 'api', 'note'];
20
- const MAX_OUT = 6000;
21
- const str = (v, max) => String(v ?? '').replace(/\r/g, '').trim().slice(0, max);
22
-
23
- const badUrl = (code) => Object.assign(new Error(code), { code });
24
-
25
- /** The saved list (never with tokens). */
26
- export function otIntegrations(ots) {
27
- try {
28
- const list = JSON.parse(ots?.settings?.INTEGRATIONS || '[]');
29
- return Array.isArray(list) ? list : [];
30
- } catch {
31
- return [];
32
- }
33
- }
34
-
35
- /** What the dashboard sees: the list plus whether each one has a token. */
36
- export function integrationsView(ots) {
37
- return otIntegrations(ots).map((c) => ({ ...c, hasToken: Boolean(ots.secrets?.[`INTEG_${c.id}`]) }));
38
- }
39
-
40
- /**
41
- * Validates the dashboard's list → { list, secrets } to save. `token` on an item replaces its token,
42
- * `token: ''` removes it, no `token` keeps the one saved.
43
- */
44
- export function normalizeOtIntegrations(items, ots) {
45
- if (!Array.isArray(items)) throw badUrl('integList');
46
- if (items.length > MAX_INTEGRATIONS) throw badUrl('integMax');
47
- const secrets = { ...(ots.secrets || {}) };
48
- const list = items.map((c) => {
49
- const kind = KINDS.includes(c?.kind) ? c.kind : 'note';
50
- const name = str(c?.name, 60);
51
- if (!name) throw badUrl('integName');
52
- const url = kind === 'note' ? '' : str(c.url, 300);
53
- if (kind !== 'note' && !/^https:\/\/[^\s"'<>]+$/i.test(url)) throw badUrl('integUrl');
54
- const id = /^[a-z0-9]{6,16}$/.test(c.id || '') ? c.id : randomBytes(5).toString('hex');
55
- if (typeof c.token === 'string') {
56
- const tok = c.token.trim().slice(0, 2000);
57
- if (tok) secrets[`INTEG_${id}`] = tok;
58
- else delete secrets[`INTEG_${id}`];
59
- }
60
- return { id, kind, name, instructions: str(c.instructions, 1500), ...(url ? { url } : {}), on: c.on !== false };
61
- });
62
- // tokens of removed integrations go too
63
- const ids = new Set(list.map((c) => c.id));
64
- for (const k of Object.keys(secrets)) if (k.startsWith('INTEG_') && !ids.has(k.slice(6))) delete secrets[k];
65
- return { list, secrets };
66
- }
67
-
68
- // ── only public hosts ──
69
-
70
- function privateIp(ip) {
71
- if (isIP(ip) === 6) {
72
- const v = ip.toLowerCase();
73
- if (v.startsWith('::ffff:')) return privateIp(v.slice(7));
74
- return v === '::' || v === '::1' || /^f[cd]/.test(v) || /^fe[89ab]/.test(v) || v.startsWith('64:ff9b:') || v.startsWith('2001:db8');
75
- }
76
- const [a, b] = ip.split('.').map(Number);
77
- return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 198 && (b === 18 || b === 19)) || a >= 224;
78
- }
79
-
80
- export async function assertPublicUrl(raw) {
81
- let u;
82
- try {
83
- u = new URL(raw);
84
- } catch {
85
- throw badUrl('integUrl');
86
- }
87
- if (u.protocol !== 'https:' || u.username || u.password) throw badUrl('integUrl');
88
- const host = u.hostname.replace(/^\[|\]$/g, '');
89
- if (/^(localhost|.*\.local|.*\.internal|metadata\.google\.internal)$/i.test(host)) throw badUrl('integPrivate');
90
- const addrs = isIP(host) ? [{ address: host }] : await lookup(host, { all: true }).catch(() => []);
91
- if (!addrs.length) throw badUrl('integDns');
92
- if (addrs.some((a) => privateIp(a.address))) throw badUrl('integPrivate');
93
- return u;
94
- }
95
-
96
- // ── running them ──
97
-
98
- const tokenOf = (ots, c) => ots.secrets?.[`INTEG_${c.id}`] || '';
99
- const redact = (s) => String(s ?? '').replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, '$1 ***');
100
-
101
- /** Dashboard → "Connect and list tools" / "Try it" for one saved integration. */
102
- export async function testIntegration(ots, c) {
103
- if (c.kind === 'note') return { ok: true, text: '' };
104
- await assertPublicUrl(c.url);
105
- if (c.kind === 'mcp') return { ok: true, tools: (await mcpTools(c, tokenOf(ots, c), { fresh: true })).map((x) => ({ name: x.name, description: x.description })) };
106
- return { ok: true, text: (await apiGet(ots, c, '')).slice(0, 1500) };
107
- }
108
-
109
- async function apiGet(ots, c, path) {
110
- const target = path && /^[/?][^\s"'<>]*$/.test(path) && !path.startsWith('//') ? c.url.replace(/\/+$/, '') + path : c.url;
111
- await assertPublicUrl(target);
112
- const tok = tokenOf(ots, c);
113
- const res = await fetch(target, { redirect: 'manual', headers: { Accept: 'application/json, text/plain;q=0.9, */*;q=0.5', ...(tok ? { Authorization: `Bearer ${tok}` } : {}) }, signal: AbortSignal.timeout(15000) });
114
- return redact(`HTTP ${res.status}\n${(await res.text()).slice(0, 20000)}`).slice(0, MAX_OUT);
115
- }
116
-
117
- const TOOLS = [
118
- {
119
- name: 'integration_tools',
120
- description: 'Lists the tools of one of your MCP integrations (see the list in your instructions).',
121
- parameters: { type: 'object', properties: { id: { type: 'string', description: 'Integration id' } }, required: ['id'] },
122
- },
123
- {
124
- name: 'integration_call',
125
- description: 'Calls a tool of one of your MCP integrations. Use the exact tool name from integration_tools.',
126
- parameters: { type: 'object', properties: { id: { type: 'string' }, tool: { type: 'string' }, args: { type: 'object', description: 'The tool arguments' } }, required: ['id', 'tool'] },
127
- },
128
- {
129
- name: 'integration_get',
130
- description: 'Reads (HTTP GET) one of your API integrations, optionally with a sub-path or query appended to its URL.',
131
- parameters: { type: 'object', properties: { id: { type: 'string' }, path: { type: 'string', description: 'Optional, starting with / or ?' } }, required: ['id'] },
132
- },
133
- ];
134
-
135
- /**
136
- * Tools and prompt text for the owner's chat, or null when the ot has no integration turned on.
137
- * @returns {{ tools: object[], names: string[], run: Function, prompt: string } | null}
138
- */
139
- export function integrationTools(ots) {
140
- const on = otIntegrations(ots).filter((c) => c.on !== false);
141
- if (!on.length) return null;
142
- const usable = on.filter((c) => c.kind !== 'note');
143
- const prompt = `Integrations your owner set up for you:\n${on.map((c) => `- ${c.name} (id ${c.id}, ${c.kind === 'mcp' ? 'MCP server' : c.kind === 'api' ? `API at ${c.url}` : 'instructions'})${c.instructions ? `: ${c.instructions}` : ''}`).join('\n')}\nOnly call a tool that changes something (creates, sends, deletes, updates) when your owner asked for exactly that.`;
144
- const find = (id, kind) => {
145
- const c = usable.find((x) => x.id === String(id || ''));
146
- if (!c || (kind && c.kind !== kind)) throw new Error(`No ${kind === 'mcp' ? 'MCP' : kind === 'api' ? 'API' : ''} integration with id ${id}`);
147
- return c;
148
- };
149
- const tools = TOOLS.filter((x) => (x.name === 'integration_get' ? usable.some((c) => c.kind === 'api') : usable.some((c) => c.kind === 'mcp')));
150
- return {
151
- prompt,
152
- tools,
153
- names: tools.map((x) => x.name),
154
- run: async (name, args = {}) => {
155
- if (name === 'integration_tools') {
156
- const c = find(args.id, 'mcp');
157
- await assertPublicUrl(c.url);
158
- return { ok: true, tools: await mcpTools(c, tokenOf(ots, c)) };
159
- }
160
- if (name === 'integration_call') {
161
- const c = find(args.id, 'mcp');
162
- await assertPublicUrl(c.url);
163
- return { ok: true, result: redact(await mcpCall(c, tokenOf(ots, c), String(args.tool || ''), args.args)).slice(0, MAX_OUT) };
164
- }
165
- if (name === 'integration_get') return { ok: true, result: await apiGet(ots, find(args.id, 'api'), String(args.path || '')) };
166
- throw new Error(`Unknown tool: ${name}`);
167
- },
168
- };
169
- }