desky-agent 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +49 -2
- package/assets/clawd.ico +0 -0
- package/assets/clawd.png +0 -0
- package/bin/cli.js +206 -0
- package/electron/icons.js +79 -0
- package/electron/main.js +219 -0
- package/firmware/boot_app0.bin +0 -0
- package/firmware/bootloader.bin +0 -0
- package/firmware/firmware.bin +0 -0
- package/firmware/manifest.json +33 -0
- package/firmware/partitions.bin +0 -0
- package/package.json +38 -4
- package/src/autostart.js +106 -0
- package/src/board.js +69 -0
- package/src/core.js +172 -0
- package/src/daemon.js +446 -0
- package/src/firmware.js +207 -0
- package/src/flasher.js +113 -0
- package/src/hook.js +86 -0
- package/src/install.js +375 -0
- package/src/link.js +207 -0
- package/src/paths.js +44 -0
- package/src/updater.js +138 -0
- package/src/webserial.js +130 -0
- package/ui/app.html +1470 -0
- package/ui/clawd3d.js +375 -0
- package/ui/models/A04_cap_J2.stl +0 -0
- package/ui/models/A04_cap_J3.stl +0 -0
- package/ui/models/A04_cap_J4.stl +0 -0
- package/ui/models/B0_base.stl +0 -0
- package/ui/models/B1_body.stl +0 -0
- package/ui/models/B2_face_plate.stl +0 -0
- package/ui/models/B3_side_left.stl +0 -0
- package/ui/models/B4_side_right.stl +0 -0
- package/ui/models/C1_column.stl +0 -0
- package/ui/models/C2_column_lid.stl +0 -0
- package/ui/models/D1_desk_frame.stl +0 -0
- package/ui/models/D2_desk_top.stl +0 -0
- package/ui/models/L1_laptop.stl +0 -0
- package/ui/models/P1_mug.stl +0 -0
- package/ui/models/P2_plant.stl +0 -0
- package/ui/models/R1_arm_left.stl +0 -0
- package/ui/models/R2_arm_right.stl +0 -0
- package/ui/models/S1_seat.stl +0 -0
- package/ui/models/S2_spacer.stl +0 -0
- package/ui/vendor/OrbitControls.js +1532 -0
- package/ui/vendor/RoomEnvironment.js +144 -0
- package/ui/vendor/STLLoader.js +410 -0
- package/ui/vendor/three.LICENSE +21 -0
- package/ui/vendor/three.module.min.js +6 -0
package/src/flasher.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Write Desky's firmware with esptool-js over node serialport: no Python, no PlatformIO on the user's machine.
|
|
3
|
+
// docs/firmware_contract.md, section 5:
|
|
4
|
+
//
|
|
5
|
+
// - the four parts at their manifest addresses in one write_flash, flash mode/frequency/size "keep";
|
|
6
|
+
// - never erase_flash, never erase_region, never a merged image: NVS (0x9000-0xDFFF) keeps the calibration;
|
|
7
|
+
// - the bootloader must say ESP32-S3, anything else is put back into its own program and left alone;
|
|
8
|
+
// - after the write a hard reset, then the board must answer "who" with the package's version.
|
|
9
|
+
|
|
10
|
+
const { NodeSerial } = require('./webserial');
|
|
11
|
+
const { checkSpans, FirmwareError } = require('./firmware');
|
|
12
|
+
const crypto = require('crypto');
|
|
13
|
+
|
|
14
|
+
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
15
|
+
const STALL_MS = 45000; // no progress this long: the link is dead
|
|
16
|
+
|
|
17
|
+
class ChipError extends FirmwareError {
|
|
18
|
+
constructor(chip) {
|
|
19
|
+
super(`це ${chip}, а не ESP32-S3: прошивка Desky на неї не стане`);
|
|
20
|
+
this.chip = chip;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let esptool = null;
|
|
25
|
+
async function loadEsptool() {
|
|
26
|
+
// esptool-js checks image digests with WebCrypto; Node 18 has it only under require('crypto')
|
|
27
|
+
if (!globalThis.crypto || !globalThis.crypto.subtle) globalThis.crypto = crypto.webcrypto;
|
|
28
|
+
if (!esptool) esptool = await import('esptool-js');
|
|
29
|
+
return esptool;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** RTS pulse with DTR (BOOT) low: the chip restarts into its program. esptool-js's own HardReset only lowers RTS. */
|
|
33
|
+
async function hardReset(transport) {
|
|
34
|
+
await transport.setDTR(false);
|
|
35
|
+
await transport.setRTS(true);
|
|
36
|
+
await sleep(120);
|
|
37
|
+
await transport.setRTS(false);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Flash bundle.parts (firmware.plan() output) to the board on `path`.
|
|
41
|
+
* beforeWrite() runs once the chip is known to be an ESP32-S3, right before the first byte is written
|
|
42
|
+
* (the updater writes its "update started" marker there)
|
|
43
|
+
* onProgress(n) 0..100
|
|
44
|
+
* log(text) esptool's own lines, for the log file
|
|
45
|
+
* Throws ChipError for any chip but the S3 (nothing written, board reset back into its program), FirmwareError
|
|
46
|
+
* for a plan that would touch NVS, other errors from the port or the bootloader. SerialPort and esptool are
|
|
47
|
+
* replaceable for tests. */
|
|
48
|
+
async function writeParts({ path, bundle, beforeWrite = async () => {}, onProgress = () => {}, log = () => {},
|
|
49
|
+
SerialPort, esptool: esp, stallMs = STALL_MS } = {}) {
|
|
50
|
+
checkSpans(bundle.parts);
|
|
51
|
+
esp = esp || await loadEsptool();
|
|
52
|
+
const device = new NodeSerial({ path, SerialPort });
|
|
53
|
+
class Transport extends esp.Transport {
|
|
54
|
+
trace(text) { // the base class prints some of these to the console even with tracing off
|
|
55
|
+
if (this.tracing) log('esptool: ' + text);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const transport = new Transport(device, false);
|
|
59
|
+
const terminal = { clean() {}, write() {}, writeLine: text => log(String(text).trim()) };
|
|
60
|
+
const loader = new esp.ESPLoader({ transport, baudrate: 115200, romBaudrate: 115200, terminal });
|
|
61
|
+
try {
|
|
62
|
+
try {
|
|
63
|
+
await loader.detectChip('default_reset');
|
|
64
|
+
} catch (e) {
|
|
65
|
+
if (e instanceof esp.UnexpectedChipIdError || e instanceof esp.UnexpectedChipMagicError) {
|
|
66
|
+
await hardReset(transport).catch(() => {});
|
|
67
|
+
throw new ChipError('невідомий чип');
|
|
68
|
+
}
|
|
69
|
+
throw e;
|
|
70
|
+
}
|
|
71
|
+
const chip = loader.chip && loader.chip.CHIP_NAME;
|
|
72
|
+
if (chip !== 'ESP32-S3') {
|
|
73
|
+
await hardReset(transport).catch(() => {});
|
|
74
|
+
throw new ChipError(chip || 'невідомий чип');
|
|
75
|
+
}
|
|
76
|
+
await loader.runStub();
|
|
77
|
+
await beforeWrite();
|
|
78
|
+
const total = bundle.parts.reduce((n, p) => n + p.data.length, 0);
|
|
79
|
+
const before = bundle.parts.map((p, i) => bundle.parts.slice(0, i).reduce((n, q) => n + q.data.length, 0));
|
|
80
|
+
let last = Date.now();
|
|
81
|
+
let stalled = null;
|
|
82
|
+
const watch = new Promise((_, reject) => {
|
|
83
|
+
stalled = setInterval(() => {
|
|
84
|
+
if (Date.now() - last > stallMs) {
|
|
85
|
+
reject(new Error(`запис зупинився більш ніж на ${Math.round(stallMs / 1000)} с: зв'язок із платою обірвався`));
|
|
86
|
+
device.close().catch(() => {}); // unblocks esptool-js's pending read
|
|
87
|
+
}
|
|
88
|
+
}, 1000);
|
|
89
|
+
});
|
|
90
|
+
await Promise.race([watch, loader.writeFlash({
|
|
91
|
+
fileArray: bundle.parts.map(p => ({ data: new Uint8Array(p.data), address: p.address })),
|
|
92
|
+
flashMode: 'keep',
|
|
93
|
+
flashFreq: 'keep',
|
|
94
|
+
flashSize: 'keep',
|
|
95
|
+
eraseAll: false,
|
|
96
|
+
compress: true,
|
|
97
|
+
// esptool-js reads the flash back as MD5 after each part and throws on a difference
|
|
98
|
+
calculateMD5Hash: image => crypto.createHash('md5').update(image).digest('hex'),
|
|
99
|
+
reportProgress: (i, written, size) => {
|
|
100
|
+
last = Date.now();
|
|
101
|
+
const done = before[i] + Math.min(written / (size || 1), 1) * bundle.parts[i].data.length;
|
|
102
|
+
onProgress(Math.round((done / total) * 100));
|
|
103
|
+
},
|
|
104
|
+
})]).finally(() => clearInterval(stalled));
|
|
105
|
+
await hardReset(transport);
|
|
106
|
+
} finally {
|
|
107
|
+
// the reset may drop the device off USB under us: closing must not hang
|
|
108
|
+
await Promise.race([transport.disconnect().catch(() => {}), sleep(2000)]);
|
|
109
|
+
await device.close().catch(() => {});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
module.exports = { writeParts, hardReset, loadEsptool, ChipError };
|
package/src/hook.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
// Claude Code hook: hand the event to Desky and get out of the way.
|
|
4
|
+
//
|
|
5
|
+
// Wired for every event by the installer. Reads the hook's JSON from stdin and POSTs it to the app on localhost.
|
|
6
|
+
// If the app does not answer, starts it in the tray (no window) and tries again for 3 s. Always exits 0 and prints
|
|
7
|
+
// nothing: a hook that fails or talks would get in the way of the session it decorates.
|
|
8
|
+
//
|
|
9
|
+
// After "desky-agent stop" or "Выйти" in the tray a marker file says so and the hook does not start the app;
|
|
10
|
+
// opening Desky or the next login clears it. CLAWD_PORT overrides the port, CLAWD_NO_SPAWN=1 skips starting (tests).
|
|
11
|
+
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const http = require('http');
|
|
14
|
+
const { spawn } = require('child_process');
|
|
15
|
+
const paths = require('./paths');
|
|
16
|
+
|
|
17
|
+
function post(body, timeout = 500) {
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
const req = http.request({ host: '127.0.0.1', port: paths.port(), path: '/event', method: 'POST', timeout,
|
|
20
|
+
headers: { 'Content-Type': 'application/json', 'Content-Length': body.length } }, res => {
|
|
21
|
+
res.resume();
|
|
22
|
+
res.on('end', () => (res.statusCode === 200 ? resolve() : reject(new Error(String(res.statusCode)))));
|
|
23
|
+
});
|
|
24
|
+
req.on('timeout', () => req.destroy(new Error('timeout')));
|
|
25
|
+
req.on('error', reject);
|
|
26
|
+
req.end(body);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Start the app detached, in the tray, so it outlives the hook and the session that ran it. */
|
|
31
|
+
function launch(extra = ['--background']) {
|
|
32
|
+
const how = JSON.parse(fs.readFileSync(paths.LAUNCH, 'utf8'));
|
|
33
|
+
const env = { ...process.env };
|
|
34
|
+
delete env.ELECTRON_RUN_AS_NODE; // set when this runs inside an Electron app such as an editor
|
|
35
|
+
// no windowsHide: Desky is a GUI program with no console, and SW_HIDE would hide its first window for good
|
|
36
|
+
const child = spawn(how.command, [...(how.args || []), ...extra], { detached: true, stdio: 'ignore', env });
|
|
37
|
+
child.unref();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function readStdin() {
|
|
41
|
+
return new Promise(resolve => {
|
|
42
|
+
if (process.stdin.isTTY) return resolve(Buffer.from('{}'));
|
|
43
|
+
const chunks = [];
|
|
44
|
+
process.stdin.on('data', c => chunks.push(c));
|
|
45
|
+
process.stdin.on('end', () => resolve(chunks.length ? Buffer.concat(chunks) : Buffer.from('{}')));
|
|
46
|
+
process.stdin.on('error', () => resolve(Buffer.from('{}')));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// what the Core reads; a PostToolUse can carry megabytes of tool output that Desky never looks at
|
|
51
|
+
const KEEP = ['hook_event_name', 'session_id', 'tool_name', 'notification_type', 'source'];
|
|
52
|
+
|
|
53
|
+
function slim(raw) {
|
|
54
|
+
try {
|
|
55
|
+
const ev = JSON.parse(raw.toString('utf8').replace(/^/, ''));
|
|
56
|
+
const out = {};
|
|
57
|
+
for (const k of KEEP) if (ev[k] !== undefined) out[k] = ev[k];
|
|
58
|
+
return Buffer.from(JSON.stringify(out));
|
|
59
|
+
} catch (e) {
|
|
60
|
+
return raw.length <= 1 << 20 ? raw : Buffer.from('{}');
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function main() {
|
|
65
|
+
const body = slim(await readStdin());
|
|
66
|
+
try {
|
|
67
|
+
await post(body);
|
|
68
|
+
return;
|
|
69
|
+
} catch (e) { /* not running */ }
|
|
70
|
+
if (process.env.CLAWD_NO_SPAWN || fs.existsSync(paths.STOPPED)) return;
|
|
71
|
+
launch();
|
|
72
|
+
const end = Date.now() + 3000;
|
|
73
|
+
while (Date.now() < end) {
|
|
74
|
+
await new Promise(r => setTimeout(r, 300));
|
|
75
|
+
try {
|
|
76
|
+
await post(body);
|
|
77
|
+
return;
|
|
78
|
+
} catch (e) { /* still starting */ }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (require.main === module) {
|
|
83
|
+
main().catch(() => {}).finally(() => process.exit(0));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
module.exports = { launch, post };
|
package/src/install.js
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Put Desky on this computer: "npx desky-agent" runs this.
|
|
3
|
+
//
|
|
4
|
+
// 1. stop a running Desky (this app, or the old Python daemon from agent/), so its files and port are free
|
|
5
|
+
// 2. install the package into ~/.clawd-desk (npx runs from a cache that npm may clear at any time)
|
|
6
|
+
// 3. make the app: Electron renamed to Desky (Windows, Linux: ~/.clawd-desk/Desky; macOS: ~/Applications/Desky.app)
|
|
7
|
+
// 4. hooks in ~/.claude/settings.json; the old Python and claude-pet hooks go
|
|
8
|
+
// 5. start at login, shortcuts (desktop and Start menu; Applications; the app menu)
|
|
9
|
+
// 6. the board's firmware: older than this package -> updated in parts, NVS (calibration) kept; newer -> a warning
|
|
10
|
+
// 7. start the app and say whether the board answered
|
|
11
|
+
//
|
|
12
|
+
// Prints Russian for people, exits non-zero only when something did not work. No questions: an agent can run it
|
|
13
|
+
// (a silent board is repaired only with the "update started" marker, or with --yes).
|
|
14
|
+
|
|
15
|
+
const fs = require('fs');
|
|
16
|
+
const os = require('os');
|
|
17
|
+
const path = require('path');
|
|
18
|
+
const http = require('http');
|
|
19
|
+
const { spawnSync } = require('child_process');
|
|
20
|
+
const paths = require('./paths');
|
|
21
|
+
const autostart = require('./autostart');
|
|
22
|
+
|
|
23
|
+
const PKG_DIR = path.join(__dirname, '..');
|
|
24
|
+
const PKG = require('../package.json');
|
|
25
|
+
const WIN = process.platform === 'win32';
|
|
26
|
+
const MAC = process.platform === 'darwin';
|
|
27
|
+
const SETTINGS = path.join(os.homedir(), '.claude', 'settings.json');
|
|
28
|
+
const INSTALLED = path.join(paths.HOME, 'node_modules', PKG.name);
|
|
29
|
+
const BUNDLE = MAC ? path.join(os.homedir(), 'Applications', 'Desky Agent.app') : path.join(paths.HOME, 'Desky Agent');
|
|
30
|
+
// before the rename (0.2.4 and older, package clawdydesk): taken away by the next install
|
|
31
|
+
const OLD_BUNDLE = MAC ? path.join(os.homedir(), 'Applications', 'Clawd.app') : path.join(paths.HOME, 'Clawd');
|
|
32
|
+
const EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'PostToolUseFailure',
|
|
33
|
+
'PermissionRequest', 'Notification', 'Stop', 'SubagentStart', 'SubagentStop', 'PreCompact'];
|
|
34
|
+
|
|
35
|
+
const say = (...a) => console.log(...a);
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------- hooks
|
|
38
|
+
/** A hook of ours: this app's hook.js, the old Python agent's hook.py, or claude-pet's claudeye.py. */
|
|
39
|
+
function ours(h) {
|
|
40
|
+
const text = [h.command || '', ...(h.args || [])].join(' ').replace(/\\/g, '/');
|
|
41
|
+
return /claudeye\.py/i.test(text) || /clawd[^"]*\/agent\/hook\.py/i.test(text)
|
|
42
|
+
|| /(clawdydesk|desky-agent)\/src\/hook\.js/i.test(text);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function clean(hooks) {
|
|
46
|
+
for (const ev of Object.keys(hooks)) {
|
|
47
|
+
const groups = (hooks[ev] || [])
|
|
48
|
+
.map(g => ({ ...g, hooks: (g.hooks || []).filter(h => !ours(h)) }))
|
|
49
|
+
.filter(g => g.hooks.length);
|
|
50
|
+
if (groups.length) hooks[ev] = groups;
|
|
51
|
+
else delete hooks[ev];
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function wire(settings, node, hook) {
|
|
56
|
+
settings.hooks = settings.hooks || {};
|
|
57
|
+
clean(settings.hooks);
|
|
58
|
+
for (const ev of EVENTS) {
|
|
59
|
+
(settings.hooks[ev] = settings.hooks[ev] || []).push({ hooks: [
|
|
60
|
+
{ type: 'command', command: node, args: [hook], timeout: 5, async: true }] });
|
|
61
|
+
}
|
|
62
|
+
return settings;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function unwire(settings) {
|
|
66
|
+
if (settings.hooks) {
|
|
67
|
+
clean(settings.hooks);
|
|
68
|
+
if (!Object.keys(settings.hooks).length) delete settings.hooks;
|
|
69
|
+
}
|
|
70
|
+
return settings;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function editSettings(fn, file = SETTINGS) {
|
|
74
|
+
let settings = {};
|
|
75
|
+
if (fs.existsSync(file)) {
|
|
76
|
+
settings = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
77
|
+
fs.copyFileSync(file, file + '.bak');
|
|
78
|
+
} else {
|
|
79
|
+
fs.mkdirSync(path.dirname(file), { recursive: true }); // a fresh machine: Claude Code has not written one
|
|
80
|
+
}
|
|
81
|
+
settings = fn(settings);
|
|
82
|
+
fs.writeFileSync(file + '.tmp', JSON.stringify(settings, null, 2) + '\n');
|
|
83
|
+
fs.renameSync(file + '.tmp', file);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ---------------------------------------------------------------- a running Desky
|
|
87
|
+
function get(p, method = 'GET', timeout = 1000) {
|
|
88
|
+
return new Promise(resolve => {
|
|
89
|
+
const req = http.request({ host: '127.0.0.1', port: paths.port(), path: p, method, timeout,
|
|
90
|
+
headers: method === 'POST' ? { 'Content-Type': 'application/json', 'Content-Length': 2 } : {} }, res => {
|
|
91
|
+
let data = '';
|
|
92
|
+
res.on('data', c => (data += c));
|
|
93
|
+
res.on('end', () => {
|
|
94
|
+
try { resolve(JSON.parse(data)); } catch (e) { resolve({}); }
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
req.on('timeout', () => req.destroy());
|
|
98
|
+
req.on('error', () => resolve(null));
|
|
99
|
+
req.end(method === 'POST' ? '{}' : undefined);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
104
|
+
|
|
105
|
+
async function waitFor(test, ms) {
|
|
106
|
+
const end = Date.now() + ms;
|
|
107
|
+
while (Date.now() < end) {
|
|
108
|
+
if (await test()) return true;
|
|
109
|
+
await sleep(250);
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Ask whatever holds the port to quit; true once nothing answers. */
|
|
115
|
+
async function stopRunning() {
|
|
116
|
+
if (!(await get('/status'))) return true;
|
|
117
|
+
await get('/stop', 'POST');
|
|
118
|
+
const gone = await waitFor(async () => !(await get('/status')), 8000);
|
|
119
|
+
await sleep(500); // the process may hold its files a moment after the port is free
|
|
120
|
+
return gone;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ---------------------------------------------------------------- the package in ~/.clawd-desk
|
|
124
|
+
function npmCli() {
|
|
125
|
+
const cands = [];
|
|
126
|
+
if (process.env.npm_execpath) cands.push(process.env.npm_execpath.replace(/npx-cli\.js$/, 'npm-cli.js'));
|
|
127
|
+
const bin = path.dirname(process.execPath);
|
|
128
|
+
cands.push(path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'));
|
|
129
|
+
cands.push(path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'));
|
|
130
|
+
return cands.find(c => /npm-cli\.js$/.test(c) && fs.existsSync(c));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function npm(args, opts = {}) {
|
|
134
|
+
const cli = npmCli();
|
|
135
|
+
const r = cli ? spawnSync(process.execPath, [cli, ...args], { stdio: 'inherit', ...opts })
|
|
136
|
+
: spawnSync(WIN ? 'npm.cmd' : 'npm', args, { stdio: 'inherit', shell: WIN, ...opts });
|
|
137
|
+
if (r.status !== 0) throw new Error('npm ' + args[0] + ' не пройшов');
|
|
138
|
+
return r;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Install the very copy that runs (from npx's cache or a checkout) into ~/.clawd-desk: packed, so the files are
|
|
142
|
+
* exactly the published ones and nothing is fetched but the dependencies. */
|
|
143
|
+
function installPackage() {
|
|
144
|
+
if (path.resolve(PKG_DIR) === path.resolve(INSTALLED)) return; // running the installed copy itself
|
|
145
|
+
fs.mkdirSync(paths.HOME, { recursive: true });
|
|
146
|
+
const manifest = path.join(paths.HOME, 'package.json');
|
|
147
|
+
if (!fs.existsSync(manifest)) fs.writeFileSync(manifest, JSON.stringify({ private: true, name: 'clawd-desk-home' }, null, 2));
|
|
148
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'clawd-'));
|
|
149
|
+
try {
|
|
150
|
+
// --ignore-scripts: prepack (copying the firmware in) belongs to publishing; the running copy already has it
|
|
151
|
+
const r = npm(['pack', PKG_DIR, '--pack-destination', tmp, '--silent', '--ignore-scripts'],
|
|
152
|
+
{ stdio: ['ignore', 'pipe', 'inherit'] });
|
|
153
|
+
const tgz = path.join(tmp, String(r.stdout).trim().split(/\r?\n/).pop());
|
|
154
|
+
npm(['install', tgz, '--prefix', paths.HOME, '--no-audit', '--no-fund', '--ignore-scripts', '--loglevel=error']);
|
|
155
|
+
} finally {
|
|
156
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Electron's own download (npm no longer runs install scripts by default), then the rename into Desky. */
|
|
161
|
+
function makeApp() {
|
|
162
|
+
const electron = path.join(paths.HOME, 'node_modules', 'electron');
|
|
163
|
+
const r = spawnSync(process.execPath, [path.join(electron, 'install.js')], { cwd: electron, stdio: 'inherit' });
|
|
164
|
+
if (r.status !== 0) throw new Error('Electron не завантажився');
|
|
165
|
+
const dist = path.join(electron, 'dist');
|
|
166
|
+
const from = MAC ? path.join(dist, 'Electron.app') : dist;
|
|
167
|
+
rmRetry(BUNDLE);
|
|
168
|
+
fs.mkdirSync(path.dirname(BUNDLE), { recursive: true });
|
|
169
|
+
try {
|
|
170
|
+
fs.renameSync(from, BUNDLE);
|
|
171
|
+
} catch (e) {
|
|
172
|
+
fs.cpSync(from, BUNDLE, { recursive: true, verbatimSymlinks: true });
|
|
173
|
+
}
|
|
174
|
+
fs.rmSync(path.join(electron, 'path.txt'), { force: true }); // dist is gone: next install fetches again
|
|
175
|
+
|
|
176
|
+
const resources = MAC ? path.join(BUNDLE, 'Contents', 'Resources') : path.join(BUNDLE, 'resources');
|
|
177
|
+
const appDir = path.join(resources, 'app');
|
|
178
|
+
fs.mkdirSync(appDir, { recursive: true });
|
|
179
|
+
fs.writeFileSync(path.join(appDir, 'package.json'),
|
|
180
|
+
JSON.stringify({ name: 'desky-agent', productName: 'Desky Agent', version: PKG.version, main: 'index.js' }, null, 2));
|
|
181
|
+
fs.writeFileSync(path.join(appDir, 'index.js'),
|
|
182
|
+
`require(${JSON.stringify(path.join(INSTALLED, 'electron', 'main.js'))});\n`);
|
|
183
|
+
fs.copyFileSync(path.join(INSTALLED, 'assets', 'clawd.png'), path.join(paths.HOME, 'clawd.png'));
|
|
184
|
+
|
|
185
|
+
let launch;
|
|
186
|
+
if (WIN) {
|
|
187
|
+
fs.renameSync(path.join(BUNDLE, 'electron.exe'), path.join(BUNDLE, 'Desky Agent.exe'));
|
|
188
|
+
fs.copyFileSync(path.join(INSTALLED, 'assets', 'clawd.ico'), path.join(paths.HOME, 'clawd.ico'));
|
|
189
|
+
launch = { command: path.join(BUNDLE, 'Desky Agent.exe'), args: [] };
|
|
190
|
+
} else if (MAC) {
|
|
191
|
+
const info = path.join(BUNDLE, 'Contents', 'Info.plist');
|
|
192
|
+
for (const [k, v] of [['CFBundleName', 'Desky Agent'], ['CFBundleDisplayName', 'Desky Agent'],
|
|
193
|
+
['CFBundleIdentifier', 'desk.clawd.app'], ['CFBundleIconFile', 'clawd.icns']]) {
|
|
194
|
+
spawnSync('plutil', ['-replace', k, '-string', v, info]);
|
|
195
|
+
}
|
|
196
|
+
spawnSync('sips', ['-s', 'format', 'icns', path.join(INSTALLED, 'assets', 'clawd.png'),
|
|
197
|
+
'--out', path.join(resources, 'clawd.icns')], { stdio: 'ignore' });
|
|
198
|
+
spawnSync('xattr', ['-cr', BUNDLE], { stdio: 'ignore' });
|
|
199
|
+
// Info.plist changed, so Electron's signature no longer matches: sign it again, ad hoc, on this Mac
|
|
200
|
+
const sign = spawnSync('codesign', ['--force', '--deep', '--sign', '-', BUNDLE], { stdio: 'ignore' });
|
|
201
|
+
if (sign.status !== 0) say('УВАГА: codesign не пройшов; якщо Desky Agent.app не відкриється, напиши про це');
|
|
202
|
+
launch = { command: path.join(BUNDLE, 'Contents', 'MacOS', 'Electron'), args: [] };
|
|
203
|
+
} else {
|
|
204
|
+
fs.renameSync(path.join(BUNDLE, 'electron'), path.join(BUNDLE, 'clawd'));
|
|
205
|
+
// Electron's sandbox wants a setuid helper that only root can make: the window shows our own local page
|
|
206
|
+
launch = { command: path.join(BUNDLE, 'clawd'), args: ['--no-sandbox'] };
|
|
207
|
+
}
|
|
208
|
+
fs.writeFileSync(paths.LAUNCH, JSON.stringify(launch, null, 2));
|
|
209
|
+
return launch;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function rmRetry(dir) {
|
|
213
|
+
for (let i = 0; i < 10; i++) {
|
|
214
|
+
try {
|
|
215
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
216
|
+
return;
|
|
217
|
+
} catch (e) {
|
|
218
|
+
if (i === 9) throw new Error(`не вдалося прибрати ${dir}: ${e.message}. Закрий Desky і запусти ще раз`);
|
|
219
|
+
spawnSync(process.execPath, ['-e', 'setTimeout(()=>{},500)']);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ---------------------------------------------------------------- shortcuts
|
|
225
|
+
function powershell(script, env) {
|
|
226
|
+
return spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script],
|
|
227
|
+
{ env: { ...process.env, ...env }, windowsHide: true, encoding: 'utf8' });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function winDesktop() {
|
|
231
|
+
const r = powershell("[Console]::OutputEncoding = [Text.Encoding]::UTF8; [Environment]::GetFolderPath('Desktop')");
|
|
232
|
+
return String(r.stdout || '').trim() || path.join(os.homedir(), 'Desktop');
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const START_MENU = () => path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs');
|
|
236
|
+
const OLD_STARTUP_LINK = () => path.join(START_MENU(), 'Startup', 'Desky desk.lnk');
|
|
237
|
+
|
|
238
|
+
function winShortcut(lnk, target) {
|
|
239
|
+
const ps = '$s = (New-Object -ComObject WScript.Shell).CreateShortcut($env:CLAWD_LNK); '
|
|
240
|
+
+ '$s.TargetPath = $env:CLAWD_TARGET; $s.WorkingDirectory = $env:CLAWD_DIR; '
|
|
241
|
+
+ '$s.IconLocation = $env:CLAWD_ICON; $s.Description = "Desky Agent"; $s.Save()';
|
|
242
|
+
powershell(ps, { CLAWD_LNK: lnk, CLAWD_TARGET: target, CLAWD_DIR: path.dirname(target),
|
|
243
|
+
CLAWD_ICON: path.join(paths.HOME, 'clawd.ico') });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const LINUX_MENU = () => path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'),
|
|
247
|
+
'applications', 'clawd.desktop');
|
|
248
|
+
|
|
249
|
+
function shortcuts(launch) {
|
|
250
|
+
if (WIN) {
|
|
251
|
+
fs.rmSync(OLD_STARTUP_LINK(), { force: true }); // the Python daemon's, replaced by the Run key
|
|
252
|
+
for (const f of [path.join(winDesktop(), 'Clawd.lnk'), path.join(START_MENU(), 'Clawd.lnk')]) fs.rmSync(f, { force: true });
|
|
253
|
+
winShortcut(path.join(winDesktop(), 'Desky Agent.lnk'), launch.command);
|
|
254
|
+
winShortcut(path.join(START_MENU(), 'Desky Agent.lnk'), launch.command);
|
|
255
|
+
return 'ярлик «Desky Agent» на робочому столі й у меню «Пуск»';
|
|
256
|
+
}
|
|
257
|
+
if (MAC) return 'Desky Agent у ~/Applications (можна перетягнути в Dock)';
|
|
258
|
+
fs.mkdirSync(path.dirname(LINUX_MENU()), { recursive: true });
|
|
259
|
+
fs.writeFileSync(LINUX_MENU(), autostart.desktopEntry(launch.command, launch.args));
|
|
260
|
+
return 'Desky Agent у меню застосунків';
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function removeShortcuts() {
|
|
264
|
+
if (WIN) {
|
|
265
|
+
for (const f of [path.join(winDesktop(), 'Desky Agent.lnk'), path.join(START_MENU(), 'Desky Agent.lnk'),
|
|
266
|
+
path.join(winDesktop(), 'Clawd.lnk'), path.join(START_MENU(), 'Clawd.lnk'), OLD_STARTUP_LINK()]) {
|
|
267
|
+
fs.rmSync(f, { force: true });
|
|
268
|
+
}
|
|
269
|
+
} else if (!MAC) {
|
|
270
|
+
fs.rmSync(LINUX_MENU(), { force: true });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function macOldAgent() {
|
|
275
|
+
// the Python agent's LaunchAgent, if it was ever installed
|
|
276
|
+
if (!MAC) return;
|
|
277
|
+
const plist = path.join(os.homedir(), 'Library', 'LaunchAgents', autostart.OLD_LABEL + '.plist');
|
|
278
|
+
spawnSync('launchctl', ['bootout', `gui/${process.getuid()}/${autostart.OLD_LABEL}`], { stdio: 'ignore' });
|
|
279
|
+
fs.rmSync(plist, { force: true });
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ---------------------------------------------------------------- firmware
|
|
283
|
+
/** "записано 42%" on one terminal line; nothing when the output is not a terminal (an agent reads it). */
|
|
284
|
+
function progressLine() {
|
|
285
|
+
let last = -1;
|
|
286
|
+
return n => {
|
|
287
|
+
if (!process.stdout.isTTY || n === last) return;
|
|
288
|
+
last = n;
|
|
289
|
+
process.stdout.write('\r записано ' + n + '%' + (n >= 100 ? '\n' : ''));
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Check and update every board's firmware while nothing holds the ports. Hooks must not start the app meanwhile:
|
|
294
|
+
* it would grab the board the moment it comes back from the reset. -> updater.run()'s result */
|
|
295
|
+
async function firmware({ force = false, yes = false, ask = null, quiet = true } = {}) {
|
|
296
|
+
const wasStopped = fs.existsSync(paths.STOPPED);
|
|
297
|
+
paths.markStopped(true);
|
|
298
|
+
try {
|
|
299
|
+
return await require('./updater').run({ force, yes, ask, quiet, say, onProgress: progressLine(),
|
|
300
|
+
log: require('./daemon').log });
|
|
301
|
+
} finally {
|
|
302
|
+
paths.markStopped(wasStopped);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ---------------------------------------------------------------- the whole thing
|
|
307
|
+
async function install({ open = true, yes = false } = {}) {
|
|
308
|
+
const [major] = process.versions.node.split('.').map(Number);
|
|
309
|
+
if (major < 18) throw new Error('потрібен Node 18 або новіший, зараз ' + process.version);
|
|
310
|
+
|
|
311
|
+
say('Desky Agent ' + PKG.version + ': встановлюю в ' + paths.HOME);
|
|
312
|
+
if (!(await stopRunning())) throw new Error('запущений Desky не зупинився: закрий його в треї й запусти ще раз');
|
|
313
|
+
installPackage();
|
|
314
|
+
renamed();
|
|
315
|
+
const launch = makeApp();
|
|
316
|
+
say('застосунок: ' + BUNDLE);
|
|
317
|
+
|
|
318
|
+
const hook = path.join(INSTALLED, 'src', 'hook.js');
|
|
319
|
+
editSettings(s => wire(s, process.execPath, hook));
|
|
320
|
+
say(`хуки в ${SETTINGS} (${EVENTS.length} подій), старі хуки Desky і claude-pet прибрано`);
|
|
321
|
+
|
|
322
|
+
macOldAgent();
|
|
323
|
+
autostart.enable();
|
|
324
|
+
say('запуск під час входу в систему ввімкнено');
|
|
325
|
+
say(shortcuts(launch));
|
|
326
|
+
|
|
327
|
+
const fwr = await firmware({ yes });
|
|
328
|
+
if (fwr.failed) process.exitCode = 1;
|
|
329
|
+
|
|
330
|
+
paths.markStopped(false);
|
|
331
|
+
require('./hook').launch(open ? [] : ['--background']);
|
|
332
|
+
if (!(await waitFor(async () => Boolean(await get('/status')), 20000))) {
|
|
333
|
+
throw new Error('Desky не запустився. Лог: ' + paths.LOG);
|
|
334
|
+
}
|
|
335
|
+
await waitFor(async () => (await get('/status') || {}).connected, 10000);
|
|
336
|
+
const st = await get('/status');
|
|
337
|
+
say(st && st.connected ? `готово: Desky на зв'язку (${st.port}), значок у треї`
|
|
338
|
+
: 'готово, значок у треї. Плату не знайдено: під\'єднай Desky кабелем, програма знайде його сама');
|
|
339
|
+
if (process.platform === 'linux') say('Linux: якщо плата не знаходиться, додай себе в групу dialout і перезайди');
|
|
340
|
+
say('перезапусти відкриті сесії Claude Code, щоб вони підхопили хуки');
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Up to 0.2.4 the package was clawdydesk and the app Clawd: its copy in ~/.clawd-desk and its app go (its hooks,
|
|
344
|
+
* shortcuts and Run value are replaced on the way, see ours(), shortcuts() and autostart). */
|
|
345
|
+
function renamed() {
|
|
346
|
+
const old = path.join(paths.HOME, 'node_modules', 'clawdydesk');
|
|
347
|
+
if (fs.existsSync(old) || fs.existsSync(OLD_BUNDLE)) say('Clawd тепер Desky Agent: прибираю стару версію');
|
|
348
|
+
try {
|
|
349
|
+
const manifest = path.join(paths.HOME, 'package.json');
|
|
350
|
+
const m = JSON.parse(fs.readFileSync(manifest, 'utf8'));
|
|
351
|
+
if (m.dependencies && m.dependencies.clawdydesk) {
|
|
352
|
+
delete m.dependencies.clawdydesk;
|
|
353
|
+
fs.writeFileSync(manifest, JSON.stringify(m, null, 2));
|
|
354
|
+
}
|
|
355
|
+
} catch (e) { /* no manifest: nothing old */ }
|
|
356
|
+
rmRetry(old);
|
|
357
|
+
rmRetry(OLD_BUNDLE);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async function uninstall() {
|
|
361
|
+
await stopRunning();
|
|
362
|
+
editSettings(unwire);
|
|
363
|
+
autostart.disable();
|
|
364
|
+
macOldAgent();
|
|
365
|
+
removeShortcuts();
|
|
366
|
+
rmRetry(BUNDLE);
|
|
367
|
+
rmRetry(OLD_BUNDLE);
|
|
368
|
+
for (const f of ['node_modules', 'package.json', 'package-lock.json', 'launch.json', 'clawd.ico', 'clawd.png']) {
|
|
369
|
+
rmRetry(path.join(paths.HOME, f));
|
|
370
|
+
}
|
|
371
|
+
say('Desky Agent прибрано: хуки, автозапуск, ярлики й застосунок. Налаштування лишилися в ' + paths.CONFIG);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
module.exports = { install, uninstall, firmware, wire, unwire, ours, editSettings, stopRunning, get, waitFor, EVENTS,
|
|
375
|
+
BUNDLE, SETTINGS, INSTALLED };
|