desky-agent 0.0.0-stage → 0.3.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.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -2
  3. package/assets/clawd.ico +0 -0
  4. package/assets/clawd.png +0 -0
  5. package/bin/cli.js +216 -0
  6. package/electron/icons.js +79 -0
  7. package/electron/main.js +244 -0
  8. package/firmware/boot_app0.bin +0 -0
  9. package/firmware/bootloader.bin +0 -0
  10. package/firmware/firmware.bin +0 -0
  11. package/firmware/manifest.json +33 -0
  12. package/firmware/partitions.bin +0 -0
  13. package/package.json +41 -6
  14. package/src/autostart.js +106 -0
  15. package/src/board.js +69 -0
  16. package/src/core.js +193 -0
  17. package/src/daemon.js +522 -0
  18. package/src/firmware.js +207 -0
  19. package/src/flasher.js +113 -0
  20. package/src/hook.js +92 -0
  21. package/src/install.js +418 -0
  22. package/src/link.js +207 -0
  23. package/src/paths.js +44 -0
  24. package/src/release.js +131 -0
  25. package/src/selfupdate.js +58 -0
  26. package/src/updater.js +138 -0
  27. package/src/webserial.js +130 -0
  28. package/ui/app.html +1519 -0
  29. package/ui/clawd3d.js +377 -0
  30. package/ui/models/A04_cap_J2.stl +0 -0
  31. package/ui/models/A04_cap_J3.stl +0 -0
  32. package/ui/models/A04_cap_J4.stl +0 -0
  33. package/ui/models/B0_base.stl +0 -0
  34. package/ui/models/B1_body.stl +0 -0
  35. package/ui/models/B2_face_plate.stl +0 -0
  36. package/ui/models/B3_side_left.stl +0 -0
  37. package/ui/models/B4_side_right.stl +0 -0
  38. package/ui/models/C1_column.stl +0 -0
  39. package/ui/models/C2_column_lid.stl +0 -0
  40. package/ui/models/D1_desk_frame.stl +0 -0
  41. package/ui/models/D2_desk_top.stl +0 -0
  42. package/ui/models/L1_laptop.stl +0 -0
  43. package/ui/models/P1_mug.stl +0 -0
  44. package/ui/models/P2_plant.stl +0 -0
  45. package/ui/models/R1_arm_left.stl +0 -0
  46. package/ui/models/R2_arm_right.stl +0 -0
  47. package/ui/models/S1_seat.stl +0 -0
  48. package/ui/models/S2_spacer.stl +0 -0
  49. package/ui/vendor/OrbitControls.js +1532 -0
  50. package/ui/vendor/RoomEnvironment.js +144 -0
  51. package/ui/vendor/STLLoader.js +410 -0
  52. package/ui/vendor/three.LICENSE +21 -0
  53. package/ui/vendor/three.module.min.js +6 -0
package/src/release.js ADDED
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+ // New versions of the app: npm's "latest" for this package, and the update the control app starts with one button.
3
+ //
4
+ // latest() the version npm calls latest, or throws (offline, the registry is down)
5
+ // newer(a, b) a is a later release than b
6
+ // canUpdate() the Node that installed Desky is still there: the app can update itself
7
+ // start(v) run the installer of version v in a process of its own (src/selfupdate.js): it stops this app,
8
+ // installs, starts the app again with its window open
9
+ // takeResult() what the last update did, once: { state: done | failed, text } or null
10
+ //
11
+ // The update is the very same "npx desky-agent@<v>" a person types: the installer of the new version does the work,
12
+ // this app only starts it and gets out of the way.
13
+
14
+ const fs = require('fs');
15
+ const os = require('os');
16
+ const path = require('path');
17
+ const https = require('https');
18
+ const { spawn } = require('child_process');
19
+ const paths = require('./paths');
20
+
21
+ const PKG = require('../package.json');
22
+ const RESULT = path.join(paths.STATE, 'app-update.json');
23
+ const UPDATE_LOG = path.join(paths.STATE, 'update.log');
24
+ const PLAIN = /^\d+\.\d+\.\d+$/; // a release; anything else never reaches a command line
25
+
26
+ function registry() {
27
+ const r = process.env.npm_config_registry || 'https://registry.npmjs.org/';
28
+ return r.endsWith('/') ? r : r + '/';
29
+ }
30
+
31
+ function latest({ name = PKG.name, timeout = 10000 } = {}) {
32
+ return new Promise((resolve, reject) => {
33
+ const req = https.get(registry() + name + '/latest', {
34
+ timeout, headers: { accept: 'application/json', 'user-agent': `${PKG.name}/${PKG.version}` },
35
+ }, res => {
36
+ if (res.statusCode !== 200) {
37
+ res.resume();
38
+ return reject(new Error('реєстр npm відповів ' + res.statusCode));
39
+ }
40
+ let data = '';
41
+ res.setEncoding('utf8');
42
+ res.on('data', c => { if (data.length < 1 << 20) data += c; });
43
+ res.on('end', () => {
44
+ try {
45
+ const v = JSON.parse(data).version;
46
+ if (!PLAIN.test(v)) throw new Error('дивна версія ' + v);
47
+ resolve(v);
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ });
52
+ return undefined;
53
+ });
54
+ req.on('timeout', () => req.destroy(new Error('реєстр npm не відповів')));
55
+ req.on('error', reject);
56
+ });
57
+ }
58
+
59
+ function newer(a, b) {
60
+ if (!PLAIN.test(String(a)) || !PLAIN.test(String(b))) return false;
61
+ const x = a.split('.').map(Number);
62
+ const y = b.split('.').map(Number);
63
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
64
+ return false;
65
+ }
66
+
67
+ /** npm's own script next to a Node: the update runs npm with that Node, not with whatever is on PATH. */
68
+ function npmCliFor(node) {
69
+ const bin = path.dirname(node);
70
+ return [path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
71
+ path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')].find(f => fs.existsSync(f)) || null;
72
+ }
73
+
74
+ /** The Node that installed Desky: launch.json says so since 0.3; before that, the hooks in settings.json ran with it.
75
+ * -> { node, npm } or null */
76
+ function runner({ launchFile = paths.LAUNCH, settingsFile = path.join(os.homedir(), '.claude', 'settings.json') } = {}) {
77
+ const cands = [];
78
+ try {
79
+ cands.push(JSON.parse(fs.readFileSync(launchFile, 'utf8')).node);
80
+ } catch (e) { /* not installed */ }
81
+ try {
82
+ const hooks = JSON.parse(fs.readFileSync(settingsFile, 'utf8')).hooks || {};
83
+ for (const h of Object.values(hooks).flat().flatMap(g => (g && g.hooks) || [])) {
84
+ if (/(clawdydesk|desky-agent)[\\/]src[\\/]hook\.js/i.test((h.args || []).join(' '))) cands.push(h.command);
85
+ }
86
+ } catch (e) { /* no settings */ }
87
+ for (const node of cands) {
88
+ if (typeof node !== 'string' || !path.isAbsolute(node) || !fs.existsSync(node)) continue;
89
+ const npm = npmCliFor(node);
90
+ if (npm) return { node, npm };
91
+ }
92
+ return null;
93
+ }
94
+
95
+ function canUpdate() {
96
+ return fs.existsSync(paths.LAUNCH) && Boolean(runner());
97
+ }
98
+
99
+ function start(version) {
100
+ if (!PLAIN.test(String(version))) throw new Error('не версія: ' + version);
101
+ const how = runner();
102
+ if (!how) throw new Error('не знайшов Node, яким ставили Desky. Онови з термінала: npx desky-agent@latest');
103
+ fs.mkdirSync(paths.STATE, { recursive: true });
104
+ fs.rmSync(RESULT, { force: true });
105
+ const env = { ...process.env };
106
+ delete env.ELECTRON_RUN_AS_NODE;
107
+ // a console program: hidden, or Windows shows an empty terminal for the whole minute
108
+ const child = spawn(how.node, [path.join(__dirname, 'selfupdate.js'), version, how.npm],
109
+ { detached: true, stdio: 'ignore', windowsHide: true, cwd: os.homedir(), env });
110
+ child.unref();
111
+ }
112
+
113
+ function writeResult(r) {
114
+ try {
115
+ fs.mkdirSync(paths.STATE, { recursive: true });
116
+ fs.writeFileSync(RESULT, JSON.stringify({ ...r, at: new Date().toISOString() }));
117
+ } catch (e) { /* the log still says it */ }
118
+ }
119
+
120
+ function takeResult() {
121
+ try {
122
+ const r = JSON.parse(fs.readFileSync(RESULT, 'utf8'));
123
+ fs.rmSync(RESULT, { force: true });
124
+ return { state: r.ok ? 'done' : 'failed', text: String(r.text || '') };
125
+ } catch (e) {
126
+ return null;
127
+ }
128
+ }
129
+
130
+ module.exports = { latest, newer, runner, npmCliFor, canUpdate, start, writeResult, takeResult, RESULT, UPDATE_LOG,
131
+ PLAIN };
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+ // node selfupdate.js <version> <npm-cli.js>: started by the app (release.start), outlives it.
3
+ //
4
+ // Runs "npm exec desky-agent@<version>", the installer of the new version: it stops the running app, installs, wires
5
+ // the hooks again and starts the app with its window open. Everything it prints goes to state/update.log. What came
6
+ // of it goes to state/app-update.json for the app to show once. If the new app did not come up, the old one (or
7
+ // whatever is installed now) is started again, so Desky is never left off after a click.
8
+
9
+ const fs = require('fs');
10
+ const os = require('os');
11
+ const path = require('path');
12
+ const { spawnSync } = require('child_process');
13
+ const paths = require('./paths');
14
+ const release = require('./release');
15
+ const { launch } = require('./hook');
16
+
17
+ const [version, npm] = process.argv.slice(2);
18
+ const PKG = require('../package.json').name;
19
+ const INSTALLED = path.join(paths.HOME, 'node_modules', PKG, 'package.json');
20
+
21
+ function installedVersion() {
22
+ try {
23
+ return JSON.parse(fs.readFileSync(INSTALLED, 'utf8')).version;
24
+ } catch (e) {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ function main() {
30
+ if (!release.PLAIN.test(String(version)) || !npm) process.exit(2);
31
+ fs.mkdirSync(paths.STATE, { recursive: true });
32
+ const out = fs.openSync(release.UPDATE_LOG, 'w');
33
+ fs.writeSync(out, `${new Date().toISOString()} оновлення Desky до ${version}\n`);
34
+ const env = { ...process.env };
35
+ delete env.ELECTRON_RUN_AS_NODE;
36
+ const r = spawnSync(process.execPath,
37
+ [npm, 'exec', '--yes', `--package=${PKG}@${version}`, '--', PKG, 'install'],
38
+ { stdio: ['ignore', out, out], cwd: os.homedir(), env, windowsHide: true, timeout: 15 * 60 * 1000 });
39
+ const now = installedVersion();
40
+ fs.writeSync(out, `\n${new Date().toISOString()} npm exec: код ${r.status}${r.error ? ', ' + r.error.message : ''}`
41
+ + `, стоїть ${now || 'нічого'}\n`);
42
+ fs.closeSync(out);
43
+
44
+ if (now === version) {
45
+ // the firmware step may have failed (exit 1) while the app updated: that one is in the log and the app says it
46
+ release.writeResult({ ok: true, version, text: `Desky оновлено до ${version}` });
47
+ return;
48
+ }
49
+ release.writeResult({ ok: false, version,
50
+ text: `оновлення до ${version} не вдалося. Лог: ${release.UPDATE_LOG}. Можна з термінала: npx desky-agent@latest` });
51
+ // the installer stops the app before it installs: bring back whatever is there now, with its window
52
+ paths.markStopped(false);
53
+ try {
54
+ launch([]);
55
+ } catch (e) { /* not installed at all any more: the log says why */ }
56
+ }
57
+
58
+ main();
package/src/updater.js ADDED
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+ // Find the boards, decide, flash, check. Shared by the installer, "desky-agent firmware" and the tray app.
3
+ // Whoever calls it must have the port free: the tray app stops its Link first, the CLI stops the tray app.
4
+
5
+ const fw = require('./firmware');
6
+ const link = require('./link');
7
+
8
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
9
+
10
+ /** Open a port without resetting the board and ask "who": { usb, who, busy }. */
11
+ async function probe(usb, ms = 8000) {
12
+ let port;
13
+ try {
14
+ port = await link.openPort(usb.path);
15
+ } catch (e) {
16
+ return { usb, who: null, busy: true };
17
+ }
18
+ try {
19
+ return { usb, who: await link.askWho(port, ms), busy: false };
20
+ } finally {
21
+ await new Promise(r => port.close(() => r()));
22
+ }
23
+ }
24
+
25
+ async function scan() {
26
+ let found = await link.ports();
27
+ for (let i = 0; i < 5 && !found.length; i++) { // a board in the middle of a reboot is off USB for a moment
28
+ await sleep(1000);
29
+ found = await link.ports();
30
+ }
31
+ const out = [];
32
+ for (const usb of found) out.push(await probe(usb));
33
+ return out;
34
+ }
35
+
36
+ /** After the reset the board drops off USB and comes back (maybe under another name on macOS): find it by its USB
37
+ * serial and wait for "who". The new program needs a few seconds to boot. */
38
+ async function waitWho(usb, ms = 30000) {
39
+ const end = Date.now() + ms;
40
+ while (Date.now() < end) {
41
+ const now = (await link.ports()).find(p => (usb.serialNumber && p.serialNumber ? p.serialNumber === usb.serialNumber
42
+ : p.path === usb.path));
43
+ if (now) {
44
+ const r = await probe(now, Math.min(8000, Math.max(1000, end - Date.now())));
45
+ if (r.who) return r.who;
46
+ }
47
+ await sleep(1000);
48
+ }
49
+ return null;
50
+ }
51
+
52
+ function bundle() {
53
+ return fw.loadBundle();
54
+ }
55
+
56
+ /** Flash one board and check it: { ok, refused?, who?, text }, text being one Russian line for people.
57
+ * The "update started" marker goes to state/ once the bootloader said ESP32-S3, before the first byte; it is
58
+ * removed only when the board answers "who" with the new version. */
59
+ async function update(usb, { bundle: b, from = null, sn = null, log = () => {}, onProgress = () => {}, deps = {} } = {}) {
60
+ const writeParts = deps.writeParts || require('./flasher').writeParts;
61
+ const wait = deps.waitWho || waitWho;
62
+ const { ChipError } = require('./flasher');
63
+ try {
64
+ await writeParts({
65
+ path: usb.path, bundle: b, log, onProgress,
66
+ beforeWrite: async () => fw.writeMarker({ port: usb.path, usbSerial: usb.serialNumber, sn, from, to: b.version }),
67
+ });
68
+ } catch (e) {
69
+ if (e instanceof ChipError || (e && e.chip)) {
70
+ fw.rememberRefused(usb, e.chip);
71
+ return { ok: false, refused: true, text: `${usb.path}: ${e.message}. Не чіпаю й більше не пробую` };
72
+ }
73
+ return { ok: false, text: `прошивка на ${usb.path} не оновилася: ${e.message}. Не від'єднуй плату й запусти `
74
+ + 'npx desky-agent firmware update' };
75
+ }
76
+ const who = await wait(usb);
77
+ if (who && who.fw === b.version) {
78
+ fw.clearMarker();
79
+ return { ok: true, who, text: `прошивку Desky оновлено: ${from || 'без версії'} → ${b.version} (${usb.path})` };
80
+ }
81
+ return { ok: false, who, text: who
82
+ ? `після запису плата на ${usb.path} відповідає fw=${who.fw || '?'}, а чекали ${b.version}`
83
+ : `після запису ${usb.path} не відповів на who. Запусти npx desky-agent firmware update` };
84
+ }
85
+
86
+ /** The whole pass over every 303A:1001 port, for the installer and the CLI.
87
+ * force "firmware update": write the same version again too (never an older one)
88
+ * yes a silent board counts as confirmed
89
+ * ask(q) a terminal question for a silent board without a marker -> true/false; null: do not ask
90
+ * quiet say nothing about boards that are fine
91
+ * -> { flashed, failed, boards } */
92
+ async function run({ force = false, yes = false, ask = null, quiet = false, say = console.log, log = () => {},
93
+ onProgress = () => {}, deps = {} } = {}) {
94
+ const result = { flashed: 0, failed: 0, boards: 0 };
95
+ let b;
96
+ try {
97
+ b = (deps.bundle || bundle)();
98
+ } catch (e) {
99
+ say('прошивка в пакеті не пройшла перевірку: ' + e.message);
100
+ result.failed += 1;
101
+ return result;
102
+ }
103
+ const boards = await (deps.scan || scan)();
104
+ result.boards = boards.length;
105
+ for (const { usb, who, busy } of boards) {
106
+ if (busy) {
107
+ say(`${usb.path} зайнятий іншою програмою: прошивку на ньому не перевірив`);
108
+ continue;
109
+ }
110
+ const base = { who, usb, bundle: b, marker: fw.readMarker(), refused: fw.refusedChip(usb), force };
111
+ let d = fw.decide({ ...base, confirmed: yes });
112
+ if (d.action === 'ask') {
113
+ const sure = ask ? await ask(`${usb.path}: плата ESP32 (303A:1001) мовчить на who. Це твій Desky, у якого `
114
+ + 'перервалося оновлення прошивки? Прошити? [y/N] ') : false;
115
+ if (!sure) {
116
+ say(`${d.why}: не чіпаю. Якщо це Desky після перерваного оновлення: npx desky-agent firmware update --yes`);
117
+ continue;
118
+ }
119
+ d = fw.decide({ ...base, confirmed: true });
120
+ }
121
+ if (d.action === 'none') {
122
+ if (!quiet) say(`${usb.path}: Desky, ${d.why}${who.sn ? ', номер ' + who.sn : ''}`);
123
+ continue;
124
+ }
125
+ if (d.action === 'warn' || d.action === 'skip') {
126
+ say(`${usb.path}: ${d.why}`);
127
+ continue;
128
+ }
129
+ say(`${usb.path}: ${d.why}. Оновлюю прошивку, не від'єднуй плату…`);
130
+ const r = await (deps.update || update)(usb, { bundle: b, from: who && who.fw, sn: who && who.sn, log, onProgress });
131
+ say(r.text);
132
+ if (r.ok) result.flashed += 1;
133
+ else if (!r.refused) result.failed += 1;
134
+ }
135
+ return result;
136
+ }
137
+
138
+ module.exports = { run, update, scan, probe, waitWho, bundle };
@@ -0,0 +1,130 @@
1
+ 'use strict';
2
+ // A Web Serial SerialPort made of node serialport, just enough for esptool-js's Transport:
3
+ // open/close, readable/writable web streams, setSignals, getInfo, setBaudRate.
4
+ //
5
+ // Two things differ from Web Serial and matter here:
6
+ // - serialport's set() fills every line it is not given with its default (DTR and RTS up), so setting RTS alone
7
+ // would raise DTR too. The adapter remembers both lines and always sends both.
8
+ // - readable and writable are recreated on access after a cancel or close, as the Web Serial spec says, while
9
+ // the port is open; esptool-js relies on that between its reads.
10
+
11
+ const { ReadableStream, WritableStream } = require('stream/web');
12
+
13
+ class NodeSerial {
14
+ /** path: the OS port; vendorId/productId: numbers, as Web Serial's getInfo() gives them (esptool-js picks the
15
+ * USB-Serial/JTAG reset by 303A:1001). SerialPort: the serialport class, replaceable in tests. */
16
+ constructor({ path, vendorId = 0x303a, productId = 0x1001, SerialPort } = {}) {
17
+ this.path = path;
18
+ this.vendorId = vendorId;
19
+ this.productId = productId;
20
+ this.SerialPort = SerialPort || require('serialport').SerialPort;
21
+ this.port = null;
22
+ this.lines = { dtr: false, rts: false, brk: false };
23
+ this._readable = null;
24
+ this._writable = null;
25
+ this._feed = null; // the data listener feeding the current readable
26
+ }
27
+
28
+ getInfo() {
29
+ return { usbVendorId: this.vendorId, usbProductId: this.productId };
30
+ }
31
+
32
+ get opened() {
33
+ return Boolean(this.port && this.port.isOpen);
34
+ }
35
+
36
+ async open({ baudRate = 115200 } = {}) {
37
+ if (this.opened) throw new Error('port already open');
38
+ const port = new this.SerialPort({ path: this.path, baudRate, autoOpen: false, hupcl: false });
39
+ port.on('error', () => {}); // an unplug mid-flash surfaces as a failed read or write, not a crash
40
+ await new Promise((res, rej) => port.open(e => (e ? rej(e) : res())));
41
+ this.port = port;
42
+ port.on('close', () => this._ended());
43
+ }
44
+
45
+ async close() {
46
+ const port = this.port;
47
+ this._ended();
48
+ this.port = null;
49
+ if (port && port.isOpen) await new Promise(res => port.close(() => res()));
50
+ }
51
+
52
+ async setSignals({ dataTerminalReady, requestToSend, break: brk } = {}) {
53
+ if (!this.opened) throw new Error('port not open');
54
+ if (dataTerminalReady !== undefined) this.lines.dtr = Boolean(dataTerminalReady);
55
+ if (requestToSend !== undefined) this.lines.rts = Boolean(requestToSend);
56
+ if (brk !== undefined) this.lines.brk = Boolean(brk);
57
+ const { dtr, rts } = this.lines;
58
+ await new Promise((res, rej) => this.port.set({ dtr, rts, brk: this.lines.brk }, e => (e ? rej(e) : res())));
59
+ }
60
+
61
+ async setBaudRate(baudRate) {
62
+ if (!this.opened) throw new Error('port not open');
63
+ await new Promise((res, rej) => this.port.update({ baudRate }, e => (e ? rej(e) : res())));
64
+ }
65
+
66
+ get readable() {
67
+ if (!this.opened) return null;
68
+ if (!this._readable) this._readable = this._makeReadable();
69
+ return this._readable;
70
+ }
71
+
72
+ get writable() {
73
+ if (!this.opened) return null;
74
+ if (!this._writable) this._writable = this._makeWritable();
75
+ return this._writable;
76
+ }
77
+
78
+ _makeReadable() {
79
+ const port = this.port;
80
+ let stream = null;
81
+ let feed = null;
82
+ const detach = () => {
83
+ if (feed) port.off('data', feed);
84
+ if (this._feed === feed) this._feed = null;
85
+ if (this._readable === stream) this._readable = null;
86
+ };
87
+ stream = new ReadableStream({
88
+ start: controller => {
89
+ feed = chunk => {
90
+ try { controller.enqueue(new Uint8Array(chunk)); } catch (e) { /* closed meanwhile */ }
91
+ };
92
+ feed.end = () => {
93
+ detach();
94
+ try { controller.close(); } catch (e) { /* already closed */ }
95
+ };
96
+ this._feed = feed;
97
+ port.on('data', feed);
98
+ },
99
+ cancel: () => detach(),
100
+ });
101
+ return stream;
102
+ }
103
+
104
+ _makeWritable() {
105
+ const port = this.port;
106
+ let stream = null;
107
+ const forget = () => {
108
+ if (this._writable === stream) this._writable = null;
109
+ };
110
+ stream = new WritableStream({
111
+ write: chunk => new Promise((res, rej) => {
112
+ port.write(Buffer.from(chunk), e => {
113
+ if (e) return rej(e);
114
+ return port.drain(d => (d ? rej(d) : res()));
115
+ });
116
+ }),
117
+ close: () => forget(),
118
+ abort: () => forget(),
119
+ });
120
+ return stream;
121
+ }
122
+
123
+ _ended() {
124
+ if (this._feed && this._feed.end) this._feed.end();
125
+ this._readable = null;
126
+ this._writable = null;
127
+ }
128
+ }
129
+
130
+ module.exports = { NodeSerial };