desky-agent 0.3.11 → 0.3.13

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/daemon.js CHANGED
@@ -13,7 +13,8 @@
13
13
  // after the app's last call (window closed) or a minute after the last hand command (window
14
14
  // left open and forgotten), and Desky goes back to the agent.
15
15
  // POST /reset restart the C3 (RTS pulse)
16
- // GET /config settings in force and their defaults; POST /config {...} saves to config.json
16
+ // GET /config settings in force, their defaults and the emotions that can be switched off (emotions_off);
17
+ // POST /config {...} saves to config.json
17
18
  // POST /app-update install the newer version npm has (src/release.js): the app quits and comes back new
18
19
  //
19
20
  // One instance only: a second one cannot bind the port.
@@ -21,7 +22,7 @@
21
22
  const fs = require('fs');
22
23
  const http = require('http');
23
24
  const path = require('path');
24
- const { Core, DEFAULTS, COLORS } = require('./core');
25
+ const { Core, DEFAULTS, COLORS, EMOTIONS, emotionKey } = require('./core');
25
26
  const paths = require('./paths');
26
27
 
27
28
  const UI_DIR = path.join(__dirname, '..', 'ui');
@@ -72,11 +73,30 @@ function cleanConfig(next) {
72
73
  if (k === 'port' && !(v >= 1024 && v <= 65535)) throw new Error(k);
73
74
  }
74
75
  if (k === 'color' && !COLORS.includes(v)) throw new Error(k);
76
+ if (k === 'emotions_off') { // names the CLI and old hands may write ("reading") become state keys
77
+ const keys = v.map(x => emotionKey(x));
78
+ if (keys.includes(null)) throw new Error(k + ': ' + v[keys.indexOf(null)]);
79
+ v = EMOTIONS.map(e => e.key).filter(x => keys.includes(x));
80
+ }
75
81
  out[k] = v;
76
82
  }
77
83
  return out;
78
84
  }
79
85
 
86
+ /** Clean the keys given and merge them into config.json; the rest of the file stays as it was. Returns the clean keys.
87
+ * The app does it on POST /config, "desky-agent emotions" when the app is not running. */
88
+ function writeConfig(next, file = paths.CONFIG) {
89
+ next = cleanConfig(next);
90
+ let saved = {};
91
+ try { saved = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { /* new file */ }
92
+ Object.assign(saved, next);
93
+ fs.mkdirSync(path.dirname(file), { recursive: true });
94
+ const tmp = file + '.tmp';
95
+ fs.writeFileSync(tmp, JSON.stringify(saved, null, 2));
96
+ fs.renameSync(tmp, file);
97
+ return next;
98
+ }
99
+
80
100
  class Daemon {
81
101
  constructor({ config, configPath = paths.CONFIG, linkFactory, clock = () => Date.now() / 1000, httpPort,
82
102
  onStop = () => {}, updater, release } = {}) {
@@ -335,14 +355,7 @@ class Daemon {
335
355
  }
336
356
 
337
357
  saveConfig(next) {
338
- next = cleanConfig(next);
339
- let saved = {};
340
- try { saved = JSON.parse(fs.readFileSync(this.configPath, 'utf8')); } catch (e) { /* new file */ }
341
- Object.assign(saved, next);
342
- fs.mkdirSync(path.dirname(this.configPath), { recursive: true });
343
- const tmp = this.configPath + '.tmp';
344
- fs.writeFileSync(tmp, JSON.stringify(saved, null, 2));
345
- fs.renameSync(tmp, this.configPath);
358
+ next = writeConfig(next, this.configPath);
346
359
  Object.assign(this.cfg, next);
347
360
  Object.assign(this.core.cfg, next);
348
361
  return this.cfg;
@@ -388,7 +401,10 @@ class Daemon {
388
401
  }
389
402
  if (u.pathname === '/status') return reply(200, this.status());
390
403
  if (u.pathname === '/lines') return reply(200, this.getLines(Number(u.searchParams.get('since') || 0)));
391
- if (u.pathname === '/config') return reply(200, { config: this.cfg, defaults: DEFAULTS });
404
+ if (u.pathname === '/config') {
405
+ return reply(200, { config: this.cfg, defaults: DEFAULTS,
406
+ emotions: EMOTIONS.map(({ key, label, hint, calm }) => ({ key, label, hint, calm })) });
407
+ }
392
408
  return reply(404, { error: 'not found' });
393
409
  }
394
410
  if (req.method !== 'POST') return reply(405, { error: 'method' });
@@ -519,4 +535,4 @@ function readBody(req) {
519
535
  });
520
536
  }
521
537
 
522
- module.exports = { Daemon, loadConfig, cleanConfig, log, VERSION };
538
+ module.exports = { Daemon, loadConfig, cleanConfig, writeConfig, log, VERSION };
package/src/release.js CHANGED
@@ -1,131 +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 };
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 };
package/src/selfupdate.js CHANGED
@@ -15,7 +15,7 @@ const release = require('./release');
15
15
  const { launch } = require('./hook');
16
16
 
17
17
  const [version, npm] = process.argv.slice(2);
18
- const PKG = require('../package.json').name;
18
+ const PKG = require('../package.json').name;
19
19
  const INSTALLED = path.join(paths.HOME, 'node_modules', PKG, 'package.json');
20
20
 
21
21
  function installedVersion() {