@7ots/cli 0.1.19 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +14 -0
- package/brand/logos/base.svg +1 -0
- package/brand/logos/clawpump.png +0 -0
- package/brand/logos/conductors.svg +1 -0
- package/brand/logos/notlogin.svg +12 -0
- package/brand/logos/pumpfun.png +0 -0
- package/brand/logos/solana.png +0 -0
- package/brand/logos/spawnerbot.svg +1 -0
- package/brand/logos/virtuals.png +0 -0
- package/cli/7ots.mjs +59 -1
- package/cli/lib/account.mjs +23 -3
- package/cli/lib/assistant.mjs +88 -13
- package/cli/lib/brain.mjs +76 -8
- package/cli/lib/config.mjs +14 -3
- package/cli/lib/desktop-sync.mjs +177 -0
- package/cli/lib/i18n.mjs +9 -0
- package/cli/lib/inferences.mjs +19 -2
- package/cli/lib/integrations.mjs +61 -6
- package/cli/lib/pet-server.mjs +316 -41
- package/cli/lib/prompts.mjs +1 -1
- package/cli/lib/senses/gestures.mjs +121 -0
- package/cli/lib/senses/index.mjs +490 -0
- package/cli/lib/senses/rules.mjs +159 -0
- package/cli/lib/senses/sources/activity.mjs +95 -0
- package/cli/lib/senses/sources/calendar.mjs +75 -0
- package/cli/lib/senses/sources/index.mjs +17 -0
- package/cli/lib/senses/sources/mail.mjs +48 -0
- package/cli/lib/senses/sources/system.mjs +39 -0
- package/cli/lib/senses/util.mjs +41 -0
- package/cli/lib/senses/vendor.mjs +78 -0
- package/cli/lib/stt-local.py +16 -8
- package/cli/lib/stt.mjs +53 -6
- package/cli/lib/tooluse.mjs +56 -0
- package/cli/lib/vm.mjs +1 -1
- package/cli/lib/wake-local.py +109 -0
- package/cli/lib/wake.mjs +102 -0
- package/cli/pet/electron/main.cjs +137 -13
- package/cli/pet/pet.html +125 -26
- package/cli/pet/senses.html +342 -0
- package/cli/pet/settings.html +787 -86
- package/dist/7ots.esm.js +373 -146
- package/dist/7ots.esm.js.map +4 -4
- package/dist/7ots.iife.js +373 -146
- package/dist/7ots.iife.js.map +4 -4
- package/llms.txt +27 -0
- package/package.json +5 -2
- package/server/channels/apuchat.mjs +2 -0
- package/server/errors.mjs +90 -0
- package/server/notify.mjs +78 -0
- package/server/server.mjs +68 -12
- package/server/settings.mjs +3 -0
- package/server/site.mjs +401 -0
- package/server/tts.mjs +29 -5
- package/src/avatar/AvatarStage.js +2 -2
- package/src/avatar/three.js +3 -2
- package/src/character/AvatarEditor.js +2 -1
- package/src/character/Character.js +1 -1
- package/src/character/TradingCard.js +2 -0
- package/src/character/beat.js +64 -2
- package/src/character/mods/orc.js +8 -1
- package/src/character/mods.js +104 -10
- package/src/character/motion.js +162 -0
- package/src/character/parts.js +40 -38
- package/src/character/styles.js +40 -38
- package/src/character3d/Character3D.js +26 -5
- package/src/character3d/body.js +14 -12
- package/src/character3d/export.js +693 -0
- package/src/character3d/fx.js +13 -0
- package/src/character3d/index.js +2 -0
- package/src/character3d/materials.js +106 -10
- package/src/character3d/room-themes.js +1184 -0
- package/src/character3d/room.js +487 -0
- package/src/character3d/stage.js +2 -1
- package/src/creator/StepCreator.js +316 -0
- package/src/i18n/index.js +3 -3
- package/src/i18n/messages/character.js +352 -4
- package/src/i18n/messages/creator.js +138 -0
- package/src/i18n/messages/identity.js +89 -1
- package/src/i18n/messages/platform.js +255 -1
- package/src/i18n/messages/server.js +443 -1
- package/src/i18n/messages/widget.js +233 -0
- package/src/identity/random.js +14 -2
- package/src/identity/schema.js +2 -1
- package/src/index.js +9 -2
- package/src/voice/tags.js +22 -0
- package/server/platform/apuchat.mjs +0 -266
- package/server/platform/auth.mjs +0 -337
- package/server/platform/byte.mjs +0 -291
- package/server/platform/connect.mjs +0 -391
- package/server/platform/crypto.mjs +0 -80
- package/server/platform/db.mjs +0 -293
- package/server/platform/device.mjs +0 -247
- package/server/platform/integrations.mjs +0 -169
- package/server/platform/look.mjs +0 -20
- package/server/platform/mods.mjs +0 -222
- package/server/platform/orquesta.mjs +0 -611
- package/server/platform/profile.mjs +0 -182
- package/server/platform/routes.mjs +0 -589
- package/server/platform/runtime.mjs +0 -286
- package/server/platform/sites.mjs +0 -146
- package/server/platform/stage3d.mjs +0 -82
- package/server/platform/store.mjs +0 -469
- package/server/platform/vm.mjs +0 -1057
- package/server/platform/wallet.mjs +0 -255
package/cli/lib/prompts.mjs
CHANGED
|
@@ -240,7 +240,7 @@ HTML tools without JS: \`<form data-ots-tool="invite_member" data-ots-descriptio
|
|
|
240
240
|
# Own server (\`npx -y @7ots/cli server\`, or \`node server/server.mjs\` from the repo)
|
|
241
241
|
|
|
242
242
|
Reads env vars / \`.env\`. Keys live only here. Admin UI at /backoffice/ (localhost only unless ADMIN_PASSWORD).
|
|
243
|
-
- Core: PORT (8787), ALLOWED_ORIGINS (comma list), SITE_KEYS, RATE_LIMIT_PER_MIN (40), TRUST_PROXY, SERVER_INSTRUCTIONS, LOCALE (es|en|pt), LOG_LEVEL.
|
|
243
|
+
- Core: PORT (8787), ALLOWED_ORIGINS (comma list), SITE_KEYS, RATE_LIMIT_PER_MIN (40), TRUST_PROXY, SERVER_INSTRUCTIONS, LOCALE (es|en|pt|zh|hi), LOG_LEVEL.
|
|
244
244
|
- LLM: LLM_PROVIDER (anthropic | openai | mock), ANTHROPIC_API_KEY, OPENAI_API_KEY, LLM_MODEL, LLM_BASE_URL (OpenAI-compatible:
|
|
245
245
|
DeepSeek, Groq, Ollama, OpenRouter…), LLM_EFFORT (low…max), LLM_MAX_TOKENS, LLM_FALLBACKS (on|off).
|
|
246
246
|
- Voice (TTS): TTS_PROVIDER (apuchat | elevenlabs | grok | fish | openai | none = browser voice; empty = first with a key);
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hand gestures → quick commands. ~/.7ots/gestures.json (edited from /settings → Senses):
|
|
3
|
+
*
|
|
4
|
+
* { "map": { "thumb_up": { "type": "confirm" }, "victory": { "type": "media", "do": "play-pause" }, … },
|
|
5
|
+
* "commands": { "lock": { "label": "Lock the screen", "run": ["loginctl", "lock-session"], "approved": false } } }
|
|
6
|
+
*
|
|
7
|
+
* Gestures (MediaPipe's): thumb_up, thumb_down, open_palm, closed_fist, victory, pointing_up, iloveyou.
|
|
8
|
+
* Action types:
|
|
9
|
+
* confirm / reject answers the ot's pending question (Approve / Reject in its bubble)
|
|
10
|
+
* media play-pause | next | prev | mute | up | down
|
|
11
|
+
* key a key combo, xdotool syntax ("super+d", "ctrl+alt+Left"), Linux X11 only
|
|
12
|
+
* command one of `commands` (an argv list, never a shell); it asks you once before the first run
|
|
13
|
+
* ask says `text` to the ot as if you had typed it ("¿qué tengo hoy?")
|
|
14
|
+
* pause camera off for `for` minutes (privacy), 15 by default
|
|
15
|
+
* react the ot just reacts (a heart, a wave)
|
|
16
|
+
* Commands (media, key, command, ask) only run after the attention gesture (`arm`, open palm by default) when
|
|
17
|
+
* senses.arm is on, so a hand passing by does nothing. confirm / reject need no arming while it is asking.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { homeFile, readJson, writeJson } from '../paths.mjs';
|
|
21
|
+
import { clip, run } from './util.mjs';
|
|
22
|
+
|
|
23
|
+
export const GESTURES = ['thumb_up', 'thumb_down', 'open_palm', 'closed_fist', 'victory', 'pointing_up', 'iloveyou'];
|
|
24
|
+
export const MEDIA = ['play-pause', 'next', 'prev', 'mute', 'up', 'down'];
|
|
25
|
+
export const TYPES = ['confirm', 'reject', 'media', 'key', 'command', 'ask', 'pause', 'react', 'none'];
|
|
26
|
+
const KEYS_RE = /^[A-Za-z0-9_+\- ]{1,60}$/;
|
|
27
|
+
const COMMAND_ID = /^[a-z0-9_-]{1,30}$/;
|
|
28
|
+
|
|
29
|
+
const DEFAULT_COMMANDS = {
|
|
30
|
+
linux: { lock: { label: 'Lock the screen', run: ['loginctl', 'lock-session'] }, shot: { label: 'Screenshot', run: ['gnome-screenshot', '-i'] } },
|
|
31
|
+
darwin: { lock: { label: 'Lock the screen', run: ['pmset', 'displaysleepnow'] } },
|
|
32
|
+
win32: { lock: { label: 'Lock the screen', run: ['rundll32.exe', 'user32.dll,LockWorkStation'] } },
|
|
33
|
+
}[process.platform] || {};
|
|
34
|
+
|
|
35
|
+
export const DEFAULT_GESTURES = {
|
|
36
|
+
map: {
|
|
37
|
+
thumb_up: { type: 'confirm' },
|
|
38
|
+
thumb_down: { type: 'reject' },
|
|
39
|
+
victory: { type: 'media', do: 'play-pause' },
|
|
40
|
+
pointing_up: { type: 'media', do: 'next' },
|
|
41
|
+
closed_fist: { type: 'pause', for: 15 },
|
|
42
|
+
iloveyou: { type: 'react' },
|
|
43
|
+
},
|
|
44
|
+
commands: DEFAULT_COMMANDS,
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** Cleans one action; null if it makes no sense. */
|
|
48
|
+
export function normalizeAction(a) {
|
|
49
|
+
if (!a || typeof a !== 'object' || !TYPES.includes(a.type)) return null;
|
|
50
|
+
if (a.type === 'media') return MEDIA.includes(a.do) ? { type: 'media', do: a.do } : null;
|
|
51
|
+
if (a.type === 'key') return KEYS_RE.test(String(a.keys || '')) ? { type: 'key', keys: String(a.keys).trim() } : null;
|
|
52
|
+
if (a.type === 'command') return COMMAND_ID.test(String(a.id || '')) ? { type: 'command', id: a.id } : null;
|
|
53
|
+
if (a.type === 'ask') return clip(a.text, 300) ? { type: 'ask', text: clip(a.text, 300) } : null;
|
|
54
|
+
if (a.type === 'pause') return { type: 'pause', for: Math.max(1, Math.min(240, Math.round(Number(a.for)) || 15)) };
|
|
55
|
+
return { type: a.type };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** `prev` = what was saved (a change from settings): a command keeps its approval only if its argv is the same. */
|
|
59
|
+
export function normalizeGestures(d = {}, prev = null) {
|
|
60
|
+
const map = {};
|
|
61
|
+
const src = d.map && typeof d.map === 'object' ? d.map : prev?.map || {};
|
|
62
|
+
for (const g of GESTURES) {
|
|
63
|
+
const a = normalizeAction(src[g]);
|
|
64
|
+
if (a && a.type !== 'none') map[g] = a;
|
|
65
|
+
}
|
|
66
|
+
const commands = {};
|
|
67
|
+
const cs = d.commands && typeof d.commands === 'object' ? d.commands : prev?.commands || {};
|
|
68
|
+
for (const [id, c] of Object.entries(cs).slice(0, 30)) {
|
|
69
|
+
if (!COMMAND_ID.test(id) || !Array.isArray(c?.run) || !c.run.length || c.run.length > 12) continue;
|
|
70
|
+
const argv = c.run.map((x) => String(x).slice(0, 300));
|
|
71
|
+
if (!argv[0].trim() || argv.some((x) => /[\u0000]/.test(x))) continue;
|
|
72
|
+
// a changed command line asks again before its first run
|
|
73
|
+
const before = prev ? prev.commands?.[id] : c;
|
|
74
|
+
const same = before && JSON.stringify(before.run) === JSON.stringify(argv);
|
|
75
|
+
commands[id] = { label: clip(c.label, 60) || id, run: argv, approved: Boolean(same && before.approved) };
|
|
76
|
+
}
|
|
77
|
+
return { map, commands };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const FILE = () => homeFile('gestures.json');
|
|
81
|
+
export function loadGestures() {
|
|
82
|
+
const raw = readJson(FILE(), null);
|
|
83
|
+
return normalizeGestures(raw || DEFAULT_GESTURES);
|
|
84
|
+
}
|
|
85
|
+
export function saveGestures(g) {
|
|
86
|
+
writeJson(FILE(), g);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const XMEDIA = { 'play-pause': 'XF86AudioPlay', next: 'XF86AudioNext', prev: 'XF86AudioPrev', mute: 'XF86AudioMute', up: 'XF86AudioRaiseVolume', down: 'XF86AudioLowerVolume' };
|
|
90
|
+
const WMEDIA = { 'play-pause': 179, next: 176, prev: 177, mute: 173, up: 175, down: 174 }; // virtual-key codes
|
|
91
|
+
const MACVOL = { mute: 'set volume output muted not (output muted of (get volume settings))', up: 'set volume output volume ((output volume of (get volume settings)) + 10)', down: 'set volume output volume ((output volume of (get volume settings)) - 10)' };
|
|
92
|
+
|
|
93
|
+
/** Presses a media key. → true if this platform could. */
|
|
94
|
+
export async function media(what) {
|
|
95
|
+
if (process.platform === 'linux') {
|
|
96
|
+
const pc = { 'play-pause': 'play-pause', next: 'next', prev: 'previous' }[what];
|
|
97
|
+
if (pc && (await run('playerctl', [pc])) != null) return true; // MPRIS, when installed: works without a focused window
|
|
98
|
+
return (await run('xdotool', ['key', XMEDIA[what]])) != null;
|
|
99
|
+
}
|
|
100
|
+
if (process.platform === 'win32') return (await run('powershell', ['-NoProfile', '-Command', `(New-Object -ComObject WScript.Shell).SendKeys([char]${WMEDIA[what]})`])) != null;
|
|
101
|
+
if (process.platform === 'darwin') {
|
|
102
|
+
if (MACVOL[what]) return (await run('osascript', ['-e', MACVOL[what]])) != null;
|
|
103
|
+
const verb = { 'play-pause': 'playpause', next: 'next track', prev: 'previous track' }[what];
|
|
104
|
+
for (const appName of ['Spotify', 'Music']) {
|
|
105
|
+
const up = await run('osascript', ['-e', `application "${appName}" is running`]);
|
|
106
|
+
if (up === 'true') return (await run('osascript', ['-e', `tell application "${appName}" to ${verb}`])) != null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** A key combo (xdotool syntax). Linux X11 only. */
|
|
113
|
+
export async function key(keys) {
|
|
114
|
+
if (process.platform !== 'linux' || !process.env.DISPLAY || !KEYS_RE.test(keys)) return false;
|
|
115
|
+
return (await run('xdotool', ['key', '--clearmodifiers', ...keys.split(/\s+/)])) != null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A whitelisted command, argv only (no shell). */
|
|
119
|
+
export async function command(c) {
|
|
120
|
+
return (await run(c.run[0], c.run.slice(1), 20_000)) != null;
|
|
121
|
+
}
|
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ot's senses: what it notices about you (camera, activity, the computer, email, calendar), what it does
|
|
3
|
+
* with that (rules, gesture commands) and a reflector that now and then asks the brain whether there is
|
|
4
|
+
* something worth doing or a rule worth proposing. See docs/SENSES.md.
|
|
5
|
+
*
|
|
6
|
+
* sources ──► events + current facts ──► rules (rules.json) ──► say / remind / quiet / notify
|
|
7
|
+
* └──► reflector (brain) ──► one line, or a rule it proposes (you accept)
|
|
8
|
+
* camera page (/senses) ──► gestures ──► gestures.json ──► confirm / media / key / command / ask / pause
|
|
9
|
+
*
|
|
10
|
+
* Kept on this computer only (never in desktop sync): ~/.7ots/senses/day-YYYY-MM-DD.json (14 days of
|
|
11
|
+
* aggregates: minutes per app, site and face state, breaks), baseline.json (your neutral face, numbers only),
|
|
12
|
+
* fired.json (rule cooldowns). Camera frames never leave the page: the daemon only gets labels.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { existsSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { homeFile, readJson, writeJson } from '../paths.mjs';
|
|
18
|
+
import { createActivity } from './sources/activity.mjs';
|
|
19
|
+
import { createCalendar } from './sources/calendar.mjs';
|
|
20
|
+
import { createMail } from './sources/mail.mjs';
|
|
21
|
+
import { createSystem } from './sources/system.mjs';
|
|
22
|
+
import { SOURCES } from './sources/index.mjs';
|
|
23
|
+
import { GESTURES, command, key, loadGestures, media, normalizeGestures, saveGestures } from './gestures.mjs';
|
|
24
|
+
import { STATES, fill, holds, loadRules, normalizeRule, saveRules } from './rules.mjs';
|
|
25
|
+
import { clip, dayKey, dur, human } from './util.mjs';
|
|
26
|
+
|
|
27
|
+
export { GESTURES, STATES, SOURCES };
|
|
28
|
+
export const SENSES_DEFAULTS = { arm: true, holdMs: 600, fps: 5, reflect: true };
|
|
29
|
+
|
|
30
|
+
const KEEP_DAYS = 14;
|
|
31
|
+
const BREAK = 5 * 60_000; // this long away = a break (the streak starts over)
|
|
32
|
+
const CAMERA_STALE = 30_000;
|
|
33
|
+
const REFLECT = { 0: Infinity, 1: 90 * 60_000, 2: 40 * 60_000, 3: 15 * 60_000 }; // by the annoyance level
|
|
34
|
+
const PROPOSE_GAP = 3 * 3_600_000;
|
|
35
|
+
const MAX_OT_RULES = 12;
|
|
36
|
+
const ARM_MS = 6000;
|
|
37
|
+
|
|
38
|
+
const T = {
|
|
39
|
+
en: { propose: (n) => `Shall I add this rule? «${n}»`, armed: 'I see you 👋 what do I do?', paused: (m) => `Camera paused for ${m} min.`, cmd: (l) => `Run «${l}» when you make that gesture?`, failed: 'That did not work here.' },
|
|
40
|
+
es: { propose: (n) => `¿Agrego esta regla? «${n}»`, armed: 'Te veo 👋 ¿qué hago?', paused: (m) => `Cámara en pausa ${m} min.`, cmd: (l) => `¿Ejecuto «${l}» cada vez que hagas ese gesto?`, failed: 'Eso no funcionó acá.' },
|
|
41
|
+
pt: { propose: (n) => `Adiciono esta regra? «${n}»`, armed: 'Te vejo 👋 o que eu faço?', paused: (m) => `Câmera pausada por ${m} min.`, cmd: (l) => `Executo «${l}» quando você fizer esse gesto?`, failed: 'Isso não funcionou aqui.' },
|
|
42
|
+
};
|
|
43
|
+
// what the seed rules say with the built-in phrases (no AI brain to word `about`)
|
|
44
|
+
const PLAIN = {
|
|
45
|
+
en: { 'seed-tired-break': 'You look tired and it has been {streak}. A short break? Water, stand up, look away.', 'seed-long-streak': '{streak} non-stop! Five minutes of break?', 'seed-tense-help': 'Rough one? Tell me if I can help.', 'seed-sad': 'I am here if you want to talk 💛', 'seed-meeting': '«{meeting}» starts in {meetingIn}.', 'seed-mail-urgent': 'Urgent-looking email: {mail}', 'seed-battery': 'Battery at {battery}%: plug it in!', 'seed-late': 'It is {time}… time to sleep?' },
|
|
46
|
+
es: { 'seed-tired-break': 'Te veo cansado y llevas {streak}. ¿Una pausa? Agua, estirarte, mirar lejos.', 'seed-long-streak': '¡{streak} sin parar! ¿Cinco minutos de pausa?', 'seed-tense-help': '¿Difícil? Dime si te ayudo.', 'seed-sad': 'Estoy aquí si quieres hablar 💛', 'seed-meeting': '«{meeting}» empieza en {meetingIn}.', 'seed-mail-urgent': 'Correo que parece urgente: {mail}', 'seed-battery': 'Batería al {battery}%: ¡enchúfame!', 'seed-late': 'Son las {time}… ¿a dormir?' },
|
|
47
|
+
pt: { 'seed-tired-break': 'Você parece cansado e já são {streak}. Uma pausa? Água, levantar, olhar longe.', 'seed-long-streak': '{streak} sem parar! Cinco minutos de pausa?', 'seed-tense-help': 'Difícil? Me diz se posso ajudar.', 'seed-sad': 'Estou aqui se quiser conversar 💛', 'seed-meeting': '«{meeting}» começa em {meetingIn}.', 'seed-mail-urgent': 'Email que parece urgente: {mail}', 'seed-battery': 'Bateria em {battery}%: liga na tomada!', 'seed-late': 'São {time}… hora de dormir?' },
|
|
48
|
+
};
|
|
49
|
+
const MEDIA_ICON = { 'play-pause': '⏯', next: '⏭', prev: '⏮', mute: '🔇', up: '🔊', down: '🔉' };
|
|
50
|
+
const FEATURE = /^[a-zA-Z]{2,40}$/;
|
|
51
|
+
|
|
52
|
+
const emptyDay = (date) => ({ date, active: 0, away: 0, breaks: 0, longest: 0, apps: {}, sites: {}, states: {}, gestures: {}, mail: 0 });
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @param o.config () => config (access.*, senses.*, integrations)
|
|
56
|
+
* @param o.talk ({ text, about, exact, kind, important, gesture }) => Promise<boolean> says a line if pacing
|
|
57
|
+
* allows; `about` is worded by the brain (unless `exact`), `text` is the line without one
|
|
58
|
+
* @param o.confirm (text) => Promise<boolean> Approve / Reject in its bubble
|
|
59
|
+
* @param o.answer (ok) => boolean answers the question it is asking now, if any
|
|
60
|
+
* @param o.asking () => boolean
|
|
61
|
+
* @param o.remind ({ at, text }) => string sets a reminder
|
|
62
|
+
* @param o.ask (text) => Promise as if you had typed it
|
|
63
|
+
* @param o.broadcast (msg) => void to the pet pages (SSE)
|
|
64
|
+
*/
|
|
65
|
+
export function createSenses({ config, brain, lang = 'en', system = () => '', annoy = () => 2, busy = () => false, talk, confirm, answer, asking, remind, ask, notify = () => {}, broadcast = () => {}, log = () => {} }) {
|
|
66
|
+
const L = T[lang] || T.en;
|
|
67
|
+
const dir = homeFile('senses');
|
|
68
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
69
|
+
const f = (n) => join(dir, n);
|
|
70
|
+
const conf = () => ({ ...SENSES_DEFAULTS, ...config().senses });
|
|
71
|
+
const acc = () => config().access || {};
|
|
72
|
+
|
|
73
|
+
// ── what it keeps ──
|
|
74
|
+
let day = { ...emptyDay(dayKey()), ...readJson(f(`day-${dayKey()}.json`), {}) };
|
|
75
|
+
const saveDay = () => writeJson(f(`day-${day.date}.json`), day, { secret: true });
|
|
76
|
+
function prune() {
|
|
77
|
+
const cut = dayKey(Date.now() - KEEP_DAYS * 86_400_000);
|
|
78
|
+
for (const n of readdirSync(dir)) if (/^day-\d{4}-\d{2}-\d{2}\.json$/.test(n) && n.slice(4, 14) < cut) unlinkSync(f(n));
|
|
79
|
+
}
|
|
80
|
+
prune();
|
|
81
|
+
let fired = readJson(f('fired.json'), {}) || {};
|
|
82
|
+
let rules = loadRules();
|
|
83
|
+
if (!existsSync(homeFile('rules.json'))) saveRules(rules);
|
|
84
|
+
let gestures = loadGestures();
|
|
85
|
+
if (!existsSync(homeFile('gestures.json'))) saveGestures(gestures);
|
|
86
|
+
const recent = []; // events of the last 2 h: { source, kind, ts, value, summary, urgency }
|
|
87
|
+
|
|
88
|
+
// ── now ──
|
|
89
|
+
const cam = { on: false, at: 0, state: 'neutral', score: 0, since: Date.now(), present: null, scores: {} };
|
|
90
|
+
let streakStart = Date.now();
|
|
91
|
+
let awaySince = 0;
|
|
92
|
+
let present = null;
|
|
93
|
+
let quietUntil = 0;
|
|
94
|
+
let armedUntil = 0;
|
|
95
|
+
let lastReflect = Date.now();
|
|
96
|
+
let lastPropose = Number(fired['@propose']) || 0;
|
|
97
|
+
let lastTick = Date.now();
|
|
98
|
+
const lastGesture = {};
|
|
99
|
+
let reflecting = false;
|
|
100
|
+
|
|
101
|
+
const activity = createActivity({ enabled: () => acc().activity === true, log });
|
|
102
|
+
const sys = createSystem();
|
|
103
|
+
const emit = (e) => {
|
|
104
|
+
const ev = { source: e.source, kind: e.kind, ts: Date.now(), value: e.value ?? null, summary: clip(e.summary, 200), urgency: Math.max(0, Math.min(3, e.urgency | 0)) };
|
|
105
|
+
recent.push(ev);
|
|
106
|
+
while (recent.length && (recent.length > 400 || recent[0].ts < Date.now() - 2 * 3_600_000)) recent.shift();
|
|
107
|
+
if (ev.source === 'mail') day.mail++;
|
|
108
|
+
return ev;
|
|
109
|
+
};
|
|
110
|
+
const mail = createMail({ config, emit, log });
|
|
111
|
+
const calendar = createCalendar({ config, log });
|
|
112
|
+
|
|
113
|
+
const camFresh = () => acc().camera === true && cam.on && Date.now() - cam.at < CAMERA_STALE;
|
|
114
|
+
const paused = () => Number(config().senses?.pausedUntil) > Date.now();
|
|
115
|
+
|
|
116
|
+
function presence() {
|
|
117
|
+
if (camFresh() && cam.present != null) return cam.present;
|
|
118
|
+
const a = activity.now;
|
|
119
|
+
if (a && Number.isFinite(a.idleMs)) return a.idleMs < BREAK;
|
|
120
|
+
return null; // nothing tells
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function facts() {
|
|
124
|
+
const now = Date.now();
|
|
125
|
+
const a = activity.now;
|
|
126
|
+
const next = calendar.next;
|
|
127
|
+
const mails = recent.filter((e) => e.source === 'mail' && e.ts > now - 10 * 60_000);
|
|
128
|
+
const urgent = mails.filter((e) => e.value?.urgent);
|
|
129
|
+
return {
|
|
130
|
+
now,
|
|
131
|
+
present,
|
|
132
|
+
state: camFresh() && cam.present !== false ? cam.state : null,
|
|
133
|
+
stateFor: now - cam.since,
|
|
134
|
+
streak: present === null ? 0 : now - streakStart,
|
|
135
|
+
away: awaySince ? now - awaySince : 0,
|
|
136
|
+
app: a?.app || '',
|
|
137
|
+
site: a?.site || '',
|
|
138
|
+
appFor: Math.max(day.apps[a?.app] || 0, day.sites[a?.site] || 0),
|
|
139
|
+
meeting: next?.title || '',
|
|
140
|
+
meetingIn: next ? next.start - now : 0,
|
|
141
|
+
battery: sys.now?.battery || null,
|
|
142
|
+
cpu: sys.now?.cpu ?? null,
|
|
143
|
+
mailNew: mails.length > 0,
|
|
144
|
+
mailUrgent: urgent.length > 0,
|
|
145
|
+
mailLast: (urgent.at(-1) || mails.at(-1))?.summary || '',
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// ── every 15 s: time adds up, rules are checked ──
|
|
150
|
+
let ticks = 0;
|
|
151
|
+
async function tick() {
|
|
152
|
+
const now = Date.now();
|
|
153
|
+
const dt = Math.min(60_000, now - lastTick);
|
|
154
|
+
lastTick = now;
|
|
155
|
+
if (dayKey(now) !== day.date) {
|
|
156
|
+
saveDay();
|
|
157
|
+
day = emptyDay(dayKey(now));
|
|
158
|
+
prune();
|
|
159
|
+
}
|
|
160
|
+
await activity.tick();
|
|
161
|
+
if (ticks % 4 === 0) await sys.tick();
|
|
162
|
+
if (ticks % 20 === 0) mail.tick();
|
|
163
|
+
if (ticks % 60 === 0) calendar.tick();
|
|
164
|
+
ticks++;
|
|
165
|
+
if (cam.on && !camFresh()) (cam.on = false), broadcast({ senses: { camera: paused() ? 'paused' : 'off' } }); // the page went away
|
|
166
|
+
present = presence();
|
|
167
|
+
if (present === true) {
|
|
168
|
+
if (awaySince && now - awaySince >= BREAK) (streakStart = now), day.breaks++;
|
|
169
|
+
awaySince = 0;
|
|
170
|
+
day.active += dt;
|
|
171
|
+
const a = activity.now;
|
|
172
|
+
if (a?.app) day.apps[a.app] = (day.apps[a.app] || 0) + dt;
|
|
173
|
+
if (a?.site) day.sites[a.site] = (day.sites[a.site] || 0) + dt;
|
|
174
|
+
if (camFresh()) day.states[cam.state] = (day.states[cam.state] || 0) + dt;
|
|
175
|
+
day.longest = Math.max(day.longest, now - streakStart);
|
|
176
|
+
} else if (present === false) {
|
|
177
|
+
awaySince ||= now;
|
|
178
|
+
day.away += dt;
|
|
179
|
+
}
|
|
180
|
+
if (ticks % 4 === 0) saveDay();
|
|
181
|
+
await checkRules();
|
|
182
|
+
if (now - lastReflect > REFLECT[annoy()] && conf().reflect !== false) reflect();
|
|
183
|
+
}
|
|
184
|
+
const timer = setInterval(() => tick().catch((e) => log(`senses: ${e.message}`)), 15_000);
|
|
185
|
+
timer.unref?.();
|
|
186
|
+
const first = setTimeout(() => tick().catch(() => {}), 3000);
|
|
187
|
+
|
|
188
|
+
// ── rules ──
|
|
189
|
+
const important = (r) => Boolean(r.when.meetingIn || r.when.mail || r.when.battery);
|
|
190
|
+
async function checkRules() {
|
|
191
|
+
if (!anyOn()) return;
|
|
192
|
+
const F = facts();
|
|
193
|
+
let said = false;
|
|
194
|
+
for (const r of rules) {
|
|
195
|
+
if (r.status !== 'active' || !holds(r.when, F)) continue;
|
|
196
|
+
if (Date.now() - (Number(fired[r.id]) || 0) < dur(r.cooldown)) continue;
|
|
197
|
+
const t = r.then;
|
|
198
|
+
if (t.type === 'say') {
|
|
199
|
+
if (said || (Date.now() < quietUntil && !important(r))) continue;
|
|
200
|
+
const plain = t.text || (PLAIN[lang] || PLAIN.en)[r.id] || '';
|
|
201
|
+
const ok = await talk({ kind: `rule:${r.id}`, about: t.about ? fill(t.about, F) : '', text: plain ? fill(plain, F) : '', exact: Boolean(t.text), important: important(r), gesture: r.when.state === 'tired' ? 'yawn' : 'wave' });
|
|
202
|
+
if (!ok) continue; // not now (it is talking, asleep, or you are chatting): it tries again on a later tick
|
|
203
|
+
said = true;
|
|
204
|
+
} else if (t.type === 'remind') remind({ at: Date.now() + (dur(t.in) || 0), text: fill(t.text, F) });
|
|
205
|
+
else if (t.type === 'quiet') {
|
|
206
|
+
quietUntil = Date.now() + (dur(t.for) || 25 * 60_000);
|
|
207
|
+
broadcast({ senses: { quiet: quietUntil } });
|
|
208
|
+
} else if (t.type === 'notify') notify(fill(t.text, F));
|
|
209
|
+
fired[r.id] = Date.now();
|
|
210
|
+
writeJson(f('fired.json'), fired);
|
|
211
|
+
log(`senses: rule ${r.id} (${t.type})`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ── the reflector: now and then, is there something worth doing? ──
|
|
216
|
+
function digest() {
|
|
217
|
+
const F = facts();
|
|
218
|
+
const top = (o, n = 6) => Object.entries(o).sort((a, b) => b[1] - a[1]).slice(0, n).filter(([, ms]) => ms >= 60_000).map(([k, ms]) => `${k} ${human(ms)}`).join(', ');
|
|
219
|
+
const faces = Object.values(day.states).reduce((a, b) => a + b, 0);
|
|
220
|
+
const lines = [
|
|
221
|
+
`Now: ${new Date(F.now).toLocaleString()}.`,
|
|
222
|
+
F.present === false ? `They are away (${human(F.away)}).` : F.present ? `At the computer for ${human(F.streak)} without a break.` : '',
|
|
223
|
+
F.app ? `Active app: ${F.app}${F.site ? ` (site: ${F.site})` : ''}, ${human(F.appFor)} today.` : '',
|
|
224
|
+
`Today: active ${human(day.active)}, away ${human(day.away)}, ${day.breaks} breaks, longest stretch ${human(day.longest)}.`,
|
|
225
|
+
top(day.apps) ? `Apps today: ${top(day.apps)}.` : '',
|
|
226
|
+
top(day.sites) ? `Sites today: ${top(day.sites)}.` : '',
|
|
227
|
+
F.state ? `Their face right now reads as ${F.state} (a hint, not a fact; for ${human(F.stateFor)}).` : '',
|
|
228
|
+
faces > 10 * 60_000 ? `Face today: ${top(day.states)}.` : '',
|
|
229
|
+
calendar.upcoming.length ? `Calendar: ${calendar.upcoming.map((e) => `«${e.title}» at ${new Date(e.start).toTimeString().slice(0, 5)}`).join(', ')}.` : '',
|
|
230
|
+
mail.latest.length && acc().mail ? `Latest emails: ${mail.latest.map((m) => `${m.from} «${m.subject}»${m.urgent ? ' (looks urgent)' : ''}`).join('; ')}.` : '',
|
|
231
|
+
F.battery ? `Battery ${F.battery.pct}%${F.battery.charging ? ' charging' : ''}.` : '',
|
|
232
|
+
F.cpu != null && F.cpu > 85 ? `The computer is busy (load ${F.cpu}%).` : '',
|
|
233
|
+
];
|
|
234
|
+
return lines.filter(Boolean).join('\n');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** For the assistant's prompt: what it notices, when any sense is on. */
|
|
238
|
+
function prompt() {
|
|
239
|
+
if (!anyOn()) return '';
|
|
240
|
+
return `What you notice about your human right now (your senses; hints, not facts — use them when relevant, never recite them):\n${digest()}`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async function reflect({ force = false } = {}) {
|
|
244
|
+
lastReflect = Date.now();
|
|
245
|
+
if (reflecting || brain.kind === 'lines' || !anyOn()) return null;
|
|
246
|
+
if (!force && (busy() || Date.now() < quietUntil || present !== true || paused())) return null;
|
|
247
|
+
reflecting = true;
|
|
248
|
+
try {
|
|
249
|
+
const mine = rules.map((r) => `- [${r.status}] ${r.name} ${JSON.stringify(r.when)} → ${r.then.type}`).join('\n');
|
|
250
|
+
const may = Date.now() - lastPropose > PROPOSE_GAP && rules.filter((r) => r.by === 'ot').length < MAX_OT_RULES;
|
|
251
|
+
const raw = await brain.think({
|
|
252
|
+
purpose: 'senses',
|
|
253
|
+
system: system(),
|
|
254
|
+
messages: [
|
|
255
|
+
{
|
|
256
|
+
role: 'user',
|
|
257
|
+
content: `You quietly look after your human and help them before they ask. What you know right now:\n${digest()}\n\nYour rules (automatic reactions):\n${mine || '(none)'}\n\nIs there ONE thing worth doing now? Most of the time there is not: then answer {"say":"","rule":null}.\n- "say": one short line to them in ${lang}, in character, useful or caring (a break, an upcoming meeting, a site eating their day, a tip about what they do). Never mention the camera or diagnose emotions as facts.\n${may ? `- "rule": only if you notice a pattern worth automating that none of your rules covers, propose ONE: {"name":"short, in ${lang}","why":"one line","when":{…},"then":{…},"cooldown":"60m"}. when keys: state (tired|tense|focused|sad|happy) + for ("5m"), streak (">90m"), away, app ("code"), site ("youtube"), appFor (">45m"), hour ("18-23"), meetingIn ("<15m"), battery ("<20"), mail ("urgent"). then: {"type":"say","about":"what to tell them; may use {streak} {app} {site} {meeting} {time}"} | {"type":"remind","text":"…","in":"0m"} | {"type":"quiet","for":"25m"}.` : '- "rule": null (no proposals now).'}\nAnswer ONLY the JSON object.`,
|
|
258
|
+
},
|
|
259
|
+
],
|
|
260
|
+
timeoutMs: 60000,
|
|
261
|
+
raw: true,
|
|
262
|
+
});
|
|
263
|
+
const j = JSON.parse(String(raw).match(/\{[\s\S]*\}/)?.[0] || '{}');
|
|
264
|
+
const say = clip(j.say, 300);
|
|
265
|
+
if (may && j.rule && typeof j.rule === 'object') {
|
|
266
|
+
let r = null;
|
|
267
|
+
try {
|
|
268
|
+
r = normalizeRule({ ...j.rule, status: 'proposed' }, { by: 'ot' });
|
|
269
|
+
} catch (e) {
|
|
270
|
+
log(`senses: proposed rule dropped (${e.message})`);
|
|
271
|
+
}
|
|
272
|
+
if (r && !rules.some((x) => JSON.stringify(x.when) === JSON.stringify(r.when) && x.then.type === r.then.type)) {
|
|
273
|
+
lastPropose = fired['@propose'] = Date.now();
|
|
274
|
+
writeJson(f('fired.json'), fired);
|
|
275
|
+
rules.push(r);
|
|
276
|
+
saveRules(rules);
|
|
277
|
+
log(`senses: proposes rule ${r.id} «${r.name}»`);
|
|
278
|
+
confirm(`${say ? `${say} ` : ''}${L.propose(r.name)}`).then((ok) => setRule(r.id, { status: ok ? 'active' : 'off' }));
|
|
279
|
+
return { say, rule: r };
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (say) await talk({ kind: 'reflect', text: say });
|
|
283
|
+
return { say, rule: null };
|
|
284
|
+
} catch (e) {
|
|
285
|
+
log(`senses reflect: ${e.message}`);
|
|
286
|
+
return null;
|
|
287
|
+
} finally {
|
|
288
|
+
reflecting = false;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// ── the camera page ──
|
|
293
|
+
async function onGesture(g) {
|
|
294
|
+
const now = Date.now();
|
|
295
|
+
if (!GESTURES.includes(g) || now - (lastGesture[g] || 0) < 1500) return;
|
|
296
|
+
lastGesture[g] = now;
|
|
297
|
+
day.gestures[g] = (day.gestures[g] || 0) + 1;
|
|
298
|
+
const a = gestures.map[g];
|
|
299
|
+
const c = conf();
|
|
300
|
+
if (asking() && (a?.type === 'confirm' || a?.type === 'reject')) {
|
|
301
|
+
answer(a.type === 'confirm');
|
|
302
|
+
return broadcast({ gesture: a.type === 'confirm' ? 'thumbsup' : 'thumbsdown', senses: { gesture: g } });
|
|
303
|
+
}
|
|
304
|
+
if (c.arm && g === 'open_palm') {
|
|
305
|
+
armedUntil = now + ARM_MS;
|
|
306
|
+
return broadcast({ gesture: 'wave', senses: { gesture: g, armed: armedUntil, hint: L.armed } });
|
|
307
|
+
}
|
|
308
|
+
if (!a || a.type === 'confirm' || a.type === 'reject') return broadcast({ senses: { gesture: g } });
|
|
309
|
+
if (a.type === 'react') return broadcast({ gesture: 'wave', effect: 'hearts', senses: { gesture: g } });
|
|
310
|
+
if (c.arm && now > armedUntil) return broadcast({ senses: { gesture: g, unarmed: true } });
|
|
311
|
+
armedUntil = 0;
|
|
312
|
+
log(`senses: gesture ${g} → ${a.type}`);
|
|
313
|
+
let ok = true;
|
|
314
|
+
let did = '';
|
|
315
|
+
if (a.type === 'media') (ok = await media(a.do)), (did = MEDIA_ICON[a.do]);
|
|
316
|
+
else if (a.type === 'key') (ok = await key(a.keys)), (did = '⌨');
|
|
317
|
+
else if (a.type === 'pause') return pause(a.for);
|
|
318
|
+
else if (a.type === 'ask') return ask(a.text);
|
|
319
|
+
else if (a.type === 'command') {
|
|
320
|
+
const cmd = gestures.commands[a.id];
|
|
321
|
+
if (!cmd) return;
|
|
322
|
+
if (!cmd.approved) {
|
|
323
|
+
if (!(await confirm(L.cmd(cmd.label)))) return;
|
|
324
|
+
cmd.approved = true;
|
|
325
|
+
saveGestures(gestures);
|
|
326
|
+
}
|
|
327
|
+
ok = await command(cmd);
|
|
328
|
+
did = '▶';
|
|
329
|
+
}
|
|
330
|
+
broadcast(ok ? { gesture: 'nod', senses: { gesture: g, did } } : { gesture: 'shrug', senses: { gesture: g, did: '✕', hint: L.failed } });
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function pause(min = 15) {
|
|
334
|
+
const until = Date.now() + Math.max(1, Math.min(240, Number(min) || 15)) * 60_000;
|
|
335
|
+
setConfig({ pausedUntil: until });
|
|
336
|
+
cam.on = false;
|
|
337
|
+
broadcast({ senses: { camera: 'paused', until, hint: L.paused(Math.round((until - Date.now()) / 60_000)) } });
|
|
338
|
+
return until;
|
|
339
|
+
}
|
|
340
|
+
let setConfig = () => {}; // the daemon saves senses.* (see bind)
|
|
341
|
+
|
|
342
|
+
/** Labels from the camera page: { kind: 'status'|'state'|'presence'|'gesture', … } */
|
|
343
|
+
function ingest(list) {
|
|
344
|
+
if (acc().camera !== true || paused()) {
|
|
345
|
+
if (cam.on) (cam.on = false), broadcast({ senses: { camera: paused() ? 'paused' : 'off' } });
|
|
346
|
+
return { ok: false, paused: paused() };
|
|
347
|
+
}
|
|
348
|
+
const now = Date.now();
|
|
349
|
+
for (const e of (Array.isArray(list) ? list : [list]).slice(0, 20)) {
|
|
350
|
+
if (!e || typeof e !== 'object') continue;
|
|
351
|
+
const wasOn = cam.on;
|
|
352
|
+
cam.on = true;
|
|
353
|
+
cam.at = now;
|
|
354
|
+
if (!wasOn) broadcast({ senses: { camera: 'on' } });
|
|
355
|
+
if (e.kind === 'status' && e.on === false) {
|
|
356
|
+
cam.on = false;
|
|
357
|
+
broadcast({ senses: { camera: 'off' } });
|
|
358
|
+
} else if (e.kind === 'state' && STATES.includes(e.state)) {
|
|
359
|
+
if (typeof e.present === 'boolean') cam.present = e.present;
|
|
360
|
+
if (e.scores && typeof e.scores === 'object') cam.scores = Object.fromEntries(STATES.map((s) => [s, Math.round(Math.max(0, Math.min(1, Number(e.scores[s]) || 0)) * 100) / 100]));
|
|
361
|
+
cam.score = Math.max(0, Math.min(1, Number(e.score) || 0));
|
|
362
|
+
if (e.state !== cam.state) {
|
|
363
|
+
cam.state = e.state;
|
|
364
|
+
cam.since = now;
|
|
365
|
+
emit({ source: 'camera', kind: 'state', value: { state: e.state, score: cam.score }, summary: `face reads ${e.state}` });
|
|
366
|
+
broadcast({ senses: { state: e.state } });
|
|
367
|
+
}
|
|
368
|
+
} else if (e.kind === 'presence' && typeof e.present === 'boolean') {
|
|
369
|
+
if (cam.present !== e.present) emit({ source: 'camera', kind: 'presence', value: { present: e.present }, summary: e.present ? 'back at the computer' : 'left the computer' });
|
|
370
|
+
cam.present = e.present;
|
|
371
|
+
} else if (e.kind === 'gesture' && typeof e.gesture === 'string') onGesture(e.gesture).catch((x) => log(`senses gesture: ${x.message}`));
|
|
372
|
+
}
|
|
373
|
+
return { ok: true };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ── for the settings page and the CLI ──
|
|
377
|
+
const anyOn = () => ['camera', 'activity', 'mail', 'calendar'].some((k) => acc()[k] === true);
|
|
378
|
+
function today() {
|
|
379
|
+
const top = (o, n = 8) => Object.entries(o).sort((a, b) => b[1] - a[1]).slice(0, n);
|
|
380
|
+
return { ...day, apps: top(day.apps), sites: top(day.sites) };
|
|
381
|
+
}
|
|
382
|
+
function status() {
|
|
383
|
+
const F = facts();
|
|
384
|
+
return {
|
|
385
|
+
on: anyOn(),
|
|
386
|
+
access: Object.fromEntries(SOURCES.filter((s) => s.access).map((s) => [s.access, acc()[s.access] === true])),
|
|
387
|
+
sources: SOURCES.map((s) => ({ ...s, ready: s.id === 'mail' ? mail.ready() : s.id === 'calendar' ? calendar.ready() : s.id === 'activity' ? activity.available : s.id === 'camera' ? camFresh() : s.available, error: s.id === 'mail' ? mail.error : s.id === 'calendar' ? calendar.error : '' })),
|
|
388
|
+
camera: { on: camFresh(), paused: paused(), pausedUntil: Number(config().senses?.pausedUntil) || 0, state: cam.state, score: cam.score, scores: cam.scores, present: cam.present, since: cam.since },
|
|
389
|
+
facts: { ...F, battery: F.battery },
|
|
390
|
+
quietUntil,
|
|
391
|
+
armedUntil,
|
|
392
|
+
today: today(),
|
|
393
|
+
upcoming: calendar.upcoming,
|
|
394
|
+
mail: acc().mail ? mail.latest : [],
|
|
395
|
+
recent: recent.slice(-30).reverse(),
|
|
396
|
+
rules,
|
|
397
|
+
gestures,
|
|
398
|
+
config: conf(),
|
|
399
|
+
baseline: Boolean(readJson(f('baseline.json'), null)),
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function setRule(id, patch) {
|
|
404
|
+
const i = rules.findIndex((r) => r.id === id);
|
|
405
|
+
if (i < 0) return null;
|
|
406
|
+
rules[i] = normalizeRule({ ...rules[i], ...patch, by: rules[i].by }, { by: rules[i].by });
|
|
407
|
+
saveRules(rules);
|
|
408
|
+
broadcast({ senses: { rules: true } });
|
|
409
|
+
return rules[i];
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
return {
|
|
413
|
+
ingest,
|
|
414
|
+
status,
|
|
415
|
+
prompt,
|
|
416
|
+
digest,
|
|
417
|
+
reflect,
|
|
418
|
+
pause,
|
|
419
|
+
facts,
|
|
420
|
+
bind(o) {
|
|
421
|
+
setConfig = o.setConfig || setConfig;
|
|
422
|
+
},
|
|
423
|
+
/** What the camera page needs. */
|
|
424
|
+
pageConfig() {
|
|
425
|
+
const c = conf();
|
|
426
|
+
return { on: acc().camera === true && !paused(), pausedUntil: Number(config().senses?.pausedUntil) || 0, holdMs: c.holdMs, fps: c.fps, arm: c.arm, baseline: readJson(f('baseline.json'), null), gestures: Object.keys(gestures.map), lang };
|
|
427
|
+
},
|
|
428
|
+
setBaseline(b) {
|
|
429
|
+
if (b === null) {
|
|
430
|
+
try {
|
|
431
|
+
unlinkSync(f('baseline.json'));
|
|
432
|
+
} catch {}
|
|
433
|
+
broadcast({ senses: { recalibrate: true } });
|
|
434
|
+
return true;
|
|
435
|
+
}
|
|
436
|
+
if (!b || typeof b !== 'object') return false;
|
|
437
|
+
const clean = Object.fromEntries(Object.entries(b).filter(([k, v]) => FEATURE.test(k) && Number.isFinite(Number(v))).slice(0, 60).map(([k, v]) => [k, Math.round(Number(v) * 10000) / 10000]));
|
|
438
|
+
writeJson(f('baseline.json'), { ...clean, at: Date.now() }, { secret: true });
|
|
439
|
+
log('senses: baseline saved');
|
|
440
|
+
return true;
|
|
441
|
+
},
|
|
442
|
+
quiet: () => Date.now() < quietUntil,
|
|
443
|
+
cameraOn: () => camFresh(),
|
|
444
|
+
setQuiet(ms) {
|
|
445
|
+
quietUntil = ms > 0 ? Date.now() + ms : 0;
|
|
446
|
+
broadcast({ senses: { quiet: quietUntil } });
|
|
447
|
+
},
|
|
448
|
+
get rules() {
|
|
449
|
+
return rules;
|
|
450
|
+
},
|
|
451
|
+
addRule(r) {
|
|
452
|
+
const n = normalizeRule({ ...r, status: r.status || 'active' }, { by: 'user' });
|
|
453
|
+
rules = [...rules.filter((x) => x.id !== n.id), n].slice(-100);
|
|
454
|
+
saveRules(rules);
|
|
455
|
+
return n;
|
|
456
|
+
},
|
|
457
|
+
setRule,
|
|
458
|
+
removeRule(id) {
|
|
459
|
+
const n = rules.length;
|
|
460
|
+
rules = rules.filter((r) => r.id !== id);
|
|
461
|
+
saveRules(rules);
|
|
462
|
+
return n !== rules.length;
|
|
463
|
+
},
|
|
464
|
+
/** Every proposed rule accepted or turned down from settings. */
|
|
465
|
+
get gestures() {
|
|
466
|
+
return gestures;
|
|
467
|
+
},
|
|
468
|
+
setGestures(d) {
|
|
469
|
+
gestures = normalizeGestures(d, gestures);
|
|
470
|
+
saveGestures(gestures);
|
|
471
|
+
broadcast({ senses: { gestures: Object.keys(gestures.map) } });
|
|
472
|
+
return gestures;
|
|
473
|
+
},
|
|
474
|
+
/** Deletes what it noticed (days, baseline, cooldowns). Rules and gestures stay. */
|
|
475
|
+
forget() {
|
|
476
|
+
for (const n of readdirSync(dir)) if (/^(day-.*|baseline|fired)\.json$/.test(n)) unlinkSync(f(n));
|
|
477
|
+
day = emptyDay(dayKey());
|
|
478
|
+
fired = {};
|
|
479
|
+
recent.length = 0;
|
|
480
|
+
broadcast({ senses: { recalibrate: true } });
|
|
481
|
+
log('senses: forgot everything noticed');
|
|
482
|
+
return true;
|
|
483
|
+
},
|
|
484
|
+
stop() {
|
|
485
|
+
clearInterval(timer);
|
|
486
|
+
clearTimeout(first);
|
|
487
|
+
saveDay();
|
|
488
|
+
},
|
|
489
|
+
};
|
|
490
|
+
}
|