@7ots/cli 0.1.38 → 0.1.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/7ots.mjs +63 -0
- package/cli/lib/i18n.mjs +9 -3
- package/cli/lib/integrations.mjs +21 -4
- package/cli/lib/pet-server.mjs +41 -1
- package/cli/lib/plugins.mjs +204 -0
- package/cli/pet/electron/main.cjs +116 -11
- package/cli/pet/pet.html +2 -1
- package/cli/pet/settings.html +165 -7
- package/package.json +3 -2
- package/server/server.mjs +4 -0
- package/src/plugins.js +137 -0
package/cli/7ots.mjs
CHANGED
|
@@ -246,6 +246,66 @@ async function cmdAsk({ pos }) {
|
|
|
246
246
|
console.log(r.reply || '');
|
|
247
247
|
}
|
|
248
248
|
|
|
249
|
+
/** Plugins: windows beside the ot and tools for its brain (cli/lib/plugins.mjs, docs/PLUGINS.md). */
|
|
250
|
+
async function cmdPlugin({ pos }) {
|
|
251
|
+
const P = await import('./lib/plugins.mjs');
|
|
252
|
+
const [sub = 'list', a, b] = pos;
|
|
253
|
+
const line = (p) => `${p.on ? '●' : '○'} ${p.id.padEnd(20)} ${p.manifest ? `${p.manifest.icon} ${p.manifest.name} v${p.manifest.version}` : `(${p.error})`}${p.source === 'local' ? ` · dev ${p.dir}` : ''}`;
|
|
254
|
+
const daemon = async (act, body) => {
|
|
255
|
+
if (!(await petAlive())) return null;
|
|
256
|
+
return fetch(`http://127.0.0.1:${PET_PORT}/plugins/${act}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-7ots-Token': petToken() }, body: JSON.stringify(body), signal: AbortSignal.timeout(5000) }).then((r) => r.json()).catch(() => null);
|
|
257
|
+
};
|
|
258
|
+
switch (sub) {
|
|
259
|
+
case 'list':
|
|
260
|
+
case 'ls': {
|
|
261
|
+
const ps = P.listPlugins();
|
|
262
|
+
return console.log(ps.length ? ps.map(line).join('\n') : t('usage.plugin'));
|
|
263
|
+
}
|
|
264
|
+
case 'catalog':
|
|
265
|
+
case 'search': {
|
|
266
|
+
const ps = await P.catalog({ q: a || '' });
|
|
267
|
+
return console.log(ps.map((v) => `${v.installed ? (v.update ? '↑' : '✓') : ' '} ${v.id.padEnd(20)} ${v.manifest.icon} ${v.manifest.name} — ${v.manifest.description || ''} (${v.official ? '7ots' : v.author})`).join('\n') || '—');
|
|
268
|
+
}
|
|
269
|
+
case 'add':
|
|
270
|
+
case 'install': {
|
|
271
|
+
if (!a) fail(t('usage.plugin'));
|
|
272
|
+
const local = /[/\\.]/.test(a) || existsSync(a);
|
|
273
|
+
const p = local ? P.addLocal(a) : await P.installFromCatalog(a);
|
|
274
|
+
console.log(line(p));
|
|
275
|
+
if (p.manifest.panel) console.log(`→ 7ots plugin open ${p.id}`);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
case 'remove':
|
|
279
|
+
case 'rm':
|
|
280
|
+
if (!a) fail(t('usage.plugin'));
|
|
281
|
+
return console.log(P.removePlugin(a) ? `removed ${a}` : `no plugin ${a}`);
|
|
282
|
+
case 'on':
|
|
283
|
+
case 'off':
|
|
284
|
+
if (!a) fail(t('usage.plugin'));
|
|
285
|
+
return console.log(P.setPluginOn(a, sub === 'on') ? `${a}: ${sub}` : `no plugin ${a}`);
|
|
286
|
+
case 'open': {
|
|
287
|
+
if (!a) fail(t('usage.plugin'));
|
|
288
|
+
if (!P.getPlugin(a)?.manifest.panel) fail(`no plugin ${a} with a window`);
|
|
289
|
+
if (!(await daemon('open', { id: a }))) fail(t('err.noPet'));
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
case 'new':
|
|
293
|
+
case 'create': {
|
|
294
|
+
if (!a) fail(t('usage.plugin'));
|
|
295
|
+
const { homedir } = await import('node:os');
|
|
296
|
+
const { dir, id } = P.scaffold(b || join(homedir(), '7ots-plugins', a), { id: a });
|
|
297
|
+
P.addLocal(dir);
|
|
298
|
+
return console.log(`${dir}\n→ 7ots plugin open ${id} · 7ots plugin publish ${dir}`);
|
|
299
|
+
}
|
|
300
|
+
case 'publish': {
|
|
301
|
+
const { plugin } = await P.publishPlugin(a || '.');
|
|
302
|
+
return console.log(`${plugin.id} v${plugin.manifest.version}: ${plugin.status} → https://7ots.com/app/#plugins`);
|
|
303
|
+
}
|
|
304
|
+
default:
|
|
305
|
+
fail(t('usage.plugin'));
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
249
309
|
async function cmdReminders({ flags }) {
|
|
250
310
|
if (!(await petAlive())) fail(t('err.noPet'));
|
|
251
311
|
if (flags.cancel) {
|
|
@@ -601,6 +661,9 @@ async function main() {
|
|
|
601
661
|
return cmdDance(cmd, args);
|
|
602
662
|
case 'reminders':
|
|
603
663
|
return cmdReminders(args);
|
|
664
|
+
case 'plugin':
|
|
665
|
+
case 'plugins':
|
|
666
|
+
return cmdPlugin(args);
|
|
604
667
|
case 'senses':
|
|
605
668
|
return cmdSenses(args);
|
|
606
669
|
case 'config':
|
package/cli/lib/i18n.mjs
CHANGED
|
@@ -20,6 +20,7 @@ const M = {
|
|
|
20
20
|
7ots status [--line|--json] pet state (--line: one line for tmux)
|
|
21
21
|
7ots ask <text> talk to it: "remind me to check email in 10 min", "open my calendar", "remember that…"
|
|
22
22
|
7ots reminders [--cancel <id>] pending reminders and what it remembers
|
|
23
|
+
7ots plugin [add|open|new|publish] … plugins: windows and tools for your ot
|
|
23
24
|
7ots senses [status|rules|pause [min]|resume|reflect|forget] what it notices (camera, apps, mail) and its rules
|
|
24
25
|
7ots config [--print] settings page: brain, what it can see, notes
|
|
25
26
|
7ots hooks install|remove [--claude] [--shell] [--global]
|
|
@@ -107,7 +108,8 @@ Docs: https://7ots.com/llms.txt`,
|
|
|
107
108
|
'err.noPet': 'The pet is not awake. Start it with: 7ots pet',
|
|
108
109
|
'pet.settings': 'Opening the settings in your browser.',
|
|
109
110
|
'usage.senses': '7ots senses [status|rules|pause [min]|resume|reflect|forget] [--json]\n\n Turn them on in settings → Senses (7ots config).',
|
|
110
|
-
'usage.
|
|
111
|
+
'usage.plugin': '7ots plugin [list|catalog [q]|add <id|./dir>|on|off|open|remove <id>|new <id> [dir]|publish <dir>]\n\n Plugins add a window beside your ot and tools for its brain. Guide: https://7ots.com/docs/plugins',
|
|
112
|
+
'usage.ask': '7ots ask <text>\n\n e.g. 7ots ask "remind me to check email in 10 minutes and open it"\n 7ots ask "remember that Fridays we demo" · 7ots ask "my reminders"\n Enable "See your screen" and "Processes and apps" in Settings (7ots config).',
|
|
111
113
|
'err.noIdentity': 'No identity yet. Create one with "7ots new" or run "7ots setup".',
|
|
112
114
|
'w.title': '7ots setup — {name}',
|
|
113
115
|
'w.intro': 'Your ot in 7 short steps. Keys stay on this computer.',
|
|
@@ -214,6 +216,7 @@ Docs: https://7ots.com/llms.txt`,
|
|
|
214
216
|
7ots status [--line|--json] estado (--line: una línea para tmux)
|
|
215
217
|
7ots ask <texto> háblale: "recuérdame ver el correo en 10 min", "abre mi calendario", "anota que…"
|
|
216
218
|
7ots reminders [--cancel <id>] recordatorios pendientes y lo que recuerda
|
|
219
|
+
7ots plugin [add|open|new|publish] … plugins: ventanas y herramientas para tu ot
|
|
217
220
|
7ots senses [status|rules|pause [min]|resume|reflect|forget] lo que nota (cámara, apps, correo) y sus reglas
|
|
218
221
|
7ots config [--print] ajustes: cerebro, qué puede ver, notas
|
|
219
222
|
7ots hooks install|remove [--claude] [--shell] [--global]
|
|
@@ -301,7 +304,8 @@ Docs: https://7ots.com/llms.txt`,
|
|
|
301
304
|
'err.noPet': 'La mascota no está despierta. Iníciala con: 7ots pet',
|
|
302
305
|
'pet.settings': 'Abriendo los ajustes en tu navegador.',
|
|
303
306
|
'usage.senses': '7ots senses [status|rules|pause [min]|resume|reflect|forget] [--json]\n\n Se activan en ajustes → Sentidos (7ots config).',
|
|
304
|
-
'usage.
|
|
307
|
+
'usage.plugin': '7ots plugin [list|catalog [q]|add <id|./carpeta>|on|off|open|remove <id>|new <id> [carpeta]|publish <carpeta>]\n\n Los plugins agregan una ventana junto a tu ot y herramientas para su cerebro. Guía: https://7ots.com/docs/plugins',
|
|
308
|
+
'usage.ask': '7ots ask <texto>\n\n ej. 7ots ask "recuérdame ver el correo en 10 minutos y ábrelo"\n 7ots ask "anota que los viernes hay demo" · 7ots ask "mis recordatorios"\n Activa "Ver tu pantalla" y "Procesos y apps" en Ajustes (7ots config).',
|
|
305
309
|
'err.noIdentity': 'Aún no hay identidad. Crea una con «7ots new» o corre «7ots setup».',
|
|
306
310
|
'w.title': 'Configuración de 7ots — {name}',
|
|
307
311
|
'w.intro': 'Tu ot en 7 pasos cortos. Las claves se quedan en este computador.',
|
|
@@ -408,6 +412,7 @@ Docs: https://7ots.com/llms.txt`,
|
|
|
408
412
|
7ots status [--line|--json] estado (--line: uma linha para tmux)
|
|
409
413
|
7ots ask <texto> fale com ele: "me lembre de ver o e-mail em 10 min", "abra minha agenda", "anote que…"
|
|
410
414
|
7ots reminders [--cancel <id>] lembretes pendentes e o que ele lembra
|
|
415
|
+
7ots plugin [add|open|new|publish] … plugins: janelas e ferramentas para o seu ot
|
|
411
416
|
7ots senses [status|rules|pause [min]|resume|reflect|forget] o que ele nota (câmera, apps, e-mail) e suas regras
|
|
412
417
|
7ots config [--print] ajustes: cérebro, o que pode ver, notas
|
|
413
418
|
7ots hooks install|remove [--claude] [--shell] [--global]
|
|
@@ -495,7 +500,8 @@ Docs: https://7ots.com/llms.txt`,
|
|
|
495
500
|
'err.noPet': 'O bichinho não está acordado. Inicie com: 7ots pet',
|
|
496
501
|
'pet.settings': 'Abrindo os ajustes no seu navegador.',
|
|
497
502
|
'usage.senses': '7ots senses [status|rules|pause [min]|resume|reflect|forget] [--json]\n\n Ative em ajustes → Sentidos (7ots config).',
|
|
498
|
-
'usage.
|
|
503
|
+
'usage.plugin': '7ots plugin [list|catalog [q]|add <id|./pasta>|on|off|open|remove <id>|new <id> [pasta]|publish <pasta>]\n\n Plugins adicionam uma janela ao lado do seu ot e ferramentas para o cérebro. Guia: https://7ots.com/docs/plugins',
|
|
504
|
+
'usage.ask': '7ots ask <texto>\n\n ex. 7ots ask "me lembre de ver o e-mail em 10 minutos e abra"\n 7ots ask "anote que às sextas tem demo" · 7ots ask "meus lembretes"\n Ative "Ver sua tela" e "Processos e apps" nas Configurações (7ots config).',
|
|
499
505
|
'err.noIdentity': 'Ainda não há identidade. Crie uma com «7ots new» ou rode «7ots setup».',
|
|
500
506
|
'w.title': 'Configuração do 7ots — {name}',
|
|
501
507
|
'w.intro': 'Seu ot em 7 passos curtos. As chaves ficam neste computador.',
|
package/cli/lib/integrations.mjs
CHANGED
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
* cloudStatus() link with 7ots.com (account.mjs) + the cloud assistant's VM: GET /api/device/ots/:id/vm (device token; see docs/VM-PLAN.md)
|
|
21
21
|
* (404 = not available yet).
|
|
22
22
|
*
|
|
23
|
-
* Extra assistant actions (assistant.mjs `extra`): read_logs · read_mail · orquesta_list · orquesta · integration
|
|
23
|
+
* Extra assistant actions (assistant.mjs `extra`): read_logs · read_mail · orquesta_list · orquesta · integration · plugin
|
|
24
|
+
* (opens an installed plugin's panel; plugins with an MCP server join the custom integrations: plugins.mjs).
|
|
24
25
|
*/
|
|
25
26
|
|
|
26
27
|
import { spawn } from 'node:child_process';
|
|
@@ -31,6 +32,7 @@ import { env, loadConfig, loadKeys } from './config.mjs';
|
|
|
31
32
|
import { SEVENOTS_URL, me as accountMe, signedIn } from './account.mjs';
|
|
32
33
|
import { mcpCall, mcpTools, mcpToolsCached } from './mcp.mjs';
|
|
33
34
|
import { recordUse } from './tooluse.mjs';
|
|
35
|
+
import { getPlugin, pluginIntegrations, pluginsPrompt } from './plugins.mjs';
|
|
34
36
|
|
|
35
37
|
const LETTA_URL = (process.env.LETTA_BASE_URL || 'https://api.letta.com').replace(/\/+$/, '');
|
|
36
38
|
const APUMAIL_API = (process.env.APUMAIL_API || 'https://api.apumail.com').replace(/\/+$/, '');
|
|
@@ -423,7 +425,7 @@ function refreshLetta(agentId) {
|
|
|
423
425
|
* confirm (text) => Promise<boolean>: asks the human (Approve / Reject) before something that acts for them
|
|
424
426
|
* connect () => Promise<{ organizationName }>: Orquesta sign-in in their browser (offered while there is no token)
|
|
425
427
|
*/
|
|
426
|
-
export function createExtras({ config, brain, system, onLater, confirm = null, connect = null, log = () => {} }) {
|
|
428
|
+
export function createExtras({ config, brain, system, onLater, confirm = null, connect = null, openPlugin = null, log = () => {} }) {
|
|
427
429
|
let projCache = { at: 0, list: [] };
|
|
428
430
|
const orq = () => import('./orquesta.mjs');
|
|
429
431
|
// Orquesta: a token here, or the one connected on 7ots.com for this ot (used through 7ots, never copied here)
|
|
@@ -445,7 +447,7 @@ export function createExtras({ config, brain, system, onLater, confirm = null, c
|
|
|
445
447
|
};
|
|
446
448
|
const mailOn = () => config().access?.inbox === true && config().integrations?.apumail?.on && Boolean(env().APUMAIL_TOKEN) && Boolean(config().integrations.apumail.inbox || isAcctToken(env().APUMAIL_TOKEN));
|
|
447
449
|
const cloudId = () => (env().SEVENOTS_TOKEN && config().account?.otsId) || null;
|
|
448
|
-
const customs = () => (config().integrations?.custom || []).filter((c) => c.on !== false && customKind(c) !== 'note' && (c.url || c.command));
|
|
450
|
+
const customs = () => [...(config().integrations?.custom || []), ...safePlugins()].filter((c) => c.on !== false && customKind(c) !== 'note' && (c.url || c.command));
|
|
449
451
|
const toolsLine = (x) => {
|
|
450
452
|
const tools = mcpToolsCached(x);
|
|
451
453
|
if (!tools) {
|
|
@@ -485,6 +487,10 @@ export function createExtras({ config, brain, system, onLater, confirm = null, c
|
|
|
485
487
|
}
|
|
486
488
|
}
|
|
487
489
|
|
|
490
|
+
// ── plugins (plugins.mjs): a broken one never breaks the assistant ──
|
|
491
|
+
const safe = (fn, d) => { try { return fn(); } catch (e) { log(`plugins: ${e.message}`); return d; } };
|
|
492
|
+
const safePlugins = () => safe(pluginIntegrations, []);
|
|
493
|
+
|
|
488
494
|
// Approve / Reject in the ot's bubble; without a way to ask (no confirm), it goes ahead as before
|
|
489
495
|
const ask = (lang, k, ...v) => (confirm ? confirm(say(lang, k, ...v)) : Promise.resolve(true));
|
|
490
496
|
|
|
@@ -504,10 +510,14 @@ export function createExtras({ config, brain, system, onLater, confirm = null, c
|
|
|
504
510
|
if (cloudId()) lines.push(`{"type":"read_inbox"} (read what people wrote to you lately on apuchat and email, your own accounts on 7ots.com, and what you answered them; then sum it up for your human)`);
|
|
505
511
|
for (const x of customs()) {
|
|
506
512
|
const kind = customKind(x);
|
|
507
|
-
if (kind === 'mcp') lines.push(`{"type":"integration","id":"${x.id}","tool":"tool name","args":{}} (MCP server "${x.name}"${toolsLine(x)})`);
|
|
513
|
+
if (kind === 'mcp') lines.push(`{"type":"integration","id":"${x.id}","tool":"tool name","args":{}} (MCP server "${x.name}"${x.id.startsWith('plugin-') && x.instructions ? `, a plugin: ${x.instructions}` : ''}${toolsLine(x)})`);
|
|
508
514
|
else if (kind === 'api') lines.push(`{"type":"integration","id":"${x.id}","path":"optional /sub/path?query"} (GET the API "${x.name}" at ${x.url})`);
|
|
509
515
|
else lines.push(`{"type":"integration","id":"${x.id}"} (run "${x.name}")`);
|
|
510
516
|
}
|
|
517
|
+
if (openPlugin) {
|
|
518
|
+
const pl = safe(pluginsPrompt, '');
|
|
519
|
+
if (pl) lines.push(pl);
|
|
520
|
+
}
|
|
511
521
|
return lines.length ? `More actions you have:\n${lines.join('\n')}` : '';
|
|
512
522
|
},
|
|
513
523
|
/** A raw AI action → a validated one, or null. */
|
|
@@ -518,6 +528,7 @@ export function createExtras({ config, brain, system, onLater, confirm = null, c
|
|
|
518
528
|
if (a?.type === 'orquesta_connect' && connect) return { type: 'orquesta_connect', extra: true };
|
|
519
529
|
if (a?.type === 'orquesta_list') return { type: 'orquesta_list', extra: true };
|
|
520
530
|
if (a?.type === 'orquesta' && a.text) return { type: 'orquesta', extra: true, project: a.project ? String(a.project).slice(0, 120) : null, text: String(a.text).slice(0, 4000) };
|
|
531
|
+
if (a?.type === 'plugin' && a.id && openPlugin) return { type: 'plugin', extra: true, id: String(a.id).slice(0, 32) };
|
|
521
532
|
if (a?.type === 'integration' && a.id) return { type: 'integration', extra: true, id: String(a.id).slice(0, 40), ...(a.tool ? { tool: String(a.tool).slice(0, 80), args: a.args && typeof a.args === 'object' && !Array.isArray(a.args) ? a.args : {} } : {}), ...(a.path ? { path: String(a.path).slice(0, 300) } : {}) };
|
|
522
533
|
return null;
|
|
523
534
|
},
|
|
@@ -565,6 +576,12 @@ export function createExtras({ config, brain, system, onLater, confirm = null, c
|
|
|
565
576
|
follow(id, p.name, lang).catch((e) => log(`orquesta: ${e.message}`));
|
|
566
577
|
return { data: `Sent to the agent of "${p.name}"${p.online === false ? ' (its agent is offline now; it runs when it comes back)' : ''}. Tell them you'll let them know when it answers.` };
|
|
567
578
|
}
|
|
579
|
+
if (a.type === 'plugin') {
|
|
580
|
+
const p = getPlugin(a.id);
|
|
581
|
+
if (!p?.on || !p.manifest.panel) return { data: '(that plugin is off, has no panel or is not installed)' };
|
|
582
|
+
openPlugin(p.id);
|
|
583
|
+
return { data: `The "${p.manifest.name}" panel just opened beside you. Tell them in a few words; do not invent what it shows.` };
|
|
584
|
+
}
|
|
568
585
|
if (a.type === 'integration') {
|
|
569
586
|
const x = customs().find((y) => y.id === a.id);
|
|
570
587
|
if (!x) return { data: '(that integration is off or does not exist)' };
|
package/cli/lib/pet-server.mjs
CHANGED
|
@@ -54,6 +54,7 @@ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
|
54
54
|
import { readFileSync, existsSync, writeFileSync, chmodSync, mkdirSync, rmSync, symlinkSync, readdirSync, statSync, createReadStream } from 'node:fs';
|
|
55
55
|
import { cardShot } from './card-shot.mjs';
|
|
56
56
|
import { join } from 'node:path';
|
|
57
|
+
import { homedir } from 'node:os';
|
|
57
58
|
import { createAssistant, notify, tr } from './assistant.mjs';
|
|
58
59
|
import { createWatchers, processes, processSummary } from './watchers.mjs';
|
|
59
60
|
import { createInferenceLog, otherInferences } from './inferences.mjs';
|
|
@@ -70,6 +71,7 @@ import { createScreenWatcher } from './screen.mjs';
|
|
|
70
71
|
import { createSiteContext } from './prowl.mjs';
|
|
71
72
|
import { createSenses } from './senses/index.mjs';
|
|
72
73
|
import { ensureVendor, vendorFile, vendorStatus } from './senses/vendor.mjs';
|
|
74
|
+
import { addLocal as addLocalPlugin, catalog as pluginCatalog, getPlugin, installFromCatalog, listPlugins, myPlugins, publishPlugin, removePlugin, scaffold as scaffoldPlugin, setPluginOn } from './plugins.mjs';
|
|
73
75
|
import { SEVENOTS_URL, cloudSpeak, community, sync as syncOt, logout as accountLogout, me as accountMe, pull as pullOt, signedIn, startLogin, use as useOt } from './account.mjs';
|
|
74
76
|
import { openUrl } from './open.mjs';
|
|
75
77
|
import { syncDesktop } from './desktop-sync.mjs';
|
|
@@ -463,6 +465,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
|
|
|
463
465
|
system: (said) => petSystem(identity, { lang: said || 'auto', role: 'assistant' }),
|
|
464
466
|
confirm,
|
|
465
467
|
connect: connectOrquesta,
|
|
468
|
+
openPlugin: (id) => broadcast({ plugin: { open: id } }), // the desktop shell opens its panel beside the ot
|
|
466
469
|
onLater: (text) => {
|
|
467
470
|
lastSpoke = Date.now();
|
|
468
471
|
pet.lastTalk = lastSpoke;
|
|
@@ -819,6 +822,7 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
|
|
|
819
822
|
screen: { on: config.access.screen === true, every: config.screen.every, last: watcher.seen?.[0] || null },
|
|
820
823
|
system: config.access.processes ? await processes({ n: 60 }) : null,
|
|
821
824
|
});
|
|
825
|
+
if (req.method === 'GET' && p === '/plugins') return json(200, { plugins: listPlugins(), signedIn: signedIn(), url: SEVENOTS_URL });
|
|
822
826
|
if (req.method === 'GET' && p === '/reminders') return json(200, { reminders: assistant.reminders, notes: assistant.notes });
|
|
823
827
|
if (req.method === 'GET' && p === '/cloud') return json(200, await cloudStatus(config));
|
|
824
828
|
const bm = /^\/byte(\/(?:games|status|play|stop|connect))?$/.exec(p);
|
|
@@ -1080,6 +1084,40 @@ export function startPetServer({ port = PET_PORT, log = () => {} } = {}) {
|
|
|
1080
1084
|
}
|
|
1081
1085
|
return restart(); // identity, language and name are read once at start
|
|
1082
1086
|
}
|
|
1087
|
+
if (p.startsWith('/plugins/')) {
|
|
1088
|
+
// plugins (plugins.mjs): the 7ots.com catalog (approved ones), your own folders (dev), and review requests
|
|
1089
|
+
const act = p.slice('/plugins/'.length);
|
|
1090
|
+
const id = String(data.id || '');
|
|
1091
|
+
try {
|
|
1092
|
+
if (act === 'catalog') return json(200, { plugins: await pluginCatalog({ q: String(data.q || '') }) });
|
|
1093
|
+
if (act === 'install') return json(200, { plugin: await installFromCatalog(id) });
|
|
1094
|
+
if (act === 'add') return json(200, { plugin: addLocalPlugin(String(data.dir || '')) });
|
|
1095
|
+
if (act === 'new') {
|
|
1096
|
+
const dir = String(data.dir || '') || join(homedir(), '7ots-plugins', String(data.id || 'my-plugin'));
|
|
1097
|
+
const r = scaffoldPlugin(dir, { id: data.id, name: data.name });
|
|
1098
|
+
return json(200, { plugin: addLocalPlugin(r.dir), dir: r.dir });
|
|
1099
|
+
}
|
|
1100
|
+
if (act === 'remove') return json(200, { ok: removePlugin(id) });
|
|
1101
|
+
if (act === 'on') return json(200, { ok: setPluginOn(id, data.on !== false) });
|
|
1102
|
+
if (act === 'open') {
|
|
1103
|
+
const pl = getPlugin(id);
|
|
1104
|
+
if (!pl?.manifest.panel) return json(404, { error: 'no panel' });
|
|
1105
|
+
broadcast({ plugin: { open: id } });
|
|
1106
|
+
return json(200, { ok: true });
|
|
1107
|
+
}
|
|
1108
|
+
if (!signedIn()) return json(401, { error: 'login' });
|
|
1109
|
+
if (act === 'mine') return json(200, await myPlugins());
|
|
1110
|
+
if (act === 'publish') {
|
|
1111
|
+
const pl = getPlugin(id);
|
|
1112
|
+
if (!pl || pl.source !== 'local') return json(400, { error: 'only your own (local) plugins can be sent for review' });
|
|
1113
|
+
return json(200, await publishPlugin(pl.dir));
|
|
1114
|
+
}
|
|
1115
|
+
} catch (e) {
|
|
1116
|
+
log(`plugins ${act}: ${e.message}`);
|
|
1117
|
+
return json(e.status || 400, { error: e.message });
|
|
1118
|
+
}
|
|
1119
|
+
return json(404, { error: 'not found' });
|
|
1120
|
+
}
|
|
1083
1121
|
if (p.startsWith('/community/')) {
|
|
1084
1122
|
// the 7ots.com gallery (server/platform/mods.mjs): browse without an account; share, rate and report with one
|
|
1085
1123
|
const act = p.slice('/community/'.length);
|
|
@@ -1489,7 +1527,9 @@ ${keys.map((k) => FIELDS[k]).join('\n')}`;
|
|
|
1489
1527
|
for (const c of clients) c.end();
|
|
1490
1528
|
server.close();
|
|
1491
1529
|
server.closeAllConnections?.();
|
|
1492
|
-
|
|
1530
|
+
// With a callback (restart): ref the timer so it always fires even if the event loop empties first.
|
|
1531
|
+
const _t = setTimeout(() => (then?.(), process.exit(0)), 200);
|
|
1532
|
+
if (!then) _t.unref();
|
|
1493
1533
|
}
|
|
1494
1534
|
|
|
1495
1535
|
return new Promise((resolve, reject) => {
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugins on this computer (src/plugins.js has the format; docs/PLUGINS.md the guide for devs).
|
|
3
|
+
*
|
|
4
|
+
* ~/.7ots/plugins.json { [id]: { on, source: 'catalog' | 'local', dir?, sha?, at } }
|
|
5
|
+
* ~/.7ots/plugins/<id>/ a catalog plugin's files (downloaded from 7ots.com, reviewed there)
|
|
6
|
+
* local plugins read live from your own folder (`7ots plugin add ./my-plugin`): for devs
|
|
7
|
+
*
|
|
8
|
+
* The catalog (7ots.com/api/plugins) only lists plugins an admin approved. A panel opens in its own sandboxed
|
|
9
|
+
* window beside the ot (electron/main.cjs, ots-plugin://<id>/…); an MCP server becomes one more integration
|
|
10
|
+
* of the brain (integrations.mjs); `instructions` tell the brain when to open the panel or use the tools.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
15
|
+
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
16
|
+
import { MAX_BYTES, MAX_FILES, PLUGIN_ID, normalizeBundle, normalizeManifest, okFilePath } from '../../src/plugins.js';
|
|
17
|
+
import { SEVENOTS_URL, api, signedIn } from './account.mjs';
|
|
18
|
+
import { homeFile, readJson, writeJson } from './paths.mjs';
|
|
19
|
+
|
|
20
|
+
const STATE = () => homeFile('plugins.json');
|
|
21
|
+
const MANIFEST = '7ots-plugin.json';
|
|
22
|
+
const state = () => readJson(STATE(), {}) || {};
|
|
23
|
+
const save = (s) => writeJson(STATE(), s);
|
|
24
|
+
export const pluginDir = (id, s = state()) => (s[id]?.source === 'local' ? s[id].dir : homeFile(join('plugins', id)));
|
|
25
|
+
|
|
26
|
+
function readManifest(dir, o) {
|
|
27
|
+
return normalizeManifest(JSON.parse(readFileSync(join(dir, MANIFEST), 'utf8')), o);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Installed plugins: [{ id, on, source, manifest, dir, sha? , error? }] */
|
|
31
|
+
export function listPlugins() {
|
|
32
|
+
const s = state();
|
|
33
|
+
return Object.entries(s).map(([id, e]) => {
|
|
34
|
+
const dir = pluginDir(id, s);
|
|
35
|
+
try {
|
|
36
|
+
return { id, on: e.on !== false, source: e.source, dir, sha: e.sha || null, at: e.at, manifest: readManifest(dir, { catalog: e.source === 'catalog' }) };
|
|
37
|
+
} catch (err) {
|
|
38
|
+
return { id, on: false, source: e.source, dir, at: e.at, error: err.code === 'ENOENT' ? 'missing' : err.message };
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
export const getPlugin = (id) => listPlugins().find((p) => p.id === id && !p.error) || null;
|
|
43
|
+
export const activePlugins = () => listPlugins().filter((p) => p.on && !p.error);
|
|
44
|
+
|
|
45
|
+
/** A file of a plugin, or null (path checked, served type from src/plugins.js). */
|
|
46
|
+
export function pluginFile(id, path) {
|
|
47
|
+
const p = getPlugin(id);
|
|
48
|
+
if (!p || !okFilePath(path)) return null;
|
|
49
|
+
const file = resolve(p.dir, path);
|
|
50
|
+
if (!file.startsWith(resolve(p.dir) + sep) || !existsSync(file)) return null;
|
|
51
|
+
return { plugin: p, file, body: readFileSync(file) };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A folder → bundle { manifest, files (base64) } as 7ots.com takes it. */
|
|
55
|
+
export function bundleOf(dir, { catalog = true } = {}) {
|
|
56
|
+
dir = resolve(dir);
|
|
57
|
+
const manifest = readManifest(dir, { catalog });
|
|
58
|
+
const files = {};
|
|
59
|
+
let n = 0;
|
|
60
|
+
const walk = (d, depth = 0) => {
|
|
61
|
+
for (const name of readdirSync(d)) {
|
|
62
|
+
if (name.startsWith('.') || name === 'node_modules' || name === MANIFEST || (d === dir && name === 'README.md')) continue;
|
|
63
|
+
const f = join(d, name);
|
|
64
|
+
if (statSync(f).isDirectory()) {
|
|
65
|
+
if (depth < 3) walk(f, depth + 1);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const rel = relative(dir, f).split(sep).join('/');
|
|
69
|
+
if (!okFilePath(rel)) continue; // only web files go up (src/plugins.js FILE_TYPES)
|
|
70
|
+
if (++n > MAX_FILES) throw new Error(`more than ${MAX_FILES} files`);
|
|
71
|
+
files[rel] = readFileSync(f).toString('base64');
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
walk(dir);
|
|
75
|
+
return normalizeBundle({ manifest, files }, { catalog });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export const bundleSha = (b) => createHash('sha256').update(JSON.stringify({ manifest: b.manifest, files: b.files })).digest('hex');
|
|
79
|
+
|
|
80
|
+
/** Adds a plugin from a folder of yours (dev): read live from there, not reviewed by anyone. */
|
|
81
|
+
export function addLocal(dir) {
|
|
82
|
+
dir = resolve(dir);
|
|
83
|
+
if (!existsSync(join(dir, MANIFEST))) throw new Error(`no ${MANIFEST} in ${dir}`);
|
|
84
|
+
const manifest = readManifest(dir, { catalog: false });
|
|
85
|
+
const s = state();
|
|
86
|
+
if (s[manifest.id]?.source === 'catalog') rmSync(homeFile(join('plugins', manifest.id)), { recursive: true, force: true });
|
|
87
|
+
s[manifest.id] = { on: true, source: 'local', dir, at: Date.now() };
|
|
88
|
+
save(s);
|
|
89
|
+
return getPlugin(manifest.id);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ── the catalog (7ots.com) ──
|
|
93
|
+
|
|
94
|
+
const pub = async (path) => {
|
|
95
|
+
const r = await fetch(`${SEVENOTS_URL}/api/plugins${path}`, { signal: AbortSignal.timeout(20000) });
|
|
96
|
+
const data = await r.json().catch(() => ({}));
|
|
97
|
+
if (!r.ok) throw Object.assign(new Error(data.error || `HTTP ${r.status}`), { status: r.status });
|
|
98
|
+
return data;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** Approved plugins on 7ots.com, with what is installed here. */
|
|
102
|
+
export async function catalog({ q = '' } = {}) {
|
|
103
|
+
const { plugins = [] } = await pub(`?q=${encodeURIComponent(q)}`);
|
|
104
|
+
const here = new Map(listPlugins().map((p) => [p.id, p]));
|
|
105
|
+
return plugins.map((v) => ({ ...v, installed: here.has(v.id), update: here.get(v.id)?.source === 'catalog' && here.get(v.id)?.sha !== v.sha }));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Downloads an approved plugin into ~/.7ots/plugins/<id> (what was reviewed: checked by its sha256). */
|
|
109
|
+
export async function installFromCatalog(id) {
|
|
110
|
+
if (!PLUGIN_ID.test(String(id))) throw new Error('id');
|
|
111
|
+
const b = await pub(`/${id}/bundle`);
|
|
112
|
+
const bundle = normalizeBundle(b, { catalog: true });
|
|
113
|
+
if (b.sha && bundleSha(bundle) !== b.sha) throw new Error('bundle changed on the way (sha256)');
|
|
114
|
+
const dir = homeFile(join('plugins', id));
|
|
115
|
+
rmSync(dir, { recursive: true, force: true });
|
|
116
|
+
for (const [p, data] of Object.entries(bundle.files)) {
|
|
117
|
+
const f = join(dir, ...p.split('/'));
|
|
118
|
+
mkdirSync(dirname(f), { recursive: true });
|
|
119
|
+
writeFileSync(f, Buffer.from(data, 'base64'));
|
|
120
|
+
}
|
|
121
|
+
writeFileSync(join(dir, MANIFEST), JSON.stringify(bundle.manifest, null, 2) + '\n');
|
|
122
|
+
const s = state();
|
|
123
|
+
s[id] = { on: true, source: 'catalog', sha: bundleSha(bundle), at: Date.now() };
|
|
124
|
+
save(s);
|
|
125
|
+
if (signedIn()) api(`/plugins/${id}/install`, { method: 'POST', body: {} }).catch(() => {}); // counts it once per account
|
|
126
|
+
return getPlugin(id);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function removePlugin(id) {
|
|
130
|
+
const s = state();
|
|
131
|
+
if (!s[id]) return false;
|
|
132
|
+
if (s[id].source === 'catalog') rmSync(homeFile(join('plugins', id)), { recursive: true, force: true });
|
|
133
|
+
delete s[id];
|
|
134
|
+
save(s);
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function setPluginOn(id, on) {
|
|
139
|
+
const s = state();
|
|
140
|
+
if (!s[id]) return false;
|
|
141
|
+
s[id].on = !!on;
|
|
142
|
+
save(s);
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Sends a plugin folder to 7ots.com for review (signed in): it is public once an admin approves it. */
|
|
147
|
+
export async function publishPlugin(dir) {
|
|
148
|
+
if (!signedIn()) throw Object.assign(new Error('sign in to 7ots.com first (7ots login)'), { status: 401 });
|
|
149
|
+
const bundle = bundleOf(dir, { catalog: true });
|
|
150
|
+
return api('/plugins', { method: 'POST', body: bundle });
|
|
151
|
+
}
|
|
152
|
+
export const myPlugins = () => api('/plugins/mine');
|
|
153
|
+
|
|
154
|
+
// ── for the brain ──
|
|
155
|
+
|
|
156
|
+
/** Plugins with an MCP server, as custom integrations (integrations.mjs). */
|
|
157
|
+
export function pluginIntegrations() {
|
|
158
|
+
return activePlugins()
|
|
159
|
+
.filter((p) => p.manifest.mcp)
|
|
160
|
+
.map((p) => ({
|
|
161
|
+
id: `plugin-${p.id}`,
|
|
162
|
+
kind: 'mcp',
|
|
163
|
+
name: p.manifest.name,
|
|
164
|
+
instructions: p.manifest.instructions || p.manifest.description,
|
|
165
|
+
...(p.manifest.mcp.url ? { url: p.manifest.mcp.url } : { command: `cd ${JSON.stringify(p.dir)} && ${p.manifest.mcp.command}` }),
|
|
166
|
+
...(p.manifest.env?.[0] ? { envVar: p.manifest.env[0] } : {}),
|
|
167
|
+
on: true,
|
|
168
|
+
}));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Action docs for the assistant: open a plugin's panel. */
|
|
172
|
+
export function pluginsPrompt() {
|
|
173
|
+
const ps = activePlugins().filter((p) => p.manifest.panel);
|
|
174
|
+
if (!ps.length) return '';
|
|
175
|
+
return ps.map((p) => `{"type":"plugin","id":"${p.id}"} (open the "${p.manifest.name}" panel beside you${p.manifest.instructions ? `: ${p.manifest.instructions}` : p.manifest.description ? ` — ${p.manifest.description}` : ''})`).join('\n');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ── a new plugin (`7ots plugin new`, settings → Plugins → Create) ──
|
|
179
|
+
|
|
180
|
+
export function scaffold(dir, { id, name } = {}) {
|
|
181
|
+
dir = resolve(dir);
|
|
182
|
+
id = String(id || dir.split(sep).pop()).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32);
|
|
183
|
+
if (!PLUGIN_ID.test(id)) throw new Error('id: 2-32 of a-z, 0-9 and -');
|
|
184
|
+
if (existsSync(join(dir, MANIFEST))) throw new Error(`${dir} already has a plugin`);
|
|
185
|
+
mkdirSync(dir, { recursive: true });
|
|
186
|
+
const nm = String(name || id.replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase())).slice(0, 40);
|
|
187
|
+
const files = {
|
|
188
|
+
[MANIFEST]: JSON.stringify({
|
|
189
|
+
id, name: nm, version: '0.1.0', icon: '🧩',
|
|
190
|
+
description: 'What it does, in one line.',
|
|
191
|
+
instructions: `When your human asks for ${nm}, open this panel.`,
|
|
192
|
+
panel: { file: 'panel.html', title: nm, width: 320, height: 220 },
|
|
193
|
+
net: [],
|
|
194
|
+
}, null, 2) + '\n',
|
|
195
|
+
'panel.html': `<!doctype html>\n<html>\n<head>\n<meta charset="utf-8">\n<title>${nm}</title>\n<link rel="stylesheet" href="panel.css">\n</head>\n<body>\n <h1>${nm}</h1>\n <p id="out">Hello from your plugin 👋</p>\n <script src="panel.js"></script>\n</body>\n</html>\n`,
|
|
196
|
+
'panel.css': 'html, body { margin: 0; height: 100%; background: #0b0b12; color: #e8e8f0; font: 13px/1.4 system-ui, sans-serif; }\nbody { padding: 12px; }\nh1 { font-size: 15px; margin: 0 0 8px; }\n',
|
|
197
|
+
'panel.js': "// Runs in its own sandboxed window. fetch() only reaches the hosts in 7ots-plugin.json \"net\" (https).\ndocument.getElementById('out').textContent += ` · ${new Date().toLocaleTimeString()}`;\n",
|
|
198
|
+
'README.md': `# ${nm}\n\nA 7ots plugin. Try it: \`7ots plugin add .\` then \`7ots plugin open ${id}\`.\nPublish it for review: \`7ots plugin publish .\` (guide: https://7ots.com/docs/plugins).\n`,
|
|
199
|
+
};
|
|
200
|
+
for (const [f, body] of Object.entries(files)) writeFileSync(join(dir, f), body);
|
|
201
|
+
return { dir, id };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export { MAX_BYTES, MAX_FILES };
|
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
|
|
13
13
|
const path = require('node:path');
|
|
14
14
|
const { execFile } = require('node:child_process');
|
|
15
|
-
const { app, BrowserWindow, Menu, Tray, globalShortcut, nativeImage, screen, session, shell, systemPreferences } = require('electron');
|
|
15
|
+
const { app, BrowserWindow, Menu, Tray, globalShortcut, nativeImage, protocol, screen, session, shell, systemPreferences } = require('electron');
|
|
16
|
+
const { pathToFileURL } = require('node:url');
|
|
16
17
|
|
|
17
18
|
const URL_ = process.env.SEVENOTS_PET_URL;
|
|
18
19
|
const TOKEN = process.env.SEVENOTS_PET_TOKEN;
|
|
@@ -31,12 +32,33 @@ const MIN = { w: 288, h: 272 };
|
|
|
31
32
|
const linux = process.platform === 'linux';
|
|
32
33
|
|
|
33
34
|
const L = {
|
|
34
|
-
en: { settings: '⚙️ Settings', talk: '💬 Talk', listen: '🎙️ Listen (Ctrl+Alt+Space)', show: 'Show pet', hide: 'Hide (keeps living)', feed: '🍎 Treat', play: '🎾 Play', byte: '🎮 Play on byte', watch: '📺 Watch the game', stopGame: '⏹ Stop the game', lastGame: 'Last played', moreGames: 'More games', noGames: 'byte: no games (sign in to 7ots.com)', sleep: '💤 Sleep', wake: '☀️ Wake up', still: 'Stay still', quit: 'Quit pet' },
|
|
35
|
-
es: { settings: '⚙️ Configuración', talk: '💬 Hablar', listen: '🎙️ Escúchame (Ctrl+Alt+Espacio)', show: 'Mostrar mascota', hide: 'Ocultar (sigue viva)', feed: '🍎 Mimar', play: '🎾 Jugar', byte: '🎮 Jugar en byte', watch: '📺 Ver la partida', stopGame: '⏹ Parar la partida', lastGame: 'Último jugado', moreGames: 'Más juegos', noGames: 'byte: sin juegos (entra a 7ots.com)', sleep: '💤 Dormir', wake: '☀️ Despertar', still: 'Quedarse quieta', quit: 'Cerrar mascota' },
|
|
36
|
-
pt: { settings: '⚙️ Configurações', talk: '💬 Falar', listen: '🎙️ Me escute (Ctrl+Alt+Espaço)', show: 'Mostrar bichinho', hide: 'Esconder (segue vivo)', feed: '🍎 Mimar', play: '🎾 Brincar', byte: '🎮 Jogar no byte', watch: '📺 Ver a partida', stopGame: '⏹ Parar a partida', lastGame: 'Último jogado', moreGames: 'Mais jogos', noGames: 'byte: sem jogos (entre no 7ots.com)', sleep: '💤 Dormir', wake: '☀️ Acordar', still: 'Ficar parado', quit: 'Fechar bichinho' },
|
|
35
|
+
en: { settings: '⚙️ Settings', talk: '💬 Talk', listen: '🎙️ Listen (Ctrl+Alt+Space)', show: 'Show pet', hide: 'Hide (keeps living)', feed: '🍎 Treat', play: '🎾 Play', byte: '🎮 Play on byte', watch: '📺 Watch the game', stopGame: '⏹ Stop the game', lastGame: 'Last played', moreGames: 'More games', noGames: 'byte: no games (sign in to 7ots.com)', sleep: '💤 Sleep', wake: '☀️ Wake up', still: 'Stay still', quit: 'Quit pet', muteStream: '🔇 Mute stream', unmuteStream: '🔊 Unmute stream', plugins: '🧩 Plugins', noPlugins: 'No plugins yet', morePlugins: 'Get or create plugins…' },
|
|
36
|
+
es: { settings: '⚙️ Configuración', talk: '💬 Hablar', listen: '🎙️ Escúchame (Ctrl+Alt+Espacio)', show: 'Mostrar mascota', hide: 'Ocultar (sigue viva)', feed: '🍎 Mimar', play: '🎾 Jugar', byte: '🎮 Jugar en byte', watch: '📺 Ver la partida', stopGame: '⏹ Parar la partida', lastGame: 'Último jugado', moreGames: 'Más juegos', noGames: 'byte: sin juegos (entra a 7ots.com)', sleep: '💤 Dormir', wake: '☀️ Despertar', still: 'Quedarse quieta', quit: 'Cerrar mascota', muteStream: '🔇 Silenciar stream', unmuteStream: '🔊 Activar sonido', plugins: '🧩 Plugins', noPlugins: 'Aún no hay plugins', morePlugins: 'Buscar o crear plugins…' },
|
|
37
|
+
pt: { settings: '⚙️ Configurações', talk: '💬 Falar', listen: '🎙️ Me escute (Ctrl+Alt+Espaço)', show: 'Mostrar bichinho', hide: 'Esconder (segue vivo)', feed: '🍎 Mimar', play: '🎾 Brincar', byte: '🎮 Jogar no byte', watch: '📺 Ver a partida', stopGame: '⏹ Parar a partida', lastGame: 'Último jogado', moreGames: 'Mais jogos', noGames: 'byte: sem jogos (entre no 7ots.com)', sleep: '💤 Dormir', wake: '☀️ Acordar', still: 'Ficar parado', quit: 'Fechar bichinho', muteStream: '🔇 Silenciar stream', unmuteStream: '🔊 Ativar som', plugins: '🧩 Plugins', noPlugins: 'Ainda sem plugins', morePlugins: 'Buscar ou criar plugins…' },
|
|
37
38
|
}[LANG] || {};
|
|
38
39
|
const tr = (k) => L[k] || { listen: 'Listen', show: 'Show pet', hide: 'Hide', talk: 'Talk', settings: 'Settings', feed: 'Feed', play: 'Play', sleep: 'Sleep', wake: 'Wake up', still: 'Stay still', quit: 'Quit pet' }[k];
|
|
39
40
|
|
|
41
|
+
// Plugins' panels (cli/lib/plugins.mjs): each one on its own origin, ots-plugin://<id>/<file>, served from its
|
|
42
|
+
// folder with a CSP that only lets it load its own files and reach the hosts its manifest lists (src/plugins.js).
|
|
43
|
+
protocol.registerSchemesAsPrivileged([{ scheme: 'ots-plugin', privileges: { standard: true, secure: true, supportFetchAPI: true } }]);
|
|
44
|
+
const pluginLibs = () => Promise.all([import(pathToFileURL(path.join(__dirname, '..', '..', 'lib', 'plugins.mjs')).href), import(pathToFileURL(path.join(__dirname, '..', '..', '..', 'src', 'plugins.js')).href)]);
|
|
45
|
+
let pluginProtocol = false;
|
|
46
|
+
function servePlugins() {
|
|
47
|
+
if (pluginProtocol) return;
|
|
48
|
+
pluginProtocol = true;
|
|
49
|
+
protocol.handle('ots-plugin', async (req) => {
|
|
50
|
+
try {
|
|
51
|
+
const u = new URL(req.url);
|
|
52
|
+
const [pl, fmt] = await pluginLibs();
|
|
53
|
+
const f = pl.pluginFile(u.hostname, decodeURIComponent(u.pathname.slice(1)) || 'index.html');
|
|
54
|
+
if (!f || !f.plugin.on) return new Response('not found', { status: 404 });
|
|
55
|
+
return new Response(f.body, { headers: { 'Content-Type': fmt.fileType(f.file), 'Content-Security-Policy': fmt.panelCsp(f.plugin.manifest), 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-cache' } });
|
|
56
|
+
} catch {
|
|
57
|
+
return new Response('error', { status: 500 });
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
40
62
|
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required'); // it talks without a click
|
|
41
63
|
if (linux && !OPAQUE) {
|
|
42
64
|
// Transparent windows on Linux: these avoid the black/grey box on most X11 setups.
|
|
@@ -172,13 +194,17 @@ async function syncSenses() {
|
|
|
172
194
|
|
|
173
195
|
// Settings in a window of our own (not a browser tab); links elsewhere open in the browser.
|
|
174
196
|
const settingsWins = new Map(); // one per ot that has its own daemon
|
|
175
|
-
function openSettings(base = URL_, tok = TOKEN) {
|
|
197
|
+
function openSettings(base = URL_, tok = TOKEN, section = '') {
|
|
198
|
+
section = /^[a-z]{2,20}$/.test(section) ? section : '';
|
|
176
199
|
let settingsWin = settingsWins.get(base);
|
|
177
|
-
if (settingsWin && !settingsWin.isDestroyed())
|
|
200
|
+
if (settingsWin && !settingsWin.isDestroyed()) {
|
|
201
|
+
if (section) settingsWin.webContents.executeJavaScript(`location.hash = ${JSON.stringify(section)}`).catch(() => {});
|
|
202
|
+
return settingsWin.show(), settingsWin.focus();
|
|
203
|
+
}
|
|
178
204
|
settingsWin = new BrowserWindow({ width: 1120, height: 820, minWidth: 420, minHeight: 480, title: '7ots', icon: ICON, autoHideMenuBar: true, backgroundColor: '#0f0d14', show: false });
|
|
179
205
|
settingsWin.removeMenu?.();
|
|
180
206
|
settingsWins.set(base, settingsWin);
|
|
181
|
-
settingsWin.loadURL(`${base}/settings?token=${encodeURIComponent(tok)}`);
|
|
207
|
+
settingsWin.loadURL(`${base}/settings?token=${encodeURIComponent(tok)}${section ? `#${section}` : ''}`);
|
|
182
208
|
settingsWin.once('ready-to-show', () => settingsWin.show());
|
|
183
209
|
const ours = (u) => String(u || '').startsWith(base);
|
|
184
210
|
settingsWin.webContents.setWindowOpenHandler(({ url }) => {
|
|
@@ -267,7 +293,14 @@ function makeOt(opt = {}) {
|
|
|
267
293
|
const ready = () => alive() && !win.webContents.isLoadingMainFrame();
|
|
268
294
|
const page = (js) => ready() && win.webContents.executeJavaScript(js).catch(() => {});
|
|
269
295
|
|
|
296
|
+
const sevenHome = process.env.SEVENOTS_HOME || path.join(require('node:os').homedir(), '.7ots');
|
|
270
297
|
let still = false;
|
|
298
|
+
if (HOST) {
|
|
299
|
+
try {
|
|
300
|
+
const cfg = JSON.parse(require('node:fs').readFileSync(path.join(sevenHome, 'config.json'), 'utf8'));
|
|
301
|
+
still = !!(cfg.pet && cfg.pet.still);
|
|
302
|
+
} catch {}
|
|
303
|
+
}
|
|
271
304
|
let lastBounds = null;
|
|
272
305
|
// How much of the window hangs off the screen it is on (a drag may leave it 40 px past the floor or the
|
|
273
306
|
// right edge, or over the taskbar): the page lifts the hover menu by that much, and moves it to the ot's
|
|
@@ -313,17 +346,37 @@ function makeOt(opt = {}) {
|
|
|
313
346
|
{ label: tr('sleep'), click: () => postOt('/event', { type: 'sleep' }) },
|
|
314
347
|
{ label: tr('wake'), click: () => postOt('/event', { type: 'wake' }) },
|
|
315
348
|
{ label: tr('byte'), click: () => gameMenu().then((m) => m.popup({ window: win })) },
|
|
349
|
+
{ label: tr('plugins'), click: () => pluginMenu().then((m) => m.popup({ window: win })) },
|
|
316
350
|
{ type: 'separator' },
|
|
317
351
|
{ label: tr('settings'), click: () => openSettings(base, tok) },
|
|
318
|
-
{ label: tr('still'), type: 'checkbox', checked: still, click: (i) =>
|
|
352
|
+
{ label: tr('still'), type: 'checkbox', checked: still, click: (i) => {
|
|
353
|
+
still = i.checked;
|
|
354
|
+
if (HOST) {
|
|
355
|
+
try {
|
|
356
|
+
const cfgPath = path.join(sevenHome, 'config.json');
|
|
357
|
+
let cfg = {};
|
|
358
|
+
try { cfg = JSON.parse(require('node:fs').readFileSync(cfgPath, 'utf8')); } catch {}
|
|
359
|
+
cfg.pet = cfg.pet || {};
|
|
360
|
+
cfg.pet.still = still;
|
|
361
|
+
require('node:fs').writeFileSync(cfgPath, JSON.stringify(cfg, null, 2));
|
|
362
|
+
} catch {}
|
|
363
|
+
}
|
|
364
|
+
}},
|
|
319
365
|
HOST ? { label: tr('quit'), click: () => post('/quit').finally(() => app.quit()) } : { label: { es: '👋 Despedir', pt: '👋 Mandar embora' }[LANG] || '👋 Send home', click: dismiss },
|
|
320
366
|
]);
|
|
321
367
|
// ── byte arena: the ot plays a game live (7ots.com runs its moves) and a small window shows it, beside it ──
|
|
322
368
|
let gameWin = null;
|
|
369
|
+
let muted = false; // stream audio mute state; persists across game sessions
|
|
323
370
|
const watchGame = (url) => {
|
|
324
371
|
if (!/^https:\/\/[^/]+\/stream\/s_[a-z0-9]+$/i.test(String(url || ''))) return;
|
|
325
372
|
url += '?bare=1'; // byte's game-only view: no header, crew grid or avatar (the ot is already on the desktop)
|
|
326
|
-
if (gameWin && !gameWin.isDestroyed())
|
|
373
|
+
if (gameWin && !gameWin.isDestroyed()) {
|
|
374
|
+
gameWin.loadURL(url);
|
|
375
|
+
gameWin.webContents.setAudioMuted(muted);
|
|
376
|
+
gameWin.showInactive();
|
|
377
|
+
win.moveTop();
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
327
380
|
const w = 480;
|
|
328
381
|
const h = 300;
|
|
329
382
|
const [wx, wy] = win.getPosition();
|
|
@@ -333,13 +386,15 @@ function makeOt(opt = {}) {
|
|
|
333
386
|
gameWin = new BrowserWindow({ x, y, width: w, height: h, minWidth: 320, minHeight: 200, alwaysOnTop: true, title: 'byte arena', icon: ICON, autoHideMenuBar: true, backgroundColor: '#0b0b12', show: false, webPreferences: { contextIsolation: true, sandbox: true } });
|
|
334
387
|
gameWin.removeMenu?.();
|
|
335
388
|
gameWin.setAlwaysOnTop(true, 'floating');
|
|
336
|
-
gameWin.webContents.setAudioMuted(
|
|
389
|
+
gameWin.webContents.setAudioMuted(muted);
|
|
337
390
|
// the page stays on byte's stream; any other link goes to the browser
|
|
338
391
|
const origin = new URL(url).origin;
|
|
339
392
|
gameWin.webContents.setWindowOpenHandler(({ url: u }) => (shell.openExternal(u).catch(() => {}), { action: 'deny' }));
|
|
340
393
|
gameWin.webContents.on('will-navigate', (e, u) => String(u).startsWith(`${origin}/stream/`) || (e.preventDefault(), shell.openExternal(u).catch(() => {})));
|
|
341
394
|
gameWin.loadURL(url);
|
|
342
|
-
|
|
395
|
+
// show immediately so the user sees the browser loading state while the stream connects (MJ-02)
|
|
396
|
+
gameWin.showInactive();
|
|
397
|
+
win.moveTop();
|
|
343
398
|
gameWin.on('closed', () => (gameWin = null));
|
|
344
399
|
};
|
|
345
400
|
// what it saw when you asked it to look at you ("¿cómo me ves?"): a small window beside it, like the game's.
|
|
@@ -365,6 +420,44 @@ function makeOt(opt = {}) {
|
|
|
365
420
|
photoWin.once('ready-to-show', () => photoWin.showInactive());
|
|
366
421
|
photoWin.on('closed', () => (photoWin = null));
|
|
367
422
|
};
|
|
423
|
+
// ── plugins: a panel in a small window beside it, like the game's; sandboxed, on its own origin ──
|
|
424
|
+
const pluginWins = new Map(); // id → BrowserWindow
|
|
425
|
+
const openPlugin = async (id) => {
|
|
426
|
+
if (!/^[a-z0-9][a-z0-9-]{1,31}$/.test(id)) return;
|
|
427
|
+
const old = pluginWins.get(id);
|
|
428
|
+
if (old && !old.isDestroyed()) return old.showInactive(), win.moveTop();
|
|
429
|
+
const [pl] = await pluginLibs();
|
|
430
|
+
const p = pl.getPlugin(id);
|
|
431
|
+
if (!p?.on || !p.manifest.panel) return;
|
|
432
|
+
servePlugins();
|
|
433
|
+
const { width: w, height: h, title, file } = p.manifest.panel;
|
|
434
|
+
const [wx, wy] = win.getPosition();
|
|
435
|
+
const a = curArea();
|
|
436
|
+
const n = [...pluginWins.values()].filter((x) => !x.isDestroyed()).length;
|
|
437
|
+
const x = Math.max(a.x, Math.min(a.x + a.width - w, wx + size.w / 2 + 40 + n * 24));
|
|
438
|
+
const y = Math.max(a.y, Math.min(a.y + a.height - h, wy + size.h - h - n * 24));
|
|
439
|
+
const pw = new BrowserWindow({ x, y, width: w, height: h, minWidth: 160, minHeight: 100, alwaysOnTop: true, title: `${p.manifest.icon} ${title}`, icon: ICON, autoHideMenuBar: true, backgroundColor: '#0b0b12', show: false, webPreferences: { contextIsolation: true, sandbox: true, nodeIntegration: false, webviewTag: false, spellcheck: false } });
|
|
440
|
+
pw.removeMenu?.();
|
|
441
|
+
pw.setAlwaysOnTop(true, 'floating');
|
|
442
|
+
const origin = `ots-plugin://${id}`;
|
|
443
|
+
// the panel stays on its own files; an https link opens in the browser, anything else goes nowhere
|
|
444
|
+
pw.webContents.setWindowOpenHandler(({ url: u }) => (/^https:\/\//.test(u) && shell.openExternal(u).catch(() => {}), { action: 'deny' }));
|
|
445
|
+
pw.webContents.on('will-navigate', (e, u) => String(u).startsWith(`${origin}/`) || (e.preventDefault(), /^https:\/\//.test(u) && shell.openExternal(u).catch(() => {})));
|
|
446
|
+
pw.webContents.on('will-attach-webview', (e) => e.preventDefault());
|
|
447
|
+
pw.once('ready-to-show', () => (pw.showInactive(), win.moveTop()));
|
|
448
|
+
pw.on('closed', () => pluginWins.delete(id));
|
|
449
|
+
pluginWins.set(id, pw);
|
|
450
|
+
pw.loadURL(`${origin}/${file}`);
|
|
451
|
+
};
|
|
452
|
+
const pluginMenu = async () => {
|
|
453
|
+
const [pl] = await pluginLibs().catch(() => [null]);
|
|
454
|
+
const ps = (pl?.activePlugins() || []).filter((p) => p.manifest.panel);
|
|
455
|
+
return Menu.buildFromTemplate([
|
|
456
|
+
...(ps.length ? ps.map((p) => ({ label: `${p.manifest.icon} ${p.manifest.name}${p.source === 'local' ? ' · dev' : ''}`, click: () => openPlugin(p.id) })) : [{ label: tr('noPlugins'), enabled: false }]),
|
|
457
|
+
{ type: 'separator' },
|
|
458
|
+
{ label: tr('morePlugins'), click: () => openSettings(base, tok, 'plugins') },
|
|
459
|
+
]);
|
|
460
|
+
};
|
|
368
461
|
const playGame = async (game) => {
|
|
369
462
|
try {
|
|
370
463
|
require('node:fs').writeFileSync(path.join(process.env.SEVENOTS_HOME || path.join(require('node:os').homedir(), '.7ots'), 'byte-last.json'), JSON.stringify({ slug: game, at: Date.now() }));
|
|
@@ -435,6 +528,10 @@ function makeOt(opt = {}) {
|
|
|
435
528
|
return Menu.buildFromTemplate([
|
|
436
529
|
{ label: `${st.play.game} · ${st.play.moves}`, enabled: false },
|
|
437
530
|
{ label: tr('watch'), click: () => watchGame(st.play.streamUrl) },
|
|
531
|
+
{ label: muted ? tr('unmuteStream') : tr('muteStream'), type: 'checkbox', checked: muted, click: (item) => {
|
|
532
|
+
muted = item.checked;
|
|
533
|
+
if (gameWin && !gameWin.isDestroyed()) gameWin.webContents.setAudioMuted(muted);
|
|
534
|
+
}},
|
|
438
535
|
{ label: tr('stopGame'), click: () => postOt('/byte/stop').then(() => gameWin && !gameWin.isDestroyed() && gameWin.close()) },
|
|
439
536
|
]);
|
|
440
537
|
}
|
|
@@ -660,6 +757,14 @@ function makeOt(opt = {}) {
|
|
|
660
757
|
return;
|
|
661
758
|
}
|
|
662
759
|
}
|
|
760
|
+
if (m.startsWith('\u00a77plugin')) {
|
|
761
|
+
try {
|
|
762
|
+
const d = JSON.parse(m.slice(8));
|
|
763
|
+
return FULL && d.open && openPlugin(String(d.open));
|
|
764
|
+
} catch {
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
663
768
|
if (m.startsWith('\u00a77view')) return setView(m.slice(6) === '3d');
|
|
664
769
|
if (m.startsWith('\u00a77enter')) return enter();
|
|
665
770
|
if (!m.startsWith('\u00a77need')) return;
|
package/cli/pet/pet.html
CHANGED
|
@@ -258,7 +258,7 @@
|
|
|
258
258
|
<script type="module">
|
|
259
259
|
const BOOT = __BOOT__;
|
|
260
260
|
const T = {
|
|
261
|
-
en: { wakeOn: 'Say “hey {name}” and I listen', game: 'Play byte', dance: 'Dance', aura: 'Farm aura', settings: 'Settings', card: 'Card', dismiss: 'Send home', listen: 'Listen', listening: 'Listening… 🎙️', noStt:
|
|
261
|
+
en: { wakeOn: 'Say “hey {name}” and I listen', game: 'Play byte', dance: 'Dance', aura: 'Farm aura', settings: 'Settings', card: 'Card', dismiss: 'Send home', listen: 'Listen', listening: 'Listening… 🎙️', noStt: 'Voice control needs an OpenAI or ElevenLabs key (Settings).', noMic: 'I can’t reach the microphone. Allow microphone access in system settings.', sttErr: 'I didn’t catch that.', talk: 'Talk', askPh: 'Remind me to check email in 10 min…', feed: 'Treat', play: 'Play', sleep: 'Sleep', wake: 'Wake', food: 'Food', energy: 'Energy', fun: 'Fun', level: 'Level {l}', xp: '{x} / {n} xp', live: 'Live', off: 'Reconnecting…', approve: 'Approve', reject: 'Reject',
|
|
262
262
|
activity: 'Activity', empty: 'Nothing yet. Run a command or ask your coding agent something.', tally: '{ok} ok · {fail} failed · turns {turns}',
|
|
263
263
|
brain: 'Brain: {b}', age: 'Born {d}', lines: 'built-in phrases', now: 'now', m: '{n}m', h: '{n}h',
|
|
264
264
|
moods: { happy: 'Happy', neutral: 'Calm', sad: 'Sad', disgust: 'Bored', sleep: 'Asleep', thinking: 'Thinking' },
|
|
@@ -791,6 +791,7 @@
|
|
|
791
791
|
if (m.backdrop !== undefined) return location.reload(); // its style's background on/off (settings)
|
|
792
792
|
if (m.view && setView(m.view === '3d')) return; // 2D ↔ 3D changed in the settings
|
|
793
793
|
if (guest) return; // the host's events are the host's
|
|
794
|
+
if (m.plugin && desktop) console.debug('\u00a77plugin' + JSON.stringify(m.plugin)); // the shell opens its panel beside the ot
|
|
794
795
|
if (m.stir || (m.say && asleep && Date.now() < stirUntil)) stir(); // awake until it has said it
|
|
795
796
|
if (m.state) render(m.state);
|
|
796
797
|
if (m.ask) ask4(m.ask); // before thinking: an approved ask hands the bubble back to the dots
|
package/cli/pet/settings.html
CHANGED
|
@@ -172,6 +172,7 @@
|
|
|
172
172
|
.ot .stars button { margin: 0; padding: 0 2px; border: 0; background: none; font-size: 18px; line-height: 1; color: var(--line); cursor: pointer; box-shadow: none; }
|
|
173
173
|
.ot .stars button.on { color: var(--warn); }
|
|
174
174
|
.ot .acts { display: flex; gap: 6px; margin: auto 12px 0; } .ot .acts button { margin: 0; flex: 1; }
|
|
175
|
+
.otgrid.plugGrid { grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); } .plugGrid .stage { height: 84px; } .plugGrid .acts { flex-wrap: wrap; margin-bottom: 12px; } .plugGrid .acts button { white-space: nowrap; } .plugGrid .acts .chip { flex: 0 0 auto; }
|
|
175
176
|
.ot .acts button.icon { flex: 0 0 auto; padding: 6px 8px; }
|
|
176
177
|
.ot .rep { display: flex; gap: 6px; padding: 6px 12px 0; } .ot .rep input { flex: 1; min-width: 0; } .ot .rep button { margin: 0; }
|
|
177
178
|
.ot .st { position: absolute; top: 8px; right: 8px; padding: 2px 8px; border-radius: 999px; font-size: 11px; font-weight: 650; background: var(--panel-2); border: 1px solid var(--line); }
|
|
@@ -359,6 +360,21 @@
|
|
|
359
360
|
<div id="integ"></div>
|
|
360
361
|
</section>
|
|
361
362
|
|
|
363
|
+
<section aria-labelledby="hPlugins">
|
|
364
|
+
<h2 id="hPlugins" data-t="plugH"></h2>
|
|
365
|
+
<p class="hint" data-t="plugHint"></p>
|
|
366
|
+
<span class="msg" id="plugMsg" role="status"></span>
|
|
367
|
+
<div id="plugMine"></div>
|
|
368
|
+
<h3 class="sh" data-t="plugCat"></h3>
|
|
369
|
+
<div class="row"><input id="plugQ" type="search" style="flex:1;min-width:140px"></div>
|
|
370
|
+
<div id="plugCat"></div>
|
|
371
|
+
<h3 class="sh" data-t="plugMake"></h3>
|
|
372
|
+
<p class="hint" data-t="plugMakeHint"></p>
|
|
373
|
+
<div class="row"><input id="plugNewId" type="text" maxlength="32" style="flex:1;min-width:140px"><button id="plugNew" class="primary"></button></div>
|
|
374
|
+
<div class="row"><input id="plugDir" type="text" style="flex:1;min-width:140px"><button id="plugAdd"></button></div>
|
|
375
|
+
<p class="hint"><a href="https://7ots.com/docs/plugins" target="_blank" rel="noopener" data-t="plugGuide"></a></p>
|
|
376
|
+
</section>
|
|
377
|
+
|
|
362
378
|
<section aria-labelledby="hSenses">
|
|
363
379
|
<h2 id="hSenses" data-t="sensesH"></h2>
|
|
364
380
|
<p class="hint" data-t="sensesHint"></p>
|
|
@@ -740,7 +756,34 @@
|
|
|
740
756
|
sForget: 'Esquecer tudo o que notou', sForgetSure: 'Certeza? Clique de novo', sForgot: 'Esquecido: dias, rosto neutro e histórico de regras.',
|
|
741
757
|
},
|
|
742
758
|
};
|
|
743
|
-
|
|
759
|
+
// Plugins (cli/lib/plugins.mjs): windows beside the ot and tools for its brain.
|
|
760
|
+
const T4 = {
|
|
761
|
+
en: {
|
|
762
|
+
plugH: 'Plugins', plugHint: 'Small apps for {name}: a window beside it (like the BTC price) and tools for its brain. The catalog only has what 7ots reviewed; yours (dev) run from your folder.',
|
|
763
|
+
plugCat: 'Catalog (7ots.com)', plugSearch: 'Search plugins…', plugEmpty: 'Nothing here yet.', plugNone: 'No plugins yet: install one from the catalog below.',
|
|
764
|
+
plugInstall: 'Install', plugUpdate: 'Update', plugInstalled: 'Installed', plugOpen: 'Open', plugRemove: 'Remove', plugPublish: 'Send to review', plugSent: 'Sent: it shows in the catalog once approved ({st}).',
|
|
765
|
+
plugDev: 'dev · your folder', plugOfficial: 'by 7ots', plugNeedLogin: 'Sign in to 7ots.com (Account) to send it for review.', plugNoPet: 'Windows open in the desktop app.',
|
|
766
|
+
plugMake: 'Make your own', plugMakeHint: 'Creates a folder with a working plugin you can edit, loads it on {name} and tells you where it is.', plugNewPh: 'my-plugin', plugNewBtn: 'Create plugin', plugCreated: 'Created in {dir}',
|
|
767
|
+
plugDirPh: '/path/to/a/plugin folder', plugAddBtn: 'Load from a folder', plugGuide: 'Guide for plugin makers →', plugTalks: 'talks to {h}', plugOn: 'On',
|
|
768
|
+
},
|
|
769
|
+
es: {
|
|
770
|
+
plugH: 'Plugins', plugHint: 'Apps pequeñas para {name}: una ventana a su lado (como el precio de BTC) y herramientas para su cerebro. El catálogo solo tiene lo que revisó 7ots; los tuyos (dev) corren desde tu carpeta.',
|
|
771
|
+
plugCat: 'Catálogo (7ots.com)', plugSearch: 'Buscar plugins…', plugEmpty: 'Todavía no hay nada.', plugNone: 'Sin plugins: instala uno del catálogo de abajo.',
|
|
772
|
+
plugInstall: 'Instalar', plugUpdate: 'Actualizar', plugInstalled: 'Instalado', plugOpen: 'Abrir', plugRemove: 'Quitar', plugPublish: 'Enviar a revisión', plugSent: 'Enviado: aparece en el catálogo cuando lo aprueben ({st}).',
|
|
773
|
+
plugDev: 'dev · tu carpeta', plugOfficial: 'de 7ots', plugNeedLogin: 'Conecta tu cuenta de 7ots.com (Cuenta) para enviarlo a revisión.', plugNoPet: 'Las ventanas se abren en la app de escritorio.',
|
|
774
|
+
plugMake: 'Haz el tuyo', plugMakeHint: 'Crea una carpeta con un plugin que funciona y puedes editar, lo carga en {name} y te dice dónde quedó.', plugNewPh: 'mi-plugin', plugNewBtn: 'Crear plugin', plugCreated: 'Creado en {dir}',
|
|
775
|
+
plugDirPh: '/ruta/a/la carpeta del plugin', plugAddBtn: 'Cargar desde carpeta', plugGuide: 'Guía para crear plugins →', plugTalks: 'se conecta a {h}', plugOn: 'Activo',
|
|
776
|
+
},
|
|
777
|
+
pt: {
|
|
778
|
+
plugH: 'Plugins', plugHint: 'Apps pequenos para {name}: uma janela ao lado dele (como o preço do BTC) e ferramentas para o cérebro. O catálogo só tem o que a 7ots revisou; os seus (dev) rodam da sua pasta.',
|
|
779
|
+
plugCat: 'Catálogo (7ots.com)', plugSearch: 'Buscar plugins…', plugEmpty: 'Ainda não há nada.', plugNone: 'Sem plugins: instale um do catálogo abaixo.',
|
|
780
|
+
plugInstall: 'Instalar', plugUpdate: 'Atualizar', plugInstalled: 'Instalado', plugOpen: 'Abrir', plugRemove: 'Remover', plugPublish: 'Enviar para revisão', plugSent: 'Enviado: aparece no catálogo quando for aprovado ({st}).',
|
|
781
|
+
plugDev: 'dev · sua pasta', plugOfficial: 'da 7ots', plugNeedLogin: 'Conecte sua conta da 7ots.com (Conta) para enviar para revisão.', plugNoPet: 'As janelas abrem no app de desktop.',
|
|
782
|
+
plugMake: 'Faça o seu', plugMakeHint: 'Cria uma pasta com um plugin que funciona e você pode editar, carrega em {name} e diz onde ficou.', plugNewPh: 'meu-plugin', plugNewBtn: 'Criar plugin', plugCreated: 'Criado em {dir}',
|
|
783
|
+
plugDirPh: '/caminho/da pasta do plugin', plugAddBtn: 'Carregar de uma pasta', plugGuide: 'Guia para criar plugins →', plugTalks: 'conecta com {h}', plugOn: 'Ativo',
|
|
784
|
+
},
|
|
785
|
+
};
|
|
786
|
+
for (const k of Object.keys(T2)) Object.assign(T[k], T2[k], T3[k], T4[k]);
|
|
744
787
|
// The system's language (LANG, or the one picked below) first, then the browser's, then the ot's.
|
|
745
788
|
const nav = (navigator.language || '').slice(0, 2);
|
|
746
789
|
const lang = T[BOOT.uiLang] ? BOOT.uiLang : T[nav] ? nav : T[BOOT.lang] ? BOOT.lang : 'en';
|
|
@@ -899,9 +942,9 @@
|
|
|
899
942
|
|
|
900
943
|
// ── navigation: one section at a time, remembered in the URL hash ──
|
|
901
944
|
const NAV = {
|
|
902
|
-
en: { home: 'Home', gMind: 'Mind', gPriv: 'Privacy', gConn: 'Connections', gLogs: 'Logs', acc: 'Account', brain: 'Brain', voice: 'Voice', access: 'Permissions', senses: 'Senses', integ: 'Integrations', wal: 'Wallet', plaza: 'Plaza', pet: 'Personality', com: 'Community', notes: 'Memory', rem: 'Processes', inf: 'Activity' },
|
|
903
|
-
es: { home: 'Su casa', gMind: 'Mente', gPriv: 'Privacidad', gConn: 'Conexiones', gLogs: 'Registros', acc: 'Cuenta', brain: 'Cerebro', voice: 'Voz', access: 'Permisos', senses: 'Sentidos', integ: 'Integraciones', wal: 'Billetera', plaza: 'Plaza', pet: 'Personalidad', com: 'Comunidad', notes: 'Memoria', rem: 'Procesos', inf: 'Actividad' },
|
|
904
|
-
pt: { home: 'Casa', gMind: 'Mente', gPriv: 'Privacidade', gConn: 'Conexões', gLogs: 'Registros', acc: 'Conta', brain: 'Cérebro', voice: 'Voz', access: 'Permissões', senses: 'Sentidos', integ: 'Integrações', wal: 'Carteira', plaza: 'Praça', pet: 'Personalidade', com: 'Comunidade', notes: 'Memória', rem: 'Processos', inf: 'Atividade' },
|
|
945
|
+
en: { home: 'Home', gMind: 'Mind', gPriv: 'Privacy', gConn: 'Connections', gLogs: 'Logs', acc: 'Account', brain: 'Brain', voice: 'Voice', access: 'Permissions', senses: 'Senses', integ: 'Integrations', plugins: 'Plugins', wal: 'Wallet', plaza: 'Plaza', pet: 'Personality', com: 'Community', notes: 'Memory', rem: 'Processes', inf: 'Activity' },
|
|
946
|
+
es: { home: 'Su casa', gMind: 'Mente', gPriv: 'Privacidad', gConn: 'Conexiones', gLogs: 'Registros', acc: 'Cuenta', brain: 'Cerebro', voice: 'Voz', access: 'Permisos', senses: 'Sentidos', integ: 'Integraciones', plugins: 'Plugins', wal: 'Billetera', plaza: 'Plaza', pet: 'Personalidad', com: 'Comunidad', notes: 'Memoria', rem: 'Procesos', inf: 'Actividad' },
|
|
947
|
+
pt: { home: 'Casa', gMind: 'Mente', gPriv: 'Privacidade', gConn: 'Conexões', gLogs: 'Registros', acc: 'Conta', brain: 'Cérebro', voice: 'Voz', access: 'Permissões', senses: 'Sentidos', integ: 'Integrações', plugins: 'Plugins', wal: 'Carteira', plaza: 'Praça', pet: 'Personalidade', com: 'Comunidade', notes: 'Memória', rem: 'Processos', inf: 'Atividade' },
|
|
905
948
|
};
|
|
906
949
|
// moods and inference purposes arrive as English codes from the daemon
|
|
907
950
|
const WORDS = {
|
|
@@ -946,11 +989,11 @@
|
|
|
946
989
|
s.classList.add('ico', `logo-${name}`);
|
|
947
990
|
return s;
|
|
948
991
|
};
|
|
949
|
-
const ICON = { home: 'house', acc: 'user-round', brain: 'cpu', voice: 'mic', access: 'shield-check', senses: 'eye', integ: 'plug', wal: 'wallet', plaza: 'share-2', pet: 'message-circle', com: 'users', notes: 'notebook-pen', rem: 'activity', inf: 'scroll-text' };
|
|
950
|
-
const SECS = { home: 'hHome', acc: 'hAcc', brain: 'hBrain', voice: 'hVoice', access: 'hAccess', senses: 'hSenses', integ: 'hInteg', wal: 'hWal', plaza: 'hPlaza', pet: 'hPet', com: 'hCom', notes: 'hNotes', rem: 'hRem', inf: 'hInf' };
|
|
992
|
+
const ICON = { plugins: 'box', home: 'house', acc: 'user-round', brain: 'cpu', voice: 'mic', access: 'shield-check', senses: 'eye', integ: 'plug', wal: 'wallet', plaza: 'share-2', pet: 'message-circle', com: 'users', notes: 'notebook-pen', rem: 'activity', inf: 'scroll-text' };
|
|
993
|
+
const SECS = { plugins: 'hPlugins', home: 'hHome', acc: 'hAcc', brain: 'hBrain', voice: 'hVoice', access: 'hAccess', senses: 'hSenses', integ: 'hInteg', wal: 'hWal', plaza: 'hPlaza', pet: 'hPet', com: 'hCom', notes: 'hNotes', rem: 'hRem', inf: 'hInf' };
|
|
951
994
|
const navT = NAV[lang] || NAV.en;
|
|
952
995
|
// a few pages on top, the rest in groups that fold (the group of the open page unfolds)
|
|
953
|
-
const GROUPS = [['home', 'acc'], ['gMind', 'brain', 'pet', 'voice', 'notes'], ['gPriv', 'access', 'senses'], ['gConn', 'integ', 'wal', 'plaza', 'com'], ['gLogs', 'rem', 'inf']];
|
|
996
|
+
const GROUPS = [['home', 'acc'], ['gMind', 'brain', 'pet', 'voice', 'notes'], ['gPriv', 'access', 'senses'], ['gConn', 'integ', 'plugins', 'wal', 'plaza', 'com'], ['gLogs', 'rem', 'inf']];
|
|
954
997
|
const navLink = (k) => el('a', { href: `#${k}` }, el('span', {}, ico(ICON[k])), el('b', { textContent: navT[k] }));
|
|
955
998
|
$('#nav').replaceChildren(...GROUPS.flatMap(([g, ...ks]) => (g.startsWith('g') ? [el('details', {}, el('summary', { textContent: navT[g] }), el('div', {}, ...ks.map(navLink)))] : [g, ...ks].map(navLink))));
|
|
956
999
|
function go() {
|
|
@@ -967,6 +1010,7 @@
|
|
|
967
1010
|
if (k === 'notes') loadMemory();
|
|
968
1011
|
if (k === 'senses') loadSenses();
|
|
969
1012
|
if (k === 'plaza') loadPlaza();
|
|
1013
|
+
if (k === 'plugins') setTimeout(renderPlugins);
|
|
970
1014
|
if (k === 'com') setTimeout(renderCommunity); // after the script ran (com is declared further down)
|
|
971
1015
|
window.scrollTo(0, 0);
|
|
972
1016
|
}
|
|
@@ -2113,6 +2157,120 @@
|
|
|
2113
2157
|
});
|
|
2114
2158
|
$('#annoy').addEventListener('change', (e) => save({ pet: { annoy: Number(e.target.value) } }, $('#petMsg')));
|
|
2115
2159
|
|
|
2160
|
+
// ── plugins (cli/lib/plugins.mjs via the daemon's /plugins/*) ──
|
|
2161
|
+
const plug = { q: '' };
|
|
2162
|
+
let plugSeq = 0;
|
|
2163
|
+
const plugName = () => S?.identity?.name || BOOT.identity?.name || 'your ot';
|
|
2164
|
+
async function renderPlugins() {
|
|
2165
|
+
const seq = ++plugSeq;
|
|
2166
|
+
const msg = $('#plugMsg');
|
|
2167
|
+
$('#plugQ').placeholder = t('plugSearch');
|
|
2168
|
+
$('#plugNewId').placeholder = t('plugNewPh');
|
|
2169
|
+
$('#plugNew').textContent = t('plugNewBtn');
|
|
2170
|
+
$('#plugDir').placeholder = t('plugDirPh');
|
|
2171
|
+
$('#plugAdd').textContent = t('plugAddBtn');
|
|
2172
|
+
for (const k of ['plugHint', 'plugMakeHint']) for (const n of document.querySelectorAll(`[data-t=${k}]`)) n.textContent = t(k, { name: plugName() });
|
|
2173
|
+
const fail = (e) => flash(msg, errText(e), 'err');
|
|
2174
|
+
const act = async (b, path, body, after) => {
|
|
2175
|
+
b.disabled = true;
|
|
2176
|
+
try {
|
|
2177
|
+
const r = await api(path, body);
|
|
2178
|
+
if (after) after(r);
|
|
2179
|
+
renderPlugins();
|
|
2180
|
+
} catch (e) {
|
|
2181
|
+
b.disabled = false;
|
|
2182
|
+
fail(e);
|
|
2183
|
+
}
|
|
2184
|
+
};
|
|
2185
|
+
const card = (m, extra) => el('div', { className: 'ot' },
|
|
2186
|
+
el('div', { className: 'stage' }, el('span', { className: 'init', textContent: m.icon || '🧩' })),
|
|
2187
|
+
el('b', { textContent: `${m.name} v${m.version}` }),
|
|
2188
|
+
el('small', { textContent: [m.description, m.net?.length ? t('plugTalks', { h: m.net.join(', ') }) : ''].filter(Boolean).join(' · ') }),
|
|
2189
|
+
...extra);
|
|
2190
|
+
let mine;
|
|
2191
|
+
try {
|
|
2192
|
+
mine = await api('/plugins');
|
|
2193
|
+
} catch (e) {
|
|
2194
|
+
return fail(e);
|
|
2195
|
+
}
|
|
2196
|
+
if (seq !== plugSeq) return;
|
|
2197
|
+
const here = mine.plugins.map((p) => {
|
|
2198
|
+
const acts = el('div', { className: 'acts' });
|
|
2199
|
+
if (p.manifest?.panel) {
|
|
2200
|
+
const o = el('button', { className: 'primary' }, ico('external-link', 15), ' ', t('plugOpen'));
|
|
2201
|
+
o.addEventListener('click', () => act(o, '/plugins/open', { id: p.id }));
|
|
2202
|
+
acts.append(o);
|
|
2203
|
+
}
|
|
2204
|
+
if (p.source === 'local') {
|
|
2205
|
+
const pb = el('button', { title: mine.signedIn ? '' : t('plugNeedLogin') }, ico('upload', 15), ' ', t('plugPublish'));
|
|
2206
|
+
pb.addEventListener('click', () => (mine.signedIn ? act(pb, '/plugins/publish', { id: p.id }, (r) => flash(msg, t('plugSent', { st: r.plugin?.status || '' }))) : flash(msg, t('plugNeedLogin'), 'err')));
|
|
2207
|
+
acts.append(pb);
|
|
2208
|
+
}
|
|
2209
|
+
const rm = el('button', { className: 'icon', title: t('plugRemove'), ariaLabel: t('plugRemove') }, ico('trash-2', 15));
|
|
2210
|
+
rm.addEventListener('click', () => act(rm, '/plugins/remove', { id: p.id }));
|
|
2211
|
+
acts.append(rm);
|
|
2212
|
+
const on = el('input', { type: 'checkbox', checked: p.on });
|
|
2213
|
+
on.addEventListener('change', () => api('/plugins/on', { id: p.id, on: on.checked }).catch(fail));
|
|
2214
|
+
const m = p.manifest || { name: p.id, version: '?', description: p.error };
|
|
2215
|
+
acts.prepend(el('label', { className: 'chip', title: t('plugOn') }, on, t('plugOn')));
|
|
2216
|
+
const c = card(m, [acts]);
|
|
2217
|
+
c.append(el('span', { className: 'st', textContent: p.source === 'local' ? t('plugDev') : t('plugInstalled') }));
|
|
2218
|
+
return c;
|
|
2219
|
+
});
|
|
2220
|
+
$('#plugMine').replaceChildren(here.length ? el('div', { className: 'otgrid plugGrid' }, ...here) : el('p', { className: 'empty', textContent: t('plugNone') }));
|
|
2221
|
+
let cat = [];
|
|
2222
|
+
try {
|
|
2223
|
+
cat = (await api('/plugins/catalog', { q: plug.q })).plugins;
|
|
2224
|
+
} catch (e) {
|
|
2225
|
+
$('#plugCat').replaceChildren(el('p', { className: 'empty', textContent: `${t('plugEmpty')} (${errText(e)})` }));
|
|
2226
|
+
}
|
|
2227
|
+
if (seq !== plugSeq) return;
|
|
2228
|
+
const cards = cat.map((v) => {
|
|
2229
|
+
const b = el('button', { className: v.installed && !v.update ? '' : 'primary', disabled: v.installed && !v.update }, ico('download', 15), ' ', v.update ? t('plugUpdate') : v.installed ? t('plugInstalled') : t('plugInstall'));
|
|
2230
|
+
b.addEventListener('click', () => act(b, '/plugins/install', { id: v.id }, (r) => r.plugin?.manifest?.panel && api('/plugins/open', { id: v.id }).catch(() => {})));
|
|
2231
|
+
const c = card(v.manifest, [el('small', { textContent: `${v.official ? t('plugOfficial') : v.author} · ${t('comInstalls', { n: v.installs })}` }), el('div', { className: 'acts' }, b)]);
|
|
2232
|
+
return c;
|
|
2233
|
+
});
|
|
2234
|
+
if (cat.length || !$('#plugCat').childElementCount) $('#plugCat').replaceChildren(cards.length ? el('div', { className: 'otgrid plugGrid' }, ...cards) : el('p', { className: 'empty', textContent: t('plugEmpty') }));
|
|
2235
|
+
}
|
|
2236
|
+
let plugQT;
|
|
2237
|
+
$('#plugQ').addEventListener('input', (e) => {
|
|
2238
|
+
clearTimeout(plugQT);
|
|
2239
|
+
plugQT = setTimeout(() => { plug.q = e.target.value.trim(); renderPlugins(); }, 300);
|
|
2240
|
+
});
|
|
2241
|
+
$('#plugNew').addEventListener('click', async (e) => {
|
|
2242
|
+
const b = e.currentTarget;
|
|
2243
|
+
const id = $('#plugNewId').value.trim().toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
2244
|
+
if (!id) return $('#plugNewId').focus();
|
|
2245
|
+
b.disabled = true;
|
|
2246
|
+
try {
|
|
2247
|
+
const r = await api('/plugins/new', { id });
|
|
2248
|
+
flash($('#plugMsg'), t('plugCreated', { dir: r.dir }));
|
|
2249
|
+
$('#plugMsg').className = 'msg ok';
|
|
2250
|
+
clearTimeout($('#plugMsg')._t); // keep the path on screen
|
|
2251
|
+
$('#plugNewId').value = '';
|
|
2252
|
+
renderPlugins();
|
|
2253
|
+
} catch (x) {
|
|
2254
|
+
flash($('#plugMsg'), errText(x), 'err');
|
|
2255
|
+
}
|
|
2256
|
+
b.disabled = false;
|
|
2257
|
+
});
|
|
2258
|
+
$('#plugAdd').addEventListener('click', async (e) => {
|
|
2259
|
+
const b = e.currentTarget;
|
|
2260
|
+
const dir = $('#plugDir').value.trim();
|
|
2261
|
+
if (!dir) return $('#plugDir').focus();
|
|
2262
|
+
b.disabled = true;
|
|
2263
|
+
try {
|
|
2264
|
+
await api('/plugins/add', { dir });
|
|
2265
|
+
$('#plugDir').value = '';
|
|
2266
|
+
flash($('#plugMsg'), t('saved'));
|
|
2267
|
+
renderPlugins();
|
|
2268
|
+
} catch (x) {
|
|
2269
|
+
flash($('#plugMsg'), errText(x), 'err');
|
|
2270
|
+
}
|
|
2271
|
+
b.disabled = false;
|
|
2272
|
+
});
|
|
2273
|
+
|
|
2116
2274
|
// ── integrations (their own section) ──
|
|
2117
2275
|
const toggle = (on, onChange, label) => {
|
|
2118
2276
|
const i = el('input', { type: 'checkbox', checked: !!on });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@7ots/cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.40",
|
|
4
4
|
"description": "7ots.com — your AI companion with a face of its own: a desktop pet that watches over your coding agent (Claude Code and shell hooks), a personal assistant (reminders, alerts, notes, opens sites, sees your screen if allowed) and a reproducible identity (face, personality, voice) for any agent — in apuchat meet calls, Orquesta projects or your own server.",
|
|
5
5
|
"homepage": "https://7ots.com",
|
|
6
6
|
"repository": {
|
|
@@ -40,7 +40,8 @@
|
|
|
40
40
|
"dev": "node --watch server/server.mjs",
|
|
41
41
|
"start": "node server/server.mjs",
|
|
42
42
|
"build": "node scripts/build.mjs",
|
|
43
|
-
"check": "node scripts/check.mjs"
|
|
43
|
+
"check": "node scripts/check.mjs",
|
|
44
|
+
"prepublishOnly": "node scripts/check.mjs"
|
|
44
45
|
},
|
|
45
46
|
"engines": {
|
|
46
47
|
"node": ">=20"
|
package/server/server.mjs
CHANGED
|
@@ -136,6 +136,10 @@ const server = createServer(async (req, res) => {
|
|
|
136
136
|
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=600' });
|
|
137
137
|
return res.end(llmsTxt(PLATFORM ? 'https://7ots.com' : originOf(req)));
|
|
138
138
|
}
|
|
139
|
+
if (url.pathname === '/docs/plugins' && (req.method === 'GET' || req.method === 'HEAD') && existsSync(join(ROOT, 'docs', 'PLUGINS.md'))) {
|
|
140
|
+
res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'public, max-age=600' });
|
|
141
|
+
return res.end(readFileSync(join(ROOT, 'docs', 'PLUGINS.md')));
|
|
142
|
+
}
|
|
139
143
|
if (publicIdentityRoute(req, res, url)) return; // tarjeta pública: cualquier origen puede leerla
|
|
140
144
|
if (await publicWidgetRoute(req, res, url)) return; // config pública y embed.js
|
|
141
145
|
if (url.pathname.startsWith(`${PREFIX}/admin/`)) {
|
package/src/plugins.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugins of an ot: small packs made by anyone that add a window beside the ot (a panel), tools for its
|
|
3
|
+
* brain (an MCP server) and a few words that tell it when to use them. Shared by the pet (cli/lib/plugins.mjs)
|
|
4
|
+
* and 7ots.com's catalog (server/platform/plugins.mjs). Guide for devs: docs/PLUGINS.md.
|
|
5
|
+
*
|
|
6
|
+
* 7ots-plugin.json
|
|
7
|
+
* {
|
|
8
|
+
* id: 'btc-price', name: 'BTC price', version: '1.0.0', icon: '₿',
|
|
9
|
+
* description: 'Bitcoin live, beside your ot',
|
|
10
|
+
* author: 'someone', homepage: 'https://…',
|
|
11
|
+
* instructions: 'When your human asks for the bitcoin price, open this panel.', // for its brain
|
|
12
|
+
* panel: { file: 'panel.html', title: 'BTC', width: 300, height: 190 }, // optional
|
|
13
|
+
* net: ['api.coingecko.com'], // hosts the panel may reach (https only); nothing else
|
|
14
|
+
* mcp: { url: 'https://…/mcp' } | { command: 'node server.mjs' }, // optional tools
|
|
15
|
+
* env: ['SOME_API_KEY'], // keys the MCP server needs (settings → keys)
|
|
16
|
+
* }
|
|
17
|
+
*
|
|
18
|
+
* A bundle = { manifest, files: { 'panel.html': '<base64>', … } }: at most MAX_FILES files and MAX_BYTES in all,
|
|
19
|
+
* only web files (FILE_TYPES). Panels run in their own sandboxed window and origin (ots-plugin://<id>/), with a
|
|
20
|
+
* CSP that only lets them load their own files and talk to `net`. An MCP `command` runs code on the human's
|
|
21
|
+
* computer: only plugins you load yourself (dev) may have one; the public catalog takes `url` only.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export const PLUGIN_ID = /^[a-z0-9][a-z0-9-]{1,31}$/;
|
|
25
|
+
export const MAX_FILES = 30;
|
|
26
|
+
export const MAX_BYTES = 512 * 1024;
|
|
27
|
+
export const FILE_TYPES = {
|
|
28
|
+
html: 'text/html; charset=utf-8',
|
|
29
|
+
css: 'text/css; charset=utf-8',
|
|
30
|
+
js: 'text/javascript; charset=utf-8',
|
|
31
|
+
mjs: 'text/javascript; charset=utf-8',
|
|
32
|
+
json: 'application/json; charset=utf-8',
|
|
33
|
+
txt: 'text/plain; charset=utf-8',
|
|
34
|
+
md: 'text/markdown; charset=utf-8',
|
|
35
|
+
svg: 'image/svg+xml',
|
|
36
|
+
png: 'image/png',
|
|
37
|
+
jpg: 'image/jpeg',
|
|
38
|
+
jpeg: 'image/jpeg',
|
|
39
|
+
webp: 'image/webp',
|
|
40
|
+
gif: 'image/gif',
|
|
41
|
+
woff2: 'font/woff2',
|
|
42
|
+
};
|
|
43
|
+
const FILE_PATH = /^(?!.*\.\.)(?!\/)[\w.-]+(\/[\w.-]+){0,3}$/;
|
|
44
|
+
const HOST = /^(?=.{3,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
|
|
45
|
+
|
|
46
|
+
const str = (v, n) => String(v ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, n);
|
|
47
|
+
const int = (v, lo, hi, d) => (Number.isFinite(Number(v)) ? Math.min(hi, Math.max(lo, Math.round(Number(v)))) : d);
|
|
48
|
+
|
|
49
|
+
/** The type a plugin file is served with, or null when that kind of file is not allowed. */
|
|
50
|
+
export const fileType = (p) => FILE_TYPES[String(p).split('.').pop().toLowerCase()] || null;
|
|
51
|
+
export const okFilePath = (p) => typeof p === 'string' && FILE_PATH.test(p) && !!fileType(p);
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A raw manifest → a clean one, or throws Error(<field>).
|
|
55
|
+
* @param {object} m
|
|
56
|
+
* @param {{ catalog?: boolean }} [o] catalog: what 7ots.com accepts (no MCP command)
|
|
57
|
+
*/
|
|
58
|
+
export function normalizeManifest(m, { catalog = false } = {}) {
|
|
59
|
+
if (!m || typeof m !== 'object' || Array.isArray(m)) throw new Error('manifest');
|
|
60
|
+
const id = String(m.id || '').toLowerCase();
|
|
61
|
+
if (!PLUGIN_ID.test(id)) throw new Error('id');
|
|
62
|
+
const name = str(m.name, 40);
|
|
63
|
+
if (!name) throw new Error('name');
|
|
64
|
+
const version = str(m.version || '1.0.0', 20);
|
|
65
|
+
if (!/^\d+\.\d+\.\d+([-.+][\w.-]+)?$/.test(version)) throw new Error('version');
|
|
66
|
+
const out = { id, name, version, icon: [...str(m.icon || '🧩', 8)].slice(0, 2).join('') || '🧩', description: str(m.description, 200), author: str(m.author, 40) };
|
|
67
|
+
const homepage = str(m.homepage, 300);
|
|
68
|
+
if (homepage && /^https:\/\/[^\s"'<>]+$/i.test(homepage)) out.homepage = homepage;
|
|
69
|
+
const instructions = str(m.instructions, 600);
|
|
70
|
+
if (instructions) out.instructions = instructions;
|
|
71
|
+
if (m.panel) {
|
|
72
|
+
const file = String(m.panel.file || 'panel.html');
|
|
73
|
+
if (!okFilePath(file) || !/\.html$/i.test(file)) throw new Error('panel');
|
|
74
|
+
out.panel = { file, title: str(m.panel.title || name, 40), width: int(m.panel.width, 200, 900, 320), height: int(m.panel.height, 120, 900, 220) };
|
|
75
|
+
}
|
|
76
|
+
const net = Array.isArray(m.net) ? m.net.map((h) => String(h).toLowerCase().trim()) : [];
|
|
77
|
+
if (net.length > 8 || net.some((h) => !HOST.test(h))) throw new Error('net');
|
|
78
|
+
if (net.length) out.net = [...new Set(net)];
|
|
79
|
+
if (m.mcp) {
|
|
80
|
+
const url = str(m.mcp.url, 300);
|
|
81
|
+
const command = str(m.mcp.command, 300);
|
|
82
|
+
if (url) {
|
|
83
|
+
if (!/^https:\/\/[^\s"'<>]+$/i.test(url)) throw new Error('mcp');
|
|
84
|
+
out.mcp = { url };
|
|
85
|
+
} else if (command && !catalog) out.mcp = { command };
|
|
86
|
+
else throw new Error('mcp');
|
|
87
|
+
}
|
|
88
|
+
const env = Array.isArray(m.env) ? m.env.map(String) : [];
|
|
89
|
+
if (env.length > 5 || env.some((e) => !/^[A-Z][A-Z0-9_]{1,63}$/.test(e))) throw new Error('env');
|
|
90
|
+
if (env.length) out.env = env;
|
|
91
|
+
if (!out.panel && !out.mcp && !out.instructions) throw new Error('empty');
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** base64 → byte length (without decoding). */
|
|
96
|
+
const b64len = (s) => Math.floor((s.length * 3) / 4) - (s.endsWith('==') ? 2 : s.endsWith('=') ? 1 : 0);
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* A raw bundle → { manifest, files } (files still base64), or throws Error(<field>).
|
|
100
|
+
* @param {{ manifest: object, files: Record<string, string> }} b
|
|
101
|
+
*/
|
|
102
|
+
export function normalizeBundle(b, o = {}) {
|
|
103
|
+
if (!b || typeof b !== 'object') throw new Error('bundle');
|
|
104
|
+
const manifest = normalizeManifest(b.manifest, o);
|
|
105
|
+
const files = {};
|
|
106
|
+
let total = 0;
|
|
107
|
+
const entries = Object.entries(b.files && typeof b.files === 'object' ? b.files : {});
|
|
108
|
+
if (entries.length > MAX_FILES) throw new Error('files');
|
|
109
|
+
for (const [p, data] of entries) {
|
|
110
|
+
if (p === '7ots-plugin.json') continue;
|
|
111
|
+
if (!okFilePath(p)) throw new Error(`file ${p}`);
|
|
112
|
+
if (typeof data !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(data)) throw new Error(`file ${p}`);
|
|
113
|
+
total += b64len(data);
|
|
114
|
+
if (total > MAX_BYTES) throw new Error('size');
|
|
115
|
+
files[p] = data;
|
|
116
|
+
}
|
|
117
|
+
if (manifest.panel && !files[manifest.panel.file]) throw new Error('panel');
|
|
118
|
+
return { manifest, files };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The Content-Security-Policy a plugin's panel runs under: its own files, plus https to its `net` hosts. */
|
|
122
|
+
export function panelCsp(manifest) {
|
|
123
|
+
const net = (manifest.net || []).map((h) => `https://${h}`).join(' ');
|
|
124
|
+
return [
|
|
125
|
+
"default-src 'none'",
|
|
126
|
+
"script-src 'self'",
|
|
127
|
+
"style-src 'self' 'unsafe-inline'",
|
|
128
|
+
`img-src 'self' data:${net ? ` ${net}` : ''}`,
|
|
129
|
+
"font-src 'self'",
|
|
130
|
+
`connect-src ${net || "'none'"}`,
|
|
131
|
+
"media-src 'self'",
|
|
132
|
+
"base-uri 'none'",
|
|
133
|
+
"form-action 'none'",
|
|
134
|
+
"frame-src 'none'",
|
|
135
|
+
"object-src 'none'",
|
|
136
|
+
].join('; ');
|
|
137
|
+
}
|