clavarium 0.2.236-next.1 → 0.2.237-beta.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.
- package/config/launch/claude-code.sh +40 -19
- package/config/launch/codex.sh +37 -0
- package/config/launch/json-set.mjs +5 -2
- package/config/launch/mcp-relay.mjs +98 -0
- package/config/launch/mcp-sock.sh +31 -0
- package/config/launch/screen-watch.mjs +173 -0
- package/config/launch/toml-block.mjs +26 -0
- package/config/launch/tools-host.mjs +93 -0
- package/config/launch/vibe.sh +40 -0
- package/config/machine/clavarium-beat +44 -0
- package/config/machine/clavarium-beat-one +40 -0
- package/config/machine/clavarium-enter +60 -0
- package/config/tools.json +170 -12
- package/deploy/clavarium-host +385 -31
- package/deploy/clavarium-tunnel +14 -3
- package/deploy/clavarium.mjs +4 -0
- package/deploy/git-read +57 -5
- package/deploy/install.sh +11 -5
- package/deploy/maintenance.html +5 -2
- package/deploy/online.mjs +251 -8
- package/deploy/relay.sh +53 -27
- package/deploy/tunnel.mjs +7 -5
- package/deploy/updater.mjs +168 -25
- package/npm-shrinkwrap.json +245 -19
- package/package.json +9 -6
- package/server/agenda.mjs +140 -0
- package/server/api.mjs +392 -28
- package/server/apikeys.mjs +1372 -0
- package/server/beat.mjs +189 -0
- package/server/binders.mjs +42 -0
- package/server/boxcollect.mjs +276 -0
- package/server/boxes.mjs +348 -29
- package/server/bridge.mjs +13 -4
- package/server/browsers.mjs +364 -0
- package/server/capacity.mjs +37 -10
- package/server/carry.mjs +143 -0
- package/server/catalog.mjs +48 -0
- package/server/contactview.mjs +122 -0
- package/server/conversations.mjs +1122 -46
- package/server/copywork.mjs +34 -0
- package/server/demandes.mjs +251 -0
- package/server/desktop.mjs +102 -0
- package/server/devices.mjs +1 -0
- package/server/dictation-engines.mjs +91 -0
- package/server/dockets.mjs +49 -6
- package/server/door.mjs +19 -5
- package/server/events.mjs +3 -0
- package/server/features.mjs +366 -0
- package/server/files.mjs +43 -1
- package/server/gitaccess.mjs +12 -3
- package/server/gitchecks.mjs +17 -3
- package/server/gitkeeper.mjs +45 -10
- package/server/gitpush.mjs +286 -71
- package/server/gitrunner.mjs +144 -10
- package/server/grants.mjs +47 -11
- package/server/guide.mjs +31 -10
- package/server/health.mjs +138 -12
- package/server/jobs.mjs +138 -0
- package/server/linkguard.mjs +191 -0
- package/server/machinelist.mjs +58 -0
- package/server/mailref.mjs +90 -0
- package/server/mailview.mjs +204 -0
- package/server/main.mjs +425 -47
- package/server/mcpoauth.mjs +338 -0
- package/server/mcpx.mjs +175 -0
- package/server/network.mjs +125 -13
- package/server/profile.mjs +129 -0
- package/server/relayjoin.mjs +67 -0
- package/server/resources.mjs +6 -0
- package/server/revive.mjs +70 -0
- package/server/rooms.mjs +462 -0
- package/server/secrets.mjs +25 -12
- package/server/serverlogs.mjs +30 -4
- package/server/settingswords.mjs +375 -0
- package/server/signinhelp.mjs +239 -0
- package/server/speech.mjs +40 -4
- package/server/spoken.mjs +60 -0
- package/server/sshconsole.mjs +99 -0
- package/server/sshmachine.mjs +76 -0
- package/server/store.mjs +15 -1
- package/server/suggest.mjs +66 -0
- package/server/talk.mjs +228 -55
- package/server/tethers.mjs +223 -13
- package/server/toolbox.mjs +30 -7
- package/server/tools.mjs +38 -6
- package/server/updates.mjs +7 -2
- package/server/vm.mjs +215 -46
- package/server/vmwatch.mjs +82 -23
- package/server/voice.mjs +183 -51
- package/server/wakelearn.mjs +214 -0
- package/server/wakeups.mjs +42 -2
- package/server/watchdog.mjs +102 -0
- package/web/app.js +5590 -1237
- package/web/desk.js +531 -0
- package/web/device.html +15 -2
- package/web/features.js +480 -0
- package/web/index.html +874 -490
- package/web/kit.js +1142 -0
- package/web/links.js +2 -2
- package/web/mail-view.js +386 -0
- package/web/manifest.webmanifest +4 -0
- package/web/style.css +1592 -268
- package/web/voice-core.js +48 -0
- package/web/voice.js +13 -5
package/server/beat.mjs
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/* THE HEARTBEAT OF A MACHINE (step 6, phase 1): its health looked at from inside it, read from here.
|
|
2
|
+
*
|
|
3
|
+
* Every two minutes, each conversation's health was one command into its machine (health.mjs, PROBE): one
|
|
4
|
+
* more line at the VM manager, in front of every other command. Now a timer in the machine (root's,
|
|
5
|
+
* config/machine/clavarium-beat) runs that same probe every minute, as the conversation's own user, and
|
|
6
|
+
* writes what it printed into its work folder, /work/.clavarium/beat.json. The work folder is a folder of
|
|
7
|
+
* THIS server: the beat is read here, as a file (read), with no command at all.
|
|
8
|
+
*
|
|
9
|
+
* WHAT IS IN IT IS THE AGENT'S: it is root in its machine and may write anything there. So the folder must
|
|
10
|
+
* be a folder (never a link), the file a plain file of a few kilobytes, opened without following a link and
|
|
11
|
+
* without waiting (a pipe put there); its words checked one by one; its conversation the one whose folder it
|
|
12
|
+
* is; its age taken from THIS server's clock (the file's time here), never from what it says; its number
|
|
13
|
+
* growing. Nothing in it is ever run: its probe text is read by readProbe, as the probe's output always was.
|
|
14
|
+
*
|
|
15
|
+
* Put in a machine once (ensure): one command at its start or opening, skipped when a fresh beat already
|
|
16
|
+
* says this version. Only with CLAVARIUM_BEAT holding `health` (main.mjs): off, nothing here is used.
|
|
17
|
+
*/
|
|
18
|
+
import { lstatSync, openSync, fstatSync, readSync, closeSync, constants, writeFileSync, renameSync, rmSync, mkdirSync, readFileSync } from 'node:fs';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { randomBytes } from 'node:crypto';
|
|
21
|
+
import { PROBE } from './health.mjs';
|
|
22
|
+
|
|
23
|
+
export const FOLDER = '.clavarium';
|
|
24
|
+
export const BEAT_FILE = 'beat.json';
|
|
25
|
+
export const EXPECTED_FILE = 'expected';
|
|
26
|
+
/* At most this big: a probe of 64 secrets' names is a few kilobytes. */
|
|
27
|
+
export const BEAT_BYTES = 16 * 1024;
|
|
28
|
+
/* Older than this (by this server's clock), it says nothing: its timer beats every minute or so. */
|
|
29
|
+
export const FRESH_MS = 180_000;
|
|
30
|
+
/* A file's time a little ahead of this server's clock is still now (a share's rounding); more is not believed. */
|
|
31
|
+
const AHEAD_MS = 10_000;
|
|
32
|
+
/* Where it is put in the machine (root's, never under /tools or /work). */
|
|
33
|
+
export const LIB = '/usr/local/lib/clavarium';
|
|
34
|
+
export const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
35
|
+
const INSTALL_MS = 90_000;
|
|
36
|
+
const NAME = /^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/;
|
|
37
|
+
const VERSION_WORD = /^[0-9A-Za-z.+-]{1,64}$/;
|
|
38
|
+
|
|
39
|
+
/* Whether CLAVARIUM_BEAT asks for it (`health`; other words for the later phases). */
|
|
40
|
+
export const beatWanted = (value, what = 'health') => String(value ?? '').split(/[\s,]+/).includes(what);
|
|
41
|
+
|
|
42
|
+
const RUNNER = new URL('../config/machine/clavarium-beat', import.meta.url);
|
|
43
|
+
const ONE = new URL('../config/machine/clavarium-beat-one', import.meta.url);
|
|
44
|
+
export const SERVICE = `[Unit]
|
|
45
|
+
Description=Clavarium heartbeat: its health, for its server
|
|
46
|
+
[Service]
|
|
47
|
+
Type=oneshot
|
|
48
|
+
ExecStart=/bin/sh ${LIB}/beat-all
|
|
49
|
+
TimeoutStartSec=300
|
|
50
|
+
Nice=10
|
|
51
|
+
`;
|
|
52
|
+
export const TIMER = `[Unit]
|
|
53
|
+
Description=Clavarium heartbeat, every minute
|
|
54
|
+
[Timer]
|
|
55
|
+
OnBootSec=20s
|
|
56
|
+
OnUnitActiveSec=60s
|
|
57
|
+
RandomizedDelaySec=10s
|
|
58
|
+
AccuracySec=5s
|
|
59
|
+
[Install]
|
|
60
|
+
WantedBy=timers.target
|
|
61
|
+
`;
|
|
62
|
+
|
|
63
|
+
/* THE ONE COMMAND THAT PUTS IT IN A MACHINE, as root: its scripts and the probe in LIB, its settings, its
|
|
64
|
+
service and timer, started. Its arguments (mode, conversation, version) are checked again there. Each file
|
|
65
|
+
is written aside, then moved: a beat that runs meanwhile finds the old or the new, never half of one. */
|
|
66
|
+
const EOF = 'CLAVARIUM_BEAT_EOF';
|
|
67
|
+
function here(text) {
|
|
68
|
+
if (String(text).split('\n').includes(EOF)) throw new Error('a file of the beat holds its own end mark');
|
|
69
|
+
return `<<'${EOF}'\n${String(text).replace(/\n?$/, '\n')}${EOF}\n`;
|
|
70
|
+
}
|
|
71
|
+
export function installScript() {
|
|
72
|
+
return [
|
|
73
|
+
'set -eu',
|
|
74
|
+
'mode="$1"; name="$2"; version="$3"',
|
|
75
|
+
'case "$mode" in own) printf \'%s\' "$name" | grep -Eq \'^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$\' || exit 64 ;; shared) name=- ;; *) exit 64 ;; esac',
|
|
76
|
+
'printf \'%s\' "$version" | grep -Eq \'^[0-9A-Za-z.+-]{1,64}$\' || exit 64',
|
|
77
|
+
`lib=${LIB}`,
|
|
78
|
+
'mkdir -p "$lib"; chown root:root "$lib"; chmod 755 "$lib"',
|
|
79
|
+
'put() { tmp="$lib/.$1.$$"; cat > "$tmp"; chmod "$2" "$tmp"; mv -f "$tmp" "$lib/$1"; }',
|
|
80
|
+
`put probe.sh 0644 ${here(PROBE)}`,
|
|
81
|
+
`put beat-one 0755 ${here(readFileSync(ONE, 'utf8'))}`,
|
|
82
|
+
`put beat-all 0755 ${here(readFileSync(RUNNER, 'utf8'))}`,
|
|
83
|
+
'printf \'mode=%s\\nconversation=%s\\nversion=%s\\n\' "$mode" "$name" "$version" | put beat.conf 0644',
|
|
84
|
+
`cat > /etc/systemd/system/clavarium-beat.service ${here(SERVICE)}`,
|
|
85
|
+
`cat > /etc/systemd/system/clavarium-beat.timer ${here(TIMER)}`,
|
|
86
|
+
'systemctl daemon-reload',
|
|
87
|
+
'systemctl enable --now clavarium-beat.timer >/dev/null 2>&1',
|
|
88
|
+
'systemctl start --no-block clavarium-beat.service',
|
|
89
|
+
].join('\n');
|
|
90
|
+
}
|
|
91
|
+
export const INSTALL_NAME = 'clavarium-beat-install';
|
|
92
|
+
|
|
93
|
+
export class Beat {
|
|
94
|
+
#vms; #workFolder; #conversations; #now; #version; #seq = new Map(); #expected = new Map(); #tried = new Map(); #installing = new Map();
|
|
95
|
+
/* `on`: CLAVARIUM_BEAT holds `health`. `workFolder(name)`: its work folder on this server.
|
|
96
|
+
`conversations`: get(name) -- whether its work is kept here. */
|
|
97
|
+
constructor({ on = false, vms, workFolder, conversations, now = () => Date.now(), version = VERSION }) {
|
|
98
|
+
this.on = Boolean(on); this.#vms = vms; this.#workFolder = workFolder; this.#conversations = conversations; this.#now = now; this.#version = version;
|
|
99
|
+
}
|
|
100
|
+
get version() { return this.#version; }
|
|
101
|
+
|
|
102
|
+
#dir(name) { if (!NAME.test(String(name))) throw new Error('not a conversation name'); return join(this.#workFolder(name), FOLDER); }
|
|
103
|
+
/* Its folder, a folder of its own (never a link), or null; made when `make` and missing. */
|
|
104
|
+
#folder(name, make = false) {
|
|
105
|
+
let dir;
|
|
106
|
+
try { dir = this.#dir(name); } catch { return null; }
|
|
107
|
+
let s = lstatSync(dir, { throwIfNoEntry: false });
|
|
108
|
+
if (!s && make) { try { mkdirSync(dir, { mode: 0o755 }); } catch { return null; } s = lstatSync(dir, { throwIfNoEntry: false }); }
|
|
109
|
+
return s && s.isDirectory() && !s.isSymbolicLink() ? dir : null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/* WHAT SHOULD BE MOUNTED, for the beat to look at (resources.expected): written when it changed. */
|
|
113
|
+
expect(name, paths) {
|
|
114
|
+
if (!this.on) return false;
|
|
115
|
+
const text = `${paths.filter((p) => /^\/[A-Za-z0-9._/-]{1,200}$/.test(p)).slice(0, 100).join('\n')}\n`;
|
|
116
|
+
try {
|
|
117
|
+
const dir = this.#folder(name, true);
|
|
118
|
+
if (!dir) return false;
|
|
119
|
+
const at = join(dir, EXPECTED_FILE);
|
|
120
|
+
const s = lstatSync(at, { throwIfNoEntry: false });
|
|
121
|
+
if (this.#expected.get(name) === text && s?.isFile()) return true;
|
|
122
|
+
/* Aside, then moved: a link put at its place is replaced, never followed. */
|
|
123
|
+
const tmp = join(dir, `.expected.${randomBytes(6).toString('hex')}`);
|
|
124
|
+
try { writeFileSync(tmp, text, { flag: 'wx', mode: 0o644 }); renameSync(tmp, at); } catch (error) { rmSync(tmp, { force: true }); throw error; }
|
|
125
|
+
this.#expected.set(name, text);
|
|
126
|
+
return true;
|
|
127
|
+
} catch { return false; }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/* ITS LAST BEAT: { ok: true, text, version, seq, at } or { ok: false, why }. `peek`: its number not
|
|
131
|
+
taken as seen (the install's look). */
|
|
132
|
+
read(name, { peek = false } = {}) {
|
|
133
|
+
const dir = this.#folder(name);
|
|
134
|
+
if (!dir) return { ok: false, why: 'none' };
|
|
135
|
+
let fd;
|
|
136
|
+
try { fd = openSync(join(dir, BEAT_FILE), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } catch (error) { return { ok: false, why: error.code === 'ENOENT' ? 'none' : 'unreadable' }; }
|
|
137
|
+
let s; let text;
|
|
138
|
+
try {
|
|
139
|
+
s = fstatSync(fd);
|
|
140
|
+
if (!s.isFile()) return { ok: false, why: 'not a file' };
|
|
141
|
+
if (s.size > BEAT_BYTES) return { ok: false, why: 'too big' };
|
|
142
|
+
const buf = Buffer.alloc(BEAT_BYTES + 1);
|
|
143
|
+
let n = 0;
|
|
144
|
+
for (let got = 1; got > 0 && n <= BEAT_BYTES; n += got) got = readSync(fd, buf, n, BEAT_BYTES + 1 - n, null);
|
|
145
|
+
if (n > BEAT_BYTES) return { ok: false, why: 'too big' };
|
|
146
|
+
text = buf.toString('utf8', 0, n);
|
|
147
|
+
} catch { return { ok: false, why: 'unreadable' }; } finally { closeSync(fd); }
|
|
148
|
+
const age = this.#now() - s.mtimeMs;
|
|
149
|
+
if (age > FRESH_MS) return { ok: false, why: 'stale' };
|
|
150
|
+
if (age < -AHEAD_MS) return { ok: false, why: 'ahead' };
|
|
151
|
+
let j;
|
|
152
|
+
try { j = JSON.parse(text); } catch { return { ok: false, why: 'not json' }; }
|
|
153
|
+
if (!j || typeof j !== 'object' || j.v !== 1) return { ok: false, why: 'not a beat' };
|
|
154
|
+
if (j.conversation !== name) return { ok: false, why: 'another conversation' };
|
|
155
|
+
if (!Number.isSafeInteger(j.seq) || j.seq < 1) return { ok: false, why: 'no number' };
|
|
156
|
+
if (typeof j.version !== 'string' || !VERSION_WORD.test(j.version)) return { ok: false, why: 'no version' };
|
|
157
|
+
if (typeof j.probe !== 'string') return { ok: false, why: 'no probe' };
|
|
158
|
+
/* ITS NUMBER GROWS: the same beat read again (same number, same time) is still it; a smaller one, or
|
|
159
|
+
the same number written again, is not believed -- and the next one is taken as a new start. */
|
|
160
|
+
const last = this.#seq.get(name);
|
|
161
|
+
if (last && !(j.seq > last.seq || (j.seq === last.seq && s.mtimeMs === last.at))) { if (!peek) this.#seq.delete(name); return { ok: false, why: 'number' }; }
|
|
162
|
+
if (!peek) this.#seq.set(name, { seq: j.seq, at: s.mtimeMs });
|
|
163
|
+
return { ok: true, text: j.probe, version: j.version, seq: j.seq, at: s.mtimeMs };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/* PUT IN ITS MACHINE, once: one command, as root. Skipped when its beat is fresh and says this version,
|
|
167
|
+
or when it was tried already for this version (`woke`: its machine has just started -- what was tried
|
|
168
|
+
is forgotten: a fresh beat may still be from before its start, and once it is stale the next call puts
|
|
169
|
+
it again). Never more than
|
|
170
|
+
one at a time per conversation. Resolves with what was done: 'off', 'fresh', 'tried', 'put', 'failed'. */
|
|
171
|
+
ensure(name, { woke = false } = {}) {
|
|
172
|
+
if (!this.on || this.#conversations?.get(name)?.work !== 'kept') return Promise.resolve('off');
|
|
173
|
+
if (woke) this.#tried.delete(name);
|
|
174
|
+
const going = this.#installing.get(name);
|
|
175
|
+
if (going) return going;
|
|
176
|
+
const beat = this.read(name, { peek: true });
|
|
177
|
+
if (beat.ok && beat.version === this.#version) return Promise.resolve('fresh');
|
|
178
|
+
if (this.#tried.get(name) === this.#version) return Promise.resolve('tried');
|
|
179
|
+
this.#tried.set(name, this.#version);
|
|
180
|
+
const mode = this.#vms.shared?.(name) ? 'shared' : 'own';
|
|
181
|
+
const run = this.#vms.execMachine(name, ['sudo', '-n', 'sh', '-c', installScript(), INSTALL_NAME, mode, mode === 'own' ? name : '-', this.#version], { timeoutMs: INSTALL_MS })
|
|
182
|
+
.then((r) => (r.code === 0 ? 'put' : 'failed'), () => 'failed')
|
|
183
|
+
.finally(() => this.#installing.delete(name));
|
|
184
|
+
this.#installing.set(name, run);
|
|
185
|
+
return run;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
forget(name) { this.#seq.delete(name); this.#expected.delete(name); this.#tried.delete(name); }
|
|
189
|
+
}
|
package/server/binders.mjs
CHANGED
|
@@ -130,6 +130,48 @@ export class Binders {
|
|
|
130
130
|
}
|
|
131
131
|
return out;
|
|
132
132
|
}
|
|
133
|
+
/* A COPY of a conversation (#221) is given the lists its original was given, with the same access. */
|
|
134
|
+
copyGrants(from, to) {
|
|
135
|
+
const keeper = { id: 'person:keeper', kind: 'person', name: 'keeper' };
|
|
136
|
+
for (const l of this.#keeper.store.lists(keeper)) {
|
|
137
|
+
const given = l.grants?.[`${AGENT}${from}`];
|
|
138
|
+
const level = typeof given === 'string' ? given : given?.access ?? given?.level;
|
|
139
|
+
if (level === 'read' || level === 'write') this.#keeper.store.grant(l.id, `${AGENT}${to}`, level, keeper);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/* WHAT IT WAS GIVEN, for a whole export (carry.mjs): each list by its id, with its access; and the same given
|
|
143
|
+
again, on an import, where the list exists here -> the ids not found. */
|
|
144
|
+
grantsOf(name) {
|
|
145
|
+
const keeper = { id: 'person:keeper', kind: 'person', name: 'keeper' };
|
|
146
|
+
const out = [];
|
|
147
|
+
for (const l of this.#keeper.store.lists(keeper)) {
|
|
148
|
+
const given = l.grants?.[`${AGENT}${name}`];
|
|
149
|
+
const level = typeof given === 'string' ? given : given?.access ?? given?.level;
|
|
150
|
+
if (level === 'read' || level === 'write') out.push({ id: l.id, level });
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
regrant(name, given = []) {
|
|
155
|
+
const keeper = { id: 'person:keeper', kind: 'person', name: 'keeper' };
|
|
156
|
+
const here = new Set(this.#keeper.store.lists(keeper).map((l) => l.id));
|
|
157
|
+
const missing = [];
|
|
158
|
+
for (const g of given) {
|
|
159
|
+
if (here.has(g?.id) && (g.level === 'read' || g.level === 'write')) this.#keeper.store.grant(g.id, `${AGENT}${name}`, g.level, keeper); else missing.push(g?.id);
|
|
160
|
+
}
|
|
161
|
+
return missing;
|
|
162
|
+
}
|
|
163
|
+
/* FOR API KEYS (apikeys.mjs): every list with who was given it, as a person sees them; a key given a list, or
|
|
164
|
+
taken back, on the list's own access -- as a conversation is. `identity`: the person, as its history says. */
|
|
165
|
+
lists() { return this.#keeper.store.lists({ id: 'person:keeper', kind: 'person', name: 'keeper' }).map((l) => ({ id: l.id, title: l.title, archived: Boolean(l.archived), grants: { ...(l.grants ?? {}) } })); }
|
|
166
|
+
grant(list, subject, level, identity = '') {
|
|
167
|
+
if (!/^apikey:[0-9a-f-]{36}$/.test(String(subject))) throw new Error('A list is given here to an API key only.');
|
|
168
|
+
this.#keeper.store.grant(list, subject, level, { id: `person:${identity || 'owner'}`, kind: 'person', name: identity || 'Owner' });
|
|
169
|
+
}
|
|
170
|
+
/* An API key asks, as an agent (never a person: Binder's gates hold). */
|
|
171
|
+
asKey(op, args, who) {
|
|
172
|
+
if (!who || who.kind !== 'agent' || !/^apikey:/.test(String(who.id))) throw new Error('Not an API key.');
|
|
173
|
+
return this.#keeper.act(String(op ?? ''), args && typeof args === 'object' ? args : {}, who);
|
|
174
|
+
}
|
|
133
175
|
/* A number that moves with every change: the page reads again when it moved. */
|
|
134
176
|
changes() { return this.#changes; }
|
|
135
177
|
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/* A COLLECT SESSION (07-11): a box's false wakes gathered on purpose, to train its next wake-word model (v3).
|
|
2
|
+
*
|
|
3
|
+
* For a set time (an empty home: the owner's go), each time the box listens nothing goes to its conversation and
|
|
4
|
+
* nothing is answered: the wake clip (wake.clip: the exact 1.6 s the box sends, 16 kHz 16-bit mono) and the first
|
|
5
|
+
* seconds after it are kept here, with one line of what is known -- no one labels them, no one listens:
|
|
6
|
+
*
|
|
7
|
+
* <dir>/<YYYY-MM-DD>/<n>.wav the wake clip, as sent (UTC day)
|
|
8
|
+
* <dir>/<YYYY-MM-DD>/<n>-suite.wav the next AFTER_MAX seconds at most (a radio: more of the same)
|
|
9
|
+
* <dir>/<YYYY-MM-DD>/index.jsonl { n, at, box, tag, reason, score, heard, word, voice, end, station, clip, after }
|
|
10
|
+
* <dir>/state.json { <boxId>: { from, until, tag, after, radio, volume, station, ... } }
|
|
11
|
+
* <dir>/ended.json { <boxId>: the last session, ended (shown on the box's card: « Exporter ») }
|
|
12
|
+
*
|
|
13
|
+
* RADIO (optional): the box asks the Google Home beside it, aloud, for one French station after another
|
|
14
|
+
* (« Ok Google, mets France Inter »), every `every` minutes, and « Ok Google, stop » at the end. No wake for
|
|
15
|
+
* QUIET_WARN_MS after a station was asked: said in the log (the speaker may not have obeyed).
|
|
16
|
+
*
|
|
17
|
+
* Off by itself at its end time, at COUNT_MAX entries or BYTES_MAX bytes on disk. Started and stopped by the
|
|
18
|
+
* operator only (/api/boxes/<id>/collect, behind the sign-on), never by a tool. exportZip(): the clips, laid out
|
|
19
|
+
* as the training notebook (v2, cell 7 bis) takes its negative examples: folders of 16 kHz WAV.
|
|
20
|
+
*/
|
|
21
|
+
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync, renameSync } from 'node:fs';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
import { Refusal } from './conversations.mjs';
|
|
24
|
+
import { wavOf } from './boxes.mjs';
|
|
25
|
+
|
|
26
|
+
export const COUNT_MAX = 1500;
|
|
27
|
+
export const BYTES_MAX = 300 * 1024 * 1024;
|
|
28
|
+
export const AFTER_DEFAULT = 8;
|
|
29
|
+
export const AFTER_MAX = 30;
|
|
30
|
+
export const HOURS_MAX = 12;
|
|
31
|
+
export const EVERY_DEFAULT = 60;
|
|
32
|
+
export const QUIET_WARN_MS = 20 * 60_000;
|
|
33
|
+
export const GRACE_MS = 5 * 60_000;
|
|
34
|
+
export const VOLUME_DEFAULT = 4; /* the Google Home's own scale, 0-10: a radio heard across the room, not loud */
|
|
35
|
+
/* French talk and music stations, as a Google Home knows them by name. */
|
|
36
|
+
export const STATIONS = ['France Inter', 'France Info', 'RTL', 'Europe 1', 'France Culture', 'Nostalgie', 'FIP', 'RMC'];
|
|
37
|
+
export const TAG = /^[a-z0-9-]{1,20}$/;
|
|
38
|
+
const BOX_ID = /^[0-9a-f-]{36}$/;
|
|
39
|
+
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
40
|
+
const dayOf = (t) => new Date(t).toISOString().slice(0, 10);
|
|
41
|
+
const timeOf = (v) => { const t = typeof v === 'number' ? v : Date.parse(String(v ?? '')); return Number.isFinite(t) ? t : NaN; };
|
|
42
|
+
|
|
43
|
+
export const stationPhrase = (name) => `Ok Google, mets ${name}`;
|
|
44
|
+
export const volumePhrase = (level) => `Ok Google, mets le volume à ${level}`;
|
|
45
|
+
export const STOP_PHRASE = 'Ok Google, stop';
|
|
46
|
+
|
|
47
|
+
export class BoxCollect {
|
|
48
|
+
#dir; #now; #log; #state; #countMax; #bytesMax; #usage = null; #next = new Map(); #ended = {};
|
|
49
|
+
|
|
50
|
+
constructor({ dir, now = () => Date.now(), log = () => {}, countMax = COUNT_MAX, bytesMax = BYTES_MAX }) {
|
|
51
|
+
this.#dir = dir; this.#now = now; this.#log = log; this.#countMax = countMax; this.#bytesMax = bytesMax;
|
|
52
|
+
try { this.#state = JSON.parse(readFileSync(join(dir, 'state.json'), 'utf8')); } catch { this.#state = {}; }
|
|
53
|
+
if (!this.#state || typeof this.#state !== 'object') this.#state = {};
|
|
54
|
+
try { this.#ended = JSON.parse(readFileSync(join(dir, 'ended.json'), 'utf8')) ?? {}; } catch { this.#ended = {}; }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
#save() {
|
|
58
|
+
mkdirSync(this.#dir, { recursive: true });
|
|
59
|
+
const file = join(this.#dir, 'state.json');
|
|
60
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(this.#state, null, 1)); renameSync(`${file}.tmp`, file);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/* What is on disk, counted once, then kept up to date. */
|
|
64
|
+
#used() {
|
|
65
|
+
if (this.#usage) return this.#usage;
|
|
66
|
+
let count = 0; let bytes = 0;
|
|
67
|
+
for (const day of existsSync(this.#dir) ? readdirSync(this.#dir).filter((d) => DAY.test(d)) : []) {
|
|
68
|
+
for (const f of readdirSync(join(this.#dir, day))) {
|
|
69
|
+
try { bytes += statSync(join(this.#dir, day, f)).size; } catch { /* gone meanwhile */ }
|
|
70
|
+
if (/^\d+\.wav$/.test(f)) count++;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
this.#usage = { count, bytes };
|
|
74
|
+
return this.#usage;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/* {from?, until, tag?, after?, radio?, every?, volume?, stations?} -> the state. */
|
|
78
|
+
start(boxId, body = {}) {
|
|
79
|
+
if (!BOX_ID.test(String(boxId))) throw new Refusal(400, 'Not a box id.');
|
|
80
|
+
const now = this.#now();
|
|
81
|
+
const from = body.from == null ? now : timeOf(body.from);
|
|
82
|
+
const until = timeOf(body.until);
|
|
83
|
+
if (!Number.isFinite(from) || !Number.isFinite(until)) throw new Refusal(400, 'An end time, please (until: ISO date).');
|
|
84
|
+
if (until <= Math.max(now, from)) throw new Refusal(400, 'The end time is already past.');
|
|
85
|
+
if (until - Math.max(now, from) > HOURS_MAX * 3_600_000) throw new Refusal(400, `${HOURS_MAX} hours at most.`);
|
|
86
|
+
const tag = String(body.tag ?? 'radio');
|
|
87
|
+
if (!TAG.test(tag)) throw new Refusal(400, 'A tag of a-z, 0-9 and -, 20 characters at most.');
|
|
88
|
+
const after = Math.round(Number(body.after ?? AFTER_DEFAULT));
|
|
89
|
+
if (!Number.isFinite(after) || after < 0 || after > AFTER_MAX) throw new Refusal(400, `after: 0 to ${AFTER_MAX} seconds.`);
|
|
90
|
+
const every = Math.round(Number(body.every ?? EVERY_DEFAULT));
|
|
91
|
+
if (!Number.isFinite(every) || every < 10 || every > 240) throw new Refusal(400, 'every: 10 to 240 minutes.');
|
|
92
|
+
const volume = Math.round(Number(body.volume ?? VOLUME_DEFAULT));
|
|
93
|
+
if (!Number.isFinite(volume) || volume < 1 || volume > 10) throw new Refusal(400, 'volume: 1 to 10 (the speaker\'s scale).');
|
|
94
|
+
const stations = Array.isArray(body.stations) && body.stations.length
|
|
95
|
+
? body.stations.map((s) => String(s).replace(/[^\p{L}\p{N} '-]/gu, '').trim().slice(0, 40)).filter(Boolean).slice(0, 12)
|
|
96
|
+
: STATIONS;
|
|
97
|
+
if (!stations.length) throw new Refusal(400, 'No station.');
|
|
98
|
+
this.#state[boxId] = {
|
|
99
|
+
from: new Date(from).toISOString(), until: new Date(until).toISOString(), tag, after, radio: body.radio === true,
|
|
100
|
+
every, volume, stations, startedAt: new Date(now).toISOString(),
|
|
101
|
+
station: null, stationAt: null, stationIndex: -1, volumeSaid: false, lastWakeAt: null, warnedAt: null,
|
|
102
|
+
kept: 0, wakes: 0, answers: [], warnings: [],
|
|
103
|
+
};
|
|
104
|
+
this.#save();
|
|
105
|
+
this.#log(`voice box ${boxId.slice(0, 8)}: collect on (${tag}) until ${new Date(until).toISOString()}${body.radio === true ? ', radio' : ''}`);
|
|
106
|
+
return this.state(boxId);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/* Off: by the operator, at its end, or full. Returns what was on (to say « stop » to the speaker), or null. */
|
|
110
|
+
stop(boxId, why = 'asked') {
|
|
111
|
+
const s = this.#state[boxId];
|
|
112
|
+
if (!s) return null;
|
|
113
|
+
delete this.#state[boxId]; this.#save();
|
|
114
|
+
this.#log(`voice box ${String(boxId).slice(0, 8)}: collect off (${why}), ${s.kept} kept`);
|
|
115
|
+
this.#ended = { ...this.#ended, [boxId]: { ...s, endedAt: new Date(this.#now()).toISOString(), why } };
|
|
116
|
+
try { writeFileSync(join(this.#dir, 'ended.json'), JSON.stringify(this.#ended)); } catch { /* shown until a restart only */ }
|
|
117
|
+
return s;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/* On now: begun, not yet ended. With the radio, GRACE_MS more: the radio plays until the box has told the
|
|
121
|
+
speaker to stop (the clock waits for a box busy listening), and its wakes must not reach the AI meanwhile. */
|
|
122
|
+
on(boxId) {
|
|
123
|
+
const s = this.#state[boxId];
|
|
124
|
+
if (!s) return false;
|
|
125
|
+
const now = this.#now();
|
|
126
|
+
return now >= Date.parse(s.from) && now < Date.parse(s.until) + (s.radio ? GRACE_MS : 0);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
state(boxId) {
|
|
130
|
+
const s = this.#state[boxId]; const u = this.#used();
|
|
131
|
+
if (!s) return { on: false, last: this.#ended[boxId] ?? null, count: u.count, bytes: u.bytes };
|
|
132
|
+
return { on: this.on(boxId), ...s, count: u.count, bytes: u.bytes, countMax: this.#countMax, bytesMax: this.#bytesMax };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/* One listen of the box, during a session: kept (wake, button, knock), or null when full or off. */
|
|
136
|
+
keep(boxId, { clip = null, after = Buffer.alloc(0), reason = '', score = null, heard = null, word = null, voice = null, end = '' } = {}) {
|
|
137
|
+
const s = this.#state[boxId];
|
|
138
|
+
if (!s || !this.on(boxId)) return null;
|
|
139
|
+
const now = this.#now();
|
|
140
|
+
if (reason === 'wake') { s.wakes++; s.lastWakeAt = new Date(now).toISOString(); }
|
|
141
|
+
const u = this.#used();
|
|
142
|
+
const tail = after.subarray(0, (s.after * 32_000) & ~1);
|
|
143
|
+
const size = (clip?.length ? clip.length + 44 : 0) + (tail.length ? tail.length + 44 : 0);
|
|
144
|
+
if (u.count >= this.#countMax || u.bytes + size > this.#bytesMax) { this.#save(); return null; }
|
|
145
|
+
const day = dayOf(now); const dir = join(this.#dir, day);
|
|
146
|
+
mkdirSync(dir, { recursive: true });
|
|
147
|
+
const n = this.#nextOf(day);
|
|
148
|
+
const line = {
|
|
149
|
+
n, at: new Date(now).toISOString(), box: boxId, tag: s.tag, reason: String(reason).slice(0, 12),
|
|
150
|
+
score: Number.isFinite(score) ? score : null, heard: heard == null ? null : String(heard).slice(0, 200),
|
|
151
|
+
word: typeof word === 'boolean' ? word : null, voice: Number.isFinite(voice) && voice > 0 ? Math.round(voice) : null,
|
|
152
|
+
end: String(end).slice(0, 12), station: s.radio ? s.station : null, clip: null, after: null,
|
|
153
|
+
};
|
|
154
|
+
if (clip?.length) { writeFileSync(join(dir, `${n}.wav`), wavOf(clip)); line.clip = `${n}.wav`; }
|
|
155
|
+
if (tail.length) { writeFileSync(join(dir, `${n}-suite.wav`), wavOf(tail)); line.after = `${n}-suite.wav`; }
|
|
156
|
+
appendFileSync(join(dir, 'index.jsonl'), `${JSON.stringify(line)}\n`);
|
|
157
|
+
u.count++; u.bytes += size; s.kept++;
|
|
158
|
+
this.#save();
|
|
159
|
+
return line;
|
|
160
|
+
}
|
|
161
|
+
#nextOf(day) {
|
|
162
|
+
if (!this.#next.has(day)) {
|
|
163
|
+
let n = 0;
|
|
164
|
+
try { for (const l of readFileSync(join(this.#dir, day, 'index.jsonl'), 'utf8').split('\n')) { try { n = Math.max(n, JSON.parse(l).n); } catch { /* a torn line */ } } } catch { /* a new day */ }
|
|
165
|
+
this.#next.set(day, n);
|
|
166
|
+
}
|
|
167
|
+
const n = this.#next.get(day) + 1; this.#next.set(day, n);
|
|
168
|
+
return n;
|
|
169
|
+
}
|
|
170
|
+
full() { const u = this.#used(); return u.count >= this.#countMax || u.bytes >= this.#bytesMax - 400_000; } /* no room for one more (a clip and AFTER_DEFAULT s) */
|
|
171
|
+
|
|
172
|
+
/* What the speaker answered when asked for a station (the box listened after it spoke). */
|
|
173
|
+
answered(boxId, text) {
|
|
174
|
+
const s = this.#state[boxId]; if (!s) return;
|
|
175
|
+
s.answers = [...s.answers, { at: new Date(this.#now()).toISOString(), station: s.station, text: String(text).slice(0, 120) }].slice(-20);
|
|
176
|
+
this.#save();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/* THE CLOCK (every half minute): what is due now, for one box -- { end } | { say, station? } | { warn } | null.
|
|
180
|
+
online: the box is connected; busy: it is listening now (a phrase then waits for the next tick). */
|
|
181
|
+
due(boxId, { online = true, busy = false } = {}) {
|
|
182
|
+
const s = this.#state[boxId];
|
|
183
|
+
if (!s) return null;
|
|
184
|
+
const now = this.#now();
|
|
185
|
+
if (this.full()) return { end: 'full', radio: s.radio };
|
|
186
|
+
if (now >= Date.parse(s.until) && (!busy || !online || now >= Date.parse(s.until) + GRACE_MS - 60_000)) return { end: 'time', radio: s.radio };
|
|
187
|
+
if (now >= Date.parse(s.until)) return null;
|
|
188
|
+
if (!s.radio || !online || busy || now < Date.parse(s.from)) return null;
|
|
189
|
+
if (!s.volumeSaid) { s.volumeSaid = true; this.#save(); return { say: volumePhrase(s.volume) }; }
|
|
190
|
+
if (s.stationIndex < 0 || now - Date.parse(s.stationAt) >= s.every * 60_000) {
|
|
191
|
+
s.stationIndex = (s.stationIndex + 1) % s.stations.length;
|
|
192
|
+
s.station = s.stations[s.stationIndex]; s.stationAt = new Date(now).toISOString(); s.warnedAt = null;
|
|
193
|
+
this.#save();
|
|
194
|
+
return { say: stationPhrase(s.station), station: s.station };
|
|
195
|
+
}
|
|
196
|
+
const quietSince = Math.max(Date.parse(s.stationAt), Date.parse(s.lastWakeAt ?? '') || 0);
|
|
197
|
+
if (!s.warnedAt && now - quietSince >= QUIET_WARN_MS) {
|
|
198
|
+
s.warnedAt = new Date(now).toISOString();
|
|
199
|
+
const text = `no wake for ${Math.round((now - quietSince) / 60_000)} min since ${s.station} was asked: the Google Home may not have obeyed`;
|
|
200
|
+
s.warnings = [...s.warnings, { at: s.warnedAt, station: s.station, text }].slice(-20);
|
|
201
|
+
this.#save();
|
|
202
|
+
return { warn: text };
|
|
203
|
+
}
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
boxes() { return Object.keys(this.#state); }
|
|
207
|
+
|
|
208
|
+
/* THE EXPORT: one zip, laid out for the training notebook (v2, cell 7 bis: a folder of 16 kHz WAV per source):
|
|
209
|
+
<tag>/<day>-<n>.wav the wake clips (1.6 s): the hard negatives
|
|
210
|
+
<tag>_suite/<day>-<n>.wav what came after them: more negative speech and music
|
|
211
|
+
index.csv file, at, reason, score, heard, word, voice, end, station
|
|
212
|
+
LISEZMOI.txt how the notebook takes them
|
|
213
|
+
Only the box's wakes (not a button or a knock) of that tag; days: all, or those given. */
|
|
214
|
+
exportZip({ tag = 'radio', days = null } = {}) {
|
|
215
|
+
if (!TAG.test(String(tag))) throw new Refusal(400, 'Not a tag.');
|
|
216
|
+
const files = []; const rows = [['file', 'suite', 'at', 'reason', 'score', 'heard', 'word', 'voice', 'end', 'station'].join(',')];
|
|
217
|
+
const wanted = Array.isArray(days) && days.length ? new Set(days.filter((d) => DAY.test(String(d)))) : null;
|
|
218
|
+
const csv = (v) => (v == null ? '' : /[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v));
|
|
219
|
+
for (const day of existsSync(this.#dir) ? readdirSync(this.#dir).filter((d) => DAY.test(d) && (!wanted || wanted.has(d))).sort() : []) {
|
|
220
|
+
let lines = [];
|
|
221
|
+
try { lines = readFileSync(join(this.#dir, day, 'index.jsonl'), 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } catch { continue; }
|
|
222
|
+
for (const l of lines) {
|
|
223
|
+
if (l.tag !== tag || l.reason !== 'wake' || !l.clip) continue;
|
|
224
|
+
const name = `${day}-${l.n}.wav`;
|
|
225
|
+
try { files.push({ name: `${tag}/${name}`, data: readFileSync(join(this.#dir, day, l.clip)) }); } catch { continue; }
|
|
226
|
+
let suite = '';
|
|
227
|
+
if (l.after) { try { files.push({ name: `${tag}_suite/${name}`, data: readFileSync(join(this.#dir, day, l.after)) }); suite = `${tag}_suite/${name}`; } catch { /* the clip alone */ } }
|
|
228
|
+
rows.push([`${tag}/${name}`, suite, l.at, l.reason, l.score, l.heard, l.word, l.voice, l.end, l.station].map(csv).join(','));
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
files.push({ name: 'index.csv', data: Buffer.from(`${rows.join('\n')}\n`) });
|
|
232
|
+
files.push({ name: 'LISEZMOI.txt', data: Buffer.from(readme(tag, rows.length - 1)) });
|
|
233
|
+
return { zip: zipOf(files, this.#now()), clips: rows.length - 1 };
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const readme = (tag, n) => `${n} faux réveils du boîtier (session « ${tag} »), sans étiquetage : personne à la maison, tout réveil est un faux.
|
|
238
|
+
|
|
239
|
+
${tag}/ les 1,6 s qui ont réveillé le boîtier (wav 16 kHz, 16 bits, mono) : les contre-exemples durs
|
|
240
|
+
${tag}_suite/ les secondes d'après (même format) : de la radio française en plus
|
|
241
|
+
index.csv score d'éveil, réécoute du serveur (word = le mot entendu), niveau de voix, station
|
|
242
|
+
|
|
243
|
+
Dans le carnet v2 (cellule 7 bis) :
|
|
244
|
+
1. décompresser ce zip dans /content ;
|
|
245
|
+
2. ajouter à la boucle c) : ('${tag}', 'negative_datasets/${tag}'), ('${tag}_suite', 'negative_datasets/${tag}_suite') ;
|
|
246
|
+
3. ajouter à config["features"] (cellule 8) deux entrées « truth: False, truncation_strategy: random »,
|
|
247
|
+
${tag} avec penalty_weight 2.0 (comme near_words), ${tag}_suite avec sampling_weight 6.0.
|
|
248
|
+
`;
|
|
249
|
+
|
|
250
|
+
/* A ZIP, stored (WAV does not compress): enough for a few hundred megabytes, no dependency. */
|
|
251
|
+
const CRC = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })();
|
|
252
|
+
export function crc32(buf) { let c = 0xffffffff; for (let i = 0; i < buf.length; i++) c = CRC[(c ^ buf[i]) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }
|
|
253
|
+
export function zipOf(files, at = Date.now()) {
|
|
254
|
+
const d = new Date(at);
|
|
255
|
+
const time = (d.getUTCHours() << 11) | (d.getUTCMinutes() << 5) | (d.getUTCSeconds() >> 1);
|
|
256
|
+
const date = ((d.getUTCFullYear() - 1980) << 9) | ((d.getUTCMonth() + 1) << 5) | d.getUTCDate();
|
|
257
|
+
const parts = []; const central = []; let offset = 0;
|
|
258
|
+
for (const f of files) {
|
|
259
|
+
const name = Buffer.from(f.name, 'utf8'); const crc = crc32(f.data);
|
|
260
|
+
const local = Buffer.alloc(30);
|
|
261
|
+
local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(0, 8);
|
|
262
|
+
local.writeUInt16LE(time, 10); local.writeUInt16LE(date, 12); local.writeUInt32LE(crc, 14);
|
|
263
|
+
local.writeUInt32LE(f.data.length, 18); local.writeUInt32LE(f.data.length, 22); local.writeUInt16LE(name.length, 26); local.writeUInt16LE(0, 28);
|
|
264
|
+
const c = Buffer.alloc(46);
|
|
265
|
+
c.writeUInt32LE(0x02014b50, 0); c.writeUInt16LE(20, 4); c.writeUInt16LE(20, 6); c.writeUInt16LE(0x0800, 8); c.writeUInt16LE(0, 10);
|
|
266
|
+
c.writeUInt16LE(time, 12); c.writeUInt16LE(date, 14); c.writeUInt32LE(crc, 16); c.writeUInt32LE(f.data.length, 20); c.writeUInt32LE(f.data.length, 24);
|
|
267
|
+
c.writeUInt16LE(name.length, 28); c.writeUInt32LE(offset, 42);
|
|
268
|
+
parts.push(local, name, f.data); central.push(c, name);
|
|
269
|
+
offset += 30 + name.length + f.data.length;
|
|
270
|
+
}
|
|
271
|
+
const size = central.reduce((s, b) => s + b.length, 0);
|
|
272
|
+
const end = Buffer.alloc(22);
|
|
273
|
+
end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10);
|
|
274
|
+
end.writeUInt32LE(size, 12); end.writeUInt32LE(offset, 16);
|
|
275
|
+
return Buffer.concat([...parts, ...central, end]);
|
|
276
|
+
}
|