kamoji-dev 0.0.0-stage → 0.1.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.
@@ -0,0 +1,749 @@
1
+ // The Kamoji Bluetooth command channel, on any "link" (a real BLE connection or a fake one in tests).
2
+ //
3
+ // Ported from kamoji-rn src/utils (kamojiAuth.ts, kamojiAppBle.ts, kamojiAssetBleTransfer.ts,
4
+ // kamojiApps.ts) and documented on docs.kamoji.bot: /docs/modding/bluetooth-protocol (Authorization,
5
+ // Commands and answers) and /docs/apps/sideloading (Bluetooth install protocol).
6
+ //
7
+ // A link is { send(text): Promise, sendRaw(buffer): Promise, maxWrite(): number, onMessage(cb): unsubscribe }:
8
+ // send = one ASCII command per write, with response; sendRaw = a binary write without response
9
+ // (ASSET_DATA frames); maxWrite = the largest write without response (ATT MTU - 3); onMessage gets every
10
+ // TX notification as text.
11
+ //
12
+ // Rules kept from the app: every wait has a timeout; UNKNOWN_CMD:<name> means "update the firmware";
13
+ // a lost ASSET:READY is asked again once (ASSET_STOP, then the PUT again); bytes go at most two ack
14
+ // windows ahead, rewinding on ASSET:RESEND or an ack timeout; a failed install sends APP_ABORT.
15
+ //
16
+ // Environment-neutral (Node and browsers): no Node module, bytes are Uint8Arrays (Buffers work too). The
17
+ // key's hashing and HMAC come from a crypto provider (Session option `crypto`): ../protocol.js gives the
18
+ // Node one (node:crypto), the web IDE a WebCrypto one with a non-extractable key. A provider is
19
+ // { md5Hex(bytes), keyId(key), hmacHex(key, bytes), enrollHex(key) }; the last three may return promises;
20
+ // enrollHex returns null when the raw key is no longer available (it can then only prove itself).
21
+ import { concat, fromBase64, fromHex, md5Hex as md5HexJs, utf8 } from './bytes.js'
22
+
23
+ export const SERVICE_UUID = '12345678-1234-5678-1234-56789abcdef0'
24
+ export const CMD_UUID = '12345678-1234-5678-1234-56789abcdef1'
25
+ export const TX_UUID = '12345678-1234-5678-1234-56789abcdef3'
26
+
27
+ /** Mini apps are modes 6, 7, 8… in APPS_LIST order (runnable ones only). */
28
+ export const FIRST_APP_MODE = 6
29
+ const DATA_HEADER = utf8('ASSET_DATA:') // + 4-byte little-endian offset
30
+ export const DATA_HEADER_BYTES = DATA_HEADER.length + 4
31
+ const MAX_ATTRIBUTE_BYTES = 512
32
+
33
+ export const TIMEOUTS = {
34
+ reply: 5000, // one answer (auth steps, SET_MODE, APP_STATUS…)
35
+ put: 5000, // APP_PUT -> ASSET:READY
36
+ putTries: 2,
37
+ ack: 3000, // no ack for this long: resend from the last acked byte
38
+ maxStalls: 4,
39
+ save: 15000, // last byte -> ASSET:SAVED (write + md5 + rename)
40
+ commit: 20000, // APP_COMMIT: manifest check, rename, rescan
41
+ abort: 4000,
42
+ listIdle: 5000, // APPS_LIST: silence after the last line
43
+ listTries: 3,
44
+ info: 3000,
45
+ shot: 20000,
46
+ authTries: 2,
47
+ files: 15000, // APP_FILES: md5 of every installed file (firmware 0.3.3, off its main loop)
48
+ edit: 20000, // APP_EDIT: staging copy of the installed app
49
+ log: 3000, // APP_LOG:ON → APP:LOG:ON
50
+ pacingStep: 4,
51
+ pacingMax: 30,
52
+ }
53
+
54
+ export class KamojiError extends Error {
55
+ /** @param {string} code @param {string} message @param {string} [hint] */
56
+ constructor(code, message, hint) {
57
+ super(message)
58
+ this.code = code
59
+ this.hint = hint
60
+ }
61
+ }
62
+
63
+ const APP_ERRORS = {
64
+ unsupported: 'This Kamoji firmware has no mini apps: update Kamoji in the Kamoji app.',
65
+ busy: 'Kamoji is busy (another transfer or an update). Try again in a moment.',
66
+ bad_id: 'Kamoji refused the app id (lowercase letters, digits and -, 2 to 40 characters).',
67
+ bad_path: 'Kamoji refused a file path of this app.',
68
+ too_big: 'A file or the app is over the size limit (2 MB).',
69
+ size: 'A file or the app is over the size limit (2 MB).',
70
+ no_space: 'Kamoji is out of storage space. Remove a mini app in the Kamoji app (Apps) and try again.',
71
+ space: 'Kamoji is out of storage space. Remove a mini app in the Kamoji app (Apps) and try again.',
72
+ md5: 'A file arrived damaged. Try again.',
73
+ no_manifest: 'Kamoji got no manifest.json.',
74
+ bad_manifest: "Kamoji refused manifest.json (not valid JSON, an id that differs, or an api_version other than 1).",
75
+ bad_ble:
76
+ "Kamoji refused the app's Bluetooth services (invalid, without the ble.gatt permission, clashing with another app's, or over a limit). The reason is in Kamoji's USB log.",
77
+ not_found: 'This mini app is not on Kamoji.',
78
+ fs: 'Kamoji could not write to its storage. Try again.',
79
+ write: 'Kamoji could not write to its storage. Try again.',
80
+ rename: 'Kamoji could not write to its storage. Try again.',
81
+ mem: 'Kamoji is short of memory right now. Try again.',
82
+ timeout: "Kamoji didn't answer in time. Keep the computer close and try again.",
83
+ state: 'Kamoji lost track of the transfer. Try again.',
84
+ name: 'Kamoji refused a file name.',
85
+ args: 'Kamoji refused a malformed command.',
86
+ }
87
+
88
+ export function errorMessage(code) {
89
+ return `${APP_ERRORS[code] ?? `Kamoji answered an error (${code}).`} [${code}]`
90
+ }
91
+
92
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
93
+
94
+ export const md5Hex = md5HexJs
95
+
96
+ /** The provider used when a Session gets none: md5 only (authorization needs a real one). */
97
+ const NO_KEY_CRYPTO = {
98
+ md5Hex: md5HexJs,
99
+ keyId: () => {
100
+ throw new Error('no crypto provider for the key')
101
+ },
102
+ hmacHex: () => {
103
+ throw new Error('no crypto provider for the key')
104
+ },
105
+ enrollHex: () => null,
106
+ }
107
+
108
+ /** The binary ASSET_DATA write: "ASSET_DATA:", the offset (u32 LE), then the bytes. */
109
+ export function dataFrame(bytes, offset, chunk) {
110
+ const part = bytes.subarray(offset, Math.min(bytes.length, offset + chunk))
111
+ const off = new Uint8Array(4)
112
+ new DataView(off.buffer).setUint32(0, offset, true)
113
+ return concat([DATA_HEADER, off, part])
114
+ }
115
+
116
+ /** The offset of an ASSET_DATA frame (dataFrame's u32 LE). */
117
+ export const frameOffset = (frame) =>
118
+ new DataView(frame.buffer, frame.byteOffset, frame.byteLength).getUint32(DATA_HEADER.length, true)
119
+
120
+ /**
121
+ * Parse `APP:ITEM`, `APP:META`, `APP:STORAGE`, `APP:LIST_END` lines. `APP:META:<id>:?:<reason>` (firmware
122
+ * 0.3.3, size not measured yet) gives bytes: null.
123
+ */
124
+ export function parseListLine(msg) {
125
+ let m
126
+ if ((m = /^APP:ITEM:([01]):([^:]*):([^:]+):(.*)$/.exec(msg)))
127
+ return { type: 'item', ok: m[1] === '1', version: m[2], id: m[3], name: m[4] }
128
+ if ((m = /^APP:META:([^:]+):(\d+|\?):(.*)$/.exec(msg)))
129
+ return { type: 'meta', id: m[1], bytes: m[2] === '?' ? null : Number(m[2]), reason: m[3] }
130
+ if ((m = /^APP:STORAGE:(\d+):(\d+)$/.exec(msg))) return { type: 'storage', used: Number(m[1]), total: Number(m[2]) }
131
+ if ((m = /^APP:LIST_END:(\d+)$/.exec(msg))) return { type: 'end', count: Number(m[1]) }
132
+ return null
133
+ }
134
+
135
+ /** `APP:LOG:<I|W|E>:<app_id>:<text>` (firmware 0.3.3, APP_LOG:ON) → { level, appId, text }, else null. */
136
+ export function parseLogLine(msg) {
137
+ const m = /^APP:LOG:([IWE]):([^:]+):(.*)$/.exec(msg)
138
+ return m ? { level: m[1], appId: m[2], text: m[3] } : null
139
+ }
140
+
141
+ /** `APP:FILE:<app_id>:<md5>:<size>:<path>` (path last, may contain ':') → { appId, md5, size, path }, else null. */
142
+ export function parseFileLine(msg) {
143
+ const m = /^APP:FILE:([^:]+):([0-9a-fA-F]{32}):(\d+):(.+)$/.exec(msg)
144
+ return m ? { appId: m[1], md5: m[2].toLowerCase(), size: Number(m[3]), path: m[4] } : null
145
+ }
146
+
147
+ /**
148
+ * Files an install keeps on Kamoji although the folder doesn't have them: the app's settings and its
149
+ * data. A changed-files update never deletes them either.
150
+ */
151
+ export const isKeptOnKamoji = (p) => p === 'config.json' || p === 'data' || p.startsWith('data/')
152
+
153
+ /**
154
+ * What to send for a changed-files update: local files whose md5 or size differ from the installed
155
+ * ones (or that are new), and installed files the folder no longer has (except isKeptOnKamoji).
156
+ * @param {{path:string, data:Uint8Array, md5:string}[]} local
157
+ * @param {{path:string, md5:string, size:number}[]} remote
158
+ */
159
+ export function diffFiles(local, remote) {
160
+ const there = new Map(remote.map((f) => [f.path, f]))
161
+ const here = new Set(local.map((f) => f.path))
162
+ const changed = local.filter((f) => {
163
+ const r = there.get(f.path)
164
+ return !r || r.md5.toLowerCase() !== f.md5.toLowerCase() || r.size !== f.data.length
165
+ })
166
+ const deleted = remote
167
+ .map((f) => f.path)
168
+ .filter((p) => !here.has(p) && !isKeptOnKamoji(p))
169
+ .sort()
170
+ return { changed, deleted }
171
+ }
172
+
173
+ /** manifest.json first, then by path (the order both tools send). */
174
+ export function orderedFiles(files) {
175
+ return [...files].sort((a, b) =>
176
+ a.path === 'manifest.json' ? -1 : b.path === 'manifest.json' ? 1 : a.path < b.path ? -1 : a.path > b.path ? 1 : 0,
177
+ )
178
+ }
179
+
180
+ /** The mode number of each runnable app, in list order (FIRST_APP_MODE, +1, …). */
181
+ export function appModes(apps) {
182
+ const modes = {}
183
+ let n = FIRST_APP_MODE
184
+ for (const a of apps) if (a.ok) modes[a.id] = n++
185
+ return modes
186
+ }
187
+
188
+ const commandName = (cmd) => cmd.split(':', 1)[0]
189
+
190
+ export class Session {
191
+ /**
192
+ * @param {{send:Function, sendRaw:Function, maxWrite:Function, onMessage:Function}} link
193
+ * @param {{timeouts?: object, crypto?: object, onMessage?: (msg:string)=>void, onLog?: (l:{level:string, appId:string, text:string})=>void}} [opts]
194
+ */
195
+ constructor(link, opts = {}) {
196
+ this.link = link
197
+ this.crypto = opts.crypto ?? NO_KEY_CRYPTO
198
+ this.t = { ...TIMEOUTS, ...(opts.timeouts ?? {}) }
199
+ this.inbox = []
200
+ this.waker = null
201
+ this.queue = Promise.resolve()
202
+ this.noLinkFast = false
203
+ this.noLinkAlive = false
204
+ this.unsubscribe = link.onMessage((text) => {
205
+ const msg = String(text ?? '').replace(/[\r\n\0]+$/g, '').trim()
206
+ if (!msg) return
207
+ opts.onMessage?.(msg)
208
+ // App log lines come at any time: they go to onLog, never into the answers being waited for.
209
+ const log = parseLogLine(msg)
210
+ if (log) {
211
+ opts.onLog?.(log)
212
+ return
213
+ }
214
+ this.inbox.push(msg)
215
+ const w = this.waker
216
+ this.waker = null
217
+ w?.()
218
+ })
219
+ }
220
+
221
+ close() {
222
+ this.unsubscribe?.()
223
+ }
224
+
225
+ /** One exchange at a time (APP:ERR names no command). */
226
+ serial(task) {
227
+ const run = this.queue.then(task, task)
228
+ this.queue = run.catch(() => undefined)
229
+ return run
230
+ }
231
+
232
+ /** The next message, or null after `ms`. */
233
+ next(ms) {
234
+ if (this.inbox.length) return Promise.resolve(this.inbox.shift())
235
+ return new Promise((resolve) => {
236
+ const timer = setTimeout(() => {
237
+ if (this.waker === wake) this.waker = null
238
+ resolve(null)
239
+ }, Math.max(0, ms))
240
+ const wake = () => {
241
+ clearTimeout(timer)
242
+ resolve(this.inbox.shift() ?? null)
243
+ }
244
+ this.waker = wake
245
+ })
246
+ }
247
+
248
+ poll() {
249
+ return this.inbox.shift() ?? null
250
+ }
251
+
252
+ /** Send a command after dropping what came before (late broadcasts are not answers). */
253
+ async ask(cmd) {
254
+ this.inbox.length = 0
255
+ await this.send(cmd)
256
+ }
257
+
258
+ /** link.send, tried again twice when the write itself fails (ATT "insufficient resources"). */
259
+ async send(cmd) {
260
+ for (let attempt = 1; ; attempt++) {
261
+ try {
262
+ return await this.link.send(cmd)
263
+ } catch (e) {
264
+ if (attempt >= 3) throw new KamojiError('link', `Bluetooth write failed: ${e?.message ?? e}`)
265
+ await sleep(250 * attempt)
266
+ }
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Wait until `fn(msg)` returns something other than undefined (that value is returned), for `ms`.
272
+ * AUTH:REQUIRED and UNKNOWN_CMD:<name of cmd> are handled here. Returns undefined on timeout.
273
+ */
274
+ async waitFor(ms, fn, cmd) {
275
+ const end = Date.now() + ms
276
+ for (;;) {
277
+ const msg = await this.next(end - Date.now())
278
+ if (msg === null) return undefined
279
+ if (msg.startsWith('AUTH:REQUIRED:'))
280
+ throw new KamojiError('auth_required', 'Kamoji asked for authorization again (the link was reset).')
281
+ if (cmd && msg === `UNKNOWN_CMD:${commandName(cmd)}`) return fn('unsupported')
282
+ const v = fn(msg)
283
+ if (v !== undefined) return v
284
+ }
285
+ }
286
+
287
+ // ------------------------------------------------------------------ link upkeep
288
+
289
+ async linkFast() {
290
+ if (this.noLinkFast) return
291
+ await this.link.send('LINK_FAST').catch(() => undefined)
292
+ }
293
+
294
+ async linkAlive() {
295
+ if (this.noLinkAlive) return
296
+ await this.link.send('LINK_ALIVE').catch(() => undefined)
297
+ }
298
+
299
+ // ------------------------------------------------------------------ authorization
300
+
301
+ /**
302
+ * AUTH_HELLO, then the proof (trusted) or the key (new and close by).
303
+ * @returns {Promise<{status:'authorized', enrolled:boolean, devices:number, rssi?:number} | {status:'legacy'}>}
304
+ */
305
+ authorize(key) {
306
+ return this.serial(async () => {
307
+ const id = await this.crypto.keyId(key)
308
+ let enrollRssi
309
+ for (let attempt = 1; attempt <= this.t.authTries; attempt++) {
310
+ await this.ask(`AUTH_HELLO:${id}`)
311
+ const hello = await this.waitFor(this.t.reply, (m) => (m === 'unsupported' || m.startsWith('AUTH:') ? m : undefined), 'AUTH_HELLO')
312
+ if (hello === undefined) continue
313
+ if (hello === 'unsupported') return { status: 'legacy' }
314
+ let answer = hello
315
+ if (hello.startsWith('AUTH:CHALLENGE:')) {
316
+ const nonce = fromHex(hello.split(':')[2])
317
+ await this.ask(`AUTH_PROOF:${await this.crypto.hmacHex(key, nonce)}`)
318
+ answer = await this.waitFor(this.t.reply, (m) => (m.startsWith('AUTH:') ? m : undefined))
319
+ } else if (hello.startsWith('AUTH:ENROLL:')) {
320
+ enrollRssi = Number(hello.split(':')[2])
321
+ const raw = await this.crypto.enrollHex(key)
322
+ if (!raw)
323
+ throw new KamojiError(
324
+ 'needs_enroll',
325
+ 'Kamoji no longer trusts this key, and the key can only prove itself (it cannot enrol again).',
326
+ 'Forget this Kamoji here, then connect again close to Kamoji.',
327
+ )
328
+ await this.ask(`AUTH_ENROLL:${raw}`)
329
+ answer = await this.waitFor(this.t.reply, (m) => (m.startsWith('AUTH:') ? m : undefined))
330
+ }
331
+ if (answer === undefined) continue
332
+ const p = answer.split(':')
333
+ if (answer.startsWith('AUTH:OK:'))
334
+ return { status: 'authorized', enrolled: p[2] === '1', devices: Number(p[3] ?? 0), rssi: enrollRssi }
335
+ if (answer.startsWith('AUTH:ERR:FAR:'))
336
+ throw new KamojiError(
337
+ 'far',
338
+ `Kamoji doesn't trust this computer yet, and it is too far to start (signal ${p[3]} dBm, needs ${p[4]} dBm or stronger).`,
339
+ 'The first time, hold the computer right next to Kamoji (in the car), then run this again. Afterwards it works from any distance.',
340
+ )
341
+ if (answer === 'AUTH:ERR:BAD_PROOF')
342
+ throw new KamojiError(
343
+ 'bad_proof',
344
+ 'Kamoji refused this computer\'s key.',
345
+ 'Run "kamoji forget" (or delete the key file) and connect again, close to Kamoji.',
346
+ )
347
+ throw new KamojiError('auth', `Authorization failed (${answer}).`)
348
+ }
349
+ throw new KamojiError('timeout', "Kamoji didn't answer the authorization.", 'Move closer and try again; restart Kamoji if it keeps happening.')
350
+ })
351
+ }
352
+
353
+ /** AUTH_FORGET: Kamoji stops trusting this key. Returns the devices it still trusts, or -1 if it never knew it. */
354
+ forget(key) {
355
+ return this.serial(async () => {
356
+ await this.ask(`AUTH_FORGET:${await this.crypto.keyId(key)}:${await this.crypto.hmacHex(key, utf8('forget'))}`)
357
+ const r = await this.waitFor(this.t.reply, (m) =>
358
+ m.startsWith('AUTH:FORGOT:') ? Number(m.split(':')[2]) : m === 'AUTH:ERR:UNKNOWN' ? -1 : undefined,
359
+ )
360
+ if (r === undefined) throw new KamojiError('timeout', "Kamoji didn't answer AUTH_FORGET.")
361
+ return r
362
+ })
363
+ }
364
+
365
+ // ------------------------------------------------------------------ info, list
366
+
367
+ /** GET_INFO → { fw, nick, assets, uptime } (fields Kamoji sent). */
368
+ info() {
369
+ return this.serial(async () => {
370
+ await this.ask('GET_INFO')
371
+ const out = {}
372
+ const end = Date.now() + this.t.info
373
+ while (Date.now() < end) {
374
+ // After FW: the other lines come right behind it; stop at a short silence.
375
+ const msg = await this.next(out.fw ? Math.min(400, end - Date.now()) : end - Date.now())
376
+ if (msg === null) break
377
+ const [k, ...rest] = msg.split(':')
378
+ const v = rest.join(':')
379
+ if (k === 'FW') out.fw = v
380
+ else if (k === 'NICK') out.nick = v
381
+ else if (k === 'AT') out.assets = Number(v)
382
+ else if (k === 'UPTIME') out.uptime = Number(v)
383
+ }
384
+ if (!out.fw) throw new KamojiError('timeout', "Kamoji didn't answer GET_INFO.")
385
+ return out
386
+ })
387
+ }
388
+
389
+ /** APPS_LIST → { apps: [{ok, version, id, name, bytes?, reason?}], storage?: {used,total}, modes } */
390
+ listApps() {
391
+ return this.serial(async () => {
392
+ let last = null
393
+ for (let attempt = 1; attempt <= this.t.listTries; attempt++) {
394
+ await this.ask('APPS_LIST')
395
+ const apps = []
396
+ const metas = {}
397
+ let storage
398
+ let end = null
399
+ let unsupported = false
400
+ for (;;) {
401
+ const msg = await this.next(this.t.listIdle)
402
+ if (msg === null) break
403
+ if (msg === 'UNKNOWN_CMD:APPS_LIST') {
404
+ unsupported = true
405
+ break
406
+ }
407
+ if (msg.startsWith('APP:ERR:')) throw new KamojiError(msg.slice(8), errorMessage(msg.slice(8)))
408
+ const p = parseListLine(msg)
409
+ if (!p) continue
410
+ if (p.type === 'item') apps.push(p)
411
+ else if (p.type === 'meta') metas[p.id] = p
412
+ else if (p.type === 'storage') storage = p
413
+ else if (p.type === 'end') {
414
+ end = p.count
415
+ break
416
+ }
417
+ }
418
+ if (unsupported) throw new KamojiError('unsupported', errorMessage('unsupported'))
419
+ for (const a of apps) if (metas[a.id]) Object.assign(a, { bytes: metas[a.id].bytes, reason: metas[a.id].reason })
420
+ last = { apps, storage, modes: appModes(apps), complete: end !== null && apps.length >= end }
421
+ if (last.complete) return last
422
+ }
423
+ if (last && last.apps.length) return last
424
+ throw new KamojiError('timeout', "Kamoji didn't send its list of mini apps.")
425
+ })
426
+ }
427
+
428
+ // ------------------------------------------------------------------ install
429
+
430
+ /**
431
+ * One file: APP_PUT → ASSET:READY → ASSET_DATA frames (acked, resent) → ASSET:SAVED:<id>:<path>.
432
+ * @param {(sent:number)=>void} [onBytes]
433
+ */
434
+ async putFile(appId, path, bytes, onBytes) {
435
+ const cmd = `APP_PUT:${bytes.length}:${this.crypto.md5Hex(bytes)}:${appId}:${path}`
436
+ const savedName = `${appId}:${path}`
437
+ const maxWrite = Math.min(this.link.maxWrite(), MAX_ATTRIBUTE_BYTES)
438
+ const chunk = maxWrite - DATA_HEADER_BYTES
439
+ if (chunk <= 0) throw new KamojiError('link', 'The Bluetooth link is too small for a file transfer (MTU).')
440
+ const s = { acked: 0, resendFrom: null, error: null, saved: false, sending: false }
441
+ const absorb = (msg) => {
442
+ if (msg === null) return
443
+ if (msg.startsWith('AUTH:REQUIRED:')) {
444
+ s.error = 'auth_required'
445
+ return
446
+ }
447
+ if (msg === 'UNKNOWN_CMD:APP_PUT') s.error = 'unsupported'
448
+ let m
449
+ if ((m = /^ASSET:ACK:(\d+)/.exec(msg))) s.acked = Math.max(s.acked, Number(m[1]))
450
+ else if ((m = /^ASSET:RESEND:(\d+)/.exec(msg))) {
451
+ s.acked = Math.max(s.acked, Number(m[1]))
452
+ s.resendFrom = Number(m[1])
453
+ } else if (msg === `ASSET:SAVED:${savedName}`) s.saved = true
454
+ else if ((m = /^(?:ASSET|APP):ERR:([^:]+)/.exec(msg))) {
455
+ // A late frame of an earlier file answers 'state' before this one started: not ours.
456
+ if (s.sending || m[1] !== 'state') s.error = m[1]
457
+ }
458
+ }
459
+ const fail = (code) => {
460
+ throw new KamojiError(code, code === 'auth_required' ? 'Kamoji asked for authorization again.' : errorMessage(code))
461
+ }
462
+ try {
463
+ // 1. APP_PUT → ASSET:READY:<ackEvery> (put once more if READY was lost)
464
+ await this.ask(cmd)
465
+ let ackEvery = 0
466
+ let tries = 1
467
+ let readyBy = Date.now() + this.t.put
468
+ while (!ackEvery) {
469
+ const msg = await this.next(readyBy - Date.now())
470
+ if (msg === null) {
471
+ if (tries < this.t.putTries) {
472
+ tries++
473
+ await this.link.send('ASSET_STOP').catch(() => undefined)
474
+ await this.ask(cmd)
475
+ readyBy = Date.now() + this.t.put
476
+ continue
477
+ }
478
+ fail('timeout')
479
+ }
480
+ const m = /^ASSET:READY:(\d+)/.exec(msg)
481
+ if (m) ackEvery = Number(m[1]) || 4096
482
+ else absorb(msg)
483
+ if (s.error) fail(s.error)
484
+ }
485
+ // 2. The bytes, at most two ack windows ahead.
486
+ s.sending = true
487
+ const window = ackEvery * 2
488
+ let offset = 0
489
+ let pacing = 0
490
+ let stalls = 0
491
+ const size = bytes.length
492
+ while (s.acked < size) {
493
+ if (s.error) fail(s.error)
494
+ if (s.resendFrom !== null) {
495
+ offset = s.resendFrom
496
+ s.resendFrom = null
497
+ pacing = Math.min(pacing + this.t.pacingStep, this.t.pacingMax)
498
+ }
499
+ if (offset >= size || offset >= s.acked + window) {
500
+ const before = s.acked
501
+ absorb(await this.next(this.t.ack))
502
+ if (s.acked > before || s.resendFrom !== null || s.error) {
503
+ onBytes?.(s.acked)
504
+ continue
505
+ }
506
+ if (++stalls > this.t.maxStalls) fail('timeout')
507
+ offset = s.acked
508
+ pacing = Math.min(pacing + this.t.pacingStep, this.t.pacingMax)
509
+ continue
510
+ }
511
+ const frame = dataFrame(bytes, offset, chunk)
512
+ await this.link.sendRaw(frame)
513
+ offset += frame.length - DATA_HEADER_BYTES
514
+ for (let msg = this.poll(); msg !== null; msg = this.poll()) absorb(msg)
515
+ if (pacing) await sleep(pacing)
516
+ }
517
+ onBytes?.(size)
518
+ // 3. Written, md5 checked, renamed.
519
+ const savedBy = Date.now() + this.t.save
520
+ while (!s.saved) {
521
+ if (s.error) fail(s.error)
522
+ const msg = await this.next(savedBy - Date.now())
523
+ if (msg === null) fail('timeout')
524
+ absorb(msg)
525
+ }
526
+ } catch (e) {
527
+ if (!s.saved) await this.link.send('ASSET_STOP').catch(() => undefined)
528
+ throw e
529
+ }
530
+ }
531
+
532
+ /**
533
+ * The whole install: every file (manifest.json first), then APP_COMMIT. APP_ABORT on failure.
534
+ * @param {{path:string, data:Uint8Array}[]} files
535
+ * @param {(p:{file:string, index:number, files:number, sent:number, total:number})=>void} [onProgress]
536
+ * @returns {Promise<{version:string, bytes:number}>}
537
+ */
538
+ install(appId, files, onProgress) {
539
+ return this.serial(async () => {
540
+ try {
541
+ const bytes = await this._putAll(appId, files, onProgress)
542
+ return { version: await this._commit(appId), bytes }
543
+ } catch (e) {
544
+ await this._abort(appId, e)
545
+ throw e
546
+ }
547
+ })
548
+ }
549
+
550
+ async _putAll(appId, files, onProgress) {
551
+ const ordered = orderedFiles(files)
552
+ const total = ordered.reduce((n, f) => n + f.data.length, 0)
553
+ let done = 0
554
+ for (let i = 0; i < ordered.length; i++) {
555
+ const f = ordered[i]
556
+ await this.putFile(appId, f.path, f.data, (sent) =>
557
+ onProgress?.({ file: f.path, index: i, files: ordered.length, sent: done + sent, total }),
558
+ )
559
+ done += f.data.length
560
+ }
561
+ return total
562
+ }
563
+
564
+ /** APP_COMMIT → the installed version. */
565
+ async _commit(appId) {
566
+ await this.ask(`APP_COMMIT:${appId}`)
567
+ const r = await this.waitFor(this.t.commit, (m) => {
568
+ if (m === 'unsupported') return { err: 'unsupported' }
569
+ if (m.startsWith(`APP:INSTALLED:${appId}:`)) return { version: m.slice(`APP:INSTALLED:${appId}:`.length) }
570
+ if (m.startsWith('APP:ERR:')) return { err: m.slice(8).split(':')[0] }
571
+ return undefined
572
+ }, 'APP_COMMIT')
573
+ if (r === undefined) throw new KamojiError('timeout', "Kamoji didn't confirm the install (APP_COMMIT).")
574
+ if (r.err) throw new KamojiError(r.err, errorMessage(r.err))
575
+ return r.version
576
+ }
577
+
578
+ async _abort(appId, e) {
579
+ if (e?.code === 'link') return
580
+ await this.ask(`APP_ABORT:${appId}`).catch(() => undefined)
581
+ await this.waitFor(this.t.abort, (m) => (m === `APP:ABORTED:${appId}` || m.startsWith('APP:ERR:') ? m : undefined)).catch(
582
+ () => undefined,
583
+ )
584
+ }
585
+
586
+ // ------------------------------------------------------------------ changed-files update (firmware 0.3.3)
587
+
588
+ /**
589
+ * APP_FILES:<id> → the installed app's files.
590
+ * @returns {Promise<{status:'ok', files:{path:string, md5:string, size:number}[]} | {status:'not_installed'|'unsupported'|'incomplete'}>}
591
+ */
592
+ installedFiles(appId) {
593
+ return this.serial(async () => {
594
+ await this.ask(`APP_FILES:${appId}`)
595
+ const files = []
596
+ const r = await this.waitFor(this.t.files, (m) => {
597
+ if (m === 'unsupported') return { status: 'unsupported' }
598
+ const f = parseFileLine(m)
599
+ if (f) {
600
+ if (f.appId === appId) files.push({ path: f.path, md5: f.md5, size: f.size })
601
+ return undefined
602
+ }
603
+ const end = /^APP:FILES_END:([^:]+):(\d+)$/.exec(m)
604
+ if (end && end[1] === appId) return { status: 'end', count: Number(end[2]) }
605
+ if (m === 'APP:ERR:not_found') return { status: 'not_installed' }
606
+ if (m.startsWith('APP:ERR:')) return { status: 'incomplete' }
607
+ return undefined
608
+ }, 'APP_FILES')
609
+ if (r === undefined) return { status: 'incomplete' }
610
+ if (r.status !== 'end') return r
611
+ // A lost notification: don't trust the list (a full install instead).
612
+ if (r.count !== files.length) return { status: 'incomplete' }
613
+ return { status: 'ok', files }
614
+ })
615
+ }
616
+
617
+ /**
618
+ * Changed-files update: APP_EDIT (Kamoji stages a copy of the installed app), APP_PUT for each changed
619
+ * or new file, APP_DELETE for each removed one, APP_COMMIT. APP_ABORT on a failure after APP_EDIT.
620
+ * When Kamoji can't start it (older firmware, APP:ERR), returns { fallback: code } and nothing is staged:
621
+ * the caller does a full install.
622
+ * @returns {Promise<{version:string, bytes:number} | {fallback:string}>}
623
+ */
624
+ update(appId, changed, deleted, onProgress) {
625
+ return this.serial(async () => {
626
+ await this.ask(`APP_EDIT:${appId}`)
627
+ const edit = await this.waitFor(this.t.edit, (m) => {
628
+ if (m === 'unsupported') return { fallback: 'unsupported' }
629
+ if (m.startsWith(`APP:EDIT:${appId}:`)) return { ok: true }
630
+ if (m.startsWith('APP:ERR:')) return { fallback: m.slice(8).split(':')[0] }
631
+ return undefined
632
+ }, 'APP_EDIT')
633
+ if (edit === undefined) {
634
+ await this._abort(appId) // it may still be copying
635
+ return { fallback: 'timeout' }
636
+ }
637
+ if (edit.fallback) return edit
638
+ try {
639
+ const bytes = await this._putAll(appId, changed, onProgress)
640
+ for (const p of deleted) {
641
+ await this.ask(`APP_DELETE:${appId}:${p}`)
642
+ const r = await this.waitFor(this.t.reply, (m) => {
643
+ if (m === `APP:DELETED:${appId}:${p}`) return { ok: true }
644
+ if (m.startsWith('APP:ERR:')) return { err: m.slice(8).split(':')[0] }
645
+ return undefined
646
+ })
647
+ if (r === undefined) throw new KamojiError('timeout', `Kamoji didn't confirm deleting ${p} (APP_DELETE).`)
648
+ if (r.err) throw new KamojiError(r.err, errorMessage(r.err))
649
+ }
650
+ return { version: await this._commit(appId), bytes }
651
+ } catch (e) {
652
+ await this._abort(appId, e)
653
+ throw e
654
+ }
655
+ })
656
+ }
657
+
658
+ // ------------------------------------------------------------------ app log over Bluetooth (firmware 0.3.3)
659
+
660
+ /** APP_LOG:ON[:<id>] → true, false when the firmware has no Bluetooth log, null when unanswered. */
661
+ appLog(appId) {
662
+ return this.serial(async () => {
663
+ await this.ask(appId ? `APP_LOG:ON:${appId}` : 'APP_LOG:ON')
664
+ const r = await this.waitFor(this.t.log, (m) => (m === 'unsupported' ? false : m === 'APP:LOG:ON' ? true : undefined), 'APP_LOG')
665
+ return r === undefined ? null : r
666
+ })
667
+ }
668
+
669
+ // ------------------------------------------------------------------ open, status, screenshot, reboot
670
+
671
+ /**
672
+ * Switch Kamoji to the app: its mode from APPS_LIST, then SET_MODE (a no-op when it is already on
673
+ * screen: APP_COMMIT restarted it). Returns { mode, confirmed, list }.
674
+ */
675
+ async open(appId, list) {
676
+ list = list ?? (await this.listApps())
677
+ const app = list.apps.find((a) => a.id === appId)
678
+ if (!app) throw new KamojiError('not_found', `${appId} is not on Kamoji.`)
679
+ if (!app.ok)
680
+ throw new KamojiError('not_runnable', `Kamoji can't run ${appId}: ${app.reason || 'its manifest was refused'}.`)
681
+ const mode = list.modes[appId]
682
+ return this.serial(async () => {
683
+ await this.ask(`SET_MODE:${mode}`)
684
+ const got = await this.waitFor(this.t.reply, (m) => {
685
+ const mm = /^SETTING:ui_mode=(-?\d+)/.exec(m)
686
+ return mm ? Number(mm[1]) : undefined
687
+ })
688
+ if (got === undefined) return { mode, confirmed: false, list }
689
+ if (got !== mode)
690
+ throw new KamojiError(
691
+ 'mode_refused',
692
+ `Kamoji stayed on mode ${got} instead of opening ${appId} (mode ${mode}).`,
693
+ 'It refuses to switch while it plays with another Kamoji or during a full-screen animation: try again in a moment.',
694
+ )
695
+ return { mode, confirmed: true, list }
696
+ })
697
+ }
698
+
699
+ /** APP_STATUS → 'ready' | 'pending_restart' | 'profile_error' | 'cleanup_pending' | null (older firmware). */
700
+ status(appId) {
701
+ return this.serial(async () => {
702
+ await this.ask(`APP_STATUS:${appId}`)
703
+ const r = await this.waitFor(this.t.reply, (m) => {
704
+ if (m === 'unsupported') return null
705
+ if (m.startsWith(`APP:STATUS:${appId}:`)) return m.slice(`APP:STATUS:${appId}:`.length)
706
+ if (m.startsWith('APP:ERR:')) return { err: m.slice(8) }
707
+ return undefined
708
+ }, 'APP_STATUS')
709
+ if (r === undefined) return null
710
+ if (r && typeof r === 'object') throw new KamojiError(r.err, errorMessage(r.err))
711
+ return r
712
+ })
713
+ }
714
+
715
+ /** SCREEN_GRAB → the JPEG (Uint8Array). */
716
+ screenshot() {
717
+ return this.serial(async () => {
718
+ await this.ask('SCREEN_GRAB')
719
+ let size = null
720
+ let buf = null
721
+ let got = 0
722
+ const end = Date.now() + this.t.shot
723
+ for (;;) {
724
+ const msg = await this.next(end - Date.now())
725
+ if (msg === null) throw new KamojiError('timeout', 'The screenshot timed out.')
726
+ if (msg === 'UNKNOWN_CMD:SCREEN_GRAB') throw new KamojiError('unsupported', 'This firmware has no Bluetooth screenshot.')
727
+ let m
728
+ if ((m = /^SHOT:ERR:(.*)$/.exec(msg))) throw new KamojiError(m[1], `Screenshot failed (${m[1]}).`)
729
+ if ((m = /^SHOT:BEGIN:(\d+):(\d+):(\d+)/.exec(msg))) {
730
+ size = Number(m[1])
731
+ buf = new Uint8Array(size)
732
+ got = 0
733
+ } else if ((m = /^SHOT:DATA:(\d+):(.*)$/.exec(msg)) && buf) {
734
+ const part = fromBase64(m[2])
735
+ const at = Number(m[1])
736
+ if (at < size) buf.set(part.subarray(0, size - at), at)
737
+ got += part.length
738
+ } else if (/^SHOT:END:/.test(msg) && buf) {
739
+ if (got !== size) throw new KamojiError('lost', `Screenshot incomplete (${got} of ${size} bytes): a notification was lost. Try again.`)
740
+ return buf
741
+ }
742
+ }
743
+ })
744
+ }
745
+
746
+ async reboot() {
747
+ await this.link.send('REBOOT').catch(() => undefined)
748
+ }
749
+ }