@7ots/cli 0.1.17 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/.env.example +14 -0
  2. package/README.md +11 -0
  3. package/brand/logos/base.svg +1 -0
  4. package/brand/logos/clawpump.png +0 -0
  5. package/brand/logos/conductors.svg +1 -0
  6. package/brand/logos/notlogin.svg +12 -0
  7. package/brand/logos/pumpfun.png +0 -0
  8. package/brand/logos/solana.png +0 -0
  9. package/brand/logos/spawnerbot.svg +1 -0
  10. package/brand/logos/virtuals.png +0 -0
  11. package/cli/7ots.mjs +61 -1
  12. package/cli/lib/account.mjs +23 -3
  13. package/cli/lib/assistant.mjs +92 -14
  14. package/cli/lib/brain.mjs +84 -11
  15. package/cli/lib/card-shot.mjs +1 -1
  16. package/cli/lib/config.mjs +14 -3
  17. package/cli/lib/desktop-sync.mjs +177 -0
  18. package/cli/lib/i18n.mjs +9 -0
  19. package/cli/lib/inferences.mjs +19 -2
  20. package/cli/lib/integrations.mjs +98 -13
  21. package/cli/lib/mcp.mjs +1 -1
  22. package/cli/lib/open.mjs +3 -1
  23. package/cli/lib/pet-server.mjs +352 -41
  24. package/cli/lib/prompts.mjs +1 -1
  25. package/cli/lib/screen.mjs +1 -1
  26. package/cli/lib/senses/gestures.mjs +121 -0
  27. package/cli/lib/senses/index.mjs +490 -0
  28. package/cli/lib/senses/rules.mjs +159 -0
  29. package/cli/lib/senses/sources/activity.mjs +95 -0
  30. package/cli/lib/senses/sources/calendar.mjs +75 -0
  31. package/cli/lib/senses/sources/index.mjs +17 -0
  32. package/cli/lib/senses/sources/mail.mjs +48 -0
  33. package/cli/lib/senses/sources/system.mjs +39 -0
  34. package/cli/lib/senses/util.mjs +41 -0
  35. package/cli/lib/senses/vendor.mjs +78 -0
  36. package/cli/lib/stt-local.py +16 -8
  37. package/cli/lib/stt.mjs +53 -6
  38. package/cli/lib/tooluse.mjs +56 -0
  39. package/cli/lib/tts-local.mjs +2 -2
  40. package/cli/lib/vm.mjs +2 -2
  41. package/cli/lib/wake-local.py +109 -0
  42. package/cli/lib/wake.mjs +102 -0
  43. package/cli/pet/electron/main.cjs +190 -8
  44. package/cli/pet/pet.html +153 -34
  45. package/cli/pet/senses.html +342 -0
  46. package/cli/pet/settings.html +815 -74
  47. package/dist/7ots.esm.js +373 -146
  48. package/dist/7ots.esm.js.map +4 -4
  49. package/dist/7ots.iife.js +373 -146
  50. package/dist/7ots.iife.js.map +4 -4
  51. package/llms.txt +27 -0
  52. package/package.json +5 -2
  53. package/server/channels/apuchat.mjs +18 -4
  54. package/server/errors.mjs +90 -0
  55. package/server/notify.mjs +78 -0
  56. package/server/server.mjs +84 -14
  57. package/server/settings.mjs +3 -0
  58. package/server/site.mjs +401 -0
  59. package/server/tts.mjs +29 -5
  60. package/src/avatar/AvatarStage.js +2 -2
  61. package/src/avatar/three.js +3 -2
  62. package/src/character/AvatarEditor.js +2 -1
  63. package/src/character/Character.js +38 -5
  64. package/src/character/TradingCard.js +2 -0
  65. package/src/character/beat.js +64 -2
  66. package/src/character/mods/orc.js +8 -1
  67. package/src/character/mods.js +104 -10
  68. package/src/character/motion.js +252 -1
  69. package/src/character/parts.js +40 -38
  70. package/src/character/styles.js +40 -38
  71. package/src/character3d/Character3D.js +26 -5
  72. package/src/character3d/body.js +14 -12
  73. package/src/character3d/export.js +693 -0
  74. package/src/character3d/fx.js +13 -0
  75. package/src/character3d/index.js +2 -0
  76. package/src/character3d/materials.js +106 -10
  77. package/src/character3d/room-themes.js +1184 -0
  78. package/src/character3d/room.js +487 -0
  79. package/src/character3d/stage.js +14 -2
  80. package/src/creator/StepCreator.js +316 -0
  81. package/src/i18n/index.js +3 -3
  82. package/src/i18n/messages/character.js +352 -4
  83. package/src/i18n/messages/creator.js +138 -0
  84. package/src/i18n/messages/identity.js +89 -1
  85. package/src/i18n/messages/platform.js +270 -4
  86. package/src/i18n/messages/server.js +443 -1
  87. package/src/i18n/messages/widget.js +233 -0
  88. package/src/identity/random.js +14 -2
  89. package/src/identity/schema.js +2 -1
  90. package/src/index.js +9 -2
  91. package/src/voice/tags.js +22 -0
  92. package/server/platform/apuchat.mjs +0 -266
  93. package/server/platform/auth.mjs +0 -319
  94. package/server/platform/connect.mjs +0 -387
  95. package/server/platform/crypto.mjs +0 -80
  96. package/server/platform/db.mjs +0 -275
  97. package/server/platform/device.mjs +0 -222
  98. package/server/platform/integrations.mjs +0 -169
  99. package/server/platform/look.mjs +0 -20
  100. package/server/platform/mods.mjs +0 -222
  101. package/server/platform/orquesta.mjs +0 -577
  102. package/server/platform/profile.mjs +0 -161
  103. package/server/platform/routes.mjs +0 -542
  104. package/server/platform/runtime.mjs +0 -242
  105. package/server/platform/sites.mjs +0 -146
  106. package/server/platform/store.mjs +0 -456
  107. package/server/platform/vm.mjs +0 -1057
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Rules: "when this holds, do that". ~/.7ots/rules.json, a list of
3
+ *
4
+ * { id, name, when: { state: 'tired', for: '3m', streak: '>60m', … }, then: { type: 'say', about: '…' },
5
+ * cooldown: '60m', by: '7ots' | 'user' | 'ot', status: 'active' | 'proposed' | 'off' }
6
+ *
7
+ * when (all must hold):
8
+ * state 'tired'|'tense'|'focused'|'sad'|'happy'|'neutral' what the camera reads, held for `for`
9
+ * streak '>90m' time at the computer without a break (5 min away = a break)
10
+ * away '>10m' time away right now
11
+ * app 'code' the active app contains this (case-insensitive); site likewise ('youtube')
12
+ * appFor '>45m' time on that app/site today
13
+ * hour '18-23' local hour range (wraps: '22-6')
14
+ * meetingIn '<11m' next calendar event
15
+ * battery '<15' percent, only when not charging
16
+ * mail 'urgent' | 'new' an email (urgent-looking) in the last 10 min
17
+ * then:
18
+ * say a line in character; `about` tells the brain what to talk about ({streak} {state} {app} {site}
19
+ * {meeting} {meetingIn} {battery} {mail} {time}), `text` is said as is (or when there is no brain)
20
+ * remind a reminder `text` in `in` ('10m'), like "remind me…"
21
+ * quiet quiet mode for `for` ('25m'): no comments, no reflector
22
+ * notify a desktop notification `text`
23
+ * The ot proposes rules of its own (by: 'ot', status: 'proposed'); they only start when you accept them.
24
+ */
25
+
26
+ import { homeFile, readJson, writeJson } from '../paths.mjs';
27
+ import { clip, cmp, cmpOf, dur, human } from './util.mjs';
28
+
29
+ export const STATES = ['tired', 'tense', 'focused', 'sad', 'happy', 'neutral'];
30
+ const THEN = ['say', 'remind', 'quiet', 'notify'];
31
+ const ID_RE = /^[\w-]{1,40}$/;
32
+
33
+ export const SEED_RULES = [
34
+ { id: 'seed-tired-break', name: 'Tired and no break → suggest a rest', when: { state: 'tired', for: '3m', streak: '>60m' }, then: { type: 'say', about: 'They look tired and have been at the computer for {streak} without a break. Suggest a short break (stand up, water, look away from the screen) and offer to remind them later.' }, cooldown: '60m' },
35
+ { id: 'seed-long-streak', name: 'Over 2 h non-stop → a break', when: { streak: '>120m' }, then: { type: 'say', about: 'They have been working {streak} non-stop. Suggest a 5 minute break, kindly.' }, cooldown: '90m' },
36
+ { id: 'seed-focus-quiet', name: 'Focused → quiet mode', when: { state: 'focused', for: '5m' }, then: { type: 'quiet', for: '25m' }, cooldown: '25m' },
37
+ { id: 'seed-tense-help', name: 'Tense → offer help', when: { state: 'tense', for: '4m' }, then: { type: 'say', about: 'They look tense or frustrated (on {app}). Gently offer help with what they are doing, or a breather. One line, no lecture.' }, cooldown: '45m' },
38
+ { id: 'seed-sad', name: 'Down → keep them company', when: { state: 'sad', for: '8m' }, then: { type: 'say', about: 'They look a bit down. Be warm and brief: ask if they want to talk or a small distraction.' }, cooldown: '120m' },
39
+ { id: 'seed-meeting', name: 'Meeting in 10 min → tell me', when: { meetingIn: '<11m' }, then: { type: 'say', about: 'Their calendar event «{meeting}» starts in {meetingIn}. Tell them, and if they have been at it for long ({streak}) suggest a quick stretch first.' }, cooldown: '20m' },
40
+ { id: 'seed-mail-urgent', name: 'Urgent email → tell me', when: { mail: 'urgent' }, then: { type: 'say', about: 'An email that looks urgent just arrived: {mail}. Tell them in one line (do not read it out).' }, cooldown: '10m' },
41
+ { id: 'seed-battery', name: 'Low battery → tell me', when: { battery: '<15' }, then: { type: 'say', about: 'The battery is at {battery}% and not charging. Tell them to plug it in.' }, cooldown: '30m' },
42
+ { id: 'seed-late', name: 'Very late → suggest sleeping', when: { hour: '1-5', streak: '>30m' }, then: { type: 'say', about: 'It is very late ({time}) and they are still at it. Kindly suggest wrapping up and sleeping.' }, cooldown: '120m' },
43
+ ].map((r) => ({ ...r, by: '7ots', status: 'active' }));
44
+
45
+ /** Cleans a rule (from the file, the settings page or the brain). Throws on what cannot be a rule. */
46
+ export function normalizeRule(r = {}, { by } = {}) {
47
+ if (!r || typeof r !== 'object') throw new Error('rule');
48
+ const w = r.when && typeof r.when === 'object' ? r.when : {};
49
+ const when = {};
50
+ if (w.state !== undefined) {
51
+ if (!STATES.includes(w.state)) throw new Error('when.state');
52
+ when.state = w.state;
53
+ if (w.for !== undefined) {
54
+ if (!Number.isFinite(dur(w.for))) throw new Error('when.for');
55
+ when.for = String(w.for);
56
+ }
57
+ }
58
+ for (const k of ['streak', 'away', 'appFor', 'meetingIn']) {
59
+ if (w[k] === undefined) continue;
60
+ if (!cmpOf(w[k])) throw new Error(`when.${k}`);
61
+ when[k] = String(w[k]).replace(/\s+/g, '');
62
+ }
63
+ if (w.battery !== undefined) {
64
+ if (!cmpOf(w.battery, false)) throw new Error('when.battery');
65
+ when.battery = String(w.battery).replace(/\s+/g, '');
66
+ }
67
+ for (const k of ['app', 'site']) if (w[k] !== undefined && clip(w[k], 60)) when[k] = clip(w[k], 60).toLowerCase();
68
+ if (w.hour !== undefined) {
69
+ const m = /^(\d{1,2})-(\d{1,2})$/.exec(String(w.hour).replace(/\s+/g, ''));
70
+ if (!m || +m[1] > 23 || +m[2] > 24) throw new Error('when.hour');
71
+ when.hour = `${+m[1]}-${+m[2]}`;
72
+ }
73
+ if (w.mail !== undefined) {
74
+ if (!['urgent', 'new'].includes(w.mail)) throw new Error('when.mail');
75
+ when.mail = w.mail;
76
+ }
77
+ if (!Object.keys(when).length) throw new Error('when');
78
+ const t = r.then && typeof r.then === 'object' ? r.then : {};
79
+ if (!THEN.includes(t.type)) throw new Error('then.type');
80
+ const then = { type: t.type };
81
+ if (t.about) then.about = clip(t.about, 400);
82
+ if (t.text) then.text = clip(t.text, 200);
83
+ if (t.type === 'remind') {
84
+ if (!then.text) throw new Error('then.text');
85
+ then.in = Number.isFinite(dur(t.in ?? '0m')) ? String(t.in ?? '0m') : '0m';
86
+ }
87
+ if (t.type === 'notify' && !then.text) throw new Error('then.text');
88
+ if (t.type === 'say' && !then.text && !then.about) throw new Error('then.about');
89
+ if (t.type === 'quiet') then.for = Number.isFinite(dur(t.for)) ? String(t.for) : '25m';
90
+ const cd = Number.isFinite(dur(r.cooldown)) ? String(r.cooldown) : '60m';
91
+ return {
92
+ id: ID_RE.test(String(r.id || '')) ? r.id : `r-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`,
93
+ name: clip(r.name, 100) || describe({ when, then }),
94
+ when,
95
+ then,
96
+ cooldown: dur(cd) < 60_000 ? '1m' : cd,
97
+ by: by || (['7ots', 'user', 'ot'].includes(r.by) ? r.by : 'user'),
98
+ status: ['active', 'proposed', 'off'].includes(r.status) ? r.status : 'active',
99
+ ...(r.why ? { why: clip(r.why, 300) } : {}),
100
+ ...(r.at ? { at: Number(r.at) || Date.now() } : { at: Date.now() }),
101
+ };
102
+ }
103
+
104
+ /** A plain description, for rules without a name. */
105
+ export function describe(r) {
106
+ const w = Object.entries(r.when).map(([k, v]) => `${k} ${v}`).join(' + ');
107
+ return `${w} → ${r.then.type}${r.then.text ? ` «${r.then.text}»` : ''}`.slice(0, 100);
108
+ }
109
+
110
+ const FILE = () => homeFile('rules.json');
111
+ export function loadRules() {
112
+ const raw = readJson(FILE(), null);
113
+ if (!Array.isArray(raw)) return SEED_RULES.map((r) => normalizeRule(r, { by: '7ots' }));
114
+ const out = [];
115
+ for (const r of raw.slice(0, 100)) {
116
+ try {
117
+ out.push(normalizeRule(r));
118
+ } catch {}
119
+ }
120
+ return out;
121
+ }
122
+ export function saveRules(rules) {
123
+ writeJson(FILE(), rules);
124
+ }
125
+
126
+ /** Whether a rule's `when` holds for these facts (see senses/index.mjs facts()). */
127
+ export function holds(when, f) {
128
+ if (when.state && (f.state !== when.state || f.stateFor < (dur(when.for) || 0))) return false;
129
+ if (when.streak && !cmp(f.streak, cmpOf(when.streak))) return false;
130
+ if (when.away && !cmp(f.away, cmpOf(when.away))) return false;
131
+ if (when.app && !String(f.app || '').toLowerCase().includes(when.app)) return false;
132
+ if (when.site && !String(f.site || '').toLowerCase().includes(when.site)) return false;
133
+ if (when.appFor && !cmp(f.appFor, cmpOf(when.appFor))) return false;
134
+ if (when.meetingIn && !(f.meetingIn > 0 && cmp(f.meetingIn, cmpOf(when.meetingIn)))) return false;
135
+ if (when.battery && !(f.battery && !f.battery.charging && cmp(f.battery.pct, cmpOf(when.battery, false)))) return false;
136
+ if (when.mail && !(when.mail === 'urgent' ? f.mailUrgent : f.mailNew)) return false;
137
+ if (when.hour) {
138
+ const [a, b] = when.hour.split('-').map(Number);
139
+ const h = new Date(f.now).getHours();
140
+ if (!(a <= b ? h >= a && h < b : h >= a || h < b)) return false;
141
+ }
142
+ return true;
143
+ }
144
+
145
+ /** {streak} {state} … in a rule's text, from the facts. */
146
+ export function fill(s, f) {
147
+ const v = {
148
+ streak: human(f.streak),
149
+ state: f.state || 'neutral',
150
+ app: f.app || '?',
151
+ site: f.site || '?',
152
+ meeting: f.meeting || '',
153
+ meetingIn: human(f.meetingIn),
154
+ battery: f.battery?.pct ?? '?',
155
+ mail: f.mailLast || '',
156
+ time: new Date(f.now).toTimeString().slice(0, 5),
157
+ };
158
+ return String(s || '').replace(/\{(\w+)\}/g, (m, k) => (k in v ? String(v[k]) : m));
159
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Activity (access.activity): which app and site you are on and whether you are at the keyboard, every 15 s.
3
+ * · Linux X11: xdotool + xprop (the active window), xprintidle when installed, else "the mouse or window moved".
4
+ * · macOS: the frontmost app (osascript) and HIDIdleTime (ioreg). No window titles (they need Accessibility).
5
+ * · Elsewhere: nothing (the camera, when on, still says whether you are there).
6
+ * Only the app and a site label leave this file; the window title stays in memory for the current reading.
7
+ */
8
+
9
+ import { run } from '../util.mjs';
10
+
11
+ const BROWSER = /firefox|chrom|brave|edge|opera|vivaldi|safari|librewolf/i;
12
+ const KNOWN = /\b(Google (Calendar|Calendario|Agenda|Docs|Sheets|Drive|Meet)|Gmail|YouTube|GitHub|GitLab|WhatsApp|Slack|Discord|Notion|Figma|Jira|Linear|Trello|Netflix|Twitch|Spotify|Reddit|LinkedIn|Instagram|Facebook|ChatGPT|Claude|Stack Overflow|Wikipedia|Outlook|Teams|Zoom|Amazon|Mercado Libre)\b/;
13
+ const SUFFIX = /\s[-—–|]\s(Mozilla Firefox|Firefox|Google Chrome|Chromium|Brave|Microsoft Edge|Opera|Vivaldi|LibreWolf|Zen Browser|Safari)\s*$/i;
14
+
15
+ /** A browser window's title → the site it shows ("Video - YouTube — Mozilla Firefox" → "YouTube"). */
16
+ export function siteOf(title = '') {
17
+ const t = String(title).replace(SUFFIX, '').replace(/^\(\d+\)\s*/, '').trim();
18
+ if (!t) return '';
19
+ const dom = t.match(/\b([a-z0-9-]+\.)+(com|org|net|io|dev|app|ai|cl|ar|br|es|co|me|tv|gg|xyz)\b/i);
20
+ if (dom) return dom[0].toLowerCase().replace(/^www\./, '');
21
+ const known = t.match(KNOWN);
22
+ if (known) return known[0].replace(/\s+/g, ' ');
23
+ // the site's name is usually the last part; skip parts that read like a page (dates, numbers, sentences)
24
+ const parts = t.split(/\s[-—–|·]\s/).map((s) => s.trim()).filter(Boolean);
25
+ if (parts.length < 2) return '';
26
+ return parts.reverse().find((p) => p.length <= 24 && !/\d/.test(p) && p.split(/\s+/).length <= 3) || '';
27
+ }
28
+
29
+ export function createActivity({ enabled, log = () => {} }) {
30
+ const x11 = process.platform === 'linux' && process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;
31
+ let hasIdle = null; // xprintidle installed?
32
+ let lastInput = Date.now();
33
+ let lastMouse = '';
34
+ let lastKey = '';
35
+ let now = null; // { app, site, title, idleMs, at }
36
+
37
+ async function idleMs() {
38
+ if (process.platform === 'darwin') {
39
+ const out = await run('ioreg', ['-c', 'IOHIDSystem', '-d', '4']);
40
+ const ns = Number(out?.match(/"HIDIdleTime"\s*=\s*(\d+)/)?.[1]);
41
+ return Number.isFinite(ns) ? ns / 1e6 : null;
42
+ }
43
+ if (!x11) return null;
44
+ if (hasIdle !== false) {
45
+ const out = await run('xprintidle', []);
46
+ hasIdle = out != null;
47
+ if (hasIdle) return Number(out) || 0;
48
+ }
49
+ const mouse = (await run('xdotool', ['getmouselocation'])) || '';
50
+ if (mouse !== lastMouse) (lastMouse = mouse), (lastInput = Date.now());
51
+ return Date.now() - lastInput;
52
+ }
53
+
54
+ async function window() {
55
+ if (process.platform === 'darwin') {
56
+ const app = await run('osascript', ['-e', 'tell application "System Events" to get name of first application process whose frontmost is true']);
57
+ return app ? { app, title: '' } : null;
58
+ }
59
+ if (!x11) return null;
60
+ const id = await run('xdotool', ['getactivewindow']);
61
+ if (!id) return null;
62
+ const [title, cls] = await Promise.all([run('xdotool', ['getwindowname', id]), run('xprop', ['-id', id, 'WM_CLASS'])]);
63
+ const app = String(cls || '').match(/"([^"]*)"\s*$/)?.[1] || '';
64
+ return { app, title: String(title || '').slice(0, 200) };
65
+ }
66
+
67
+ async function tick() {
68
+ if (!enabled()) return (now = null);
69
+ try {
70
+ const [w, idle] = await Promise.all([window(), idleMs()]);
71
+ const key = `${w?.app}|${w?.title}`;
72
+ if (key !== lastKey) (lastKey = key), hasIdle === false && (lastInput = Date.now()); // switching windows is input too
73
+ const ownWindow = /7ots/i.test(w?.title || '') || /^7ots/i.test(w?.app || '');
74
+ now = {
75
+ app: ownWindow ? now?.app || '' : String(w?.app || '').slice(0, 60),
76
+ site: ownWindow ? now?.site || '' : BROWSER.test(w?.app || '') ? siteOf(w?.title).slice(0, 60) : '',
77
+ title: ownWindow ? now?.title || '' : w?.title || '',
78
+ idleMs: idle,
79
+ at: Date.now(),
80
+ };
81
+ } catch (e) {
82
+ log(`activity: ${e.message}`);
83
+ }
84
+ return now;
85
+ }
86
+
87
+ return {
88
+ id: 'activity',
89
+ tick,
90
+ get now() {
91
+ return now && Date.now() - now.at < 60_000 ? now : null;
92
+ },
93
+ available: Boolean(x11 || process.platform === 'darwin'),
94
+ };
95
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Calendar (access.calendar): the private ICS address of your calendars (Google Calendar → Settings → "Secret
3
+ * address in iCal format"; Outlook, iCloud and Proton have one too), kept as the key SENSES_ICS_URL in
4
+ * ~/.7ots/keys.json (several separated by spaces). Read every 15 minutes; only the next 24 h of timed events
5
+ * stay in memory (title and start). Repeating events (RRULE) count only on their first date.
6
+ */
7
+
8
+ import { env } from '../../config.mjs';
9
+
10
+ /** "20261008T150000Z" | "20261008T150000" (local) | "20261008" (all day → null) → ms */
11
+ function icsTime(v, params = '') {
12
+ const m = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/.exec(v.trim());
13
+ if (!m || !m[4] || /VALUE=DATE(?!-)/.test(params)) return null;
14
+ const [y, mo, d, h, mi, s] = m.slice(1, 7).map(Number);
15
+ return m[7] ? Date.UTC(y, mo - 1, d, h, mi, s) : new Date(y, mo - 1, d, h, mi, s).getTime(); // TZID: read as local
16
+ }
17
+
18
+ export function parseIcs(text) {
19
+ const lines = String(text).replace(/\r\n[ \t]/g, '').replace(/\n[ \t]/g, '').split(/\r?\n/);
20
+ const out = [];
21
+ let ev = null;
22
+ for (const l of lines) {
23
+ if (l === 'BEGIN:VEVENT') ev = {};
24
+ else if (l === 'END:VEVENT') {
25
+ if (ev?.start && ev.status !== 'CANCELLED') out.push({ title: ev.title || '(sin título)', start: ev.start });
26
+ ev = null;
27
+ } else if (ev) {
28
+ const i = l.indexOf(':');
29
+ if (i < 0) continue;
30
+ const [name, ...params] = l.slice(0, i).split(';');
31
+ const val = l.slice(i + 1);
32
+ if (name === 'DTSTART') ev.start = icsTime(val, params.join(';'));
33
+ else if (name === 'SUMMARY') ev.title = val.replace(/\\([,;\\])/g, '$1').replace(/\\n/gi, ' ').slice(0, 120);
34
+ else if (name === 'STATUS') ev.status = val.trim().toUpperCase();
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+
40
+ export function createCalendar({ config, log = () => {} }) {
41
+ let events = [];
42
+ let err = '';
43
+ const urls = () => String(env().SENSES_ICS_URL || '').split(/\s+/).filter((u) => /^(https?|webcal):\/\//i.test(u));
44
+ const ready = () => config().access?.calendar === true && urls().length > 0;
45
+ return {
46
+ id: 'calendar',
47
+ ready,
48
+ async tick() {
49
+ if (!ready()) return (events = []);
50
+ const now = Date.now();
51
+ const all = [];
52
+ for (const u of urls().slice(0, 5)) {
53
+ try {
54
+ const r = await fetch(u.replace(/^webcal:/i, 'https:'), { signal: AbortSignal.timeout(20000) });
55
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
56
+ all.push(...parseIcs((await r.text()).slice(0, 8_000_000)));
57
+ err = '';
58
+ } catch (e) {
59
+ if (e.message !== err) log(`senses calendar: ${(err = e.message)}`); // never the URL: it is a secret
60
+ }
61
+ }
62
+ events = all.filter((e) => e.start > now - 30 * 60_000 && e.start < now + 24 * 3_600_000).sort((a, b) => a.start - b.start).slice(0, 20);
63
+ },
64
+ /** The next event that has not started yet: { title, start } */
65
+ get next() {
66
+ return events.find((e) => e.start > Date.now()) || null;
67
+ },
68
+ get upcoming() {
69
+ return events.filter((e) => e.start > Date.now()).slice(0, 5);
70
+ },
71
+ get error() {
72
+ return err;
73
+ },
74
+ };
75
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The data sources the senses can use, as the settings page lists them. Adding one = a module here with
3
+ * { id, ready(), tick(), … } wired in senses/index.mjs, plus its own access key (off by default).
4
+ *
5
+ * WhatsApp is listed but not available: personal accounts have no official API (only WhatsApp Business), and
6
+ * the unofficial WhatsApp Web clients break its terms and can get the number banned. It will come through the
7
+ * Business API or a bridge you run yourself.
8
+ */
9
+
10
+ export const SOURCES = [
11
+ { id: 'camera', access: 'camera', available: true },
12
+ { id: 'activity', access: 'activity', available: true },
13
+ { id: 'system', access: null, available: true },
14
+ { id: 'mail', access: 'mail', available: true, needs: 'apumail' },
15
+ { id: 'calendar', access: 'calendar', available: true, needs: 'SENSES_ICS_URL' },
16
+ { id: 'whatsapp', access: 'whatsapp', available: false },
17
+ ];
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Email (access.mail, plus Integrations → email on with APUMAIL_TOKEN): every 5 minutes, which mails are new.
3
+ * Only who, the subject and "looks urgent" become events; the body never leaves here.
4
+ */
5
+
6
+ import { mailMessages } from '../../integrations.mjs';
7
+ import { env } from '../../config.mjs';
8
+
9
+ const URGENT = /\b(urgente?|asap|importante|important|cr[ií]tico|critical|hoy mismo|deadline|vence hoy|plazo|incidente?|incident|ca[ií]do|outage)\b/i;
10
+
11
+ export function createMail({ config, emit, log = () => {} }) {
12
+ const seen = new Set();
13
+ let primed = false;
14
+ let last = [];
15
+ let err = '';
16
+ const ready = () => {
17
+ const c = config();
18
+ return c.access?.mail === true && c.integrations?.apumail?.on && Boolean(env().APUMAIL_TOKEN);
19
+ };
20
+ return {
21
+ id: 'mail',
22
+ ready,
23
+ async tick() {
24
+ if (!ready()) return (primed = false), seen.clear();
25
+ try {
26
+ const list = await mailMessages(config().integrations.apumail.inbox, { n: 15 });
27
+ err = '';
28
+ const fresh = list.filter((m) => !seen.has(m.id));
29
+ for (const m of list) seen.add(m.id);
30
+ if (seen.size > 500) for (const id of [...seen].slice(0, 200)) seen.delete(id);
31
+ last = list.slice(0, 5).map((m) => ({ at: m.at, from: m.from, subject: m.subject, urgent: URGENT.test(`${m.subject} ${m.text}`) }));
32
+ if (!primed) return (primed = true); // what was already there is not news
33
+ for (const m of fresh.slice(0, 5)) {
34
+ const urgent = URGENT.test(`${m.subject} ${m.text}`);
35
+ emit({ source: 'mail', kind: 'message', value: { from: m.from, subject: m.subject, urgent }, summary: `email from ${m.from}: «${m.subject || '(no subject)'}»`, urgency: urgent ? 2 : 0 });
36
+ }
37
+ } catch (e) {
38
+ if (e.message !== err) log(`senses mail: ${(err = e.message)}`);
39
+ }
40
+ },
41
+ get latest() {
42
+ return last;
43
+ },
44
+ get error() {
45
+ return err;
46
+ },
47
+ };
48
+ }
@@ -0,0 +1,39 @@
1
+ /** The computer itself (always on, nothing leaves it): load, memory and battery, read once a minute. */
2
+
3
+ import { readdirSync, readFileSync } from 'node:fs';
4
+ import { cpus, freemem, loadavg, totalmem } from 'node:os';
5
+ import { run } from '../util.mjs';
6
+
7
+ async function battery() {
8
+ if (process.platform === 'linux') {
9
+ try {
10
+ const b = readdirSync('/sys/class/power_supply').find((d) => /^BAT/i.test(d));
11
+ if (!b) return null;
12
+ const r = (f) => readFileSync(`/sys/class/power_supply/${b}/${f}`, 'utf8').trim();
13
+ return { pct: Number(r('capacity')), charging: !/discharging/i.test(r('status')) };
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+ if (process.platform === 'darwin') {
19
+ const out = await run('pmset', ['-g', 'batt']);
20
+ const pct = Number(out?.match(/(\d+)%/)?.[1]);
21
+ return Number.isFinite(pct) ? { pct, charging: !/discharging/i.test(out) } : null;
22
+ }
23
+ return null;
24
+ }
25
+
26
+ export function createSystem() {
27
+ let now = null;
28
+ return {
29
+ id: 'system',
30
+ async tick() {
31
+ const n = cpus().length || 1;
32
+ now = { cpu: Math.round((loadavg()[0] / n) * 100), mem: Math.round((1 - freemem() / totalmem()) * 100), battery: await battery(), at: Date.now() };
33
+ return now;
34
+ },
35
+ get now() {
36
+ return now;
37
+ },
38
+ };
39
+ }
@@ -0,0 +1,41 @@
1
+ /** Small helpers shared by the senses: durations, comparisons, a quiet child process, days on disk. */
2
+
3
+ import { execFile } from 'node:child_process';
4
+
5
+ export const run = (cmd, args, ms = 4000) =>
6
+ new Promise((res) => execFile(cmd, args, { timeout: ms, windowsHide: true }, (e, out) => res(e ? null : String(out).trim())));
7
+
8
+ /** '90s' | '20m' | '2h' | 15 (minutes) → ms. Anything else → NaN. */
9
+ export function dur(v) {
10
+ if (typeof v === 'number') return v * 60_000;
11
+ const m = /^\s*(\d+(?:\.\d+)?)\s*(s|m|h|d)?\s*$/i.exec(String(v ?? ''));
12
+ if (!m) return NaN;
13
+ return Number(m[1]) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[(m[2] || 'm').toLowerCase()];
14
+ }
15
+
16
+ /** '>90m' / '<15' / '>=2h' → { op, v } (v in ms when it has a unit or `time`, else a number). */
17
+ export function cmpOf(s, time = true) {
18
+ const m = /^\s*(>=|<=|>|<)\s*(.+)$/.exec(String(s ?? ''));
19
+ if (!m) return null;
20
+ const v = time ? dur(m[2]) : Number(m[2]);
21
+ return Number.isFinite(v) ? { op: m[1], v } : null;
22
+ }
23
+ export function cmp(x, c) {
24
+ if (!c || x == null || !Number.isFinite(x)) return false;
25
+ return c.op === '>' ? x > c.v : c.op === '<' ? x < c.v : c.op === '>=' ? x >= c.v : x <= c.v;
26
+ }
27
+
28
+ /** 5_400_000 → '1h30', 600_000 → '10 min' */
29
+ export function human(ms) {
30
+ if (!Number.isFinite(ms) || ms < 0) return '?';
31
+ const m = Math.round(ms / 60_000);
32
+ if (m < 60) return `${m} min`;
33
+ return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`;
34
+ }
35
+
36
+ export const dayKey = (t = Date.now()) => {
37
+ const d = new Date(t);
38
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
39
+ };
40
+
41
+ export const clip = (s, n) => String(s ?? '').replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, n);
@@ -0,0 +1,78 @@
1
+ /**
2
+ * MediaPipe Tasks Vision for the camera page (/senses), downloaded once on first use into ~/.7ots/senses/vendor
3
+ * (≈35 MB: not shipped in the app) and served from the daemon, so the page never loads code from the internet.
4
+ * Every file is pinned by version and sha256: a file that does not match is not kept.
5
+ */
6
+
7
+ import { createHash } from 'node:crypto';
8
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { homeFile } from '../paths.mjs';
11
+
12
+ const MP = 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.35';
13
+ const MODELS = 'https://storage.googleapis.com/mediapipe-models';
14
+
15
+ /** published name → { url, sha256, type } */
16
+ export const VENDOR = {
17
+ 'vision_bundle.mjs': { url: `${MP}/vision_bundle.mjs`, sha256: '55d7ab624fbb70dcc5adc4ae6d7ea9cfcb569139d3dbfbf2b1deafcb966bc0fe', type: 'text/javascript; charset=utf-8' },
18
+ 'vision_wasm_internal.js': { url: `${MP}/wasm/vision_wasm_internal.js`, sha256: 'e7fd9858e8e8f221d9b96eddc11f8e077f263e0b7bbd79d3cbe882b134274f8c', type: 'text/javascript; charset=utf-8' },
19
+ 'vision_wasm_internal.wasm': { url: `${MP}/wasm/vision_wasm_internal.wasm`, sha256: '6a5c64584c2ab61c763b6e204afbdbc7ce1caf7f5216187322bca8df94f646bc', type: 'application/wasm' },
20
+ 'face_landmarker.task': { url: `${MODELS}/face_landmarker/face_landmarker/float16/1/face_landmarker.task`, sha256: '64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff', type: 'application/octet-stream' },
21
+ 'gesture_recognizer.task': { url: `${MODELS}/gesture_recognizer/gesture_recognizer/float16/1/gesture_recognizer.task`, sha256: '97952348cf6a6a4915c2ea1496b4b37ebabc50cbbf80571435643c455f2b0482', type: 'application/octet-stream' },
22
+ };
23
+
24
+ const dir = () => homeFile(join('senses', 'vendor'));
25
+ const sha = (buf) => createHash('sha256').update(buf).digest('hex');
26
+ const okFile = new Map(); // name → mtime already checked
27
+
28
+ function present(name) {
29
+ const f = join(dir(), name);
30
+ if (!existsSync(f)) return false;
31
+ const m = statSync(f).mtimeMs;
32
+ if (okFile.get(name) === m) return true;
33
+ const good = sha(readFileSync(f)) === VENDOR[name].sha256;
34
+ if (good) okFile.set(name, m);
35
+ return good;
36
+ }
37
+
38
+ let fetching = null;
39
+ let progress = { done: 0, total: Object.keys(VENDOR).length, error: '' };
40
+
41
+ /** { ready, done, total, error } */
42
+ export function vendorStatus() {
43
+ const done = Object.keys(VENDOR).filter(present).length;
44
+ return { ready: done === progress.total, done, total: progress.total, busy: !!fetching, error: progress.error };
45
+ }
46
+
47
+ /** Downloads what is missing (once at a time). Resolves with vendorStatus(). */
48
+ export function ensureVendor(log = () => {}) {
49
+ if (vendorStatus().ready) return Promise.resolve(vendorStatus());
50
+ fetching ||= (async () => {
51
+ progress.error = '';
52
+ mkdirSync(dir(), { recursive: true, mode: 0o700 });
53
+ for (const [name, v] of Object.entries(VENDOR)) {
54
+ if (present(name)) continue;
55
+ log(`senses: downloading ${name}`);
56
+ const r = await fetch(v.url, { signal: AbortSignal.timeout(180_000) });
57
+ if (!r.ok) throw new Error(`${name}: HTTP ${r.status}`);
58
+ const buf = Buffer.from(await r.arrayBuffer());
59
+ if (sha(buf) !== v.sha256) throw new Error(`${name}: checksum mismatch`);
60
+ const f = join(dir(), name);
61
+ writeFileSync(`${f}.part`, buf);
62
+ renameSync(`${f}.part`, f);
63
+ }
64
+ log('senses: camera models ready');
65
+ })()
66
+ .catch((e) => {
67
+ progress.error = e.message;
68
+ log(`senses: ${e.message}`);
69
+ })
70
+ .finally(() => (fetching = null));
71
+ return fetching.then(vendorStatus);
72
+ }
73
+
74
+ /** The file to serve for /senses/vendor/<name>, or null. */
75
+ export function vendorFile(name) {
76
+ if (!Object.hasOwn(VENDOR, name) || !present(name)) return null;
77
+ return { file: join(dir(), name), type: VENDOR[name].type };
78
+ }
@@ -1,14 +1,22 @@
1
- """Local speech to text for the 7ots pet: python stt-local.py <audio file> [lang] [model] → prints the text.
2
- Runs in the venv ~/.7ots/stt (pip install faster-whisper); the model (base, ~140 MB) is cached on first use.
3
- Audio is decoded with ffmpeg (16 kHz mono) instead of PyAV, whose newer releases break faster-whisper."""
1
+ """Local speech to text for the 7ots pet, a worker that keeps the Whisper model loaded (loading it took ~3 s of each
2
+ ~12 s clip): python stt-local.py [model] reads JSON lines {"file": "/tmp/x.webm", "lang": "es"} and answers one JSON
3
+ line {"text": …} or {"error": …}. Runs in the venv ~/.7ots/stt (pip install faster-whisper); the model (base,
4
+ ~140 MB) is cached on first use. Audio is decoded with ffmpeg (16 kHz mono) instead of PyAV, whose newer releases
5
+ break faster-whisper. A fixed language matters: detecting it on a short, noisy clip often lands on the wrong one."""
6
+ import json
4
7
  import subprocess
5
8
  import sys
6
9
 
7
10
  import numpy as np
8
11
  from faster_whisper import WhisperModel
9
12
 
10
- pcm = subprocess.run(['ffmpeg', '-nostdin', '-loglevel', 'error', '-i', sys.argv[1], '-f', 'f32le', '-ac', '1', '-ar', '16000', '-'], capture_output=True, check=True).stdout
11
- audio = np.frombuffer(pcm, dtype=np.float32)
12
- model = WhisperModel(sys.argv[3] if len(sys.argv) > 3 else 'base', device='cpu', compute_type='int8')
13
- segments, _ = model.transcribe(audio, language=(sys.argv[2] or None) if len(sys.argv) > 2 else None, vad_filter=True, beam_size=1)
14
- print(' '.join(s.text.strip() for s in segments).strip())
13
+ model = WhisperModel(sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] else 'base', device='cpu', compute_type='int8')
14
+ print(json.dumps({'ready': True}), flush=True)
15
+ for line in sys.stdin:
16
+ try:
17
+ job = json.loads(line)
18
+ pcm = subprocess.run(['ffmpeg', '-nostdin', '-loglevel', 'error', '-i', job['file'], '-f', 'f32le', '-ac', '1', '-ar', '16000', '-'], capture_output=True, check=True).stdout
19
+ segments, _ = model.transcribe(np.frombuffer(pcm, dtype=np.float32), language=job.get('lang') or None, vad_filter=True, beam_size=1)
20
+ print(json.dumps({'text': ' '.join(s.text.strip() for s in segments).strip()}), flush=True)
21
+ except Exception as e: # keep serving
22
+ print(json.dumps({'error': str(e).split('\n')[0]}), flush=True)