clavarium 0.2.174-next.1 → 0.2.176-next.1

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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.174-next.1",
3
+ "version": "0.2.176-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.174-next.1",
9
+ "version": "0.2.176-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -14,7 +14,7 @@
14
14
  "clavarium-binder": "0.1.43-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
16
  "clavarium-parley": "0.17.33-next.1",
17
- "clavarium-tether": "0.1.0-next.40",
17
+ "clavarium-tether": "0.1.0-next.42",
18
18
  "mermaid": "11.17.2",
19
19
  "node-pty": "^1.1.0",
20
20
  "pdfjs-dist": "6.4.299",
@@ -760,9 +760,9 @@
760
760
  }
761
761
  },
762
762
  "node_modules/clavarium-tether": {
763
- "version": "0.1.0-next.40",
764
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.40.tgz",
765
- "integrity": "sha512-9vAcoV4GlNDduX+slPUfJyMB0wTb/mUAe6VVaOlmwLlWhsM691nI2F9AUb6/QH+uPI3A2e67U6koafYn4TqntA==",
763
+ "version": "0.1.0-next.42",
764
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.42.tgz",
765
+ "integrity": "sha512-ms19DnB+9f6x8C0H5Qp6XCJIk/TA8oIT4UisAtiyEUlfa0tHVYITaAh7jO11tDRvvk2lnh439EBRgGVeKdFJIA==",
766
766
  "license": "MIT",
767
767
  "bin": {
768
768
  "tether": "bin/cli.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.174-next.1",
3
+ "version": "0.2.176-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
@@ -47,7 +47,7 @@
47
47
  "clavarium-binder": "0.1.43-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
49
  "clavarium-parley": "0.17.33-next.1",
50
- "clavarium-tether": "0.1.0-next.40",
50
+ "clavarium-tether": "0.1.0-next.42",
51
51
  "mermaid": "11.17.2",
52
52
  "node-pty": "^1.1.0",
53
53
  "pdfjs-dist": "6.4.299",
package/server/boxes.mjs CHANGED
@@ -22,9 +22,14 @@ import { Refusal } from './conversations.mjs';
22
22
  export const CODE_MINUTES = 10;
23
23
  export const PAIR_PATH = '/c/api/box/pair';
24
24
  export const LINK_PATH = '/c/api/box/ws';
25
+ /* A firmware a box downloads to update itself: a one-use address, kept a few minutes. */
26
+ export const FIRMWARE_PATH = '/c/api/box/firmware/';
27
+ export const FIRMWARE_MINUTES = 10;
25
28
  export const SENTENCE_MAX = 15 * 32_000 + 32_000; /* 15 s of 16 kHz 16-bit mono, and some slack */
26
29
  export const TRIES_PER_MINUTE = 10;
27
30
  export const NAME_MAX = 40;
31
+ /* The volume a box is given when it connects, until someone sets another (its own default was soft). */
32
+ export const VOLUME_DEFAULT = 80;
28
33
  /* Where a box in setup answers, on its own Wi-Fi: ESP-IDF's access point address, the same on
29
34
  every box (written from its parts: it is no machine of anybody's). */
30
35
  export const SETUP_ADDRESS = `http://${[192, 168, 4, 1].join('.')}/`;
@@ -69,12 +74,12 @@ export function forSpeech(text) {
69
74
 
70
75
  export class Boxes {
71
76
  #file; #codes = new Map(); #links = new Map(); #tries = []; #now;
72
- #exists; #hear; #say; #speak; #log; #changed;
77
+ #exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin;
73
78
 
74
79
  /* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
75
80
  exists(conversation), hear(wav) -> text, say(conversation, text, room), speak(text) -> PCM 16 kHz. */
76
- constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, now = () => Date.now(), log = () => {} }) {
77
- this.#file = file; this.#changed = changed; this.#exists = exists; this.#hear = hear; this.#say = say; this.#speak = speak; this.#now = now; this.#log = log;
81
+ constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {} }) {
82
+ this.#file = file; this.#changed = changed; this.#origin = origin; this.#exists = exists; this.#hear = hear; this.#say = say; this.#speak = speak; this.#now = now; this.#log = log;
78
83
  }
79
84
 
80
85
  #all() { const v = this.#file.get(); return Array.isArray(v) ? v : []; }
@@ -85,7 +90,7 @@ export class Boxes {
85
90
 
86
91
  /* What the operator sees: never the key, nor its hash. */
87
92
  all() {
88
- return this.#all().map(({ keyHash, ...b }) => ({ ...b, online: this.#links.has(b.id), muted: this.#links.get(b.id)?.muted ?? null, volume: this.#links.get(b.id)?.volume ?? null }));
93
+ return this.#all().map(({ keyHash, ...b }) => ({ ...b, online: this.#links.has(b.id), muted: this.#links.get(b.id)?.muted ?? null, volume: b.volume ?? this.#links.get(b.id)?.volume ?? VOLUME_DEFAULT }));
89
94
  }
90
95
 
91
96
  code(conversation, name) {
@@ -130,6 +135,43 @@ export class Boxes {
130
135
  this.#change(id, { name: label });
131
136
  }
132
137
 
138
+ /* Louder or softer: kept, and given to the box now if it is connected. */
139
+ async setVolume(id, level) {
140
+ const n = Math.round(Number(level));
141
+ if (!Number.isFinite(n) || n < 0 || n > 100) throw new Refusal(400, 'A volume from 0 to 100.');
142
+ this.#change(id, { volume: n });
143
+ const link = this.#links.get(id);
144
+ if (!link) return { ok: true, offline: true };
145
+ const a = await this.command(id, { t: 'volume', level: n });
146
+ if (a?.ok !== false) link.volume = n;
147
+ return a;
148
+ }
149
+
150
+ /* UPDATED OVER ITS WI-FI: the image is offered at a one-use address on this server (under /c/,
151
+ no sign-on: the token is the right), the box told to fetch it with its sha256; it answers
152
+ once installed, then restarts. */
153
+ async update(id, image, version = '') {
154
+ if (!this.#links.has(id)) throw new Refusal(409, 'This voice box is not connected: it is updated when it is online.');
155
+ const bytes = Buffer.isBuffer(image) ? image : Buffer.from(String(image ?? ''), 'base64');
156
+ if (bytes.length < 1024 || bytes[0] !== 0xe9) throw new Refusal(400, 'Not an ESP32 program image (it starts with 0xE9; a merged image is for a cable flash only).');
157
+ const origin = this.#origin();
158
+ if (!origin) throw new Refusal(409, 'This server does not know its public address: the box could not fetch the image.');
159
+ const token = randomBytes(24).toString('base64url');
160
+ this.#images.set(token, { bytes, until: this.#now() + FIRMWARE_MINUTES * 60_000 });
161
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
162
+ try {
163
+ const a = await this.command(id, { t: 'ota', url: `${origin}${FIRMWARE_PATH}${token}.bin`, sha256 }, 5 * 60_000);
164
+ if (a?.ok === false) throw new Refusal(502, `The box did not install it: ${a.detail ?? 'no reason given'}.`);
165
+ this.#log(`voice box ${this.#all().find((b) => b.id === id)?.name ?? id}: updated${version ? ` to ${version}` : ''}, restarting`);
166
+ return { ok: true };
167
+ } finally { this.#images.delete(token); }
168
+ }
169
+ image(token) {
170
+ const now = this.#now();
171
+ for (const [k, v] of this.#images) if (v.until < now) this.#images.delete(k);
172
+ return this.#images.get(String(token).replace(/\.bin$/, ''))?.bytes;
173
+ }
174
+
133
175
  /* Where it is (a home, a family house): grouped by it, named with it. */
134
176
  place(id, place) { this.#change(id, { place: String(place ?? '').trim().slice(0, NAME_MAX) }); }
135
177
 
@@ -213,6 +255,11 @@ export class Boxes {
213
255
  if (!m || typeof m !== 'object') return;
214
256
  if (m.t === 'ping') { send({ t: 'pong' }); return; }
215
257
  if (m.t === 'hello' && typeof m.problem === 'string' && m.problem) this.#log(`voice box ${box.name}: back online after ${Number(m.tries) || '?'} tries; it had: ${m.problem.slice(0, 160)}`);
258
+ if (m.t === 'hello') {
259
+ /* Its volume, as set here: given at each connection (a box keeps its own, softer, otherwise). */
260
+ const wanted = link.box().volume ?? VOLUME_DEFAULT;
261
+ if (m.volume !== wanted) { send({ t: 'volume', id: randomUUID(), level: wanted }); m.volume = wanted; }
262
+ }
216
263
  if (m.t === 'hello') { link.muted = m.muted === true; link.volume = Number.isFinite(m.volume) ? m.volume : null; this.#change(box.id, { firmware: String(m.firmware ?? '').slice(0, 20) }); seen(); return; }
217
264
  if (m.t === 'listen.start') { sentence = []; size = 0; return; }
218
265
  if (m.t === 'listen.end' && sentence) {
@@ -303,7 +350,7 @@ export async function handleBoxes(request, response, boxes, originOk, headers =
303
350
  case 'move': boxes.move(id, String(body.conversation ?? '')); return send(200, { ok: true });
304
351
  case 'place': boxes.place(id, body.place); return send(200, { ok: true });
305
352
  case 'revoke': boxes.revoke(id); return send(200, { ok: true });
306
- case 'volume': return answered(await boxes.command(id, { t: 'volume', level: Math.round(Number(body.level)) }));
353
+ case 'volume': return answered(await boxes.setVolume(id, body.level));
307
354
  case 'wifi-scan': { const r = await boxes.command(id, { t: 'wifi.scan' }); return send(200, { networks: Array.isArray(r.networks) ? r.networks : [] }); }
308
355
  case 'wifi-join': return answered(await boxes.command(id, { t: 'wifi.join', ssid: String(body.ssid ?? ''), password: String(body.password ?? '') }, 90_000));
309
356
  case 'alert': return answered(await boxes.command(id, { t: 'alert', text: String(body.text ?? '').slice(0, 300) }, 10 * 60_000));
@@ -314,3 +361,31 @@ export async function handleBoxes(request, response, boxes, originOk, headers =
314
361
  return send(error.status ?? (error instanceof SyntaxError ? 400 : 500), { error: error instanceof SyntaxError ? 'Not JSON.' : error.message });
315
362
  }
316
363
  }
364
+
365
+ /* VOICE BOXES AS TETHER TARGETS (kind voicebox): what an assistant may do to the boxes of its
366
+ own conversation -- louder, softer, an alert -- through Tether's rights and journal. One
367
+ target per box, given to its conversation at "free" (nothing in it is risky), taken back when
368
+ the box moves or goes. */
369
+ export const targetOf = (box) => `voicebox-${box.id.slice(0, 8)}`;
370
+ export function voiceboxConnector(boxes) {
371
+ return {
372
+ async run(verb, t, a = {}) {
373
+ const id = t.config?.box;
374
+ if (verb === 'voicebox.volume') { const r = await boxes.setVolume(id, a.level); return { text: r?.offline ? `Volume ${a.level} kept: the box is offline, it gets it when it comes back.` : `Volume set to ${a.level}.` }; }
375
+ if (verb === 'voicebox.update') { await boxes.update(id, a.image, a.version); return { text: `Installed${a.version ? ` (${a.version})` : ''}: the box restarts and comes back in a moment.` }; }
376
+ if (verb === 'voicebox.alert') { await boxes.command(id, { t: 'alert', text: String(a.text ?? '').slice(0, 300) }, 10 * 60_000); return { text: 'The alert was seen: someone pressed its button.' }; }
377
+ throw new Error(`${verb} is not for a voice box`);
378
+ },
379
+ };
380
+ }
381
+ export function syncTargets(store, list) {
382
+ const wanted = new Map(list.map((b) => [targetOf(b), b]));
383
+ for (const t of store.targets()) if (t.kind === 'voicebox' && !wanted.has(t.id)) store.removeTarget(t.id);
384
+ for (const [id, b] of wanted) {
385
+ const before = store.target(id);
386
+ store.putTarget({ id, title: `Voice box ${b.name}${b.place ? ` (${b.place})` : ''}`, kind: 'voicebox', connector: 'voicebox', config: { box: b.id } });
387
+ const agent = `conversation:${b.conversation}`;
388
+ for (const who of Object.keys(store.target(id)?.grants ?? {})) if (who !== agent) store.grant(id, who, null);
389
+ if (!before || !store.target(id)?.grants?.[agent]) store.grant(id, agent, 'free');
390
+ }
391
+ }
package/server/main.mjs CHANGED
@@ -76,7 +76,7 @@ import { Events } from './events.mjs';
76
76
  import { Bundles } from './bundle.mjs';
77
77
  import { migrateData } from './dataformat.mjs';
78
78
  import { VmWatch } from './vmwatch.mjs';
79
- import { Boxes, handleBoxes, PAIR_PATH as BOX_PAIR_PATH } from './boxes.mjs';
79
+ import { Boxes, handleBoxes, voiceboxConnector, syncTargets, PAIR_PATH as BOX_PAIR_PATH, FIRMWARE_PATH as BOX_FIRMWARE_PATH } from './boxes.mjs';
80
80
  import { Speech } from './speech.mjs';
81
81
  import { WebSocketServer } from 'ws';
82
82
 
@@ -198,6 +198,13 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
198
198
  return;
199
199
  }
200
200
  /* A voice box pairing: under /c/, no sign-on; the one-use code is the right (boxes.mjs). */
201
+ /* A firmware a box fetches to update itself: the one-use token in the address is the right. */
202
+ if (boxes && pathname.startsWith(BOX_FIRMWARE_PATH) && request.method === 'GET') {
203
+ const bytes = boxes.image(pathname.slice(BOX_FIRMWARE_PATH.length));
204
+ if (!bytes) { response.writeHead(404, HEADERS).end(); return; }
205
+ response.writeHead(200, { ...HEADERS, 'content-type': 'application/octet-stream', 'content-length': bytes.length, 'cache-control': 'no-store' }).end(bytes);
206
+ return;
207
+ }
201
208
  if (boxes && pathname === BOX_PAIR_PATH) {
202
209
  const say = (status, body) => response.writeHead(status, { ...HEADERS, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body));
203
210
  if (request.method !== 'POST') { say(405, { error: 'Call this address with POST.' }); return; }
@@ -426,7 +433,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
426
433
  /* The accesses an agent was given -- a machine over SSH, an online folder, a
427
434
  mailbox, a calendar, an address book -- held here with their secrets read from
428
435
  the vault by name, never in a machine: see tethers.mjs. */
429
- const tethers = new Tethers({ dataDir, resources: folders, conversations: () => all.list().map((c) => c.name), secrets });
436
+ /* Voice boxes are Tether targets too (boxes.mjs): their connector reaches them through `boxes`, made below. */
437
+ const tethers = new Tethers({ dataDir, resources: folders, conversations: () => all.list().map((c) => c.name), secrets, connectors: { voicebox: { run: (...a) => voiceboxConnector(boxes).run(...a) } } });
430
438
  const stopTethers = tethers.start();
431
439
  /* Connecting a mailbox, calendar or address book by token: the consent happens
432
440
  in the owner's browser, the refresh token is kept host-only (never in a
@@ -601,7 +609,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
601
609
  /* Said as the person's own message, the room named (one speaker for now). */
602
610
  say: (name, text, by) => talk.say(name, text, undefined, undefined, 'voice', { by }),
603
611
  /* Each conversation's thread knows its boxes: their names, and the ids its agent answers. */
604
- changed: () => { for (const c of all.list()) talk.speakers(c.name, boxes.speakersOf(c.name)); },
612
+ origin: () => publicOrigin ?? null,
613
+ changed: () => { for (const c of all.list()) talk.speakers(c.name, boxes.speakersOf(c.name)); try { syncTargets(tethers.store(), boxes.all()); } catch (error) { console.error(`voice boxes in Tether: ${error.message}`); } },
605
614
  speak: (text) => speech.speak(text),
606
615
  log: (line) => events.add({ kind: 'server', text: line }) });
607
616
  const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
@@ -609,6 +618,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
609
618
  let closing = false;
610
619
  boxes.attach(server, WebSocketServer);
611
620
  for (const c of all.list()) talk.speakers(c.name, boxes.speakersOf(c.name));
621
+ try { syncTargets(tethers.store(), boxes.all()); } catch (error) { console.error(`voice boxes in Tether: ${error.message}`); }
612
622
  bridge = attachBridge(server, {
613
623
  onRejoin: (name) => all.rejoin(name),
614
624
  onTyped: (name, data) => { answerer.typed(name, data); talk.typed(name); all.touch(name); typingWatch.typed(name, data); },
package/server/setup.mjs CHANGED
@@ -305,7 +305,7 @@ export class Setup {
305
305
  const TCAT = { mail: 'mailbox', calendar: 'agenda', contacts: 'contacts' };
306
306
  for (const t of p.tethers?.store?.().targets() ?? []) {
307
307
  /* The USB device of the owner's browser is not an asset: nothing of it to show or carry. */
308
- if (t.kind === 'device') continue;
308
+ if (t.kind === 'device' || t.kind === 'voicebox') continue;
309
309
  const kind = TCAT[t.kind] ?? 'mailbox';
310
310
  nodes.push({ id: `connexion:${t.id}`, kind, name: t.title, sub: `${t.kind} (live)`, tether: true, record: t });
311
311
  for (const [agent, grant] of Object.entries(t.grants ?? {})) {
@@ -155,7 +155,7 @@ export class Tethers {
155
155
  given() {
156
156
  const out = {};
157
157
  for (const t of this.#keeper.store.targets()) {
158
- if (t.kind === 'device') continue; /* offered to every conversation: not an access worth counting */
158
+ if (t.kind === 'device' || t.kind === 'voicebox') continue; /* offered with a conversation or a box: not an access worth counting */
159
159
  for (const id of Object.keys(t.grants ?? {})) if (id.startsWith(AGENT)) out[id.slice(AGENT.length)] = (out[id.slice(AGENT.length)] ?? 0) + 1;
160
160
  }
161
161
  return out;
package/web/app.js CHANGED
@@ -8864,7 +8864,13 @@
8864
8864
  /* Where it is (a home): typed once, then offered for the next ones. */
8865
8865
  const place = el('input'); place.value = b.place ?? ''; place.maxLength = 40; place.placeholder = 'Place (a home)'; place.setAttribute('list', 'box-places'); place.setAttribute('aria-label', `Place of ${b.name}`);
8866
8866
  place.addEventListener('change', async () => { await post(`${API}/boxes/${b.id}/place`, { place: place.value.trim() }).catch(() => {}); await paintBoxes(); });
8867
- const acts = el('div', 'action-row'); acts.append(whereRow, place, rename, remove);
8867
+ /* Louder, softer: kept here, given to the box now or when it comes back. */
8868
+ const vol = el('input'); vol.type = 'range'; vol.min = '0'; vol.max = '100'; vol.step = '5'; vol.value = String(b.volume ?? 80); vol.setAttribute('aria-label', `Volume of ${b.name}`);
8869
+ const volSaid = el('small', 'hint', `${vol.value} %`);
8870
+ vol.addEventListener('input', () => { volSaid.textContent = `${vol.value} %`; });
8871
+ vol.addEventListener('change', async () => { await post(`${API}/boxes/${b.id}/volume`, { level: Number(vol.value) }).catch((error) => { volSaid.textContent = error.message; }); });
8872
+ const volRow = el('label', 'box-volume'); volRow.append('Volume ', vol, volSaid);
8873
+ const acts = el('div', 'action-row'); acts.append(whereRow, place, volRow, rename, remove);
8868
8874
  card.append(head, acts);
8869
8875
  rows.append(card);
8870
8876
  }