desky-agent 0.3.1 → 0.3.3

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/README.md CHANGED
@@ -1,57 +1,57 @@
1
- # desky-agent
2
-
3
- Desky — настольный робот, который показывает, что делает Claude Code или Codex: печатает, пока агент работает, смотрит в экран, когда агент читает, поворачивается к тебе с трелью, когда агент ждёт ответа, и засыпает в тишине.
4
-
5
- Этот пакет ставит на компьютер всё, что нужно роботу: приложение в трее, хуки Claude Code и Codex и запуск при входе в систему. Windows, macOS, Linux.
6
-
7
- *A desk robot that acts out what Claude Code (or Codex) is doing. This package installs the tray app, the Claude Code and Codex hooks and start-at-login in one command.*
8
-
9
- ## Установка
10
-
11
- ```
12
- npx desky-agent
13
- ```
14
-
15
- Нужен Node 18 или новее. Вопросов установщик не задаёт, поэтому команду может запустить и агент. После установки перезапусти открытые сессии Claude Code.
16
-
17
- Что появится:
18
-
19
- - **Desky в трее** (на macOS — в строке меню). Держит USB-порт платы и получает события от хуков, даже когда окно закрыто. Значок показывает состояние: серый — плата не подключена, глаза закрыты — спит, смотрит вниз — читает, руки вверх — ждёт тебя.
20
- - **Пульт** — открывается кликом по значку: сессии, ползунки суставов, сценки, калибровка серво, звуки, настройки, монитор порта.
21
- - **Хуки** в `~/.claude/settings.json`. Чужие хуки не трогаются, прежний файл остаётся рядом как `settings.json.bak`. Если Desky не запущен, первый же хук поднимет его в трее.
22
- - **Хуки Codex** в `~/.codex/hooks.json` (или `$CODEX_HOME`), если Codex стоит на этом компьютере. Codex запускает чужие хуки только после одобрения: набери `/hooks` в Codex (в приложении: «Review hooks» у поля ввода) и доверь хуки Desky. Если Codex поставлен позже Desky, запусти `npx desky-agent` ещё раз. Отличия от Claude Code: Codex читает файлы командами в терминале, поэтому «читает» Desky показывает по самой команде (`rg`, `cat`, `Get-Content`, `git diff`…); упавшая команда в Codex не отличается от удачной, так что анимации ошибки нет.
23
- - **Запуск при входе** и ярлык «Desky» (рабочий стол и «Пуск» на Windows, `~/Applications` на macOS, меню приложений на Linux).
24
-
25
- Всё ставится в `~/.clawd-desk`.
26
-
27
- ## Обновления
28
-
29
- Desky сам проверяет, не вышла ли новая версия (через пару секунд после запуска и потом раз в 6 часов, запрос к реестру npm). Если вышла, в пульте появляется плашка «Вышла версия …» с кнопкой «Обновить», в трее — уведомление и пункт «Обновить Desky до …». По кнопке запускается тот же `npx desky-agent@<версия>`: окно закроется, через минуту Desky откроется уже новым. Настройки и калибровка остаются. Что делал установщик, лежит в `~/.clawd-desk/state/update.log`.
30
-
31
- Из терминала то же самое: `npx desky-agent@latest`.
32
-
33
- ## Команды
34
-
35
- ```
36
- npx desky-agent поставить или обновить
37
- npx desky-agent open открыть пульт
38
- npx desky-agent start запустить в трее, без окна
39
- npx desky-agent stop выйти и отпустить порт (хуки не запустят Desky до open или start)
40
- npx desky-agent status плата, состояние, сессии
41
- npx desky-agent doctor проверить всё по порядку и подсказать, что исправить
42
- npx desky-agent firmware версия прошивки в пакете и на плате
43
- npx desky-agent firmware update перепрошить плату версией из пакета (калибровка остаётся)
44
- npx desky-agent uninstall убрать всё, кроме настроек
45
- ```
46
-
47
- ## Прошивка
48
-
49
- Пакет везёт прошивку своей версии. Если на плате прошивка старше, `npx desky-agent` или приложение в трее обновляют её сами: пишется одна строка «прошивка Desky обновлена: 0.1.0 → 0.2.0». Калибровка и серийный номер в памяти робота при этом не стираются. Python и PlatformIO не нужны.
50
-
51
- - Не отключай плату, пока идёт обновление. Если оно всё же прервалось, следующий запуск `npx desky-agent` допишет прошивку сам.
52
- - Если прошивка на плате новее пакета, пакет её не трогает и просит обновить себя: `npx desky-agent@latest`.
53
- - Чужие платы не прошиваются: только ESP32-S3, которая отвечает как Desky. Молчащую плату пакет прошьёт, только если обновление прервалось на этом компьютере или ты подтвердил вопрос (или передал `--yes`).
54
-
55
- ## Плата
56
-
57
- Waveshare ESP32-S3-Zero с прошивкой Desky, по USB. Порт находится сам (`COM…`, `/dev/cu.usbmodem…`, `/dev/ttyACM…`) и открывается без перезагрузки платы. На Linux для доступа к порту нужна группа `dialout`.
1
+ # desky-agent
2
+
3
+ Desky — настольный робот, который показывает, что делает Claude Code или Codex: печатает, пока агент работает, смотрит в экран, когда агент читает, поворачивается к тебе с трелью, когда агент ждёт ответа, барабанит пальцами, пока агент ждёт запущенное в фоне, роняет голову под пустой батарейкой, когда кончились лимиты, и засыпает в тишине.
4
+
5
+ Этот пакет ставит на компьютер всё, что нужно роботу: приложение в трее, хуки Claude Code и Codex и запуск при входе в систему. Windows, macOS, Linux.
6
+
7
+ *A desk robot that acts out what Claude Code (or Codex) is doing. This package installs the tray app, the Claude Code and Codex hooks and start-at-login in one command.*
8
+
9
+ ## Установка
10
+
11
+ ```
12
+ npx desky-agent
13
+ ```
14
+
15
+ Нужен Node 18 или новее. Вопросов установщик не задаёт, поэтому команду может запустить и агент. После установки перезапусти открытые сессии Claude Code.
16
+
17
+ Что появится:
18
+
19
+ - **Desky в трее** (на macOS — в строке меню). Держит USB-порт платы и получает события от хуков, даже когда окно закрыто. Значок показывает состояние: серый — плата не подключена, глаза закрыты — спит, смотрит вниз — читает, руки вверх — ждёт тебя.
20
+ - **Пульт** — открывается кликом по значку: сессии, ползунки суставов, сценки, калибровка серво, звуки, настройки, монитор порта.
21
+ - **Хуки** в `~/.claude/settings.json`. Чужие хуки не трогаются, прежний файл остаётся рядом как `settings.json.bak`. Если Desky не запущен, первый же хук поднимет его в трее.
22
+ - **Хуки Codex** в `~/.codex/hooks.json` (или `$CODEX_HOME`), если Codex стоит на этом компьютере. Codex запускает чужие хуки только после одобрения: набери `/hooks` в Codex (в приложении: «Review hooks» у поля ввода) и доверь хуки Desky. Если Codex поставлен позже Desky, запусти `npx desky-agent` ещё раз. Отличия от Claude Code: Codex читает файлы командами в терминале, поэтому «читает» Desky показывает по самой команде (`rg`, `cat`, `Get-Content`, `git diff`…); упавшая команда в Codex не отличается от удачной, так что анимации ошибки нет.
23
+ - **Запуск при входе** и ярлык «Desky» (рабочий стол и «Пуск» на Windows, `~/Applications` на macOS, меню приложений на Linux).
24
+
25
+ Всё ставится в `~/.clawd-desk`.
26
+
27
+ ## Обновления
28
+
29
+ Desky сам проверяет, не вышла ли новая версия (через пару секунд после запуска и потом раз в 6 часов, запрос к реестру npm). Если вышла, в пульте появляется плашка «Вышла версия …» с кнопкой «Обновить», в трее — уведомление и пункт «Обновить Desky до …». По кнопке запускается тот же `npx desky-agent@<версия>`: окно закроется, через минуту Desky откроется уже новым. Настройки и калибровка остаются. Что делал установщик, лежит в `~/.clawd-desk/state/update.log`.
30
+
31
+ Из терминала то же самое: `npx desky-agent@latest`.
32
+
33
+ ## Команды
34
+
35
+ ```
36
+ npx desky-agent поставить или обновить
37
+ npx desky-agent open открыть пульт
38
+ npx desky-agent start запустить в трее, без окна
39
+ npx desky-agent stop выйти и отпустить порт (хуки не запустят Desky до open или start)
40
+ npx desky-agent status плата, состояние, сессии
41
+ npx desky-agent doctor проверить всё по порядку и подсказать, что исправить
42
+ npx desky-agent firmware версия прошивки в пакете и на плате
43
+ npx desky-agent firmware update перепрошить плату версией из пакета (калибровка остаётся)
44
+ npx desky-agent uninstall убрать всё, кроме настроек
45
+ ```
46
+
47
+ ## Прошивка
48
+
49
+ Пакет везёт прошивку своей версии. Если на плате прошивка старше, `npx desky-agent` или приложение в трее обновляют её сами: пишется одна строка «прошивка Desky обновлена: 0.1.0 → 0.2.0». Калибровка и серийный номер в памяти робота при этом не стираются. Python и PlatformIO не нужны.
50
+
51
+ - Не отключай плату, пока идёт обновление. Если оно всё же прервалось, следующий запуск `npx desky-agent` допишет прошивку сам.
52
+ - Если прошивка на плате новее пакета, пакет её не трогает и просит обновить себя: `npx desky-agent@latest`.
53
+ - Чужие платы не прошиваются: только ESP32-S3, которая отвечает как Desky. Молчащую плату пакет прошьёт, только если обновление прервалось на этом компьютере или ты подтвердил вопрос (или передал `--yes`).
54
+
55
+ ## Плата
56
+
57
+ Waveshare ESP32-S3-Zero с прошивкой Desky, по USB. Порт находится сам (`COM…`, `/dev/cu.usbmodem…`, `/dev/ttyACM…`) и открывается без перезагрузки платы. На Linux для доступа к порту нужна группа `dialout`.
package/bin/cli.js CHANGED
@@ -23,7 +23,8 @@ const HELP = `desky-agent ${require('../package.json').version}: Desky Agent —
23
23
  --yes плата мовчить на who після перерваного оновлення: прошити без питання`;
24
24
 
25
25
  const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
26
- error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
26
+ wait: 'чекає на фонову задачу', limit: 'скінчилися ліміти', error: 'помилка', done: 'закінчив',
27
+ idle: 'нічого не робить', sleep: 'спить' };
27
28
 
28
29
  function fail(text) {
29
30
  console.error('помилка: ' + text);
package/electron/main.js CHANGED
@@ -18,7 +18,8 @@ const autostart = require('../src/autostart');
18
18
  const { trayPngs, trayKind } = require('./icons');
19
19
 
20
20
  const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
21
- error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
21
+ wait: 'чекає на фонову задачу', limit: 'скінчилися ліміти', error: 'помилка', done: 'закінчив',
22
+ idle: 'нічого не робить', sleep: 'спить' };
22
23
  const MAC = process.platform === 'darwin';
23
24
  const quietLaunch = argv => argv.includes('--background') || argv.includes('--login');
24
25
 
Binary file
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clawd-desk",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "chip": "esp32s3",
5
5
  "board": "waveshare-esp32-s3-zero",
6
6
  "flash_size": "4MB",
@@ -26,8 +26,8 @@
26
26
  {
27
27
  "file": "firmware.bin",
28
28
  "address": "0x10000",
29
- "size": 338304,
30
- "sha256": "a73638b97c94b2ac2885c544b8bac8b8c08b44a42c8016e03fe023548fa636a0"
29
+ "size": 339200,
30
+ "sha256": "598356e15112da0a3088f6bd1b2201c00cfa03ffdd89aab97e9b85de17697b0b"
31
31
  }
32
32
  ]
33
33
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "desky-agent",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Desky Agent: Desky, a desk robot that acts out what Claude Code or Codex is doing. Tray app, hooks and installer in one npx command",
5
5
  "keywords": [
6
6
  "claude-code",
package/src/core.js CHANGED
@@ -2,6 +2,9 @@
2
2
  // What Desky shows: Claude Code's and Codex's hook events in, lines for the C3 out. Codex sends the same events
3
3
  // under the same names (hook.js marks them agent: "codex"), less Notification and PostToolUseFailure, plus Interrupt.
4
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
+ //
5
8
  // No timers, no port, no wall clock: the daemon feeds events and ticks, the tests do the same with a fake clock.
6
9
  // The firmware acts a state out until the next one; everything about time lives here (how long "done" lasts, when
7
10
  // to sleep, the ask trill repeats, the way back after an error, quiet hours). Times are in seconds.
@@ -21,11 +24,19 @@ const DEFAULTS = {
21
24
  // Desky "working". The longest tool call is a 10 min Bash, so a working session silent for 11 min is gone.
22
25
  busy_ttl_secs: 660,
23
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
24
31
  listen_secs: 1.5, // the nod after your message, then work
25
32
  error_secs: 1.2,
26
33
  wake_secs: 2.5,
27
34
  read_tools: ['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'LS', 'NotebookRead', 'ToolSearch'],
28
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'],
29
40
  // Codex reads with shell commands (tool "Bash"): a command made only of these reads, anything else works.
30
41
  // Matched at the start of each part of a command line split at && || ; |, ignoring case.
31
42
  read_commands: ['rg', 'grep', 'egrep', 'cat', 'head', 'tail', 'less', 'more', 'ls', 'dir', 'find', 'fd', 'tree',
@@ -38,8 +49,9 @@ const DEFAULTS = {
38
49
  };
39
50
 
40
51
  // what wins when sessions disagree
41
- const RANK = { ask: 5, work: 4, read: 3, done: 2, idle: 1 };
42
- const SOUND_ON_ENTER = { wake: 'wake', listen: 'tick', error: 'error', done: 'done', sleep: 'sleep', ask: 'ask' };
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' };
43
55
 
44
56
  const now = () => Date.now() / 1000;
45
57
  const localHour = t => new Date(t * 1000).getHours();
@@ -83,6 +95,7 @@ class Core {
83
95
  this.overlay = ['listen', t + c.listen_secs];
84
96
  } else if (name === 'PreToolUse') {
85
97
  if (c.ask_tools.includes(tool)) set(s, 'ask');
98
+ else if (waits(tool, ev.command, c.wait_tools)) set(s, 'wait');
86
99
  else if (c.read_tools.includes(tool)) set(s, 'read');
87
100
  else if (ev.agent === 'codex' && tool === 'Bash' && readsOnly(ev.command, c.read_commands)) set(s, 'read');
88
101
  else set(s, 'work');
@@ -90,17 +103,31 @@ class Core {
90
103
  set(s, 'ask');
91
104
  } else if (name === 'Notification') {
92
105
  // idle_prompt comes a minute after Stop ("waiting for your input"): that is "done", not a call for you
93
- if (ev.notification_type === 'permission_prompt' || ev.notification_type === 'elicitation_dialog') set(s, 'ask');
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');
94
111
  } else if (name === 'PostToolUse') {
95
- if (['ask', 'done', 'idle'].includes(s.state)) set(s, 'work');
112
+ if (!['work', 'read'].includes(s.state)) set(s, 'work'); // answered, waited, or back from a limit
96
113
  } else if (name === 'PostToolUseFailure') {
97
- if (['ask', 'done', 'idle'].includes(s.state)) set(s, 'work');
114
+ if (!['work', 'read'].includes(s.state)) set(s, 'work');
98
115
  this.overlay = ['error', t + c.error_secs];
99
116
  } else if (['SubagentStop', 'SubagentStart', 'PreCompact'].includes(name)) {
100
117
  if (s.state !== 'ask') set(s, 'work');
101
118
  } else if (name === 'Stop') {
102
- set(s, 'done');
103
- s.doneT = t;
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
+ }
104
131
  } else if (name === 'Interrupt') {
105
132
  set(s, 'idle'); // you stopped it yourself: no "done" fanfare
106
133
  }
@@ -112,7 +139,8 @@ class Core {
112
139
  const c = this.cfg;
113
140
  let best = null;
114
141
  for (const [sid, s] of this.sessions) {
115
- const ttl = s.state === 'ask' ? c.ask_ttl_secs
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
116
144
  : s.state === 'work' || s.state === 'read' ? c.busy_ttl_secs : c.session_ttl_secs;
117
145
  if (t - s.t >= ttl) {
118
146
  this.sessions.delete(sid);
@@ -185,9 +213,32 @@ function readsOnly(command, words) {
185
213
  return parts.length > 0 && parts.every(p => words.some(w => p === w || p.startsWith(w + ' ')));
186
214
  }
187
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
+
188
239
  function set(s, state) {
189
240
  s.state = state;
190
241
  if (state !== 'done') s.doneT = null;
191
242
  }
192
243
 
193
- module.exports = { Core, DEFAULTS, COLORS, readsOnly };
244
+ module.exports = { Core, DEFAULTS, COLORS, readsOnly, waits, waitingOn };
package/src/hook.js CHANGED
@@ -13,6 +13,7 @@ const fs = require('fs');
13
13
  const http = require('http');
14
14
  const { spawn } = require('child_process');
15
15
  const paths = require('./paths');
16
+ const { waitingOn } = require('./core');
16
17
 
17
18
  function post(body, timeout = 500) {
18
19
  return new Promise((resolve, reject) => {
@@ -48,7 +49,7 @@ function readStdin() {
48
49
  }
49
50
 
50
51
  // what the Core reads; a PostToolUse can carry megabytes of tool output that Desky never looks at
51
- const KEEP = ['hook_event_name', 'session_id', 'tool_name', 'notification_type', 'source'];
52
+ const KEEP = ['hook_event_name', 'session_id', 'tool_name', 'notification_type', 'source', 'error'];
52
53
 
53
54
  /** agent: "codex" when Codex ran us (its hooks.json passes the word), else Claude Code. Codex reads files with
54
55
  * shell commands, so for it the start of the command goes along: the Core tells reading from working by it. */
@@ -58,9 +59,11 @@ function slim(raw, agent = null) {
58
59
  const out = {};
59
60
  for (const k of KEEP) if (ev[k] !== undefined) out[k] = ev[k];
60
61
  if (agent) out.agent = agent;
61
- if (agent === 'codex' && ev.tool_input && typeof ev.tool_input.command === 'string') {
62
- out.command = ev.tool_input.command.slice(0, 500);
63
- }
62
+ // the start of a shell command: Codex reads files with commands, and "sleep 30" in either agent is waiting
63
+ if (ev.tool_input && typeof ev.tool_input.command === 'string') out.command = ev.tool_input.command.slice(0, 500);
64
+ // Stop lists the background work still in flight; only its kinds go along (see waitingOn in core.js)
65
+ const waits = waitingOn(ev);
66
+ if (waits.length) out.waiting_on = waits;
64
67
  return Buffer.from(JSON.stringify(out));
65
68
  } catch (e) {
66
69
  return raw.length <= 1 << 20 ? raw : Buffer.from('{}');
package/src/install.js CHANGED
@@ -33,7 +33,7 @@ const BUNDLE = MAC ? path.join(os.homedir(), 'Applications', 'Desky Agent.app')
33
33
  // before the rename (0.2.4 and older, package clawdydesk): taken away by the next install
34
34
  const OLD_BUNDLE = MAC ? path.join(os.homedir(), 'Applications', 'Clawd.app') : path.join(paths.HOME, 'Clawd');
35
35
  const EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'PostToolUseFailure',
36
- 'PermissionRequest', 'Notification', 'Stop', 'SubagentStart', 'SubagentStop', 'PreCompact'];
36
+ 'PermissionRequest', 'Notification', 'Stop', 'StopFailure', 'SubagentStart', 'SubagentStop', 'PreCompact'];
37
37
  // Codex has no Notification or PostToolUseFailure, and has Interrupt
38
38
  const CODEX_EVENTS = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse',
39
39
  'PermissionRequest', 'Stop', 'SubagentStart', 'SubagentStop', 'PreCompact', 'Interrupt'];
package/ui/app.html CHANGED
@@ -607,11 +607,12 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
607
607
  const css = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
608
608
  const wait = ms => new Promise(r => setTimeout(r, ms));
609
609
  const NAMES = { wake: 'прокинувся', listen: 'слухає', work: 'працює', read: 'читає', ask: 'чекає на тебе',
610
- error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
610
+ wait: 'чекає на фонову задачу', limit: 'скінчилися ліміти', error: 'помилка', done: 'закінчив', idle: 'нічого не робить', sleep: 'спить' };
611
611
  const WHAT = { wake: 'Щойно прокинувся', listen: 'Почув твоє повідомлення', work: 'Агент пише код або запускає команди',
612
- read: 'Агент читає файли', ask: 'Агент чекає на відповідь', error: 'Інструмент повернув помилку',
612
+ read: 'Агент читає файли', ask: 'Агент чекає на відповідь',
613
+ wait: 'Агент чекає, поки допрацює запущене у фоні', limit: 'Скінчилися ліміти, чекає на скидання', error: 'Інструмент повернув помилку',
613
614
  done: 'Задачу виконано', idle: '', sleep: 'Давно не було подій' };
614
- const SOUNDS = { wake: 'прокинувся', tick: 'тік', ask: 'трель', error: 'помилка', done: 'готово', sleep: 'засинає' };
615
+ const SOUNDS = { wake: 'прокинувся', tick: 'тік', ask: 'трель', error: 'помилка', done: 'готово', sleep: 'засинає', limit: 'ліміти' };
615
616
  // The colours Desky is printed in (src/core.js COLORS). body and eye: his plastic and the face on his screen (the
616
617
  // board keeps them, "color"); a and d: the app's accent, hover and text on it, for light and dark windows
617
618
  const PALETTE = {
@@ -655,6 +656,28 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
655
656
 
656
657
  // ---------------------------------------------------------------- talking to the daemon
657
658
  let up = false, connected = false, manual = false, beat = null;
659
+ // "on" powers the servos one by one, 400 ms each (play.cpp attachAll), and the board reads nothing meanwhile: a move
660
+ // sent behind it waits, and the "home" that ends a demo is already queued and cuts that move off at once. So "on"
661
+ // goes only when the servos are let go (the heartbeat says so), and the next command waits until the board is back.
662
+ // a move the wizard waits for: any line that reaches the board mid-move stops that move (play.cpp pollStop), so a
663
+ // demo's "home", then its move, then "home" again only work one after another. Done on the board's "ok <cmd>",
664
+ // refused on "Нельзя"/"err", and 4 s at most whatever happens (an old firmware, a lost line).
665
+ const waiters = [];
666
+ function move(cmd, ms = 4000) {
667
+ const word = cmd.trim().split(/\s+/)[0].toLowerCase();
668
+ return new Promise(resolve => {
669
+ const w = { word };
670
+ w.done = ok => { clearTimeout(w.t); const i = waiters.indexOf(w); if (i >= 0) waiters.splice(i, 1); resolve(ok); };
671
+ w.t = setTimeout(() => w.done(false), ms);
672
+ waiters.push(w);
673
+ send(cmd);
674
+ });
675
+ }
676
+ let onUntil = 0; // until then the board is still busy with the last "on" (any page sends it)
677
+ async function servosOn() {
678
+ if (!beat || /отпущены/.test(beat)) await send('on');
679
+ await wait(Math.max(0, onUntil - Date.now()));
680
+ }
658
681
  async function api(path, body) {
659
682
  const r = await fetch(path, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
660
683
  if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || r.status);
@@ -675,6 +698,7 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
675
698
  const FACTORY = ['trim', 'inv', 'here', 'save', 'swap', 'flip', 'probe', 'hold', 'yawhold', 'sn', 'calset', 'face'];
676
699
  async function send(cmd, quiet) {
677
700
  if (FACTORY.includes(cmd.trim().split(/\s+/)[0].toLowerCase())) await api('/cmd', { line: 'factory on', hand: false }).catch(() => {});
701
+ if (cmd === 'on') onUntil = Date.now() + 1800;
678
702
  if (!quiet) { lastHand = Date.now(); manual = true; showMode(); if (!/^trim /.test(cmd)) atRef = null; }
679
703
  try { await api('/cmd', { line: cmd, hand: !quiet }); } catch (e) { log('не надіслано: ' + e.message, 'dim'); }
680
704
  }
@@ -847,6 +871,7 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
847
871
  const bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
848
872
  bg.setAttribute('width', 64); bg.setAttribute('height', 48); bg.setAttribute('rx', 4); bg.setAttribute('fill', PALETTE[COLOR].body); s.appendChild(bg);
849
873
  const eyes = { work: [9, 7, 0, 6], read: [7, 8, -4, 6], ask: [13, 13, 0, 0], sleep: [11, 2, 0, 4], idle: [8, 14, 0, 0],
874
+ wait: [8, 11, 0, 3], limit: [11, 3, 0, 4],
850
875
  wake: [8, 14, 0, 0], listen: [8, 14, 0, 0] }[state];
851
876
  if (state === 'done' || state === 'happy') { for (const x of [16, 48]) for (let i = 0; i < 6; i++) { add(x - 6 + i, 26 - i, 2, 2); add(x + i, 21 + i, 2, 2); } return; }
852
877
  if (state === 'sad') { for (const x of [16, 48]) for (let i = 0; i < 6; i++) { add(x - 6 + i, 20 + i, 2, 2); add(x + i, 25 - i, 2, 2); } return; }
@@ -854,6 +879,7 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
854
879
  const [w, h, dx, dy] = eyes || [8, 14, 0, 0];
855
880
  for (const x of [16, 48]) add(x - w / 2 + dx, 24 - h / 2 + dy, w, h, state === 'sleep' ? '' : 'eye');
856
881
  if (state === 'sleep') add(54, 4, 5, 2), add(57, 6, 2, 2), add(54, 8, 5, 2);
882
+ if (state === 'limit') { add(26, 3, 12, 1); add(26, 9, 12, 1); add(26, 3, 1, 7); add(37, 3, 1, 7); add(38, 5, 1, 3); add(28, 5, 2, 3); }
857
883
  }
858
884
 
859
885
  // ---------------------------------------------------------------- previews
@@ -939,6 +965,9 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
939
965
  let SWAP = null, FLIP = null;
940
966
  const touched = [0, 0, 0, 0]; // when this window last moved a joint's trim: ignore echoes then
941
967
  function onLine(line) {
968
+ const ok = line.match(/^ok (\S+)/);
969
+ if (ok) { const w = waiters.find(x => x.word === ok[1]); if (w) w.done(true); }
970
+ else if (/^(Нельзя|err )/.test(line) && waiters.length) waiters[0].done(false);
942
971
  if (/^Серво отпущены/i.test(line)) $('limpbox').hidden = false;
943
972
  if (/^Нельзя:/.test(line)) toast('Desky так не стане: зачепить стіл або ноутбук', true);
944
973
  let m = line.match(/поза: J1 ([+-]?\d+)\s+J2 ([+-]?\d+)\s+J3 (-?\d+)\s+J4 (-?\d+)/);
@@ -1375,7 +1404,7 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
1375
1404
  foot: [back('color'), spacer(), fix, ok],
1376
1405
  });
1377
1406
  $('wizBody').querySelector('.slot .row').appendChild(replay);
1378
- async function demo() { C3 && C3.state('wave', true); await send('on'); await send('home'); await send('wave'); await wait(3500); await send('home'); }
1407
+ async function demo() { C3 && C3.state('wave', true); await servosOn(); await move('home'); await move('wave', 8000); await move('home'); }
1379
1408
  busy(replay, demo);
1380
1409
  }
1381
1410
 
@@ -1400,7 +1429,7 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
1400
1429
  foot: [back('check'), spacer(), btn('Пропустити крок', 'ghost', () => go('screen'))],
1401
1430
  });
1402
1431
  const ch = $('wizBody').querySelector('.choices'); ch.append(ca, cb);
1403
- async function show() { await send('on'); await send('home'); await send('j1 10'); await wait(1600); await send('home'); }
1432
+ async function show() { await servosOn(); await move('home'); await move('j1 10'); await wait(1200); await move('home'); }
1404
1433
  async function answer(ok) {
1405
1434
  if (ok) { go('screen'); return; }
1406
1435
  if (W.retried) { note.hidden = false; note.className = 'note bad';
@@ -1453,7 +1482,7 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
1453
1482
  foot: [back(j === 0 ? 'screen' : 'j' + (j - 1)), spacer(), btn('Пропустити суглоб', 'ghost', () => go(j < 3 ? 'j' + (j + 1) : 'done'))],
1454
1483
  });
1455
1484
  $('wizBody').querySelector('.choices').append(yes, no);
1456
- async function show() { await send('on'); await send('home'); await send('j' + jj.n + ' ' + (jj.base + jj.plus)); await wait(1500); await send('home'); }
1485
+ async function show() { await servosOn(); await move('home'); await move('j' + jj.n + ' ' + (jj.base + jj.plus)); await wait(1200); await move('home'); }
1457
1486
  async function answer(ok) {
1458
1487
  if (ok) { await send('home'); go('j' + j, 'centre'); return; }
1459
1488
  if (W.retried) { note.hidden = false; note.className = 'note bad';
@@ -1485,7 +1514,7 @@ svg.alive .eye { transform-box: fill-box; transform-origin: center; animation: b
1485
1514
  foot: [back('j' + j), spacer(), done],
1486
1515
  });
1487
1516
  W.onCal = k => { if (k === j) dial.sync(); };
1488
- (async () => { await send('on'); await toRef(j); await send('cal', true); })();
1517
+ (async () => { await servosOn(); await toRef(j); await send('cal', true); })();
1489
1518
  setTimeout(() => dial.querySelector('input').focus(), 80);
1490
1519
  }
1491
1520