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.
package/src/dev.js ADDED
@@ -0,0 +1,314 @@
1
+ // One development session: a Kamoji link (reconnected when it drops), the app folder, the USB log.
2
+ // Used by `kamoji dev` (watch), `kamoji install` (once), `kamoji apps`, `kamoji shot`, `kamoji forget`.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { bundleHash, checkApp, compareVersions } from './check.js'
6
+ import { KamojiError, Session } from './protocol.js'
7
+ import { classify } from './logfilter.js'
8
+
9
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
10
+ export const kb = (n) => `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB`
11
+ const secs = (ms) => `${(ms / 1000).toFixed(1)} s`
12
+
13
+ /** Terminal output: one place, so tests can collect it. */
14
+ export function makeUi({ stream = process.stdout, color = stream.isTTY && !process.env.NO_COLOR, verbose = false } = {}) {
15
+ const paint = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s)
16
+ const stamp = () => paint('2', new Date().toTimeString().slice(0, 8))
17
+ let progressShown = false
18
+ const line = (s) => {
19
+ if (progressShown) {
20
+ stream.write('\r\x1b[K')
21
+ progressShown = false
22
+ }
23
+ stream.write(`${stamp()} ${s}\n`)
24
+ }
25
+ return {
26
+ verbose,
27
+ info: (s) => line(s),
28
+ ok: (s) => line(paint('32', s)),
29
+ warn: (s) => line(paint('33', `warning: ${s}`)),
30
+ error: (s, hint) => {
31
+ line(paint('31', `error: ${s}`))
32
+ if (hint) for (const h of String(hint).split('\n')) stream.write(` ${h}\n`)
33
+ },
34
+ log: (kind, s) => {
35
+ const tags = { lua: '36', error: '31', crash: '31;1', stopped: '31', cpu: '33', warn: '33', entered: '32', boot: '35', usb: '35', app: '0' }
36
+ line(`${paint(tags[kind] ?? '0', `[${kind === 'lua' ? 'print' : kind}]`)} ${s}`)
37
+ },
38
+ raw: (s) => line(paint('2', s)),
39
+ progress: (s) => {
40
+ if (!stream.isTTY) return
41
+ stream.write(`\r\x1b[K${stamp()} ${s}`)
42
+ progressShown = true
43
+ },
44
+ }
45
+ }
46
+
47
+ export function printProblems(ui, result) {
48
+ for (const p of result.problems) {
49
+ const where = p.where ? `${p.where}: ` : ''
50
+ if (p.level === 'error') ui.error(`${where}${p.message} [${p.id}]`)
51
+ else if (p.level === 'warning') ui.warn(`${where}${p.message} [${p.id}]`)
52
+ else ui.info(`${where}${p.message}`)
53
+ }
54
+ }
55
+
56
+ export class DevSession {
57
+ /**
58
+ * @param {object} o
59
+ * @param {string} [o.folder]
60
+ * @param {ReturnType<typeof makeUi>} o.ui
61
+ * @param {(opts:{onDisconnect:Function}) => Promise<{link:any, board:string, name?:string, revision?:string, firmware?:string}>} o.connector
62
+ * @param {(board:string) => {key:Buffer, created:boolean}} o.keys
63
+ * @param {import('./serial.js').SerialLog} [o.serial]
64
+ * @param {object} [o.timeouts]
65
+ * @param {boolean} [o.reboot] restart Kamoji by itself when the app's Bluetooth services need it
66
+ * @param {boolean} [o.lua]
67
+ */
68
+ constructor(o) {
69
+ Object.assign(this, { reboot: false, lua: true, ...o })
70
+ this.session = null
71
+ this.conn = null
72
+ this.connected = false
73
+ this.connecting = null
74
+ this.lastHash = null
75
+ this.lastList = null
76
+ this.busy = false
77
+ this.closed = false
78
+ this.appId = null
79
+ this.keepalive = null
80
+ }
81
+
82
+ // ------------------------------------------------------------------ connection
83
+
84
+ async connect() {
85
+ if (this.connected) return
86
+ this.connecting ??= this._connect().finally(() => (this.connecting = null))
87
+ return this.connecting
88
+ }
89
+
90
+ async _connect() {
91
+ const ui = this.ui
92
+ ui.info('Looking for Kamoji over Bluetooth…')
93
+ const conn = await this.connector({ onDisconnect: (reason) => this._lost(reason) })
94
+ this.conn = conn
95
+ const session = new Session(conn.link, { timeouts: this.timeouts })
96
+ this.session = session
97
+ const { key, created } = this.keys(conn.board)
98
+ let auth
99
+ try {
100
+ auth = await session.authorize(key)
101
+ } catch (e) {
102
+ await conn.link.disconnect?.()
103
+ throw e
104
+ }
105
+ this.connected = true
106
+ if (auth.status === 'authorized' && auth.enrolled)
107
+ ui.ok(`${conn.name ?? conn.board} trusts this computer now (signal ${auth.rssi ?? '?'} dBm; ${auth.devices} trusted device(s)).`)
108
+ else if (created && auth.status === 'authorized') ui.info('Kamoji already trusted this key.')
109
+ await session.linkFast()
110
+ const info = await session.info()
111
+ this.firmware = info.fw
112
+ ui.ok(
113
+ `Connected to ${conn.name ?? conn.board}${info.nick ? ` "${info.nick}"` : ''}: firmware ${info.fw}${conn.revision ? `, ${conn.revision}` : ''}.`,
114
+ )
115
+ this.lastList = await session.listApps()
116
+ const st = this.lastList.storage
117
+ ui.info(
118
+ `${this.lastList.apps.length} mini app(s) on it${st ? `, storage ${kb(st.used)} of ${kb(st.total)} used` : ''}.`,
119
+ )
120
+ this._startKeepalive()
121
+ }
122
+
123
+ _lost(reason) {
124
+ if (!this.connected) return
125
+ this.connected = false
126
+ this.session?.close()
127
+ if (this.closed) return
128
+ this.ui.warn(`Bluetooth link to Kamoji lost${reason !== undefined ? ` (${reason})` : ''}: it restarted, went out of range, or another device connected.`)
129
+ if (this.watching) this._reconnectLoop()
130
+ }
131
+
132
+ async _reconnectLoop() {
133
+ for (let attempt = 1; !this.closed && !this.connected; attempt++) {
134
+ await sleep(attempt <= 10 ? 3000 : 10000)
135
+ if (this.closed || this.connected) return
136
+ try {
137
+ await this.connect()
138
+ if (this.appId) await this.open()
139
+ return
140
+ } catch (e) {
141
+ if (attempt === 1 || attempt % 10 === 0) this.ui.info(`Reconnecting… (${e.message})`)
142
+ }
143
+ }
144
+ }
145
+
146
+ _startKeepalive() {
147
+ if (this.keepalive) clearInterval(this.keepalive)
148
+ this.keepalive = setInterval(() => {
149
+ if (!this.connected) return
150
+ this.session.linkAlive()
151
+ // While watching (`kamoji dev`), keep the link fast between saves: Kamoji holds it LINK_FAST_HOLD_MS (8 s)
152
+ // after the last LINK_FAST, then relaxes to an 800 ms interval, and the next reload waited ~8 s at that
153
+ // pace for the fast parameters to come back (12.7 s installs instead of 2-3 s, R8 test 2026-11-17).
154
+ if (this.busy || this.watching) this.session.linkFast()
155
+ }, 5000)
156
+ this.keepalive.unref?.()
157
+ }
158
+
159
+ async close() {
160
+ this.closed = true
161
+ if (this.keepalive) clearInterval(this.keepalive)
162
+ this.session?.close()
163
+ await this.conn?.link.disconnect?.()
164
+ await this.serial?.close()
165
+ }
166
+
167
+ // ------------------------------------------------------------------ the app
168
+
169
+ /** Check the folder; print problems; returns the check result (null = errors). */
170
+ check() {
171
+ const r = checkApp(this.folder, { lua: this.lua })
172
+ const shown = r.problems.filter((p) => p.level !== 'info' || p.id !== 'skipped' || this.ui.verbose)
173
+ printProblems(this.ui, { problems: shown })
174
+ if (r.errors.length) {
175
+ this.ui.error(`${r.errors.length} problem(s) to fix first: nothing was sent.`)
176
+ return null
177
+ }
178
+ return r
179
+ }
180
+
181
+ /**
182
+ * Check, install and open. Returns true when the app is on screen.
183
+ * @param {{force?: boolean}} [o]
184
+ */
185
+ async deploy({ force = false } = {}) {
186
+ const ui = this.ui
187
+ const r = this.check()
188
+ if (!r) return false
189
+ const hash = bundleHash(r.files)
190
+ if (!force && hash === this.lastHash) {
191
+ ui.info('No change in the files: nothing sent.')
192
+ return true
193
+ }
194
+ this.appId = r.appId
195
+ const mf = r.manifest.min_firmware
196
+ await this.connect()
197
+ if (typeof mf === 'string' && this.firmware && compareVersions(this.firmware, mf) < 0) {
198
+ ui.error(
199
+ `${r.appId} needs firmware ${mf} or newer; this Kamoji runs ${this.firmware} [firmware-too-old]`,
200
+ 'Update Kamoji in the Kamoji app (Settings > Firmware), or lower min_firmware if the app does not need it.',
201
+ )
202
+ return false
203
+ }
204
+ const st = this.lastList?.storage
205
+ if (st && r.bytes > st.total - st.used) {
206
+ ui.error(
207
+ `${r.appId} is ${kb(r.bytes)}; Kamoji has ${kb(Math.max(0, st.total - st.used))} free [no-space]`,
208
+ 'Remove a mini app in the Kamoji app (Apps), or make this one smaller.',
209
+ )
210
+ return false
211
+ }
212
+ this.busy = true
213
+ const t0 = Date.now()
214
+ try {
215
+ await this.session.linkFast()
216
+ const res = await this.session.install(r.appId, r.files, (p) =>
217
+ ui.progress(`sending ${p.file} (${p.index + 1}/${p.files}): ${kb(p.sent)} of ${kb(p.total)}`),
218
+ )
219
+ const t1 = Date.now()
220
+ this.lastHash = hash
221
+ const rate = res.bytes / Math.max(0.001, (t1 - t0) / 1000)
222
+ ui.ok(`Installed ${r.appId} ${res.version} in ${secs(t1 - t0)} (${r.files.length} file(s), ${kb(res.bytes)}, ${kb(rate)}/s).`)
223
+ await this.afterInstall(r, t0)
224
+ return true
225
+ } catch (e) {
226
+ this._explain(e)
227
+ return false
228
+ } finally {
229
+ this.busy = false
230
+ }
231
+ }
232
+
233
+ async afterInstall(r, t0) {
234
+ const ui = this.ui
235
+ this.lastList = await this.session.listApps()
236
+ const app = this.lastList.apps.find((a) => a.id === r.appId)
237
+ if (app && !app.ok) {
238
+ ui.error(`Kamoji installed ${r.appId} but can't run it: ${app.reason || 'see the USB log'}.`)
239
+ return
240
+ }
241
+ if (r.manifest.ble !== undefined) {
242
+ const status = await this.session.status(r.appId)
243
+ if (status === 'pending_restart') {
244
+ if (this.reboot) {
245
+ ui.info('Its Bluetooth services are new or changed: restarting Kamoji (--reboot)…')
246
+ await this.restart()
247
+ return
248
+ }
249
+ ui.warn('Its Bluetooth services are new or changed: they go live after a restart of Kamoji. Press b + Enter to restart it (or use --reboot).')
250
+ } else if (status === 'profile_error') ui.error('Its Bluetooth services could not start: details in the USB log.')
251
+ }
252
+ await this.open(t0)
253
+ }
254
+
255
+ async open(t0) {
256
+ const r = await this.session.open(this.appId, this.lastList ?? undefined)
257
+ const total = t0 ? `, ${secs(Date.now() - t0)} after the first byte` : ''
258
+ this.ui.ok(`${this.appId} is on screen (mode ${r.mode}${r.confirmed ? '' : ', not confirmed'}${total}).`)
259
+ return r
260
+ }
261
+
262
+ async restart() {
263
+ await this.session.reboot()
264
+ this.connected = false
265
+ this.session.close()
266
+ await this.conn?.link.disconnect?.()
267
+ await sleep(8000)
268
+ for (let i = 0; i < 10 && !this.connected; i++) {
269
+ try {
270
+ await this.connect()
271
+ } catch {
272
+ await sleep(3000)
273
+ }
274
+ }
275
+ if (!this.connected) throw new KamojiError('timeout', 'Kamoji did not come back after the restart.')
276
+ if (this.appId) await this.open()
277
+ }
278
+
279
+ _explain(e) {
280
+ if (e instanceof KamojiError) this.ui.error(e.message, e.hint)
281
+ else this.ui.error(e?.message ?? String(e))
282
+ }
283
+
284
+ // ------------------------------------------------------------------ screenshots, USB log
285
+
286
+ async screenshot(dir) {
287
+ const name = `${this.appId ?? 'kamoji'}-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.jpg`
288
+ let jpeg
289
+ let via
290
+ if (this.serial) {
291
+ jpeg = await this.serial.screenshot(90)
292
+ via = 'USB'
293
+ } else {
294
+ await this.connect()
295
+ jpeg = await this.session.screenshot()
296
+ via = 'Bluetooth'
297
+ }
298
+ fs.mkdirSync(dir, { recursive: true })
299
+ const file = path.join(dir, name)
300
+ fs.writeFileSync(file, jpeg)
301
+ this.ui.ok(`Screenshot (${via}, ${kb(jpeg.length)}): ${file}`)
302
+ return file
303
+ }
304
+
305
+ /** The USB log line printer (filtered to the app unless verbose). */
306
+ logLine(line) {
307
+ if (this.ui.verbose) {
308
+ this.ui.raw(line)
309
+ return
310
+ }
311
+ const c = classify(line, this.appId)
312
+ if (c) this.ui.log(c.kind, c.text)
313
+ }
314
+ }
package/src/keys.js ADDED
@@ -0,0 +1,37 @@
1
+ // This computer's key for one Kamoji: 32 random bytes in ~/.config/kamoji/<board>.key (hex, mode 0600).
2
+ // The Python worker/rig/kamoji_dev.py of kamoji-cms uses the same files, so either tool works without
3
+ // enrolling twice. The key is never printed: whoever has it can control that Kamoji.
4
+ import crypto from 'node:crypto'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+
9
+ export function configDir() {
10
+ return process.env.KAMOJI_CONFIG_DIR || path.join(os.homedir(), '.config', 'kamoji')
11
+ }
12
+
13
+ /** A file name from the board's Bluetooth name (KMJ-1A2B): letters, digits, - and _ only. */
14
+ export function keyPath(board) {
15
+ const safe = String(board || 'kamoji').replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)
16
+ return path.join(configDir(), `${safe}.key`)
17
+ }
18
+
19
+ /** The key for `board`, created on first use. Returns { key: Buffer, created: boolean, file }. */
20
+ export function loadOrCreateKey(board) {
21
+ const file = keyPath(board)
22
+ try {
23
+ const hex = fs.readFileSync(file, 'utf8').trim()
24
+ if (/^[0-9a-fA-F]{64}$/.test(hex)) return { key: Buffer.from(hex, 'hex'), created: false, file }
25
+ throw new Error(`${file} is not a Kamoji key (64 hex characters expected): delete it to start again`)
26
+ } catch (e) {
27
+ if (e.code !== 'ENOENT') throw e
28
+ }
29
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
30
+ const key = crypto.randomBytes(32)
31
+ fs.writeFileSync(file, `${key.toString('hex')}\n`, { mode: 0o600, flag: 'wx' })
32
+ return { key, created: true, file }
33
+ }
34
+
35
+ export function deleteKey(board) {
36
+ fs.rmSync(keyPath(board), { force: true })
37
+ }
@@ -0,0 +1,56 @@
1
+ // Which lines of Kamoji's USB log a mini app developer wants to see. Formats from kamoji-esphome
2
+ // kamoji_app_manager.cpp (print() → [app.lua], "[<id>] entered in N ms", "[<id>] stopped: …", "CPU budget
3
+ // exceeded", "app <id> ok (mode N)" / "unavailable: …", "APP_COMMIT <id>: …"), ESPHome and ESP-IDF
4
+ // (panics, resets). Same patterns as kamoji-cms worker/rig/logparse.py.
5
+
6
+ const ANSI = /\x1b\[[0-9;]*m/g
7
+ const CRASH = /Guru Meditation|abort\(\) was called|assert failed|Backtrace:|Rebooting\.\.\.|rst:0x[0-9a-f]+ \(|Stack canary|LoadProhibited|StoreProhibited|IllegalInstruction|task_wdt/
8
+ const SECRETS = /\b(password|passwd|pass|psk|token|secret|api[_-]?key|authorization)(\s*[:=]\s*)("[^"]*"|\S+)/gi
9
+ const ECODE = /\bE3[0-9]\d\d\b/
10
+
11
+ export function clean(line) {
12
+ return String(line).replace(ANSI, '').replace(/\r/g, '').trimEnd()
13
+ }
14
+
15
+ export function redact(s) {
16
+ return s.replace(SECRETS, (_m, k, sep) => `${k}${sep}***`)
17
+ }
18
+
19
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
20
+ /** The message part of an ESPHome log line ("[I][apps:123]: text" → "text"). */
21
+ const message = (ln) => {
22
+ const i = ln.indexOf(']: ')
23
+ return i >= 0 ? ln.slice(i + 3) : ln
24
+ }
25
+
26
+ /**
27
+ * @returns {null | {kind: 'lua'|'error'|'warn'|'cpu'|'stopped'|'entered'|'app'|'crash'|'boot'|'usb', text: string}}
28
+ */
29
+ export function classify(raw, appId) {
30
+ const ln = clean(raw)
31
+ if (!ln) return null
32
+ if (ln.startsWith('### ')) return { kind: 'usb', text: ln.slice(4) }
33
+ if (CRASH.test(ln)) return { kind: 'crash', text: redact(ln).slice(0, 300) }
34
+ if (ln.includes('setup() finished')) return { kind: 'boot', text: 'Kamoji started (setup finished)' }
35
+ if (ln.includes('[app.lua')) return { kind: 'lua', text: redact(message(ln)).slice(0, 400) }
36
+ const level = /^\[([EWI])\]/.exec(ln)?.[1]
37
+ if (ln.includes('[apps:')) {
38
+ const msg = message(ln)
39
+ if (msg.startsWith('BLE: ')) return null // the install itself, echoed
40
+ if (appId) {
41
+ const tag = `[${appId}]`
42
+ const mentions = msg.includes(tag) || new RegExp(`\\b(app|APP_COMMIT|APP_PUT) ${esc(appId)}\\b`).test(msg)
43
+ if (!mentions) return ECODE.test(msg) ? { kind: 'error', text: redact(msg) } : null
44
+ const rest = msg.includes(tag) ? msg.split(tag).slice(1).join(tag).trim() : msg
45
+ if (rest.startsWith('stopped:')) return { kind: 'stopped', text: redact(msg) }
46
+ if (rest.includes('CPU budget exceeded')) return { kind: 'cpu', text: redact(msg) }
47
+ if (rest.startsWith('entered in')) return { kind: 'entered', text: msg }
48
+ if (level === 'E') return { kind: 'error', text: redact(msg) }
49
+ if (level === 'W') return { kind: 'warn', text: redact(msg) }
50
+ return { kind: 'app', text: redact(msg) }
51
+ }
52
+ return level === 'E' || level === 'W' ? { kind: level === 'E' ? 'error' : 'warn', text: redact(msg) } : null
53
+ }
54
+ if (ECODE.test(ln)) return { kind: 'error', text: redact(message(ln)) }
55
+ return null
56
+ }