@7ots/cli 0.1.19 → 0.1.37

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 +145 -16
  38. package/cli/pet/pet.html +127 -27
  39. package/cli/pet/senses.html +342 -0
  40. package/cli/pet/settings.html +787 -86
  41. package/dist/7ots.esm.js +374 -146
  42. package/dist/7ots.esm.js.map +4 -4
  43. package/dist/7ots.iife.js +374 -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 +9 -3
  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 +10 -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,286 +0,0 @@
1
- /**
2
- * Runtime de cada ots en la plataforma: su entorno, su LLM, su voz y sus canales.
3
- *
4
- * Cada ots tiene un "entorno" propio (un objeto, nunca process.env) hecho de:
5
- * 1. lo que fija la plataforma (hub de apuchat, API de apumail, servicio de voz),
6
- * 2. sus ajustes y claves (solo las de OTS_KEYS),
7
- * 3. si no trae clave de IA o de voz, la de la plataforma, con cupo gratis por cuenta y mes:
8
- * PLATFORM_LLM_PROVIDER (anthropic | openai, compatibles como DeepSeek) · PLATFORM_LLM_API_KEY
9
- * PLATFORM_LLM_BASE_URL (openai compatibles) · PLATFORM_LLM_MODEL
10
- * (PLATFORM_ANTHROPIC_API_KEY sigue valiendo: equivale a provider anthropic + esa clave)
11
- * PLATFORM_FREE_MESSAGES respuestas de IA gratis por cuenta y mes (defecto 100)
12
- * PLATFORM_APUCHAT_VOICE_TOKEN · PLATFORM_FREE_TTS (audios gratis por cuenta y mes, defecto 100)
13
- * Partidas de byte (cupo aparte, no gastan los mensajes): PLATFORM_FREE_GAMES por cuenta y día
14
- * (defecto 3) · PLATFORM_GAME_LLM_MODEL (modelo barato para las jugadas; defecto el de la plataforma)
15
- * Así un ots nunca ve las claves del proceso ni las de otro ots.
16
- */
17
-
18
- import { createLLM } from '../llm.mjs';
19
- import { synthesize as synthesizeWith, ttsProvider, openaiTtsKey } from '../tts.mjs';
20
- import { startAgentChannels } from '../channels/index.mjs';
21
- import { apumailConfigFromEnv } from '../channels/apumail.mjs';
22
- import { apuchatConfigFromEnv } from '../channels/apuchat.mjs';
23
- import { i18nError } from '../i18n.mjs';
24
- import { OTS_KEYS, accountUsage, addUsage, allLiveOts, getOts, logTurn } from './store.mjs';
25
- import { orquestaTools } from './orquesta.mjs';
26
-
27
- const penv = process.env;
28
- const FIXED = ['APUCHAT_HUB', 'APUMAIL_API', 'APUCHAT_VOICE_URL'];
29
- // Where tenants' tokens are sent: read once at boot, so nothing that writes process.env later can redirect them.
30
- const BOOT_FIXED = Object.freeze(Object.fromEntries(FIXED.filter((k) => penv[k]).map((k) => [k, penv[k]])));
31
- // Platform-paid calls in flight per account (counted with usage, so parallel requests can't overrun the quota).
32
- const inflight = new Map(); // `${accountId}:${kind}` → n
33
- const MAX_INFLIGHT = () => Number(penv.PLATFORM_MAX_INFLIGHT || 4);
34
- const LLM_KEYS = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY'];
35
- const TTS_KEYS = ['APUCHAT_VOICE_TOKEN', 'ELEVENLABS_API_KEY', 'XAI_API_KEY', 'FISH_API_KEY', 'OPENAI_API_KEY'];
36
-
37
- /** IA de la plataforma, o null si no hay. Nunca se mezcla con ajustes del ots (ni base URL ni modelo). */
38
- export function platformLlmEnv() {
39
- const key = penv.PLATFORM_LLM_API_KEY || penv.PLATFORM_ANTHROPIC_API_KEY;
40
- if (!key) return null;
41
- const provider = (penv.PLATFORM_LLM_PROVIDER || (penv.PLATFORM_LLM_API_KEY ? 'openai' : 'anthropic')).toLowerCase();
42
- const base = { LLM_EFFORT: 'low', LLM_MAX_TOKENS: '4000' };
43
- if (provider === 'openai') return { ...base, LLM_PROVIDER: 'openai', OPENAI_API_KEY: key, LLM_BASE_URL: penv.PLATFORM_LLM_BASE_URL || '', LLM_MODEL: penv.PLATFORM_LLM_MODEL || 'gpt-4.1-mini' };
44
- return { ...base, LLM_PROVIDER: 'anthropic', ANTHROPIC_API_KEY: key, LLM_MODEL: penv.PLATFORM_LLM_MODEL || 'claude-sonnet-5-5' };
45
- }
46
-
47
- export const freeMessages = () => Number(penv.PLATFORM_FREE_MESSAGES ?? 100);
48
- export const freeTts = () => Number(penv.PLATFORM_FREE_TTS ?? 100);
49
- export const freeGames = () => Number(penv.PLATFORM_FREE_GAMES ?? 3);
50
- const dayOf = () => new Date().toISOString().slice(0, 10);
51
-
52
- /**
53
- * Entorno del ots.
54
- * @returns {{ env: object, llmEnv: object, platformLlm: boolean, platformTts: boolean }}
55
- */
56
- export function otsEnv(ots) {
57
- const env = {};
58
- Object.assign(env, BOOT_FIXED);
59
- for (const [k, meta] of Object.entries(OTS_KEYS)) {
60
- const v = meta.secret ? ots.secrets[k] : ots.settings[k];
61
- if (v == null || v === '') continue;
62
- env[k] = meta.max ? String(Math.min(meta.max, Math.max(0, Number(v) || 0))) : String(v);
63
- }
64
-
65
- // IA: la suya o la de la plataforma (modelo fijo para controlar el coste).
66
- let platformLlm = false;
67
- const provider = (env.LLM_PROVIDER || '').toLowerCase();
68
- const ownLlm = provider === 'openai' ? !!env.OPENAI_API_KEY : provider === 'anthropic' ? !!env.ANTHROPIC_API_KEY : LLM_KEYS.some((k) => env[k]);
69
- if (provider === 'mock') {
70
- // Modo de pruebas: sin IA real.
71
- } else if (!ownLlm && platformLlmEnv()) {
72
- platformLlm = true;
73
- } else if (!ownLlm) {
74
- env.LLM_PROVIDER = 'mock';
75
- }
76
- // The platform key lives only in llmEnv (never in env, which voice and channels see), and none of the
77
- // ot's own settings (provider, model, base URL) reach it.
78
- const llmEnv = platformLlm ? platformLlmEnv() : env;
79
-
80
- // Voz: la suya o la de apuchat de la plataforma.
81
- let platformTts = false;
82
- if (!TTS_KEYS.some((k) => (k === 'OPENAI_API_KEY' ? openaiTtsKey(env) : env[k])) && penv.PLATFORM_APUCHAT_VOICE_TOKEN && (!env.TTS_PROVIDER || env.TTS_PROVIDER === 'apuchat')) {
83
- platformTts = true;
84
- // On the platform's token the engine and model are the platform's, not the ot's.
85
- delete env.APUCHAT_VOICE_PROVIDER;
86
- delete env.APUCHAT_VOICE_MODEL;
87
- Object.assign(env, { TTS_PROVIDER: 'apuchat', APUCHAT_VOICE_TOKEN: penv.PLATFORM_APUCHAT_VOICE_TOKEN });
88
- }
89
- return { env, llmEnv, platformLlm, platformTts };
90
- }
91
-
92
- // ───────────────────────────── LLM con cupo ─────────────────────────────
93
-
94
- const llms = new Map(); // ots.id → { stamp, llm }
95
-
96
- /** LLM del ots (se rehace cuando cambia el ots). */
97
- function rawLlm(ots) {
98
- const stamp = ots.updatedAt;
99
- const hit = llms.get(ots.id);
100
- if (hit?.stamp === stamp) return hit;
101
- const { llmEnv, platformLlm } = otsEnv(ots);
102
- const entry = { stamp, llm: createLLM(llmEnv), platformLlm };
103
- if (llms.size > 2000) llms.clear();
104
- llms.set(ots.id, entry);
105
- return entry;
106
- }
107
-
108
- /** ¿Le queda cupo gratis a la cuenta? */
109
- export function llmAllowed(ots) {
110
- const { platformLlm } = rawLlm(ots);
111
- return !platformLlm || accountUsage(ots.accountId, 'llm_platform') < freeMessages();
112
- }
113
-
114
- /**
115
- * Takes one unit of the account's free quota before a platform-paid call (synchronous, so it is atomic in Node).
116
- * Returns release(spent): on success the unit becomes usage; on failure it is given back.
117
- */
118
- function reserve(ots, kind, limit, errorKey) {
119
- const k = `${ots.accountId}:${kind}`;
120
- const n = inflight.get(k) || 0;
121
- if (accountUsage(ots.accountId, kind) + n >= limit) throw i18nError(402, errorKey);
122
- if (n >= MAX_INFLIGHT()) throw i18nError(429, 'server.http.rateLimited');
123
- inflight.set(k, n + 1);
124
- return (spent) => {
125
- const left = (inflight.get(k) || 1) - 1;
126
- if (left > 0) inflight.set(k, left);
127
- else inflight.delete(k);
128
- if (spent) addUsage(ots, kind);
129
- };
130
- }
131
-
132
- /**
133
- * Un paso de LLM para este ots, contando el uso.
134
- * Sin cupo lanza 402 con clave `platform.quota.llm` (la ruta lo convierte en una respuesta amable).
135
- */
136
- export async function otsStep(ots, args) {
137
- const { llm, platformLlm } = rawLlm(ots);
138
- const release = platformLlm ? reserve(ots, 'llm_platform', freeMessages(), 'platform.quota.llm') : null;
139
- let out;
140
- try {
141
- out = await llm.step(args);
142
- } catch (e) {
143
- release?.(false);
144
- // The platform's provider errors stay in our logs (they can echo parts of the platform key).
145
- if (platformLlm) {
146
- console.error('[7ots] platform llm', e?.status || '', e?.message || e);
147
- throw i18nError(502, 'server.http.internal');
148
- }
149
- throw e;
150
- }
151
- release?.(true);
152
- addUsage(ots, 'llm');
153
- return out;
154
- }
155
-
156
- // ───────────────────────────── partidas de byte (cupo aparte) ─────────────────────────────
157
-
158
- let gameLlm = null; // { model, llm }: el LLM de la plataforma para jugar, compartido
159
- function platformGameLlm() {
160
- const e = platformLlmEnv();
161
- if (!e) return null;
162
- const model = penv.PLATFORM_GAME_LLM_MODEL || e.LLM_MODEL;
163
- if (gameLlm?.model !== model) gameLlm = { model, llm: createLLM({ ...e, LLM_MODEL: model, LLM_MAX_TOKENS: '800' }) };
164
- return gameLlm.llm;
165
- }
166
-
167
- /**
168
- * Takes one of today's free games for an ot on the platform's AI (402 `platform.quota.games` when used
169
- * up). Ots with their own key play without a cap. Called once per game, before it starts; returns refund().
170
- */
171
- export function takeGame(ots) {
172
- if (!rawLlm(ots).platformLlm) return;
173
- const limit = freeGames();
174
- if (accountUsage(ots.accountId, 'byte_game', dayOf()) >= limit) throw i18nError(402, 'platform.quota.games', { count: limit });
175
- const day = dayOf();
176
- addUsage(ots, 'byte_game', 1, day);
177
- return () => addUsage(ots, 'byte_game', -1, day); // the game never started: give it back
178
- }
179
-
180
- /**
181
- * Una jugada de byte: con la IA propia del ot cuenta como siempre (llm); con la de la plataforma usa el
182
- * modelo de juego y NO gasta los mensajes gratis del chat (el cupo es por partida, ver takeGame).
183
- */
184
- export async function otsGameStep(ots, args) {
185
- if (!rawLlm(ots).platformLlm) return otsStep(ots, args);
186
- try {
187
- const out = await platformGameLlm().step(args);
188
- addUsage(ots, 'byte_move');
189
- return out;
190
- } catch (e) {
191
- console.error('[7ots] platform game llm', e?.status || '', e?.message || e);
192
- throw i18nError(502, 'server.http.internal');
193
- }
194
- }
195
-
196
- export function otsLlmInfo(ots) {
197
- const { llm, platformLlm } = rawLlm(ots);
198
- return { name: llm.name, model: llm.model, platform: platformLlm };
199
- }
200
-
201
- // ───────────────────────────── voz ─────────────────────────────
202
-
203
- export async function otsSynthesize(ots, { text, voice = ots.identity.voice }) {
204
- const { env, platformTts } = otsEnv(ots);
205
- const release = platformTts ? reserve(ots, 'tts_platform', freeTts(), 'platform.quota.tts') : null;
206
- let out;
207
- try {
208
- out = await synthesizeWith({ text, voice: platformTts && voice && typeof voice === 'object' ? { ...voice, model: undefined } : voice, env });
209
- } catch (e) {
210
- release?.(false);
211
- throw e;
212
- }
213
- release?.(true);
214
- addUsage(ots, 'tts');
215
- return out;
216
- }
217
-
218
- export function otsTtsProvider(ots) {
219
- return ttsProvider(otsEnv(ots).env);
220
- }
221
-
222
- // ───────────────────────────── canales ─────────────────────────────
223
-
224
- const channels = new Map(); // ots.id → { stamp, ch }
225
- const NO_CHANNELS = {
226
- handle: async () => false,
227
- live: () => ({ email: false, apuchat: null, meet: false }),
228
- openCall: () => {
229
- throw i18nError(501, 'server.channels.noApuchat');
230
- },
231
- status: () => ({ apumail: false, apuchat: false }),
232
- stop: async () => {},
233
- };
234
-
235
- /** Clave que identifica la configuración de canales (si no cambia, no se reinician). */
236
- function channelStamp(ots) {
237
- const { env } = otsEnv(ots);
238
- return JSON.stringify([ots.status, ...Object.keys(OTS_KEYS).filter((k) => OTS_KEYS[k].channels).map((k) => env[k] || '')]);
239
- }
240
-
241
- /** Canales del ots (apumail/apuchat), arrancándolos o reiniciándolos si hace falta. */
242
- export function otsChannels(ots) {
243
- if (!ots || ots.status !== 'on') return NO_CHANNELS;
244
- const stamp = channelStamp(ots);
245
- const hit = channels.get(ots.id);
246
- if (hit?.stamp === stamp) return hit.ch;
247
- hit?.ch.stop().catch(() => {});
248
- const { env } = otsEnv(ots);
249
- const id = ots.id;
250
- // Siempre la versión vigente del ots: identidad e instrucciones cambian sin reiniciar.
251
- const current = () => getOts(id) || ots;
252
- const ch = startAgentChannels({
253
- llm: { get name() { return otsLlmInfo(current()).name; }, get model() { return otsLlmInfo(current()).model; }, step: (a) => otsStep(current(), a) },
254
- identity: () => current().identity,
255
- instructions: () => current().settings.SERVER_INSTRUCTIONS || '',
256
- config: { apumail: { ...apumailConfigFromEnv(env), webhookSecret: '' }, apuchat: apuchatConfigFromEnv(env) },
257
- log: (...a) => console.log(`[7ots:${id}]`, ...a),
258
- // Orquesta tasks: only for senders on the ot's own list (see orquesta.mjs), read on every message.
259
- tools: (ctx) => orquestaTools(current(), ctx),
260
- // mails and DMs go to its conversations (dashboard, and the desktop ot through /api/device/…/inbox)
261
- onTurn: ({ key, channel, user, reply }) => logTurn(current(), { key, channel: channel === 'dm' ? 'apuchat' : 'apumail', visitor: key.replace(/^\w+:/, ''), user, reply }),
262
- });
263
- channels.set(id, { stamp, ch });
264
- return ch;
265
- }
266
-
267
- /** Para los canales de un ots (al pausarlo o borrarlo). */
268
- export async function stopOtsChannels(id) {
269
- const hit = channels.get(id);
270
- channels.delete(id);
271
- llms.delete(id);
272
- await hit?.ch.stop().catch(() => {});
273
- }
274
-
275
- /** Arranca los canales de todos los ots encendidos que los tengan configurados. */
276
- export function startAllChannels() {
277
- for (const ots of allLiveOts()) {
278
- const s = ots.settings;
279
- const sec = ots.secrets;
280
- if ((s.APUMAIL_AGENT_INBOX && sec.APUMAIL_AGENT_TOKEN) || sec.APUCHAT_AGENT_IDENTITY_KEY) otsChannels(ots);
281
- }
282
- }
283
-
284
- export async function stopAllChannels() {
285
- await Promise.all([...channels.keys()].map(stopOtsChannels));
286
- }
@@ -1,146 +0,0 @@
1
- /**
2
- * Sites, APIs and MCP servers an account enrolls so ots know how to use them.
3
- *
4
- * The directory is Prowl.world: 7ots registers the entry there (source '7ots') as one Prowl
5
- * vendor, starts the domain claim and hands the owner Prowl's three proofs (DNS TXT,
6
- * /.well-known/prowl-verify.txt or a <meta>). Once verified, Prowl serves the owner's usage
7
- * guide at GET /v1/context/{domain}, which is what desktop ots read.
8
- *
9
- * From the dashboard (session cookie, X-7ots-Admin: 1, same origin; see routes.mjs):
10
- * GET /api/platform/sites → { sites, enabled }
11
- * POST /api/platform/sites { kind, url, name, guide } → { site }
12
- * POST /api/platform/sites/:id/verify → { site } (422 while the proof isn't there)
13
- * DELETE /api/platform/sites/:id
14
- *
15
- * Env: PROWL_API (default https://prowl.world), PROWL_EMAIL + PROWL_PASSWORD (the 7ots vendor).
16
- */
17
-
18
- import { getDb } from './db.mjs';
19
- import { newId } from './crypto.mjs';
20
-
21
- const KINDS = ['site', 'api', 'mcp'];
22
- const base = () => (process.env.PROWL_API || 'https://prowl.world').replace(/\/+$/, '');
23
- export const sitesEnabled = () => !!(process.env.PROWL_EMAIL && process.env.PROWL_PASSWORD);
24
-
25
- let access = null;
26
- async function prowl(path, { method = 'GET', body, retry = true } = {}) {
27
- if (!access) {
28
- const r = await fetch(`${base()}/v1/auth/login`, {
29
- method: 'POST',
30
- headers: { 'content-type': 'application/json' },
31
- body: JSON.stringify({ email: process.env.PROWL_EMAIL, password: process.env.PROWL_PASSWORD }),
32
- signal: AbortSignal.timeout(15_000),
33
- });
34
- if (!r.ok) throw Object.assign(new Error(`prowl login ${r.status}`), { status: 502 });
35
- access = (await r.json()).access_token;
36
- }
37
- const r = await fetch(`${base()}${path}`, {
38
- method,
39
- headers: { authorization: `Bearer ${access}`, ...(body ? { 'content-type': 'application/json' } : {}) },
40
- body: body ? JSON.stringify(body) : undefined,
41
- signal: AbortSignal.timeout(30_000),
42
- });
43
- if (r.status === 401 && retry) {
44
- access = null;
45
- return prowl(path, { method, body, retry: false });
46
- }
47
- const data = await r.json().catch(() => ({}));
48
- return { status: r.status, data };
49
- }
50
-
51
- const row = (r) =>
52
- r && {
53
- id: r.id,
54
- kind: r.kind,
55
- url: r.url,
56
- domain: r.domain,
57
- name: r.name,
58
- guide: r.guide,
59
- status: r.status,
60
- proof: JSON.parse(r.proof || 'null'),
61
- createdAt: r.created_at,
62
- verifiedAt: r.verified_at,
63
- };
64
-
65
- export function listSites(accountId) {
66
- return getDb().prepare('SELECT * FROM sites WHERE account_id = ? ORDER BY created_at DESC').all(accountId).map(row);
67
- }
68
-
69
- function cleanUrl(raw) {
70
- let u;
71
- try {
72
- u = new URL(/^https?:\/\//i.test(raw) ? raw : `https://${raw}`);
73
- } catch {
74
- return null;
75
- }
76
- if (!/^https?:$/.test(u.protocol) || !u.hostname.includes('.')) return null;
77
- return u;
78
- }
79
-
80
- export function createSites({ send, readJson }) {
81
- const fail = (res, e) => send(res, e.status || 502, { error: e.message || 'Prowl error' });
82
-
83
- return async function sites(req, res, account, path) {
84
- if (!path.startsWith('/sites')) return false;
85
- const d = getDb();
86
- if (path === '/sites' && req.method === 'GET') return send(res, 200, { sites: listSites(account.id), enabled: sitesEnabled() }), true;
87
- if (!sitesEnabled()) return send(res, 503, { error: 'Site enrollment is not configured on this server (PROWL_EMAIL/PROWL_PASSWORD).' }), true;
88
-
89
- if (path === '/sites' && req.method === 'POST') {
90
- const { kind, url, name, guide } = await readJson(req, 32 * 1024);
91
- const u = cleanUrl(String(url || '').trim());
92
- if (!u) return send(res, 400, { error: 'Invalid URL' }), true;
93
- const k = KINDS.includes(kind) ? kind : 'site';
94
- const domain = u.hostname.replace(/^www\./, '').toLowerCase();
95
- if (d.prepare('SELECT 1 FROM sites WHERE account_id = ? AND domain = ?').get(account.id, domain)) return send(res, 409, { error: `${domain} is already registered` }), true;
96
- const title = String(name || '').trim().slice(0, 120) || domain;
97
- const text = String(guide || '').trim().slice(0, 8000);
98
- try {
99
- const reg = await prowl('/v1/register', {
100
- method: 'POST',
101
- body: {
102
- name: title,
103
- website_url: `https://${domain}`,
104
- category: [k === 'mcp' ? 'mcp' : k === 'api' ? 'api' : 'website'],
105
- kind: k,
106
- usage_guide: text || undefined,
107
- source: '7ots',
108
- ...(k === 'mcp' ? { mcp_manifest_url: u.href } : k === 'api' && u.pathname !== '/' ? { api_docs_url: u.href } : {}),
109
- },
110
- });
111
- const serviceId = reg.status === 201 ? reg.data.id : reg.status === 409 ? reg.data.detail?.service_id : null;
112
- if (!serviceId) throw Object.assign(new Error(reg.data.detail?.message || reg.data.detail || `Prowl register ${reg.status}`), { status: 502 });
113
- const claim = await prowl('/v1/claim', { method: 'POST', body: { service_id: serviceId } });
114
- if (claim.status !== 200) throw Object.assign(new Error(claim.data.detail || `Prowl claim ${claim.status}`), { status: claim.status === 409 ? 409 : 502 });
115
- const c = claim.data;
116
- const proof = { dnsRecord: c.dns_record, dnsValue: c.dns_value, wellKnownUrl: c.well_known_url, wellKnownContent: c.well_known_content, metaTag: c.meta_tag };
117
- const id = newId('site');
118
- d.prepare('INSERT INTO sites (id, account_id, kind, url, domain, name, guide, service_id, status, proof, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)')
119
- .run(id, account.id, k, u.href, domain, title, text, serviceId, 'pending', JSON.stringify(proof), Date.now());
120
- return send(res, 201, { site: row(d.prepare('SELECT * FROM sites WHERE id = ?').get(id)) }), true;
121
- } catch (e) {
122
- return fail(res, e), true;
123
- }
124
- }
125
-
126
- const m = path.match(/^\/sites\/(site_[A-Za-z0-9_-]{6,60})(\/verify)?$/);
127
- const s = m && d.prepare('SELECT * FROM sites WHERE id = ? AND account_id = ?').get(m[1], account.id);
128
- if (!s) return send(res, 404, { error: 'Not found' }), true;
129
- if (m[2] && req.method === 'POST') {
130
- try {
131
- const v = await prowl('/v1/claim/verify', { method: 'POST', body: { service_id: s.service_id } });
132
- if (v.status === 422) return send(res, 422, { error: 'proof_missing', site: row(s) }), true;
133
- if (v.status !== 200) throw Object.assign(new Error(v.data.detail || `Prowl verify ${v.status}`), { status: 502 });
134
- d.prepare("UPDATE sites SET status = 'verified', verified_at = ? WHERE id = ?").run(Date.now(), s.id);
135
- return send(res, 200, { site: row(d.prepare('SELECT * FROM sites WHERE id = ?').get(s.id)) }), true;
136
- } catch (e) {
137
- return fail(res, e), true;
138
- }
139
- }
140
- if (!m[2] && req.method === 'DELETE') {
141
- d.prepare('DELETE FROM sites WHERE id = ?').run(s.id);
142
- return send(res, 200, { ok: true }), true;
143
- }
144
- return send(res, 405, { error: 'Method not allowed' }), true;
145
- };
146
- }
@@ -1,82 +0,0 @@
1
- /**
2
- * GET /api/o/:id/3d — the ot alone, in 3D, as a page other apps embed in an <iframe>
3
- * (meet.apuchat.com puts it on a call tile when an agent wears this ot as its persona).
4
- *
5
- * The page draws the ot's own character (same spec as the 2D face, mods included) on a
6
- * transparent background and takes two messages from its parent:
7
- * { type: '7ots:speaking', on: boolean } babble the mouth while the ot is talking
8
- * { type: '7ots:gesture', name: string } one of the 3D gestures (wave, nod, …)
9
- * Neither carries data nor reaches the server, so any parent may send them. A look that is
10
- * not a character (an uploaded picture) falls back to /portrait.svg.
11
- */
12
-
13
- // Who may frame it. Kept to the apps that actually embed ots; widen it here, not in Caddy.
14
- export const STAGE3D_FRAME_ANCESTORS = [
15
- "'self'",
16
- 'https://meet.apuchat.com',
17
- 'https://apuchat.com', 'https://*.apuchat.com',
18
- 'https://getorquesta.com', 'https://*.getorquesta.com',
19
- 'https://rogerthat.chat', 'https://*.rogerthat.chat',
20
- ];
21
-
22
- export function stage3dHeaders() {
23
- return {
24
- 'Content-Type': 'text/html; charset=utf-8',
25
- 'Cache-Control': 'no-cache',
26
- 'X-Content-Type-Options': 'nosniff',
27
- 'Referrer-Policy': 'no-referrer',
28
- // frame-ancestors supersedes the X-Frame-Options the edge adds to every response.
29
- 'Content-Security-Policy': `frame-ancestors ${STAGE3D_FRAME_ANCESTORS.join(' ')}; base-uri 'none'; object-src 'none'`,
30
- };
31
- }
32
-
33
- export function stage3dPage() {
34
- return `<!doctype html>
35
- <html lang="en">
36
- <head>
37
- <meta charset="utf-8">
38
- <meta name="viewport" content="width=device-width,initial-scale=1">
39
- <meta name="robots" content="noindex">
40
- <title>7ots</title>
41
- <script type="importmap">
42
- { "imports": {
43
- "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
44
- "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
45
- } }
46
- </script>
47
- <style>
48
- html, body { margin: 0; height: 100%; background: transparent; overflow: hidden; }
49
- #ot { position: absolute; inset: 0; }
50
- img { position: absolute; inset: 0; margin: auto; height: 70%; max-width: 85%; object-fit: contain; }
51
- </style>
52
- </head>
53
- <body>
54
- <div id="ot"></div>
55
- <script type="module">
56
- import { createCharacter3D } from '/src/character3d/index.js';
57
- const el = document.getElementById('ot');
58
- const base = location.pathname.replace(/\\/3d\\/?$/, '');
59
- const flat = () => { el.innerHTML = ''; const i = new Image(); i.alt = ''; i.src = base + '/portrait.svg'; el.append(i); };
60
- let ot = null;
61
- try {
62
- const card = await fetch(base + '/identity', { headers: { accept: 'application/json' } }).then((r) => r.json());
63
- const look = card && card.look;
64
- if (look && look.kind === 'character' && look.character) ot = createCharacter3D(el, look.character, { orbit: false, backdrop: false });
65
- else flat();
66
- } catch { flat(); }
67
- let talk = null;
68
- addEventListener('message', (e) => {
69
- const m = e.data;
70
- if (!ot || !m || typeof m !== 'object') return;
71
- if (m.type === '7ots:speaking') {
72
- if (m.on && !talk) talk = ot.speak(600000);
73
- else if (!m.on && talk) { talk.stop(); talk = null; }
74
- } else if (m.type === '7ots:gesture' && typeof m.name === 'string') {
75
- try { ot.gesture(m.name.slice(0, 32)); } catch {}
76
- }
77
- });
78
- parent !== window && parent.postMessage({ type: '7ots:ready' }, '*');
79
- </script>
80
- </body>
81
- </html>`;
82
- }