desky-agent 0.3.0 → 0.3.2

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/core.js CHANGED
@@ -1,172 +1,244 @@
1
- 'use strict';
2
- // What Desky shows: Claude Code's hook events in, lines for the C3 out.
3
- //
4
- // No timers, no port, no wall clock: the daemon feeds events and ticks, the tests do the same with a fake clock.
5
- // The firmware acts a state out until the next one; everything about time lives here (how long "done" lasts, when
6
- // to sleep, the ask trill repeats, the way back after an error, quiet hours). Times are in seconds.
7
-
8
- // the colours Desky is printed in; the app and the face on his screen follow the one chosen (ui/app.html, PALETTE)
9
- const COLORS = ['orange', 'white', 'mint', 'blue', 'graphite'];
10
-
11
- const DEFAULTS = {
12
- color: 'orange', // which Desky this is: his body colour
13
- quiet_hours: [23, 8], // no sound from 23:00 to 08:00; [0, 0] = never quiet
14
- done_secs: 120, // "done" looks at you this long, then idle
15
- sleep_secs: 600, // no events this long: sleep
16
- ask_repeat_secs: 120, // the ask trill again after this long ...
17
- ask_times: 3, // ... at most this many times in all
18
- session_ttl_secs: 1800, // a done or idle session silent this long stops counting
19
- // A session killed mid-task (PC or app restarted, terminal closed) never sends Stop or SessionEnd and would keep
20
- // Desky "working". The longest tool call is a 10 min Bash, so a working session silent for 11 min is gone.
21
- busy_ttl_secs: 660,
22
- ask_ttl_secs: 3600, // nobody answered for an hour: that question is not coming back
23
- listen_secs: 1.5, // the nod after your message, then work
24
- error_secs: 1.2,
25
- wake_secs: 2.5,
26
- read_tools: ['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'LS', 'NotebookRead', 'ToolSearch'],
27
- ask_tools: ['AskUserQuestion'],
28
- port: 47811,
29
- };
30
-
31
- // what wins when sessions disagree
32
- const RANK = { ask: 5, work: 4, read: 3, done: 2, idle: 1 };
33
- const SOUND_ON_ENTER = { wake: 'wake', listen: 'tick', error: 'error', done: 'done', sleep: 'sleep', ask: 'ask' };
34
-
35
- const now = () => Date.now() / 1000;
36
- const localHour = t => new Date(t * 1000).getHours();
37
-
38
- class Core {
39
- constructor(send, { clock = now, config = {}, hour = localHour } = {}) {
40
- this.send = send;
41
- this.clock = clock;
42
- this.hour = hour;
43
- this.cfg = { ...DEFAULTS, ...config };
44
- this.sessions = new Map(); // id -> { state, t, doneT }
45
- this.overlay = null; // [state, until]: wake / listen / error play over the computed state
46
- this.lastEvent = clock();
47
- this.shown = null; // the last state sent
48
- this.asksPlayed = 0;
49
- this.nextAsk = null;
50
- }
51
-
52
- // ------------------------------------------------------------ events
53
- event(ev) {
54
- const t = this.clock();
55
- const name = ev.hook_event_name || '';
56
- const sid = ev.session_id || '?';
57
- const tool = ev.tool_name || '';
58
- const before = this.display(t);
59
- this.lastEvent = t;
60
- if (name === 'SessionEnd') {
61
- this.sessions.delete(sid);
62
- this.tick();
63
- return;
64
- }
65
- let s = this.sessions.get(sid);
66
- if (!s) this.sessions.set(sid, (s = { state: 'idle', t, doneT: null }));
67
- s.t = t;
68
- const c = this.cfg;
69
- if (name === 'SessionStart') {
70
- set(s, 'idle'); // resumed after a restart: whatever it was doing then is over
71
- if (before === 'idle' || before === 'sleep') this.overlay = ['wake', t + c.wake_secs];
72
- } else if (name === 'UserPromptSubmit') {
73
- set(s, 'work');
74
- this.overlay = ['listen', t + c.listen_secs];
75
- } else if (name === 'PreToolUse') {
76
- if (c.ask_tools.includes(tool)) set(s, 'ask');
77
- else set(s, c.read_tools.includes(tool) ? 'read' : 'work');
78
- } else if (name === 'PermissionRequest') {
79
- set(s, 'ask');
80
- } else if (name === 'Notification') {
81
- // idle_prompt comes a minute after Stop ("waiting for your input"): that is "done", not a call for you
82
- if (ev.notification_type === 'permission_prompt' || ev.notification_type === 'elicitation_dialog') set(s, 'ask');
83
- } else if (name === 'PostToolUse') {
84
- if (['ask', 'done', 'idle'].includes(s.state)) set(s, 'work');
85
- } else if (name === 'PostToolUseFailure') {
86
- if (['ask', 'done', 'idle'].includes(s.state)) set(s, 'work');
87
- this.overlay = ['error', t + c.error_secs];
88
- } else if (['SubagentStop', 'SubagentStart', 'PreCompact'].includes(name)) {
89
- if (s.state !== 'ask') set(s, 'work');
90
- } else if (name === 'Stop') {
91
- set(s, 'done');
92
- s.doneT = t;
93
- }
94
- this.tick();
95
- }
96
-
97
- // ------------------------------------------------------------ time
98
- computed(t) {
99
- const c = this.cfg;
100
- let best = null;
101
- for (const [sid, s] of this.sessions) {
102
- const ttl = s.state === 'ask' ? c.ask_ttl_secs
103
- : s.state === 'work' || s.state === 'read' ? c.busy_ttl_secs : c.session_ttl_secs;
104
- if (t - s.t >= ttl) {
105
- this.sessions.delete(sid);
106
- continue;
107
- }
108
- if (s.state === 'done' && s.doneT !== null && t - s.doneT >= c.done_secs) set(s, 'idle');
109
- if (best === null || RANK[s.state] > RANK[best]) best = s.state;
110
- }
111
- if ((best === null || best === 'idle') && t - this.lastEvent >= c.sleep_secs) return 'sleep';
112
- return best || 'idle';
113
- }
114
-
115
- display(t) {
116
- const base = this.computed(t);
117
- if (this.overlay && t >= this.overlay[1]) this.overlay = null;
118
- if (this.overlay && base !== 'ask') return this.overlay[0]; // nothing hides a call for you
119
- return base;
120
- }
121
-
122
- tick() {
123
- const t = this.clock();
124
- const st = this.display(t);
125
- if (st !== this.shown) {
126
- this.shown = st;
127
- this.send('state ' + st);
128
- if (st === 'ask') {
129
- this.asksPlayed = 0;
130
- this.nextAsk = t;
131
- }
132
- if (SOUND_ON_ENTER[st] && st !== 'ask') this.sound(SOUND_ON_ENTER[st], t);
133
- }
134
- if (st === 'ask' && this.nextAsk !== null && t >= this.nextAsk) {
135
- this.sound('ask', t);
136
- this.asksPlayed += 1;
137
- this.nextAsk = this.asksPlayed < this.cfg.ask_times ? t + this.cfg.ask_repeat_secs : null;
138
- }
139
- }
140
-
141
- sound(name, t) {
142
- if (!this.quiet(t)) this.send('sound ' + name);
143
- }
144
-
145
- quiet(t) {
146
- const [a, b] = this.cfg.quiet_hours;
147
- const h = this.hour(t);
148
- if (a === b) return false;
149
- return a > b ? a <= h || h < b : a <= h && h < b;
150
- }
151
-
152
- // ------------------------------------------------------------ port
153
- /** After a (re)connect: the C3 may have restarted, so say the current state again. */
154
- resend() {
155
- if (this.shown) this.send('state ' + this.shown);
156
- }
157
-
158
- status() {
159
- const t = this.clock();
160
- const bySession = {};
161
- const state = this.display(t);
162
- for (const [k, s] of this.sessions) bySession[k.slice(0, 8)] = s.state;
163
- return { state, sessions: this.sessions.size, by_session: bySession };
164
- }
165
- }
166
-
167
- function set(s, state) {
168
- s.state = state;
169
- if (state !== 'done') s.doneT = null;
170
- }
171
-
172
- module.exports = { Core, DEFAULTS, COLORS };
1
+ 'use strict';
2
+ // What Desky shows: Claude Code's and Codex's hook events in, lines for the C3 out. Codex sends the same events
3
+ // under the same names (hook.js marks them agent: "codex"), less Notification and PostToolUseFailure, plus Interrupt.
4
+ //
5
+ // Two states besides the plain ones: "wait" (Claude stopped, but background work he started will wake him) and
6
+ // "limit" (the turn died on running out of usage, StopFailure with error rate_limit).
7
+ //
8
+ // No timers, no port, no wall clock: the daemon feeds events and ticks, the tests do the same with a fake clock.
9
+ // The firmware acts a state out until the next one; everything about time lives here (how long "done" lasts, when
10
+ // to sleep, the ask trill repeats, the way back after an error, quiet hours). Times are in seconds.
11
+
12
+ // the colours Desky is printed in; the app and the face on his screen follow the one chosen (ui/app.html, PALETTE)
13
+ const COLORS = ['orange', 'white', 'mint', 'blue', 'graphite'];
14
+
15
+ const DEFAULTS = {
16
+ color: 'orange', // which Desky this is: his body colour
17
+ quiet_hours: [23, 8], // no sound from 23:00 to 08:00; [0, 0] = never quiet
18
+ done_secs: 120, // "done" looks at you this long, then idle
19
+ sleep_secs: 600, // no events this long: sleep
20
+ ask_repeat_secs: 120, // the ask trill again after this long ...
21
+ ask_times: 3, // ... at most this many times in all
22
+ session_ttl_secs: 1800, // a done or idle session silent this long stops counting
23
+ // A session killed mid-task (PC or app restarted, terminal closed) never sends Stop or SessionEnd and would keep
24
+ // Desky "working". The longest tool call is a 10 min Bash, so a working session silent for 11 min is gone.
25
+ busy_ttl_secs: 660,
26
+ ask_ttl_secs: 3600, // nobody answered for an hour: that question is not coming back
27
+ // Claude stopped with background work in flight and waits for it to call him back. A dev server left running
28
+ // never does, so after half an hour of silence the session stops waiting and counts no more.
29
+ wait_ttl_secs: 1800,
30
+ limit_ttl_secs: 18000, // out of usage: the 5-hour window resets by then at the latest
31
+ listen_secs: 1.5, // the nod after your message, then work
32
+ error_secs: 1.2,
33
+ wake_secs: 2.5,
34
+ read_tools: ['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'LS', 'NotebookRead', 'ToolSearch'],
35
+ ask_tools: ['AskUserQuestion', 'request_user_input'],
36
+ // tools that only wait for something already running; so does any tool named "..._wait" (MCP) and "sleep N"
37
+ wait_tools: ['TaskOutput', 'BashOutput', 'AgentOutputTool'],
38
+ // StopFailure errors that mean "out of usage" rather than "something broke"
39
+ limit_errors: ['rate_limit', 'billing_error'],
40
+ // Codex reads with shell commands (tool "Bash"): a command made only of these reads, anything else works.
41
+ // Matched at the start of each part of a command line split at && || ; |, ignoring case.
42
+ read_commands: ['rg', 'grep', 'egrep', 'cat', 'head', 'tail', 'less', 'more', 'ls', 'dir', 'find', 'fd', 'tree',
43
+ 'wc', 'pwd', 'stat', 'file', 'which', 'where', 'type', 'findstr', 'nl', 'sort', 'uniq', 'cut', 'jq', 'sed -n',
44
+ 'cd', 'git status', 'git log', 'git diff', 'git show', 'git blame', 'git grep', 'git ls-files', 'git branch',
45
+ 'git rev-parse', 'get-content', 'gc', 'get-childitem', 'gci', 'select-string', 'sls', 'get-item', 'test-path',
46
+ 'resolve-path', 'select-object', 'sort-object', 'measure-object', 'where-object', 'format-table', 'format-list',
47
+ 'out-string'],
48
+ port: 47811,
49
+ };
50
+
51
+ // what wins when sessions disagree
52
+ const RANK = { ask: 7, work: 6, read: 5, wait: 4, limit: 3, done: 2, idle: 1 };
53
+ const SOUND_ON_ENTER = { wake: 'wake', listen: 'tick', error: 'error', done: 'done', sleep: 'sleep', ask: 'ask',
54
+ limit: 'limit' };
55
+
56
+ const now = () => Date.now() / 1000;
57
+ const localHour = t => new Date(t * 1000).getHours();
58
+
59
+ class Core {
60
+ constructor(send, { clock = now, config = {}, hour = localHour } = {}) {
61
+ this.send = send;
62
+ this.clock = clock;
63
+ this.hour = hour;
64
+ this.cfg = { ...DEFAULTS, ...config };
65
+ this.sessions = new Map(); // id -> { state, t, doneT }
66
+ this.overlay = null; // [state, until]: wake / listen / error play over the computed state
67
+ this.lastEvent = clock();
68
+ this.shown = null; // the last state sent
69
+ this.asksPlayed = 0;
70
+ this.nextAsk = null;
71
+ }
72
+
73
+ // ------------------------------------------------------------ events
74
+ event(ev) {
75
+ const t = this.clock();
76
+ const name = ev.hook_event_name || '';
77
+ const sid = ev.session_id || '?';
78
+ const tool = ev.tool_name || '';
79
+ const before = this.display(t);
80
+ this.lastEvent = t;
81
+ if (name === 'SessionEnd') {
82
+ this.sessions.delete(sid);
83
+ this.tick();
84
+ return;
85
+ }
86
+ let s = this.sessions.get(sid);
87
+ if (!s) this.sessions.set(sid, (s = { state: 'idle', t, doneT: null }));
88
+ s.t = t;
89
+ const c = this.cfg;
90
+ if (name === 'SessionStart') {
91
+ set(s, 'idle'); // resumed after a restart: whatever it was doing then is over
92
+ if (before === 'idle' || before === 'sleep') this.overlay = ['wake', t + c.wake_secs];
93
+ } else if (name === 'UserPromptSubmit') {
94
+ set(s, 'work');
95
+ this.overlay = ['listen', t + c.listen_secs];
96
+ } else if (name === 'PreToolUse') {
97
+ if (c.ask_tools.includes(tool)) set(s, 'ask');
98
+ else if (waits(tool, ev.command, c.wait_tools)) set(s, 'wait');
99
+ else if (c.read_tools.includes(tool)) set(s, 'read');
100
+ else if (ev.agent === 'codex' && tool === 'Bash' && readsOnly(ev.command, c.read_commands)) set(s, 'read');
101
+ else set(s, 'work');
102
+ } else if (name === 'PermissionRequest') {
103
+ set(s, 'ask');
104
+ } else if (name === 'Notification') {
105
+ // idle_prompt comes a minute after Stop ("waiting for your input"): that is "done", not a call for you
106
+ const type = ev.notification_type;
107
+ if (['permission_prompt', 'elicitation_dialog', 'elicitation_url_dialog'].includes(type)) set(s, 'ask');
108
+ else if (type === 'quota_auto_resume_fired') set(s, 'work'); // the limit reset, the task goes on
109
+ else if (type === 'quota_auto_resume_stale') set(s, 'ask'); // reset while asleep: press Enter
110
+ else if (type === 'quota_auto_resume_disabled' && s.state === 'limit') set(s, 'idle');
111
+ } else if (name === 'PostToolUse') {
112
+ if (!['work', 'read'].includes(s.state)) set(s, 'work'); // answered, waited, or back from a limit
113
+ } else if (name === 'PostToolUseFailure') {
114
+ if (!['work', 'read'].includes(s.state)) set(s, 'work');
115
+ this.overlay = ['error', t + c.error_secs];
116
+ } else if (['SubagentStop', 'SubagentStart', 'PreCompact'].includes(name)) {
117
+ if (s.state !== 'ask') set(s, 'work');
118
+ } else if (name === 'Stop') {
119
+ if (waitingOn(ev).length) set(s, 'wait'); // not done: background work will wake it
120
+ else {
121
+ set(s, 'done');
122
+ s.doneT = t;
123
+ }
124
+ } else if (name === 'StopFailure') {
125
+ // the turn died on an API error: out of usage is a state of its own, the rest is a hiccup with no fanfare
126
+ if (c.limit_errors.includes(ev.error)) set(s, 'limit');
127
+ else {
128
+ set(s, 'idle');
129
+ this.overlay = ['error', t + c.error_secs];
130
+ }
131
+ } else if (name === 'Interrupt') {
132
+ set(s, 'idle'); // you stopped it yourself: no "done" fanfare
133
+ }
134
+ this.tick();
135
+ }
136
+
137
+ // ------------------------------------------------------------ time
138
+ computed(t) {
139
+ const c = this.cfg;
140
+ let best = null;
141
+ for (const [sid, s] of this.sessions) {
142
+ const ttl = s.state === 'ask' ? c.ask_ttl_secs : s.state === 'wait' ? c.wait_ttl_secs
143
+ : s.state === 'limit' ? c.limit_ttl_secs
144
+ : s.state === 'work' || s.state === 'read' ? c.busy_ttl_secs : c.session_ttl_secs;
145
+ if (t - s.t >= ttl) {
146
+ this.sessions.delete(sid);
147
+ continue;
148
+ }
149
+ if (s.state === 'done' && s.doneT !== null && t - s.doneT >= c.done_secs) set(s, 'idle');
150
+ if (best === null || RANK[s.state] > RANK[best]) best = s.state;
151
+ }
152
+ if ((best === null || best === 'idle') && t - this.lastEvent >= c.sleep_secs) return 'sleep';
153
+ return best || 'idle';
154
+ }
155
+
156
+ display(t) {
157
+ const base = this.computed(t);
158
+ if (this.overlay && t >= this.overlay[1]) this.overlay = null;
159
+ if (this.overlay && base !== 'ask') return this.overlay[0]; // nothing hides a call for you
160
+ return base;
161
+ }
162
+
163
+ tick() {
164
+ const t = this.clock();
165
+ const st = this.display(t);
166
+ if (st !== this.shown) {
167
+ this.shown = st;
168
+ this.send('state ' + st);
169
+ if (st === 'ask') {
170
+ this.asksPlayed = 0;
171
+ this.nextAsk = t;
172
+ }
173
+ if (SOUND_ON_ENTER[st] && st !== 'ask') this.sound(SOUND_ON_ENTER[st], t);
174
+ }
175
+ if (st === 'ask' && this.nextAsk !== null && t >= this.nextAsk) {
176
+ this.sound('ask', t);
177
+ this.asksPlayed += 1;
178
+ this.nextAsk = this.asksPlayed < this.cfg.ask_times ? t + this.cfg.ask_repeat_secs : null;
179
+ }
180
+ }
181
+
182
+ sound(name, t) {
183
+ if (!this.quiet(t)) this.send('sound ' + name);
184
+ }
185
+
186
+ quiet(t) {
187
+ const [a, b] = this.cfg.quiet_hours;
188
+ const h = this.hour(t);
189
+ if (a === b) return false;
190
+ return a > b ? a <= h || h < b : a <= h && h < b;
191
+ }
192
+
193
+ // ------------------------------------------------------------ port
194
+ /** After a (re)connect: the C3 may have restarted, so say the current state again. */
195
+ resend() {
196
+ if (this.shown) this.send('state ' + this.shown);
197
+ }
198
+
199
+ status() {
200
+ const t = this.clock();
201
+ const bySession = {};
202
+ const state = this.display(t);
203
+ for (const [k, s] of this.sessions) bySession[k.slice(0, 8)] = s.state;
204
+ return { state, sessions: this.sessions.size, by_session: bySession };
205
+ }
206
+ }
207
+
208
+ /** True when every part of a shell command line only reads (see read_commands). */
209
+ function readsOnly(command, words) {
210
+ if (typeof command !== 'string' || !command.trim()) return false;
211
+ if (/(^|[^0-9])>/.test(command)) return false; // "> file" writes; "2>/dev/null" does not
212
+ const parts = command.split(/&&|\|\||;|\|/).map(p => p.trim().toLowerCase()).filter(Boolean);
213
+ return parts.length > 0 && parts.every(p => words.some(w => p === w || p.startsWith(w + ' ')));
214
+ }
215
+
216
+ /** True when a tool call only waits for something already running: a wait tool, an MCP "..._wait", or a shell
217
+ * command that is nothing but a sleep. */
218
+ function waits(tool, command, tools) {
219
+ if (tools.includes(tool) || /_wait$/i.test(tool)) return true;
220
+ return typeof command === 'string' && /^\s*(sleep|start-sleep)\s+[-\w.\s]*$/i.test(command);
221
+ }
222
+
223
+ // a background task that is over does not keep the session waiting
224
+ const OVER = /^(completed|done|failed|killed|stopped|cancell?ed|error)$/i;
225
+
226
+ /** What a Stop says the session still waits for: the kinds of background work in flight (shell, monitor, subagent
227
+ * ...) and "wakeup" for each one-off scheduled wake-up. A recurring cron (/loop) is no wait. hook.js sends the
228
+ * list as waiting_on; an event that skipped the hook carries Claude Code's own arrays. */
229
+ function waitingOn(ev) {
230
+ if (Array.isArray(ev.waiting_on)) return ev.waiting_on.map(String);
231
+ const tasks = Array.isArray(ev.background_tasks) ? ev.background_tasks : [];
232
+ const crons = Array.isArray(ev.session_crons) ? ev.session_crons : [];
233
+ return [
234
+ ...tasks.filter(b => b && !OVER.test(String(b.status || ''))).map(b => String(b.type || 'task')),
235
+ ...crons.filter(c => c && !c.recurring).map(() => 'wakeup'),
236
+ ].slice(0, 20);
237
+ }
238
+
239
+ function set(s, state) {
240
+ s.state = state;
241
+ if (state !== 'done') s.doneT = null;
242
+ }
243
+
244
+ module.exports = { Core, DEFAULTS, COLORS, readsOnly, waits, waitingOn };