kamoji-dev 0.0.0-stage → 0.1.0

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,574 @@
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
+ import crypto from 'node:crypto'
16
+
17
+ export const SERVICE_UUID = '12345678-1234-5678-1234-56789abcdef0'
18
+ export const CMD_UUID = '12345678-1234-5678-1234-56789abcdef1'
19
+ export const TX_UUID = '12345678-1234-5678-1234-56789abcdef3'
20
+
21
+ /** Mini apps are modes 6, 7, 8… in APPS_LIST order (runnable ones only). */
22
+ export const FIRST_APP_MODE = 6
23
+ const DATA_HEADER = Buffer.from('ASSET_DATA:', 'ascii') // + 4-byte little-endian offset
24
+ export const DATA_HEADER_BYTES = DATA_HEADER.length + 4
25
+ const MAX_ATTRIBUTE_BYTES = 512
26
+
27
+ export const TIMEOUTS = {
28
+ reply: 5000, // one answer (auth steps, SET_MODE, APP_STATUS…)
29
+ put: 5000, // APP_PUT -> ASSET:READY
30
+ putTries: 2,
31
+ ack: 3000, // no ack for this long: resend from the last acked byte
32
+ maxStalls: 4,
33
+ save: 15000, // last byte -> ASSET:SAVED (write + md5 + rename)
34
+ commit: 20000, // APP_COMMIT: manifest check, rename, rescan
35
+ abort: 4000,
36
+ listIdle: 5000, // APPS_LIST: silence after the last line
37
+ listTries: 3,
38
+ info: 3000,
39
+ shot: 20000,
40
+ authTries: 2,
41
+ pacingStep: 4,
42
+ pacingMax: 30,
43
+ }
44
+
45
+ export class KamojiError extends Error {
46
+ /** @param {string} code @param {string} message @param {string} [hint] */
47
+ constructor(code, message, hint) {
48
+ super(message)
49
+ this.code = code
50
+ this.hint = hint
51
+ }
52
+ }
53
+
54
+ const APP_ERRORS = {
55
+ unsupported: 'This Kamoji firmware has no mini apps: update Kamoji in the Kamoji app.',
56
+ busy: 'Kamoji is busy (another transfer or an update). Try again in a moment.',
57
+ bad_id: 'Kamoji refused the app id (lowercase letters, digits and -, 2 to 40 characters).',
58
+ bad_path: 'Kamoji refused a file path of this app.',
59
+ too_big: 'A file or the app is over the size limit (2 MB).',
60
+ size: 'A file or the app is over the size limit (2 MB).',
61
+ no_space: 'Kamoji is out of storage space. Remove a mini app in the Kamoji app (Apps) and try again.',
62
+ space: 'Kamoji is out of storage space. Remove a mini app in the Kamoji app (Apps) and try again.',
63
+ md5: 'A file arrived damaged. Try again.',
64
+ no_manifest: 'Kamoji got no manifest.json.',
65
+ bad_manifest: "Kamoji refused manifest.json (not valid JSON, an id that differs, or an api_version other than 1).",
66
+ bad_ble:
67
+ "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.",
68
+ not_found: 'This mini app is not on Kamoji.',
69
+ fs: 'Kamoji could not write to its storage. Try again.',
70
+ write: 'Kamoji could not write to its storage. Try again.',
71
+ rename: 'Kamoji could not write to its storage. Try again.',
72
+ mem: 'Kamoji is short of memory right now. Try again.',
73
+ timeout: "Kamoji didn't answer in time. Keep the computer close and try again.",
74
+ state: 'Kamoji lost track of the transfer. Try again.',
75
+ name: 'Kamoji refused a file name.',
76
+ args: 'Kamoji refused a malformed command.',
77
+ }
78
+
79
+ export function errorMessage(code) {
80
+ return `${APP_ERRORS[code] ?? `Kamoji answered an error (${code}).`} [${code}]`
81
+ }
82
+
83
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
84
+
85
+ export function keyId(key) {
86
+ return crypto.createHash('sha256').update(key).digest().subarray(0, 8).toString('hex')
87
+ }
88
+ export function hmacHex(key, data) {
89
+ return crypto.createHmac('sha256', key).update(data).digest('hex')
90
+ }
91
+ export function md5Hex(data) {
92
+ return crypto.createHash('md5').update(data).digest('hex')
93
+ }
94
+
95
+ /** The binary ASSET_DATA write: "ASSET_DATA:", the offset (u32 LE), then the bytes. */
96
+ export function dataFrame(bytes, offset, chunk) {
97
+ const part = bytes.subarray(offset, Math.min(bytes.length, offset + chunk))
98
+ const off = Buffer.alloc(4)
99
+ off.writeUInt32LE(offset)
100
+ return Buffer.concat([DATA_HEADER, off, part])
101
+ }
102
+
103
+ /** Parse `APP:ITEM`, `APP:META`, `APP:STORAGE`, `APP:LIST_END` lines. */
104
+ export function parseListLine(msg) {
105
+ let m
106
+ if ((m = /^APP:ITEM:([01]):([^:]*):([^:]+):(.*)$/.exec(msg)))
107
+ return { type: 'item', ok: m[1] === '1', version: m[2], id: m[3], name: m[4] }
108
+ if ((m = /^APP:META:([^:]+):(\d+):(.*)$/.exec(msg))) return { type: 'meta', id: m[1], bytes: Number(m[2]), reason: m[3] }
109
+ if ((m = /^APP:STORAGE:(\d+):(\d+)$/.exec(msg))) return { type: 'storage', used: Number(m[1]), total: Number(m[2]) }
110
+ if ((m = /^APP:LIST_END:(\d+)$/.exec(msg))) return { type: 'end', count: Number(m[1]) }
111
+ return null
112
+ }
113
+
114
+ /** The mode number of each runnable app, in list order (FIRST_APP_MODE, +1, …). */
115
+ export function appModes(apps) {
116
+ const modes = {}
117
+ let n = FIRST_APP_MODE
118
+ for (const a of apps) if (a.ok) modes[a.id] = n++
119
+ return modes
120
+ }
121
+
122
+ const commandName = (cmd) => cmd.split(':', 1)[0]
123
+
124
+ export class Session {
125
+ /**
126
+ * @param {{send:Function, sendRaw:Function, maxWrite:Function, onMessage:Function}} link
127
+ * @param {{timeouts?: object, onOther?: (msg:string)=>void}} [opts]
128
+ */
129
+ constructor(link, opts = {}) {
130
+ this.link = link
131
+ this.t = { ...TIMEOUTS, ...(opts.timeouts ?? {}) }
132
+ this.inbox = []
133
+ this.waker = null
134
+ this.queue = Promise.resolve()
135
+ this.noLinkFast = false
136
+ this.noLinkAlive = false
137
+ this.unsubscribe = link.onMessage((text) => {
138
+ const msg = String(text ?? '').replace(/[\r\n\0]+$/g, '').trim()
139
+ if (!msg) return
140
+ this.inbox.push(msg)
141
+ opts.onMessage?.(msg)
142
+ const w = this.waker
143
+ this.waker = null
144
+ w?.()
145
+ })
146
+ }
147
+
148
+ close() {
149
+ this.unsubscribe?.()
150
+ }
151
+
152
+ /** One exchange at a time (APP:ERR names no command). */
153
+ serial(task) {
154
+ const run = this.queue.then(task, task)
155
+ this.queue = run.catch(() => undefined)
156
+ return run
157
+ }
158
+
159
+ /** The next message, or null after `ms`. */
160
+ next(ms) {
161
+ if (this.inbox.length) return Promise.resolve(this.inbox.shift())
162
+ return new Promise((resolve) => {
163
+ const timer = setTimeout(() => {
164
+ if (this.waker === wake) this.waker = null
165
+ resolve(null)
166
+ }, Math.max(0, ms))
167
+ const wake = () => {
168
+ clearTimeout(timer)
169
+ resolve(this.inbox.shift() ?? null)
170
+ }
171
+ this.waker = wake
172
+ })
173
+ }
174
+
175
+ poll() {
176
+ return this.inbox.shift() ?? null
177
+ }
178
+
179
+ /** Send a command after dropping what came before (late broadcasts are not answers). */
180
+ async ask(cmd) {
181
+ this.inbox.length = 0
182
+ await this.send(cmd)
183
+ }
184
+
185
+ /** link.send, tried again twice when the write itself fails (ATT "insufficient resources"). */
186
+ async send(cmd) {
187
+ for (let attempt = 1; ; attempt++) {
188
+ try {
189
+ return await this.link.send(cmd)
190
+ } catch (e) {
191
+ if (attempt >= 3) throw new KamojiError('link', `Bluetooth write failed: ${e?.message ?? e}`)
192
+ await sleep(250 * attempt)
193
+ }
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Wait until `fn(msg)` returns something other than undefined (that value is returned), for `ms`.
199
+ * AUTH:REQUIRED and UNKNOWN_CMD:<name of cmd> are handled here. Returns undefined on timeout.
200
+ */
201
+ async waitFor(ms, fn, cmd) {
202
+ const end = Date.now() + ms
203
+ for (;;) {
204
+ const msg = await this.next(end - Date.now())
205
+ if (msg === null) return undefined
206
+ if (msg.startsWith('AUTH:REQUIRED:'))
207
+ throw new KamojiError('auth_required', 'Kamoji asked for authorization again (the link was reset).')
208
+ if (cmd && msg === `UNKNOWN_CMD:${commandName(cmd)}`) return fn('unsupported')
209
+ const v = fn(msg)
210
+ if (v !== undefined) return v
211
+ }
212
+ }
213
+
214
+ // ------------------------------------------------------------------ link upkeep
215
+
216
+ async linkFast() {
217
+ if (this.noLinkFast) return
218
+ await this.link.send('LINK_FAST').catch(() => undefined)
219
+ }
220
+
221
+ async linkAlive() {
222
+ if (this.noLinkAlive) return
223
+ await this.link.send('LINK_ALIVE').catch(() => undefined)
224
+ }
225
+
226
+ // ------------------------------------------------------------------ authorization
227
+
228
+ /**
229
+ * AUTH_HELLO, then the proof (trusted) or the key (new and close by).
230
+ * @returns {Promise<{status:'authorized', enrolled:boolean, devices:number, rssi?:number} | {status:'legacy'}>}
231
+ */
232
+ authorize(key) {
233
+ return this.serial(async () => {
234
+ const id = keyId(key)
235
+ let enrollRssi
236
+ for (let attempt = 1; attempt <= this.t.authTries; attempt++) {
237
+ await this.ask(`AUTH_HELLO:${id}`)
238
+ const hello = await this.waitFor(this.t.reply, (m) => (m === 'unsupported' || m.startsWith('AUTH:') ? m : undefined), 'AUTH_HELLO')
239
+ if (hello === undefined) continue
240
+ if (hello === 'unsupported') return { status: 'legacy' }
241
+ let answer = hello
242
+ if (hello.startsWith('AUTH:CHALLENGE:')) {
243
+ const nonce = Buffer.from(hello.split(':')[2], 'hex')
244
+ await this.ask(`AUTH_PROOF:${hmacHex(key, nonce)}`)
245
+ answer = await this.waitFor(this.t.reply, (m) => (m.startsWith('AUTH:') ? m : undefined))
246
+ } else if (hello.startsWith('AUTH:ENROLL:')) {
247
+ enrollRssi = Number(hello.split(':')[2])
248
+ await this.ask(`AUTH_ENROLL:${key.toString('hex')}`)
249
+ answer = await this.waitFor(this.t.reply, (m) => (m.startsWith('AUTH:') ? m : undefined))
250
+ }
251
+ if (answer === undefined) continue
252
+ const p = answer.split(':')
253
+ if (answer.startsWith('AUTH:OK:'))
254
+ return { status: 'authorized', enrolled: p[2] === '1', devices: Number(p[3] ?? 0), rssi: enrollRssi }
255
+ if (answer.startsWith('AUTH:ERR:FAR:'))
256
+ throw new KamojiError(
257
+ 'far',
258
+ `Kamoji doesn't trust this computer yet, and it is too far to start (signal ${p[3]} dBm, needs ${p[4]} dBm or stronger).`,
259
+ 'The first time, hold the computer right next to Kamoji (in the car), then run this again. Afterwards it works from any distance.',
260
+ )
261
+ if (answer === 'AUTH:ERR:BAD_PROOF')
262
+ throw new KamojiError(
263
+ 'bad_proof',
264
+ 'Kamoji refused this computer\'s key.',
265
+ 'Run "kamoji forget" (or delete the key file) and connect again, close to Kamoji.',
266
+ )
267
+ throw new KamojiError('auth', `Authorization failed (${answer}).`)
268
+ }
269
+ throw new KamojiError('timeout', "Kamoji didn't answer the authorization.", 'Move closer and try again; restart Kamoji if it keeps happening.')
270
+ })
271
+ }
272
+
273
+ /** AUTH_FORGET: Kamoji stops trusting this key. Returns the devices it still trusts, or -1 if it never knew it. */
274
+ forget(key) {
275
+ return this.serial(async () => {
276
+ await this.ask(`AUTH_FORGET:${keyId(key)}:${hmacHex(key, Buffer.from('forget'))}`)
277
+ const r = await this.waitFor(this.t.reply, (m) =>
278
+ m.startsWith('AUTH:FORGOT:') ? Number(m.split(':')[2]) : m === 'AUTH:ERR:UNKNOWN' ? -1 : undefined,
279
+ )
280
+ if (r === undefined) throw new KamojiError('timeout', "Kamoji didn't answer AUTH_FORGET.")
281
+ return r
282
+ })
283
+ }
284
+
285
+ // ------------------------------------------------------------------ info, list
286
+
287
+ /** GET_INFO → { fw, nick, assets, uptime } (fields Kamoji sent). */
288
+ info() {
289
+ return this.serial(async () => {
290
+ await this.ask('GET_INFO')
291
+ const out = {}
292
+ const end = Date.now() + this.t.info
293
+ while (Date.now() < end) {
294
+ // After FW: the other lines come right behind it; stop at a short silence.
295
+ const msg = await this.next(out.fw ? Math.min(400, end - Date.now()) : end - Date.now())
296
+ if (msg === null) break
297
+ const [k, ...rest] = msg.split(':')
298
+ const v = rest.join(':')
299
+ if (k === 'FW') out.fw = v
300
+ else if (k === 'NICK') out.nick = v
301
+ else if (k === 'AT') out.assets = Number(v)
302
+ else if (k === 'UPTIME') out.uptime = Number(v)
303
+ }
304
+ if (!out.fw) throw new KamojiError('timeout', "Kamoji didn't answer GET_INFO.")
305
+ return out
306
+ })
307
+ }
308
+
309
+ /** APPS_LIST → { apps: [{ok, version, id, name, bytes?, reason?}], storage?: {used,total}, modes } */
310
+ listApps() {
311
+ return this.serial(async () => {
312
+ let last = null
313
+ for (let attempt = 1; attempt <= this.t.listTries; attempt++) {
314
+ await this.ask('APPS_LIST')
315
+ const apps = []
316
+ const metas = {}
317
+ let storage
318
+ let end = null
319
+ let unsupported = false
320
+ for (;;) {
321
+ const msg = await this.next(this.t.listIdle)
322
+ if (msg === null) break
323
+ if (msg === 'UNKNOWN_CMD:APPS_LIST') {
324
+ unsupported = true
325
+ break
326
+ }
327
+ if (msg.startsWith('APP:ERR:')) throw new KamojiError(msg.slice(8), errorMessage(msg.slice(8)))
328
+ const p = parseListLine(msg)
329
+ if (!p) continue
330
+ if (p.type === 'item') apps.push(p)
331
+ else if (p.type === 'meta') metas[p.id] = p
332
+ else if (p.type === 'storage') storage = p
333
+ else if (p.type === 'end') {
334
+ end = p.count
335
+ break
336
+ }
337
+ }
338
+ if (unsupported) throw new KamojiError('unsupported', errorMessage('unsupported'))
339
+ for (const a of apps) if (metas[a.id]) Object.assign(a, { bytes: metas[a.id].bytes, reason: metas[a.id].reason })
340
+ last = { apps, storage, modes: appModes(apps), complete: end !== null && apps.length >= end }
341
+ if (last.complete) return last
342
+ }
343
+ if (last && last.apps.length) return last
344
+ throw new KamojiError('timeout', "Kamoji didn't send its list of mini apps.")
345
+ })
346
+ }
347
+
348
+ // ------------------------------------------------------------------ install
349
+
350
+ /**
351
+ * One file: APP_PUT → ASSET:READY → ASSET_DATA frames (acked, resent) → ASSET:SAVED:<id>:<path>.
352
+ * @param {(sent:number)=>void} [onBytes]
353
+ */
354
+ async putFile(appId, path, bytes, onBytes) {
355
+ const cmd = `APP_PUT:${bytes.length}:${md5Hex(bytes)}:${appId}:${path}`
356
+ const savedName = `${appId}:${path}`
357
+ const maxWrite = Math.min(this.link.maxWrite(), MAX_ATTRIBUTE_BYTES)
358
+ const chunk = maxWrite - DATA_HEADER_BYTES
359
+ if (chunk <= 0) throw new KamojiError('link', 'The Bluetooth link is too small for a file transfer (MTU).')
360
+ const s = { acked: 0, resendFrom: null, error: null, saved: false, sending: false }
361
+ const absorb = (msg) => {
362
+ if (msg === null) return
363
+ if (msg.startsWith('AUTH:REQUIRED:')) {
364
+ s.error = 'auth_required'
365
+ return
366
+ }
367
+ if (msg === 'UNKNOWN_CMD:APP_PUT') s.error = 'unsupported'
368
+ let m
369
+ if ((m = /^ASSET:ACK:(\d+)/.exec(msg))) s.acked = Math.max(s.acked, Number(m[1]))
370
+ else if ((m = /^ASSET:RESEND:(\d+)/.exec(msg))) {
371
+ s.acked = Math.max(s.acked, Number(m[1]))
372
+ s.resendFrom = Number(m[1])
373
+ } else if (msg === `ASSET:SAVED:${savedName}`) s.saved = true
374
+ else if ((m = /^(?:ASSET|APP):ERR:([^:]+)/.exec(msg))) {
375
+ // A late frame of an earlier file answers 'state' before this one started: not ours.
376
+ if (s.sending || m[1] !== 'state') s.error = m[1]
377
+ }
378
+ }
379
+ const fail = (code) => {
380
+ throw new KamojiError(code, code === 'auth_required' ? 'Kamoji asked for authorization again.' : errorMessage(code))
381
+ }
382
+ try {
383
+ // 1. APP_PUT → ASSET:READY:<ackEvery> (put once more if READY was lost)
384
+ await this.ask(cmd)
385
+ let ackEvery = 0
386
+ let tries = 1
387
+ let readyBy = Date.now() + this.t.put
388
+ while (!ackEvery) {
389
+ const msg = await this.next(readyBy - Date.now())
390
+ if (msg === null) {
391
+ if (tries < this.t.putTries) {
392
+ tries++
393
+ await this.link.send('ASSET_STOP').catch(() => undefined)
394
+ await this.ask(cmd)
395
+ readyBy = Date.now() + this.t.put
396
+ continue
397
+ }
398
+ fail('timeout')
399
+ }
400
+ const m = /^ASSET:READY:(\d+)/.exec(msg)
401
+ if (m) ackEvery = Number(m[1]) || 4096
402
+ else absorb(msg)
403
+ if (s.error) fail(s.error)
404
+ }
405
+ // 2. The bytes, at most two ack windows ahead.
406
+ s.sending = true
407
+ const window = ackEvery * 2
408
+ let offset = 0
409
+ let pacing = 0
410
+ let stalls = 0
411
+ const size = bytes.length
412
+ while (s.acked < size) {
413
+ if (s.error) fail(s.error)
414
+ if (s.resendFrom !== null) {
415
+ offset = s.resendFrom
416
+ s.resendFrom = null
417
+ pacing = Math.min(pacing + this.t.pacingStep, this.t.pacingMax)
418
+ }
419
+ if (offset >= size || offset >= s.acked + window) {
420
+ const before = s.acked
421
+ absorb(await this.next(this.t.ack))
422
+ if (s.acked > before || s.resendFrom !== null || s.error) {
423
+ onBytes?.(s.acked)
424
+ continue
425
+ }
426
+ if (++stalls > this.t.maxStalls) fail('timeout')
427
+ offset = s.acked
428
+ pacing = Math.min(pacing + this.t.pacingStep, this.t.pacingMax)
429
+ continue
430
+ }
431
+ const frame = dataFrame(bytes, offset, chunk)
432
+ await this.link.sendRaw(frame)
433
+ offset += frame.length - DATA_HEADER_BYTES
434
+ for (let msg = this.poll(); msg !== null; msg = this.poll()) absorb(msg)
435
+ if (pacing) await sleep(pacing)
436
+ }
437
+ onBytes?.(size)
438
+ // 3. Written, md5 checked, renamed.
439
+ const savedBy = Date.now() + this.t.save
440
+ while (!s.saved) {
441
+ if (s.error) fail(s.error)
442
+ const msg = await this.next(savedBy - Date.now())
443
+ if (msg === null) fail('timeout')
444
+ absorb(msg)
445
+ }
446
+ } catch (e) {
447
+ if (!s.saved) await this.link.send('ASSET_STOP').catch(() => undefined)
448
+ throw e
449
+ }
450
+ }
451
+
452
+ /**
453
+ * The whole install: every file (manifest.json first), then APP_COMMIT. APP_ABORT on failure.
454
+ * @param {{path:string, data:Buffer}[]} files
455
+ * @param {(p:{file:string, index:number, files:number, sent:number, total:number})=>void} [onProgress]
456
+ * @returns {Promise<{version:string, bytes:number}>}
457
+ */
458
+ install(appId, files, onProgress) {
459
+ return this.serial(async () => {
460
+ const ordered = [...files].sort((a, b) =>
461
+ a.path === 'manifest.json' ? -1 : b.path === 'manifest.json' ? 1 : a.path < b.path ? -1 : a.path > b.path ? 1 : 0,
462
+ )
463
+ const total = ordered.reduce((n, f) => n + f.data.length, 0)
464
+ let done = 0
465
+ try {
466
+ for (let i = 0; i < ordered.length; i++) {
467
+ const f = ordered[i]
468
+ await this.putFile(appId, f.path, f.data, (sent) =>
469
+ onProgress?.({ file: f.path, index: i, files: ordered.length, sent: done + sent, total }),
470
+ )
471
+ done += f.data.length
472
+ }
473
+ await this.ask(`APP_COMMIT:${appId}`)
474
+ const r = await this.waitFor(this.t.commit, (m) => {
475
+ if (m === 'unsupported') return { err: 'unsupported' }
476
+ if (m.startsWith(`APP:INSTALLED:${appId}:`)) return { version: m.slice(`APP:INSTALLED:${appId}:`.length) }
477
+ if (m.startsWith('APP:ERR:')) return { err: m.slice(8).split(':')[0] }
478
+ return undefined
479
+ }, 'APP_COMMIT')
480
+ if (r === undefined) throw new KamojiError('timeout', "Kamoji didn't confirm the install (APP_COMMIT).")
481
+ if (r.err) throw new KamojiError(r.err, errorMessage(r.err))
482
+ return { version: r.version, bytes: total }
483
+ } catch (e) {
484
+ if (e.code !== 'link') {
485
+ await this.ask(`APP_ABORT:${appId}`).catch(() => undefined)
486
+ await this.waitFor(this.t.abort, (m) => (m === `APP:ABORTED:${appId}` || m.startsWith('APP:ERR:') ? m : undefined)).catch(
487
+ () => undefined,
488
+ )
489
+ }
490
+ throw e
491
+ }
492
+ })
493
+ }
494
+
495
+ // ------------------------------------------------------------------ open, status, screenshot, reboot
496
+
497
+ /**
498
+ * Switch Kamoji to the app: its mode from APPS_LIST, then SET_MODE (a no-op when it is already on
499
+ * screen: APP_COMMIT restarted it). Returns { mode, confirmed, list }.
500
+ */
501
+ async open(appId, list) {
502
+ list = list ?? (await this.listApps())
503
+ const app = list.apps.find((a) => a.id === appId)
504
+ if (!app) throw new KamojiError('not_found', `${appId} is not on Kamoji.`)
505
+ if (!app.ok)
506
+ throw new KamojiError('not_runnable', `Kamoji can't run ${appId}: ${app.reason || 'its manifest was refused'}.`)
507
+ const mode = list.modes[appId]
508
+ return this.serial(async () => {
509
+ await this.ask(`SET_MODE:${mode}`)
510
+ const got = await this.waitFor(this.t.reply, (m) => {
511
+ const mm = /^SETTING:ui_mode=(-?\d+)/.exec(m)
512
+ return mm ? Number(mm[1]) : undefined
513
+ })
514
+ if (got === undefined) return { mode, confirmed: false, list }
515
+ if (got !== mode)
516
+ throw new KamojiError(
517
+ 'mode_refused',
518
+ `Kamoji stayed on mode ${got} instead of opening ${appId} (mode ${mode}).`,
519
+ 'It refuses to switch while it plays with another Kamoji or during a full-screen animation: try again in a moment.',
520
+ )
521
+ return { mode, confirmed: true, list }
522
+ })
523
+ }
524
+
525
+ /** APP_STATUS → 'ready' | 'pending_restart' | 'profile_error' | 'cleanup_pending' | null (older firmware). */
526
+ status(appId) {
527
+ return this.serial(async () => {
528
+ await this.ask(`APP_STATUS:${appId}`)
529
+ const r = await this.waitFor(this.t.reply, (m) => {
530
+ if (m === 'unsupported') return null
531
+ if (m.startsWith(`APP:STATUS:${appId}:`)) return m.slice(`APP:STATUS:${appId}:`.length)
532
+ if (m.startsWith('APP:ERR:')) return { err: m.slice(8) }
533
+ return undefined
534
+ }, 'APP_STATUS')
535
+ if (r === undefined) return null
536
+ if (r && typeof r === 'object') throw new KamojiError(r.err, errorMessage(r.err))
537
+ return r
538
+ })
539
+ }
540
+
541
+ /** SCREEN_GRAB → the JPEG (Buffer). */
542
+ screenshot() {
543
+ return this.serial(async () => {
544
+ await this.ask('SCREEN_GRAB')
545
+ let size = null
546
+ let buf = null
547
+ let got = 0
548
+ const end = Date.now() + this.t.shot
549
+ for (;;) {
550
+ const msg = await this.next(end - Date.now())
551
+ if (msg === null) throw new KamojiError('timeout', 'The screenshot timed out.')
552
+ if (msg === 'UNKNOWN_CMD:SCREEN_GRAB') throw new KamojiError('unsupported', 'This firmware has no Bluetooth screenshot.')
553
+ let m
554
+ if ((m = /^SHOT:ERR:(.*)$/.exec(msg))) throw new KamojiError(m[1], `Screenshot failed (${m[1]}).`)
555
+ if ((m = /^SHOT:BEGIN:(\d+):(\d+):(\d+)/.exec(msg))) {
556
+ size = Number(m[1])
557
+ buf = Buffer.alloc(size)
558
+ got = 0
559
+ } else if ((m = /^SHOT:DATA:(\d+):(.*)$/.exec(msg)) && buf) {
560
+ const part = Buffer.from(m[2], 'base64')
561
+ part.copy(buf, Number(m[1]))
562
+ got += part.length
563
+ } else if (/^SHOT:END:/.test(msg) && buf) {
564
+ if (got !== size) throw new KamojiError('lost', `Screenshot incomplete (${got} of ${size} bytes): a notification was lost. Try again.`)
565
+ return buf
566
+ }
567
+ }
568
+ })
569
+ }
570
+
571
+ async reboot() {
572
+ await this.link.send('REBOOT').catch(() => undefined)
573
+ }
574
+ }