desky-agent 0.3.12 → 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/core.js CHANGED
@@ -1,244 +1,298 @@
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 };
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
+ // What Desky acts out, as the owner can switch it off (pult "Емоції", "desky-agent emotions"). key: the state the
16
+ // firmware plays; calm: still enough for "only calm ones" and the tray's quiet mode. "idle" is not here: it is
17
+ // where every switched-off state goes, so it cannot be switched off itself. Order: how often you see them.
18
+ const EMOTIONS = [
19
+ { key: 'work', calm: false, label: 'Друкує', hint: 'агент пише код або запускає команди: руки над клавіатурою',
20
+ alias: ['typing', 'working', 'type'] },
21
+ { key: 'read', calm: true, label: 'Читає код', hint: 'агент читає файли й шукає: сидить, очі бігають рядками',
22
+ alias: ['reading'] },
23
+ { key: 'listen', calm: false, label: 'Слухає', hint: 'кивок, коли ти надіслав повідомлення',
24
+ alias: ['listening', 'nod'] },
25
+ { key: 'ask', calm: true, label: 'Кличе тебе', hint: 'агент чекає на відповідь чи дозвіл: дивиться на тебе, трель',
26
+ alias: ['asking', 'question'] },
27
+ { key: 'wait', calm: true, label: 'Чекає на фонову задачу', hint: 'щось запущене ще працює: барабанить пальцями',
28
+ alias: ['waiting'] },
29
+ { key: 'done', calm: false, label: 'Радіє готовому', hint: 'задачу виконано: махає руками, очі «^ ^»',
30
+ alias: ['happy', 'finished'] },
31
+ { key: 'error', calm: false, label: 'Засмучується через помилку', hint: 'інструмент повернув помилку: хитає головою',
32
+ alias: ['error', 'errors', 'oops', 'sad'] },
33
+ { key: 'limit', calm: true, label: 'Втомився: скінчилися ліміти', hint: 'голова звисає, руки опущені',
34
+ alias: ['limits', 'tired'] },
35
+ { key: 'wake', calm: false, label: 'Прокидається', hint: 'нова сесія після сну: випрямляється й дивиться на тебе',
36
+ alias: ['waking'] },
37
+ { key: 'sleep', calm: true, label: 'Спить', hint: "довго немає подій: обм'як, очі заплющені",
38
+ alias: ['sleeping'] },
39
+ ];
40
+ const EMOTION_KEYS = EMOTIONS.map(e => e.key);
41
+ // where a switched-off state goes: the calm "nothing to do" pose (arms down, now and then a look round)
42
+ const FALLBACK = 'idle';
43
+
44
+ /** "reading", "Read", "читає код" ... -> "read"; null for nothing known. */
45
+ function emotionKey(word) {
46
+ const w = String(word || '').trim().toLowerCase();
47
+ const e = EMOTIONS.find(x => x.key === w || x.alias.includes(w) || x.label.toLowerCase() === w);
48
+ return e ? e.key : null;
49
+ }
50
+
51
+ /** The "only calm ones" list of switched-off states. */
52
+ const NOT_CALM = EMOTIONS.filter(e => !e.calm).map(e => e.key);
53
+
54
+ const DEFAULTS = {
55
+ color: 'orange', // which Desky this is: his body colour
56
+ emotions_off: [], // states Desky does not act out (EMOTIONS keys); idle stands in for them
57
+ quiet_hours: [23, 8], // no sound from 23:00 to 08:00; [0, 0] = never quiet
58
+ done_secs: 120, // "done" looks at you this long, then idle
59
+ sleep_secs: 600, // no events this long: sleep
60
+ ask_repeat_secs: 120, // the ask trill again after this long ...
61
+ ask_times: 3, // ... at most this many times in all
62
+ session_ttl_secs: 1800, // a done or idle session silent this long stops counting
63
+ // A session killed mid-task (PC or app restarted, terminal closed) never sends Stop or SessionEnd and would keep
64
+ // Desky "working". The longest tool call is a 10 min Bash, so a working session silent for 11 min is gone.
65
+ busy_ttl_secs: 660,
66
+ ask_ttl_secs: 3600, // nobody answered for an hour: that question is not coming back
67
+ // Claude stopped with background work in flight and waits for it to call him back. A dev server left running
68
+ // never does, so after half an hour of silence the session stops waiting and counts no more.
69
+ wait_ttl_secs: 1800,
70
+ limit_ttl_secs: 18000, // out of usage: the 5-hour window resets by then at the latest
71
+ listen_secs: 1.5, // the nod after your message, then work
72
+ error_secs: 1.2,
73
+ wake_secs: 2.5,
74
+ read_tools: ['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'LS', 'NotebookRead', 'ToolSearch'],
75
+ ask_tools: ['AskUserQuestion', 'request_user_input'],
76
+ // tools that only wait for something already running; so does any tool named "..._wait" (MCP) and "sleep N"
77
+ wait_tools: ['TaskOutput', 'BashOutput', 'AgentOutputTool'],
78
+ // StopFailure errors that mean "out of usage" rather than "something broke"
79
+ limit_errors: ['rate_limit', 'billing_error'],
80
+ // Codex reads with shell commands (tool "Bash"): a command made only of these reads, anything else works.
81
+ // Matched at the start of each part of a command line split at && || ; |, ignoring case.
82
+ read_commands: ['rg', 'grep', 'egrep', 'cat', 'head', 'tail', 'less', 'more', 'ls', 'dir', 'find', 'fd', 'tree',
83
+ 'wc', 'pwd', 'stat', 'file', 'which', 'where', 'type', 'findstr', 'nl', 'sort', 'uniq', 'cut', 'jq', 'sed -n',
84
+ 'cd', 'git status', 'git log', 'git diff', 'git show', 'git blame', 'git grep', 'git ls-files', 'git branch',
85
+ 'git rev-parse', 'get-content', 'gc', 'get-childitem', 'gci', 'select-string', 'sls', 'get-item', 'test-path',
86
+ 'resolve-path', 'select-object', 'sort-object', 'measure-object', 'where-object', 'format-table', 'format-list',
87
+ 'out-string'],
88
+ port: 47811,
89
+ };
90
+
91
+ // what wins when sessions disagree
92
+ const RANK = { ask: 7, work: 6, read: 5, wait: 4, limit: 3, done: 2, idle: 1 };
93
+ const SOUND_ON_ENTER = { wake: 'wake', listen: 'tick', error: 'error', done: 'done', sleep: 'sleep', ask: 'ask',
94
+ limit: 'limit' };
95
+
96
+ const now = () => Date.now() / 1000;
97
+ const localHour = t => new Date(t * 1000).getHours();
98
+
99
+ class Core {
100
+ constructor(send, { clock = now, config = {}, hour = localHour } = {}) {
101
+ this.send = send;
102
+ this.clock = clock;
103
+ this.hour = hour;
104
+ this.cfg = { ...DEFAULTS, ...config };
105
+ this.sessions = new Map(); // id -> { state, t, doneT }
106
+ this.overlay = null; // [state, until]: wake / listen / error play over the computed state
107
+ this.lastEvent = clock();
108
+ this.shown = null; // the last state sent
109
+ this.asksPlayed = 0;
110
+ this.nextAsk = null;
111
+ }
112
+
113
+ // ------------------------------------------------------------ events
114
+ event(ev) {
115
+ const t = this.clock();
116
+ const name = ev.hook_event_name || '';
117
+ const sid = ev.session_id || '?';
118
+ const tool = ev.tool_name || '';
119
+ const before = this.actual(t);
120
+ this.lastEvent = t;
121
+ if (name === 'SessionEnd') {
122
+ this.sessions.delete(sid);
123
+ this.tick();
124
+ return;
125
+ }
126
+ let s = this.sessions.get(sid);
127
+ if (!s) this.sessions.set(sid, (s = { state: 'idle', t, doneT: null }));
128
+ s.t = t;
129
+ const c = this.cfg;
130
+ if (name === 'SessionStart') {
131
+ set(s, 'idle'); // resumed after a restart: whatever it was doing then is over
132
+ if (before === 'idle' || before === 'sleep') this.overlay = ['wake', t + c.wake_secs];
133
+ } else if (name === 'UserPromptSubmit') {
134
+ set(s, 'work');
135
+ this.overlay = ['listen', t + c.listen_secs];
136
+ } else if (name === 'PreToolUse') {
137
+ if (c.ask_tools.includes(tool)) set(s, 'ask');
138
+ else if (waits(tool, ev.command, c.wait_tools)) set(s, 'wait');
139
+ else if (c.read_tools.includes(tool)) set(s, 'read');
140
+ else if (ev.agent === 'codex' && tool === 'Bash' && readsOnly(ev.command, c.read_commands)) set(s, 'read');
141
+ else set(s, 'work');
142
+ } else if (name === 'PermissionRequest') {
143
+ set(s, 'ask');
144
+ } else if (name === 'Notification') {
145
+ // idle_prompt comes a minute after Stop ("waiting for your input"): that is "done", not a call for you
146
+ const type = ev.notification_type;
147
+ if (['permission_prompt', 'elicitation_dialog', 'elicitation_url_dialog'].includes(type)) set(s, 'ask');
148
+ else if (type === 'quota_auto_resume_fired') set(s, 'work'); // the limit reset, the task goes on
149
+ else if (type === 'quota_auto_resume_stale') set(s, 'ask'); // reset while asleep: press Enter
150
+ else if (type === 'quota_auto_resume_disabled' && s.state === 'limit') set(s, 'idle');
151
+ } else if (name === 'PostToolUse') {
152
+ if (!['work', 'read'].includes(s.state)) set(s, 'work'); // answered, waited, or back from a limit
153
+ } else if (name === 'PostToolUseFailure') {
154
+ if (!['work', 'read'].includes(s.state)) set(s, 'work');
155
+ this.overlay = ['error', t + c.error_secs];
156
+ } else if (['SubagentStop', 'SubagentStart', 'PreCompact'].includes(name)) {
157
+ if (s.state !== 'ask') set(s, 'work');
158
+ } else if (name === 'Stop') {
159
+ if (waitingOn(ev).length) set(s, 'wait'); // not done: background work will wake it
160
+ else {
161
+ set(s, 'done');
162
+ s.doneT = t;
163
+ }
164
+ } else if (name === 'StopFailure') {
165
+ // the turn died on an API error: out of usage is a state of its own, the rest is a hiccup with no fanfare
166
+ if (c.limit_errors.includes(ev.error)) set(s, 'limit');
167
+ else {
168
+ set(s, 'idle');
169
+ this.overlay = ['error', t + c.error_secs];
170
+ }
171
+ } else if (name === 'Interrupt') {
172
+ set(s, 'idle'); // you stopped it yourself: no "done" fanfare
173
+ }
174
+ this.tick();
175
+ }
176
+
177
+ // ------------------------------------------------------------ time
178
+ computed(t) {
179
+ const c = this.cfg;
180
+ let best = null;
181
+ for (const [sid, s] of this.sessions) {
182
+ const ttl = s.state === 'ask' ? c.ask_ttl_secs : s.state === 'wait' ? c.wait_ttl_secs
183
+ : s.state === 'limit' ? c.limit_ttl_secs
184
+ : s.state === 'work' || s.state === 'read' ? c.busy_ttl_secs : c.session_ttl_secs;
185
+ if (t - s.t >= ttl) {
186
+ this.sessions.delete(sid);
187
+ continue;
188
+ }
189
+ if (s.state === 'done' && s.doneT !== null && t - s.doneT >= c.done_secs) set(s, 'idle');
190
+ if (best === null || RANK[s.state] > RANK[best]) best = s.state;
191
+ }
192
+ if ((best === null || best === 'idle') && t - this.lastEvent >= c.sleep_secs) return 'sleep';
193
+ return best || 'idle';
194
+ }
195
+
196
+ /** What the agent is doing, every emotion on. */
197
+ actual(t) {
198
+ const base = this.computed(t);
199
+ if (this.overlay && t >= this.overlay[1]) this.overlay = null;
200
+ if (this.overlay && base !== 'ask') return this.overlay[0]; // nothing hides a call for you
201
+ return base;
202
+ }
203
+
204
+ /** What Desky shows: a switched-off overlay (wake, listen, error) lets the state under it show, a switched-off
205
+ * state gives way to idle. Its sound goes with it: Desky enters idle, which has none. */
206
+ display(t) {
207
+ const off = this.cfg.emotions_off || [];
208
+ const base = this.computed(t);
209
+ if (this.overlay && t >= this.overlay[1]) this.overlay = null;
210
+ if (this.overlay && base !== 'ask' && !off.includes(this.overlay[0])) return this.overlay[0];
211
+ return off.includes(base) ? FALLBACK : base;
212
+ }
213
+
214
+ tick() {
215
+ const t = this.clock();
216
+ const st = this.display(t);
217
+ if (st !== this.shown) {
218
+ this.shown = st;
219
+ this.send('state ' + st);
220
+ if (st === 'ask') {
221
+ this.asksPlayed = 0;
222
+ this.nextAsk = t;
223
+ }
224
+ if (SOUND_ON_ENTER[st] && st !== 'ask') this.sound(SOUND_ON_ENTER[st], t);
225
+ }
226
+ if (st === 'ask' && this.nextAsk !== null && t >= this.nextAsk) {
227
+ this.sound('ask', t);
228
+ this.asksPlayed += 1;
229
+ this.nextAsk = this.asksPlayed < this.cfg.ask_times ? t + this.cfg.ask_repeat_secs : null;
230
+ }
231
+ }
232
+
233
+ sound(name, t) {
234
+ if (!this.quiet(t)) this.send('sound ' + name);
235
+ }
236
+
237
+ quiet(t) {
238
+ const [a, b] = this.cfg.quiet_hours;
239
+ const h = this.hour(t);
240
+ if (a === b) return false;
241
+ return a > b ? a <= h || h < b : a <= h && h < b;
242
+ }
243
+
244
+ // ------------------------------------------------------------ port
245
+ /** After a (re)connect: the C3 may have restarted, so say the current state again. */
246
+ resend() {
247
+ if (this.shown) this.send('state ' + this.shown);
248
+ }
249
+
250
+ status() {
251
+ const t = this.clock();
252
+ const bySession = {};
253
+ const state = this.display(t);
254
+ const actual = this.actual(t);
255
+ for (const [k, s] of this.sessions) bySession[k.slice(0, 8)] = s.state;
256
+ return { state, actual, emotions_off: [...(this.cfg.emotions_off || [])], sessions: this.sessions.size,
257
+ by_session: bySession };
258
+ }
259
+ }
260
+
261
+ /** True when every part of a shell command line only reads (see read_commands). */
262
+ function readsOnly(command, words) {
263
+ if (typeof command !== 'string' || !command.trim()) return false;
264
+ if (/(^|[^0-9])>/.test(command)) return false; // "> file" writes; "2>/dev/null" does not
265
+ const parts = command.split(/&&|\|\||;|\|/).map(p => p.trim().toLowerCase()).filter(Boolean);
266
+ return parts.length > 0 && parts.every(p => words.some(w => p === w || p.startsWith(w + ' ')));
267
+ }
268
+
269
+ /** True when a tool call only waits for something already running: a wait tool, an MCP "..._wait", or a shell
270
+ * command that is nothing but a sleep. */
271
+ function waits(tool, command, tools) {
272
+ if (tools.includes(tool) || /_wait$/i.test(tool)) return true;
273
+ return typeof command === 'string' && /^\s*(sleep|start-sleep)\s+[-\w.\s]*$/i.test(command);
274
+ }
275
+
276
+ // a background task that is over does not keep the session waiting
277
+ const OVER = /^(completed|done|failed|killed|stopped|cancell?ed|error)$/i;
278
+
279
+ /** What a Stop says the session still waits for: the kinds of background work in flight (shell, monitor, subagent
280
+ * ...) and "wakeup" for each one-off scheduled wake-up. A recurring cron (/loop) is no wait. hook.js sends the
281
+ * list as waiting_on; an event that skipped the hook carries Claude Code's own arrays. */
282
+ function waitingOn(ev) {
283
+ if (Array.isArray(ev.waiting_on)) return ev.waiting_on.map(String);
284
+ const tasks = Array.isArray(ev.background_tasks) ? ev.background_tasks : [];
285
+ const crons = Array.isArray(ev.session_crons) ? ev.session_crons : [];
286
+ return [
287
+ ...tasks.filter(b => b && !OVER.test(String(b.status || ''))).map(b => String(b.type || 'task')),
288
+ ...crons.filter(c => c && !c.recurring).map(() => 'wakeup'),
289
+ ].slice(0, 20);
290
+ }
291
+
292
+ function set(s, state) {
293
+ s.state = state;
294
+ if (state !== 'done') s.doneT = null;
295
+ }
296
+
297
+ module.exports = { Core, DEFAULTS, COLORS, EMOTIONS, EMOTION_KEYS, NOT_CALM, FALLBACK, emotionKey, readsOnly, waits,
298
+ waitingOn };