desky-agent 0.3.0 → 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.
package/src/install.js CHANGED
@@ -1,375 +1,418 @@
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 };
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. Codex installed (~/.codex or
8
+ // $CODEX_HOME): hooks in its hooks.json too, which Codex runs only after the person trusts them in /hooks
9
+ // 5. start at login, shortcuts (desktop and Start menu; Applications; the app menu)
10
+ // 6. the board's firmware: older than this package -> updated in parts, NVS (calibration) kept; newer -> a warning
11
+ // 7. start the app and say whether the board answered
12
+ //
13
+ // Prints Russian for people, exits non-zero only when something did not work. No questions: an agent can run it
14
+ // (a silent board is repaired only with the "update started" marker, or with --yes).
15
+
16
+ const fs = require('fs');
17
+ const os = require('os');
18
+ const path = require('path');
19
+ const http = require('http');
20
+ const { spawnSync } = require('child_process');
21
+ const paths = require('./paths');
22
+ const autostart = require('./autostart');
23
+
24
+ const PKG_DIR = path.join(__dirname, '..');
25
+ const PKG = require('../package.json');
26
+ const WIN = process.platform === 'win32';
27
+ const MAC = process.platform === 'darwin';
28
+ const SETTINGS = path.join(os.homedir(), '.claude', 'settings.json');
29
+ const CODEX_DIR = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
30
+ const CODEX_HOOKS = path.join(CODEX_DIR, 'hooks.json');
31
+ const INSTALLED = path.join(paths.HOME, 'node_modules', PKG.name);
32
+ const BUNDLE = MAC ? path.join(os.homedir(), 'Applications', 'Desky Agent.app') : path.join(paths.HOME, 'Desky Agent');
33
+ // before the rename (0.2.4 and older, package clawdydesk): taken away by the next install
34
+ const OLD_BUNDLE = MAC ? path.join(os.homedir(), 'Applications', 'Clawd.app') : path.join(paths.HOME, 'Clawd');
35
+ const EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'PostToolUseFailure',
36
+ 'PermissionRequest', 'Notification', 'Stop', 'SubagentStart', 'SubagentStop', 'PreCompact'];
37
+ // Codex has no Notification or PostToolUseFailure, and has Interrupt
38
+ const CODEX_EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse',
39
+ 'PermissionRequest', 'Stop', 'SubagentStart', 'SubagentStop', 'PreCompact', 'Interrupt'];
40
+ // Codex allows these 3 s at most
41
+ const CODEX_SHORT = ['SessionEnd', 'Interrupt'];
42
+ // Not in the background: a background Stop dies with "codex exec" before it is sent, and a background SessionStart
43
+ // can land after the prompt and reset it to idle. All rare, so waiting for them costs nothing; tool events stay async.
44
+ const CODEX_SYNC = ['SessionStart', 'Stop', 'SessionEnd', 'Interrupt'];
45
+
46
+ const say = (...a) => console.log(...a);
47
+
48
+ // ---------------------------------------------------------------- hooks
49
+ /** A hook of ours: this app's hook.js, the old Python agent's hook.py, or claude-pet's claudeye.py. */
50
+ function ours(h) {
51
+ const text = [h.command || '', ...(h.args || [])].join(' ').replace(/\\/g, '/');
52
+ return /claudeye\.py/i.test(text) || /clawd[^"]*\/agent\/hook\.py/i.test(text)
53
+ || /(clawdydesk|desky-agent)\/src\/hook\.js/i.test(text);
54
+ }
55
+
56
+ function clean(hooks) {
57
+ for (const ev of Object.keys(hooks)) {
58
+ const groups = (hooks[ev] || [])
59
+ .map(g => ({ ...g, hooks: (g.hooks || []).filter(h => !ours(h)) }))
60
+ .filter(g => g.hooks.length);
61
+ if (groups.length) hooks[ev] = groups;
62
+ else delete hooks[ev];
63
+ }
64
+ }
65
+
66
+ function wire(settings, node, hook) {
67
+ settings.hooks = settings.hooks || {};
68
+ clean(settings.hooks);
69
+ for (const ev of EVENTS) {
70
+ (settings.hooks[ev] = settings.hooks[ev] || []).push({ hooks: [
71
+ { type: 'command', command: node, args: [hook], timeout: 5, async: true }] });
72
+ }
73
+ return settings;
74
+ }
75
+
76
+ /** Codex takes one command line, no args, and runs it in PowerShell on Windows and a POSIX shell elsewhere.
77
+ * The trailing "codex" tells hook.js whose event it is. */
78
+ function codexCommand(node, hook, win = WIN) {
79
+ // single quotes: nothing inside is expanded; PowerShell escapes ' as '', a POSIX shell as '\''
80
+ const q = win ? a => "'" + a.replace(/'/g, "''") + "'" : a => "'" + a.replace(/'/g, "'\\''") + "'";
81
+ return (win ? '& ' : '') + `${q(node)} ${q(hook)} codex`;
82
+ }
83
+
84
+ /** ~/.codex/hooks.json: the same layout as Claude's settings, only the handler differs. */
85
+ function wireCodex(file, node, hook, win = WIN) {
86
+ file.hooks = file.hooks || {};
87
+ clean(file.hooks);
88
+ const command = codexCommand(node, hook, win);
89
+ for (const ev of CODEX_EVENTS) {
90
+ (file.hooks[ev] = file.hooks[ev] || []).push({ hooks: [
91
+ { type: 'command', command, timeout: CODEX_SHORT.includes(ev) ? 3 : 5, async: !CODEX_SYNC.includes(ev) }] });
92
+ }
93
+ return file;
94
+ }
95
+
96
+ function unwire(settings) {
97
+ if (settings.hooks) {
98
+ clean(settings.hooks);
99
+ if (!Object.keys(settings.hooks).length) delete settings.hooks;
100
+ }
101
+ return settings;
102
+ }
103
+
104
+ function editSettings(fn, file = SETTINGS) {
105
+ let settings = {};
106
+ if (fs.existsSync(file)) {
107
+ settings = JSON.parse(fs.readFileSync(file, 'utf8'));
108
+ fs.copyFileSync(file, file + '.bak');
109
+ } else {
110
+ fs.mkdirSync(path.dirname(file), { recursive: true }); // a fresh machine: Claude Code has not written one
111
+ }
112
+ settings = fn(settings);
113
+ fs.writeFileSync(file + '.tmp', JSON.stringify(settings, null, 2) + '\n');
114
+ fs.renameSync(file + '.tmp', file);
115
+ }
116
+
117
+ // ---------------------------------------------------------------- a running Desky
118
+ function get(p, method = 'GET', timeout = 1000) {
119
+ return new Promise(resolve => {
120
+ const req = http.request({ host: '127.0.0.1', port: paths.port(), path: p, method, timeout,
121
+ headers: method === 'POST' ? { 'Content-Type': 'application/json', 'Content-Length': 2 } : {} }, res => {
122
+ let data = '';
123
+ res.on('data', c => (data += c));
124
+ res.on('end', () => {
125
+ try { resolve(JSON.parse(data)); } catch (e) { resolve({}); }
126
+ });
127
+ });
128
+ req.on('timeout', () => req.destroy());
129
+ req.on('error', () => resolve(null));
130
+ req.end(method === 'POST' ? '{}' : undefined);
131
+ });
132
+ }
133
+
134
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
135
+
136
+ async function waitFor(test, ms) {
137
+ const end = Date.now() + ms;
138
+ while (Date.now() < end) {
139
+ if (await test()) return true;
140
+ await sleep(250);
141
+ }
142
+ return false;
143
+ }
144
+
145
+ /** Ask whatever holds the port to quit; true once nothing answers. */
146
+ async function stopRunning() {
147
+ if (!(await get('/status'))) return true;
148
+ await get('/stop', 'POST');
149
+ const gone = await waitFor(async () => !(await get('/status')), 8000);
150
+ await sleep(500); // the process may hold its files a moment after the port is free
151
+ return gone;
152
+ }
153
+
154
+ // ---------------------------------------------------------------- the package in ~/.clawd-desk
155
+ function npmCli() {
156
+ const cands = [];
157
+ if (process.env.npm_execpath) cands.push(process.env.npm_execpath.replace(/npx-cli\.js$/, 'npm-cli.js'));
158
+ const bin = path.dirname(process.execPath);
159
+ cands.push(path.join(bin, 'node_modules', 'npm', 'bin', 'npm-cli.js'));
160
+ cands.push(path.join(bin, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'));
161
+ return cands.find(c => /npm-cli\.js$/.test(c) && fs.existsSync(c));
162
+ }
163
+
164
+ function npm(args, opts = {}) {
165
+ const cli = npmCli();
166
+ const r = cli ? spawnSync(process.execPath, [cli, ...args], { stdio: 'inherit', ...opts })
167
+ : spawnSync(WIN ? 'npm.cmd' : 'npm', args, { stdio: 'inherit', shell: WIN, ...opts });
168
+ if (r.status !== 0) throw new Error('npm ' + args[0] + ' не пройшов');
169
+ return r;
170
+ }
171
+
172
+ /** Install the very copy that runs (from npx's cache or a checkout) into ~/.clawd-desk: packed, so the files are
173
+ * exactly the published ones and nothing is fetched but the dependencies. */
174
+ function installPackage() {
175
+ if (path.resolve(PKG_DIR) === path.resolve(INSTALLED)) return; // running the installed copy itself
176
+ fs.mkdirSync(paths.HOME, { recursive: true });
177
+ const manifest = path.join(paths.HOME, 'package.json');
178
+ if (!fs.existsSync(manifest)) fs.writeFileSync(manifest, JSON.stringify({ private: true, name: 'clawd-desk-home' }, null, 2));
179
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'clawd-'));
180
+ try {
181
+ // --ignore-scripts: prepack (copying the firmware in) belongs to publishing; the running copy already has it
182
+ const r = npm(['pack', PKG_DIR, '--pack-destination', tmp, '--silent', '--ignore-scripts'],
183
+ { stdio: ['ignore', 'pipe', 'inherit'] });
184
+ const tgz = path.join(tmp, String(r.stdout).trim().split(/\r?\n/).pop());
185
+ npm(['install', tgz, '--prefix', paths.HOME, '--no-audit', '--no-fund', '--ignore-scripts', '--loglevel=error']);
186
+ } finally {
187
+ fs.rmSync(tmp, { recursive: true, force: true });
188
+ }
189
+ }
190
+
191
+ /** Electron's own download (npm no longer runs install scripts by default), then the rename into Desky. */
192
+ function makeApp() {
193
+ const electron = path.join(paths.HOME, 'node_modules', 'electron');
194
+ const r = spawnSync(process.execPath, [path.join(electron, 'install.js')], { cwd: electron, stdio: 'inherit' });
195
+ if (r.status !== 0) throw new Error('Electron не завантажився');
196
+ const dist = path.join(electron, 'dist');
197
+ const from = MAC ? path.join(dist, 'Electron.app') : dist;
198
+ rmRetry(BUNDLE);
199
+ fs.mkdirSync(path.dirname(BUNDLE), { recursive: true });
200
+ try {
201
+ fs.renameSync(from, BUNDLE);
202
+ } catch (e) {
203
+ fs.cpSync(from, BUNDLE, { recursive: true, verbatimSymlinks: true });
204
+ }
205
+ fs.rmSync(path.join(electron, 'path.txt'), { force: true }); // dist is gone: next install fetches again
206
+
207
+ const resources = MAC ? path.join(BUNDLE, 'Contents', 'Resources') : path.join(BUNDLE, 'resources');
208
+ const appDir = path.join(resources, 'app');
209
+ fs.mkdirSync(appDir, { recursive: true });
210
+ fs.writeFileSync(path.join(appDir, 'package.json'),
211
+ JSON.stringify({ name: 'desky-agent', productName: 'Desky Agent', version: PKG.version, main: 'index.js' }, null, 2));
212
+ fs.writeFileSync(path.join(appDir, 'index.js'),
213
+ `require(${JSON.stringify(path.join(INSTALLED, 'electron', 'main.js'))});\n`);
214
+ fs.copyFileSync(path.join(INSTALLED, 'assets', 'clawd.png'), path.join(paths.HOME, 'clawd.png'));
215
+
216
+ let launch;
217
+ if (WIN) {
218
+ fs.renameSync(path.join(BUNDLE, 'electron.exe'), path.join(BUNDLE, 'Desky Agent.exe'));
219
+ fs.copyFileSync(path.join(INSTALLED, 'assets', 'clawd.ico'), path.join(paths.HOME, 'clawd.ico'));
220
+ launch = { command: path.join(BUNDLE, 'Desky Agent.exe'), args: [] };
221
+ } else if (MAC) {
222
+ const info = path.join(BUNDLE, 'Contents', 'Info.plist');
223
+ for (const [k, v] of [['CFBundleName', 'Desky Agent'], ['CFBundleDisplayName', 'Desky Agent'],
224
+ ['CFBundleIdentifier', 'desk.clawd.app'], ['CFBundleIconFile', 'clawd.icns']]) {
225
+ spawnSync('plutil', ['-replace', k, '-string', v, info]);
226
+ }
227
+ spawnSync('sips', ['-s', 'format', 'icns', path.join(INSTALLED, 'assets', 'clawd.png'),
228
+ '--out', path.join(resources, 'clawd.icns')], { stdio: 'ignore' });
229
+ spawnSync('xattr', ['-cr', BUNDLE], { stdio: 'ignore' });
230
+ // Info.plist changed, so Electron's signature no longer matches: sign it again, ad hoc, on this Mac
231
+ const sign = spawnSync('codesign', ['--force', '--deep', '--sign', '-', BUNDLE], { stdio: 'ignore' });
232
+ if (sign.status !== 0) say('УВАГА: codesign не пройшов; якщо Desky Agent.app не відкриється, напиши про це');
233
+ launch = { command: path.join(BUNDLE, 'Contents', 'MacOS', 'Electron'), args: [] };
234
+ } else {
235
+ fs.renameSync(path.join(BUNDLE, 'electron'), path.join(BUNDLE, 'clawd'));
236
+ // Electron's sandbox wants a setuid helper that only root can make: the window shows our own local page
237
+ launch = { command: path.join(BUNDLE, 'clawd'), args: ['--no-sandbox'] };
238
+ }
239
+ // node: the app updates itself with the Node that installed it (src/release.js), not the one on PATH
240
+ fs.writeFileSync(paths.LAUNCH, JSON.stringify({ ...launch, node: process.execPath }, null, 2));
241
+ return launch;
242
+ }
243
+
244
+ function rmRetry(dir) {
245
+ for (let i = 0; i < 10; i++) {
246
+ try {
247
+ fs.rmSync(dir, { recursive: true, force: true });
248
+ return;
249
+ } catch (e) {
250
+ if (i === 9) throw new Error(`не вдалося прибрати ${dir}: ${e.message}. Закрий Desky і запусти ще раз`);
251
+ spawnSync(process.execPath, ['-e', 'setTimeout(()=>{},500)']);
252
+ }
253
+ }
254
+ }
255
+
256
+ // ---------------------------------------------------------------- shortcuts
257
+ function powershell(script, env) {
258
+ return spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script],
259
+ { env: { ...process.env, ...env }, windowsHide: true, encoding: 'utf8' });
260
+ }
261
+
262
+ function winDesktop() {
263
+ const r = powershell("[Console]::OutputEncoding = [Text.Encoding]::UTF8; [Environment]::GetFolderPath('Desktop')");
264
+ return String(r.stdout || '').trim() || path.join(os.homedir(), 'Desktop');
265
+ }
266
+
267
+ const START_MENU = () => path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs');
268
+ const OLD_STARTUP_LINK = () => path.join(START_MENU(), 'Startup', 'Desky desk.lnk');
269
+
270
+ function winShortcut(lnk, target) {
271
+ const ps = '$s = (New-Object -ComObject WScript.Shell).CreateShortcut($env:CLAWD_LNK); '
272
+ + '$s.TargetPath = $env:CLAWD_TARGET; $s.WorkingDirectory = $env:CLAWD_DIR; '
273
+ + '$s.IconLocation = $env:CLAWD_ICON; $s.Description = "Desky Agent"; $s.Save()';
274
+ powershell(ps, { CLAWD_LNK: lnk, CLAWD_TARGET: target, CLAWD_DIR: path.dirname(target),
275
+ CLAWD_ICON: path.join(paths.HOME, 'clawd.ico') });
276
+ }
277
+
278
+ const LINUX_MENU = () => path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'),
279
+ 'applications', 'clawd.desktop');
280
+
281
+ function shortcuts(launch) {
282
+ if (WIN) {
283
+ fs.rmSync(OLD_STARTUP_LINK(), { force: true }); // the Python daemon's, replaced by the Run key
284
+ for (const f of [path.join(winDesktop(), 'Clawd.lnk'), path.join(START_MENU(), 'Clawd.lnk')]) fs.rmSync(f, { force: true });
285
+ winShortcut(path.join(winDesktop(), 'Desky Agent.lnk'), launch.command);
286
+ winShortcut(path.join(START_MENU(), 'Desky Agent.lnk'), launch.command);
287
+ return 'ярлик «Desky Agent» на робочому столі й у меню «Пуск»';
288
+ }
289
+ if (MAC) return 'Desky Agent у ~/Applications (можна перетягнути в Dock)';
290
+ fs.mkdirSync(path.dirname(LINUX_MENU()), { recursive: true });
291
+ fs.writeFileSync(LINUX_MENU(), autostart.desktopEntry(launch.command, launch.args));
292
+ return 'Desky Agent у меню застосунків';
293
+ }
294
+
295
+ function removeShortcuts() {
296
+ if (WIN) {
297
+ for (const f of [path.join(winDesktop(), 'Desky Agent.lnk'), path.join(START_MENU(), 'Desky Agent.lnk'),
298
+ path.join(winDesktop(), 'Clawd.lnk'), path.join(START_MENU(), 'Clawd.lnk'), OLD_STARTUP_LINK()]) {
299
+ fs.rmSync(f, { force: true });
300
+ }
301
+ } else if (!MAC) {
302
+ fs.rmSync(LINUX_MENU(), { force: true });
303
+ }
304
+ }
305
+
306
+ function macOldAgent() {
307
+ // the Python agent's LaunchAgent, if it was ever installed
308
+ if (!MAC) return;
309
+ const plist = path.join(os.homedir(), 'Library', 'LaunchAgents', autostart.OLD_LABEL + '.plist');
310
+ spawnSync('launchctl', ['bootout', `gui/${process.getuid()}/${autostart.OLD_LABEL}`], { stdio: 'ignore' });
311
+ fs.rmSync(plist, { force: true });
312
+ }
313
+
314
+ // ---------------------------------------------------------------- firmware
315
+ /** "записано 42%" on one terminal line; nothing when the output is not a terminal (an agent reads it). */
316
+ function progressLine() {
317
+ let last = -1;
318
+ return n => {
319
+ if (!process.stdout.isTTY || n === last) return;
320
+ last = n;
321
+ process.stdout.write('\r записано ' + n + '%' + (n >= 100 ? '\n' : ''));
322
+ };
323
+ }
324
+
325
+ /** Check and update every board's firmware while nothing holds the ports. Hooks must not start the app meanwhile:
326
+ * it would grab the board the moment it comes back from the reset. -> updater.run()'s result */
327
+ async function firmware({ force = false, yes = false, ask = null, quiet = true } = {}) {
328
+ const wasStopped = fs.existsSync(paths.STOPPED);
329
+ paths.markStopped(true);
330
+ try {
331
+ return await require('./updater').run({ force, yes, ask, quiet, say, onProgress: progressLine(),
332
+ log: require('./daemon').log });
333
+ } finally {
334
+ paths.markStopped(wasStopped);
335
+ }
336
+ }
337
+
338
+ // ---------------------------------------------------------------- the whole thing
339
+ async function install({ open = true, yes = false } = {}) {
340
+ const [major] = process.versions.node.split('.').map(Number);
341
+ if (major < 18) throw new Error('потрібен Node 18 або новіший, зараз ' + process.version);
342
+
343
+ say('Desky Agent ' + PKG.version + ': встановлюю в ' + paths.HOME);
344
+ if (!(await stopRunning())) throw new Error('запущений Desky не зупинився: закрий його в треї й запусти ще раз');
345
+ installPackage();
346
+ renamed();
347
+ const launch = makeApp();
348
+ say('застосунок: ' + BUNDLE);
349
+
350
+ const hook = path.join(INSTALLED, 'src', 'hook.js');
351
+ editSettings(s => wire(s, process.execPath, hook));
352
+ say(`хуки в ${SETTINGS} (${EVENTS.length} подій), старі хуки Desky і claude-pet прибрано`);
353
+ const codex = fs.existsSync(CODEX_DIR);
354
+ if (codex) {
355
+ editSettings(f => wireCodex(f, process.execPath, hook), CODEX_HOOKS);
356
+ say(`хуки Codex в ${CODEX_HOOKS} (${CODEX_EVENTS.length} подій)`);
357
+ }
358
+
359
+ macOldAgent();
360
+ autostart.enable();
361
+ say('запуск під час входу в систему ввімкнено');
362
+ say(shortcuts(launch));
363
+
364
+ const fwr = await firmware({ yes });
365
+ if (fwr.failed) process.exitCode = 1;
366
+
367
+ paths.markStopped(false);
368
+ require('./hook').launch(open ? [] : ['--background']);
369
+ if (!(await waitFor(async () => Boolean(await get('/status')), 20000))) {
370
+ throw new Error('Desky не запустився. Лог: ' + paths.LOG);
371
+ }
372
+ await waitFor(async () => (await get('/status') || {}).connected, 10000);
373
+ const st = await get('/status');
374
+ say(st && st.connected ? `готово: Desky на зв'язку (${st.port}), значок у треї`
375
+ : 'готово, значок у треї. Плату не знайдено: під\'єднай Desky кабелем, програма знайде його сама');
376
+ if (process.platform === 'linux') say('Linux: якщо плата не знаходиться, додай себе в групу dialout і перезайди');
377
+ say('перезапусти відкриті сесії Claude Code, щоб вони підхопили хуки');
378
+ if (codex) {
379
+ say('Codex: хуки запрацюють після схвалення. У Codex набери /hooks (у застосунку: «Review hooks» біля поля вводу)'
380
+ + ' і довір хуки Desky. Codex спитає знову, якщо команда хука зміниться (наприклад, переїде Node)');
381
+ }
382
+ }
383
+
384
+ /** Up to 0.2.4 the package was clawdydesk and the app Clawd: its copy in ~/.clawd-desk and its app go (its hooks,
385
+ * shortcuts and Run value are replaced on the way, see ours(), shortcuts() and autostart). */
386
+ function renamed() {
387
+ const old = path.join(paths.HOME, 'node_modules', 'clawdydesk');
388
+ if (fs.existsSync(old) || fs.existsSync(OLD_BUNDLE)) say('Clawd тепер Desky Agent: прибираю стару версію');
389
+ try {
390
+ const manifest = path.join(paths.HOME, 'package.json');
391
+ const m = JSON.parse(fs.readFileSync(manifest, 'utf8'));
392
+ if (m.dependencies && m.dependencies.clawdydesk) {
393
+ delete m.dependencies.clawdydesk;
394
+ fs.writeFileSync(manifest, JSON.stringify(m, null, 2));
395
+ }
396
+ } catch (e) { /* no manifest: nothing old */ }
397
+ rmRetry(old);
398
+ rmRetry(OLD_BUNDLE);
399
+ }
400
+
401
+ async function uninstall() {
402
+ await stopRunning();
403
+ editSettings(unwire);
404
+ if (fs.existsSync(CODEX_HOOKS)) editSettings(unwire, CODEX_HOOKS);
405
+ autostart.disable();
406
+ macOldAgent();
407
+ removeShortcuts();
408
+ rmRetry(BUNDLE);
409
+ rmRetry(OLD_BUNDLE);
410
+ for (const f of ['node_modules', 'package.json', 'package-lock.json', 'launch.json', 'clawd.ico', 'clawd.png']) {
411
+ rmRetry(path.join(paths.HOME, f));
412
+ }
413
+ say('Desky Agent прибрано: хуки (Claude Code і Codex), автозапуск, ярлики й застосунок. Налаштування лишилися в '
414
+ + paths.CONFIG);
415
+ }
416
+
417
+ module.exports = { install, uninstall, firmware, wire, unwire, wireCodex, codexCommand, ours, editSettings, stopRunning,
418
+ get, waitFor, EVENTS, CODEX_EVENTS, BUNDLE, SETTINGS, CODEX_DIR, CODEX_HOOKS, INSTALLED };