dsh-tg-bridge 1.35.0 → 1.38.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.
Files changed (57) hide show
  1. package/README.md +1 -1
  2. package/bot-menu.mjs +112 -91
  3. package/bridge.mjs +12 -0
  4. package/chat/callbacks.mjs +20 -0
  5. package/chat/commands-registry.mjs +2 -2
  6. package/chat/commands.mjs +32 -0
  7. package/chat/control.mjs +4 -1
  8. package/chat/handle-message.mjs +23 -34
  9. package/chat/help-explain.mjs +3 -3
  10. package/chat/media.mjs +7 -2
  11. package/chat/menu-card.mjs +3 -2
  12. package/chat/panel.mjs +43 -2
  13. package/chat/reply-guard.mjs +55 -0
  14. package/chat/thoughts.mjs +36 -3
  15. package/control/cmd-bridge.mjs +12 -0
  16. package/control/cmd-compact.mjs +60 -0
  17. package/control/cmd-dsh.mjs +160 -0
  18. package/control/cmd-every.mjs +108 -0
  19. package/control/cmd-views.mjs +33 -16
  20. package/control/model-card.mjs +408 -233
  21. package/core/dsh-version.mjs +183 -0
  22. package/docs/CHANGELOG.md +244 -0
  23. package/docs/DEV-LOOP.md +80 -0
  24. package/goal.mjs +12 -1
  25. package/i18n/en/core.mjs +13 -2
  26. package/i18n/en/ctrl.mjs +4 -2
  27. package/i18n/en/dsh.mjs +37 -0
  28. package/i18n/en/every.mjs +21 -0
  29. package/i18n/en/fallback.mjs +1 -1
  30. package/i18n/en/model.mjs +16 -2
  31. package/i18n/en.mjs +3 -1
  32. package/i18n/ru/core.mjs +13 -2
  33. package/i18n/ru/ctrl.mjs +4 -2
  34. package/i18n/ru/dsh.mjs +35 -0
  35. package/i18n/ru/every.mjs +21 -0
  36. package/i18n/ru/fallback.mjs +1 -1
  37. package/i18n/ru/model.mjs +14 -2
  38. package/i18n/ru.mjs +3 -1
  39. package/i18n/zh/core.mjs +13 -2
  40. package/i18n/zh/ctrl.mjs +4 -2
  41. package/i18n/zh/dsh.mjs +35 -0
  42. package/i18n/zh/every.mjs +20 -0
  43. package/i18n/zh/fallback.mjs +1 -1
  44. package/i18n/zh/model.mjs +14 -2
  45. package/i18n/zh.mjs +3 -1
  46. package/install-hooks.mjs +5 -0
  47. package/jev-gate.mjs +132 -0
  48. package/model/fallback.mjs +113 -9
  49. package/package.json +81 -80
  50. package/plugin-bridge.mjs +44 -19
  51. package/profile/settings-card.mjs +33 -8
  52. package/turn/failures.mjs +25 -3
  53. package/turn/job-loops.mjs +89 -2
  54. package/turn/provider-banner.mjs +64 -0
  55. package/turn/turn-outcome.mjs +14 -1
  56. package/work/reminders.mjs +8 -2
  57. package/work/schedules.mjs +108 -0
package/README.md CHANGED
@@ -323,7 +323,7 @@ Goals: /goal (plan + checklist) · /goal reopen · /tasks (checklist only
323
323
  Sessions: /status · /sessions · /sessions <id> · /rewind [n|undo|fork [n]|branches]
324
324
  Agents: /agents · /agents <id> · /agents set model|depth|filter
325
325
  Models: /model · /model <route> · /model <route> all · /model auto · /endpoint · /prices
326
- Tuning: /effort · /permissions · /preset · /plan · /jobs · /remind
326
+ Tuning: /effort · /permissions · /preset · /plan · /jobs · /remind · /every
327
327
  Profiles: /profile · /profile <name> · /profile new <name> from <template>
328
328
  Sets: /crew · /crew use|off|new|copy|rm · /crew model <v>
329
329
  Extensions: /skills · /plugins · /plugins search <word> · /plugins disable|enable <id> · /soul
package/bot-menu.mjs CHANGED
@@ -1,91 +1,112 @@
1
- // dsh-bot-menu — install the Telegram command menu that matches THIS bridge.
2
- //
3
- // Why it exists: the menu the person sees is whatever `setMyCommands` last
4
- // wrote, and another plugin (@xmanrui/dsh-im) had set a Chinese list of 31
5
- // commands that this bridge does not implement. A menu that lies is worse than
6
- // no menu, so the bridge owns its own list and re-asserts it on start.
7
- //
8
- // What it publishes comes from `MENU_COMMANDS` in `commands-registry.mjs`, not
9
- // from a second list kept here. That second list is how `/task` stayed in the
10
- // menu for a release after `/task` had become an alias: the registry said one
11
- // thing, the menu said another, and both were "the source of truth".
12
- //
13
- // Usage: node bot-menu.mjs [--delete]
14
-
15
- import { readFileSync } from 'node:fs';
16
- import { join } from 'node:path';
17
- import { homedir } from 'node:os';
18
- import { MENU_COMMANDS } from './chat/commands-registry.mjs';
19
- import { LANGS, t } from './core/i18n.mjs';
20
-
21
- const args = new Set(process.argv.slice(2));
22
-
23
- const token = (() => {
24
- const env = (process.env.DSH_TELEGRAM_BOT_TOKEN || '').trim();
25
- if (env) return env;
26
- try {
27
- const home = process.env.DSH_HOME || join(homedir(), '.dsh');
28
- const yaml = readFileSync(join(home, '.credentials.yaml'), 'utf8');
29
- // `dsh-tg init` writes the plain name; the DSH app adds a random suffix.
30
- const m = /^\s*(DSH_TELEGRAM_BOT_TOKEN[A-Z0-9_]*):\s*["']?([^"'\s]+)/m.exec(yaml);
31
- return m ? m[2] : '';
32
- } catch {
33
- return '';
34
- }
35
- })();
36
-
37
- /** The menu rows for one language, straight from the registry. */
38
- function rows(lang) {
39
- return MENU_COMMANDS.map((name) => ({
40
- // Telegram caps a description at 256 characters and a name at 32; an
41
- // over-long row makes the whole call fail, so the cut happens here once.
42
- command: name,
43
- description: String(t(lang, `menu.cmd.${name}`)).slice(0, 256),
44
- }));
45
- }
46
-
47
- async function api(method, body) {
48
- const res = await fetch(`https://api.telegram.org/bot${token}/${method}`, {
49
- method: 'POST',
50
- headers: { 'content-type': 'application/json' },
51
- body: JSON.stringify(body ?? {}),
52
- signal: AbortSignal.timeout(20000),
53
- });
54
- const json = await res.json().catch(() => ({}));
55
- if (!json.ok) throw new Error(`${method}: ${json.description || res.status}`);
56
- return json.result;
57
- }
58
-
59
- async function main() {
60
- if (!token) {
61
- console.error('bot token not found in ~/.dsh/.credentials.yaml');
62
- process.exit(1);
63
- }
64
- if (args.has('--delete')) {
65
- await api('deleteMyCommands', {});
66
- console.log('menu deleted');
67
- return;
68
- }
69
- // The default list is the language the owner reads; the others are installed
70
- // per language_code so an English or Chinese phone sees its own words.
71
- await api('setMyCommands', { commands: rows('ru') });
72
- // Telegram validates language_code against its own ISO list: 'zh-hans' is
73
- // rejected with "invalid language code", 'zh' is accepted. Each language is
74
- // installed independently — one refusal must not leave the others unset.
75
- for (const code of LANGS.filter((lang) => lang !== 'ru')) {
76
- try {
77
- await api('setMyCommands', { commands: rows(code), language_code: code });
78
- console.log(`menu installed for ${code}: ${MENU_COMMANDS.length} commands`);
79
- } catch (error) {
80
- console.error(`menu for ${code} failed: ${error.message}`);
81
- }
82
- }
83
- const check = await api('getMyCommands', {});
84
- console.log(`menu installed: ${check.length} commands`);
85
- for (const c of check) console.log(` /${c.command} — ${c.description}`);
86
- }
87
-
88
- main().catch((error) => {
89
- console.error(error.message);
90
- process.exit(1);
91
- });
1
+ // dsh-bot-menu — install the Telegram command menu that matches THIS bridge.
2
+ //
3
+ // Why it exists: the menu the person sees is whatever `setMyCommands` last
4
+ // wrote, and another plugin (@xmanrui/dsh-im) had set a Chinese list of 31
5
+ // commands that this bridge does not implement. A menu that lies is worse than
6
+ // no menu, so the bridge owns its own list and re-asserts it on start.
7
+ //
8
+ // What it publishes comes from `MENU_COMMANDS` in `commands-registry.mjs`, not
9
+ // from a second list kept here. That second list is how `/task` stayed in the
10
+ // menu for a release after `/task` had become an alias: the registry said one
11
+ // thing, the menu said another, and both were "the source of truth".
12
+ //
13
+ // "Re-asserts it on start" used to be a comment and nothing else: the install
14
+ // ran only from `init`/`setup`, so any later plugin that wrote its own list kept
15
+ // it until somebody ran this file by hand. `bridge.mjs` calls `installMenu()`
16
+ // once per start for that reason.
17
+ //
18
+ // Usage: node bot-menu.mjs [--delete]
19
+
20
+ import { pathToFileURL } from 'node:url';
21
+ import { MENU_COMMANDS } from './chat/commands-registry.mjs';
22
+ import { LANGS, t } from './core/i18n.mjs';
23
+ import { findToken } from './core/secrets.mjs';
24
+
25
+ /** The menu rows for one language, straight from the registry. */
26
+ export function rows(lang) {
27
+ return MENU_COMMANDS.map((name) => ({
28
+ // Telegram caps a description at 256 characters and a name at 32; an
29
+ // over-long row makes the whole call fail, so the cut happens here once.
30
+ command: name,
31
+ description: String(t(lang, `menu.cmd.${name}`)).slice(0, 256),
32
+ }));
33
+ }
34
+
35
+ function botToken() {
36
+ return findToken();
37
+ }
38
+
39
+ /**
40
+ * Publish the registry's menu for every language we speak, then read it back.
41
+ *
42
+ * Returns what actually landed, so a caller can log one honest line instead of
43
+ * assuming a `setMyCommands` it never checked. A language Telegram refuses is
44
+ * reported and skipped: one refusal must not leave the others unset.
45
+ */
46
+ export async function installMenu({ call, log = () => {}, token = findToken() } = {}) {
47
+ const api = call || ((method, body) => telegram(token, method, body));
48
+ await api('setMyCommands', { commands: rows('ru') });
49
+ const languages = ['ru'];
50
+ const failed = [];
51
+ // Telegram validates language_code against its own ISO list: 'zh-hans' is
52
+ // rejected with "invalid language code", 'zh' is accepted.
53
+ for (const code of LANGS.filter((lang) => lang !== 'ru')) {
54
+ try {
55
+ await api('setMyCommands', { commands: rows(code), language_code: code });
56
+ languages.push(code);
57
+ } catch (error) {
58
+ failed.push(code);
59
+ log(`menu for ${code} failed: ${error.message}`);
60
+ }
61
+ }
62
+ const check = await api('getMyCommands', {});
63
+ return {
64
+ languages,
65
+ failed,
66
+ count: Array.isArray(check) ? check.length : 0,
67
+ rows: Array.isArray(check) ? check : [],
68
+ };
69
+ }
70
+
71
+ async function telegram(token, method, body) {
72
+ if (!token) throw new Error('bot token not found in ~/.dsh/.credentials.yaml');
73
+ const res = await fetch(`https://api.telegram.org/bot${token}/${method}`, {
74
+ method: 'POST',
75
+ headers: { 'content-type': 'application/json' },
76
+ body: JSON.stringify(body ?? {}),
77
+ signal: AbortSignal.timeout(20000),
78
+ });
79
+ const json = await res.json().catch(() => ({}));
80
+ if (!json.ok) throw new Error(`${method}: ${json.description || res.status}`);
81
+ return json.result;
82
+ }
83
+
84
+ export async function deleteMenu({ call, token = findToken() } = {}) {
85
+ const api = call || ((method, body) => telegram(token, method, body));
86
+ await api('deleteMyCommands', {});
87
+ }
88
+
89
+ async function main() {
90
+ const args = new Set(process.argv.slice(2));
91
+ const token = findToken();
92
+ if (!token) {
93
+ console.error('bot token not found in ~/.dsh/.credentials.yaml');
94
+ process.exit(1);
95
+ }
96
+ if (args.has('--delete')) {
97
+ await deleteMenu({ token });
98
+ console.log('menu deleted');
99
+ return;
100
+ }
101
+ const result = await installMenu({ token, log: (line) => console.error(line) });
102
+ for (const code of result.languages) console.log(`menu installed for ${code}: ${MENU_COMMANDS.length} commands`);
103
+ console.log(`menu installed: ${result.count} commands`);
104
+ for (const c of result.rows) console.log(` /${c.command} — ${c.description}`);
105
+ }
106
+
107
+ if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
108
+ main().catch((error) => {
109
+ console.error(error.message);
110
+ process.exit(1);
111
+ });
112
+ }
package/bridge.mjs CHANGED
@@ -39,6 +39,7 @@ import { answerPressFailed, handleCallback, renderTaskCard, taskRows } from './c
39
39
  import { boundSetOf, handleCardPress } from './profile/settings-press.mjs';
40
40
  import { runCommandFromButton } from './core/run-command.mjs';
41
41
  import { startJobLoops } from './turn/job-loops.mjs';
42
+ import { installMenu } from './bot-menu.mjs';
42
43
  import { ensureProfile } from './profile/profiles.mjs';
43
44
  import { firstLiveModel, describeVerdicts, probeHint, probeModel } from './model/model-probe.mjs';
44
45
  import { explainFailure } from './turn/failures.mjs';
@@ -192,6 +193,17 @@ async function main() {
192
193
  } catch (error) {
193
194
  log(`startup notice failed: ${error.message}`);
194
195
  }
196
+ // The menu belongs to this bridge, but `setMyCommands` is global state that any
197
+ // other plugin can overwrite after an install — the Chinese list of 31 rows
198
+ // this bot does not implement came exactly that way. Re-asserting it on every
199
+ // start is three API calls, and it is the only moment the bridge is known to be
200
+ // awake. A failure here is logged, never fatal: a wrong menu must not stop turns.
201
+ try {
202
+ const menu = await installMenu({ log });
203
+ log(`menu asserted: ${menu.count} commands (${menu.languages.join(', ')}${menu.failed.length ? `, failed ${menu.failed.join(', ')}` : ''})`);
204
+ } catch (error) {
205
+ log(`menu assert failed: ${error.message}`);
206
+ }
195
207
 
196
208
  /** One update: journal first, then the turn, then ack after delivery. */
197
209
  const accept = (update, replay = false) => {
@@ -80,6 +80,26 @@ export async function handleCallback(query) {
80
80
  return;
81
81
  }
82
82
 
83
+ // `/dsh`'s own two presses. Each types the command the card advertised, so the
84
+ // install path and the confirmation in front of it exist exactly once — a
85
+ // button that called npm itself would be a second way to replace the harness.
86
+ if (data.startsWith('ds:')) {
87
+ await clearKeyboard();
88
+ await answer(t(lang, 'bridge.cb.done'));
89
+ await runCommandFromButton(`/dsh ${data === 'ds:confirm' ? 'update confirm' : 'update'}`, { chatId, threadId, key, lang });
90
+ return;
91
+ }
92
+
93
+ // `/compact`'s one press: the card explains where compaction lives and offers
94
+ // the thing that does work here, which is a fresh session. It types the command
95
+ // rather than doing the work, so `/new` keeps exactly one implementation.
96
+ if (data === 'cp:new') {
97
+ await clearKeyboard();
98
+ await answer(t(lang, 'bridge.cb.done'));
99
+ await runCommandFromButton('/new', { chatId, threadId, key, lang });
100
+ return;
101
+ }
102
+
83
103
  if (isRewindPress(data)) {
84
104
  // A rewind button. What it acts on is read here, not taken from the card:
85
105
  // between drawing "go back 2" and the press, the session may have moved on,
@@ -8,11 +8,11 @@
8
8
  // file imports nothing, so it can never be part of one.
9
9
  export const CONTROL_COMMANDS = [
10
10
  'status', 'models', 'model', 'effort', 'profile', 'agents', 'preset', 'permissions', 'plan',
11
- 'jobs', 'remind', 'sessions', 'resume', 'plugins', 'plugin',
11
+ 'jobs', 'remind', 'every', 'sessions', 'resume', 'plugins', 'plugin',
12
12
  'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
13
13
  'prices', 'cost', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
14
14
  'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
15
- 'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint',
15
+ 'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact',
16
16
  ];
17
17
 
18
18
  /**
package/chat/commands.mjs CHANGED
@@ -65,6 +65,38 @@ export function immediateCommandOf(text) {
65
65
  return immediateKind(collapsed, rest);
66
66
  }
67
67
 
68
+ /**
69
+ * Split a message into its command and argument, including the collapsed forms.
70
+ *
71
+ * `/apprestart.confirm` (no space) is a real way to mistype the service command
72
+ * and used to fall through to a full AI turn. Heads are matched WITHOUT their
73
+ * punctuation, so `/apprestart.confirm` and `/app-restart-confirm` both arrive
74
+ * as `apprestartconfirm`, and the dotted form already says "restart" — the only
75
+ * missing word is `confirm`.
76
+ *
77
+ * Pure, and moved here from the message handler: what a head means is command
78
+ * knowledge, not the business of one-message-becomes-one-turn.
79
+ */
80
+ export function commandParts(text, known) {
81
+ const space = String(text).indexOf(' ');
82
+ const head = space === -1 ? String(text) : String(text).slice(0, space);
83
+ const command = commandOf(head);
84
+ const arg = space === -1 ? '' : String(text).slice(space + 1).trim();
85
+ const collapsed = command.replace(/^\//, '').replace(/[.-]+/g, '');
86
+ const set = known instanceof Set ? known : new Set(known);
87
+ let effective = set.has(collapsed) ? `/${collapsed}` : '';
88
+ let effectiveArg = arg;
89
+ if (collapsed === 'apprestart' || collapsed === 'apprestartconfirm') {
90
+ effective = '/app';
91
+ effectiveArg = arg || 'restart confirm';
92
+ } else if (collapsed === 'restartconfirm') {
93
+ effective = '/restart';
94
+ effectiveArg = arg || 'confirm';
95
+ }
96
+ if (effectiveArg === 'restartconfirm' || effectiveArg === 'restart.confirm') effectiveArg = 'restart confirm';
97
+ return { head, command, arg, collapsed, effective, effectiveArg };
98
+ }
99
+
68
100
  /**
69
101
  * Language for a chat and topic.
70
102
  *
package/chat/control.mjs CHANGED
@@ -38,6 +38,9 @@ import { handleSkillCommands } from '../control/cmd-skills.mjs';
38
38
  import { handleTaskCommands } from '../control/cmd-task.mjs';
39
39
  import { handleViewCommands } from '../control/cmd-views.mjs';
40
40
  import { handleEndpointCommands } from '../control/cmd-endpoint.mjs';
41
+ import { handleEveryCommands } from '../control/cmd-every.mjs';
42
+ import { handleDshCommands } from '../control/cmd-dsh.mjs';
43
+ import { handleCompactCommands } from '../control/cmd-compact.mjs';
41
44
  import { APP, CLI_JS, DSH_CMD, DSH_HOME, EXE, HOME, PROFILES, THOUGHT_DIR } from '../core/paths.mjs';
42
45
  import { read, readJson, patchPath, pkgPath, OVERLAY_MARK, modelsOf, modelOf, windowOf, modelIndent, depthOf, modelsReport, setModel, disabledIds, setDisabled, writePatch } from '../control/models.mjs';
43
46
  import { listPids, waitForExit, waitForStart, pluginsOf, bundleRowIds, addBundle, removeBundle, createProfile, dshPlugin } from '../control/plugins.mjs';
@@ -109,7 +112,7 @@ export async function handleControl(ctx) {
109
112
  // that is not its job. The order is alphabetical, not meaningful: no two
110
113
  // groups claim the same command, so a miss falls through to `default` below.
111
114
  const child = { ...ctx, effective, command, arg: effectiveArgText, send, reply, log, profile, state, key, config, lang };
112
- for (const handler of [handleAgentCommands, handleBridgeCommands, handleDiffCommands, handleFallbackCommands, handleLoadCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands]) {
115
+ for (const handler of [handleAgentCommands, handleBridgeCommands, handleCompactCommands, handleDiffCommands, handleEveryCommands, handleDshCommands, handleFallbackCommands, handleLoadCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands]) {
113
116
  if (await handler(child)) return true;
114
117
  }
115
118
  // Nothing claimed it: the bridge answers an unknown `/` command itself, with
@@ -5,7 +5,7 @@
5
5
  // topic's session, profile, request and progress panel fit together. Everything
6
6
  // it calls lives in a module of its own.
7
7
 
8
- import { GENERAL_SAFE, commandOf } from './commands.mjs';
8
+ import { commandParts, GENERAL_SAFE } from './commands.mjs';
9
9
  import { CONTROL_COMMANDS, handleControl, modelOf } from './control.mjs';
10
10
  import { reasoningMode } from './notes.mjs';
11
11
  import { explainFailure } from '../turn/failures.mjs';
@@ -17,7 +17,7 @@ import { holdIfLoaded } from '../work/load-guard.mjs';
17
17
  import { guardOf } from '../core/machine.mjs';
18
18
  import { mediaPrompt } from './media.mjs';
19
19
  import { keyboardCommand } from './menu-card.mjs';
20
- import { looksLikeReasoning } from './panel.mjs';
20
+ import { replyText } from './reply-guard.mjs';
21
21
  import { QUIET_MS, quietGuard } from './quiet-guard.mjs';
22
22
  import { DIR, GOAL_CMD, THOUGHT_DIR } from '../core/paths.mjs';
23
23
  import { renderPrices } from '../model/prices.mjs';
@@ -173,34 +173,12 @@ export async function handleMessage(msg, album = null) {
173
173
  }
174
174
  }
175
175
 
176
- const space = text.indexOf(' ');
177
- const head = space === -1 ? text : text.slice(0, space);
178
- const command = commandOf(head);
179
- const arg = space === -1 ? '' : text.slice(space + 1).trim();
180
-
181
- // `/apprestart.confirm` (no space) is a real way to mistype the service
182
- // command and used to fall through to a full AI turn. Map the collapsed
183
- // forms onto the canonical command + argument instead.
184
- //
185
- // Heads are matched WITHOUT their punctuation, so `/apprestart.confirm` and
186
- // `/app-restart-confirm` both arrive here as "apprestartconfirm".
187
- const collapsed = command.replace(/^\//, '').replace(/[.-]+/g, '');
188
- const known = new Set(CONTROL_COMMANDS);
189
- let effective = known.has(collapsed) ? `/${collapsed}` : '';
190
- let effectiveArg = arg;
191
- if (collapsed === 'apprestart' || collapsed === 'apprestartconfirm') {
192
- effective = '/app';
193
- // The dotted/solid form already says "restart", so confirm is the only
194
- // missing word: `/apprestart.confirm` must mean `/app restart confirm`.
195
- effectiveArg = arg || 'restart confirm';
196
- } else if (collapsed === 'restartconfirm') {
197
- effective = '/restart';
198
- effectiveArg = arg || 'confirm';
199
- }
176
+ // Command knowledge lives in `commands.mjs`: a collapsed head like
177
+ // `/apprestart.confirm` must reach the control command, never the model.
178
+ const { head, command, effective, effectiveArg } = commandParts(text, CONTROL_COMMANDS);
200
179
  if (effective && effective !== command) {
201
180
  log(`command alias: ${head} -> ${effective} ${effectiveArg}`);
202
181
  }
203
- if (effectiveArg === 'restartconfirm' || effectiveArg === 'restart.confirm') effectiveArg = 'restart confirm';
204
182
 
205
183
  // General is the lobby: a prompt written there runs in the most recently active
206
184
  // topic so one project stays in one place. A command that CHANGES things must
@@ -380,7 +358,10 @@ ${t(lang, 'help.body')}`,
380
358
  log,
381
359
  onSession: (id) => liveSessions.set(key, id),
382
360
  });
383
- const attempt = turnAttempt(text, key, { onEvent, onAbort: () => killTurn(key), env: thoughtEnv, profile: turnProfile || profileOf(key), cwd, lang });
361
+ // One options object for every attempt on this message, so the retries below
362
+ // cannot drift from the first call — the bug that made 1.30.0 fail everywhere.
363
+ const turnOptions = { onEvent, onAbort: () => killTurn(key), env: thoughtEnv, profile: turnProfile || profileOf(key), cwd, lang };
364
+ const attempt = turnAttempt(text, key, turnOptions);
384
365
  let result = await attempt(sessionAtStart);
385
366
  if (result.error && /unknown id|not found|не найдена|was recorded in/i.test(result.error) && sessionAtStart) {
386
367
  delete state.sessions[key];
@@ -479,15 +460,23 @@ ${t(lang, 'help.body')}`,
479
460
  // An answered turn proves this release works, and makes it the version a later
480
461
  // rollback returns to.
481
462
  await noteTurn(state, { saveState });
482
- // A turn that ends without an answer hands back its last assistant text —
483
- // the reasoning — and sending that looks exactly like the bot answering with
484
- // its own notes. Say what happened instead of forwarding the page.
485
- if (looksLikeReasoning(result.text, progress.reasoning())) {
486
- log(`reasoning echo suppressed for ${where} (${String(result.text).length} chars)`);
463
+ // A turn that ends without an answer hands back its last assistant text — the
464
+ // reasoning. `reply-guard.mjs` decides what the chat sees: one more ask, the
465
+ // honest sentence when that fails too, and never a page of the model's notes.
466
+ const reply = await replyText({
467
+ result,
468
+ reasoning: () => progress.reasoning(),
469
+ key,
470
+ turnOptions,
471
+ sessionId: sessionAtStart,
472
+ where,
473
+ log,
474
+ });
475
+ if (reply.echoed) {
487
476
  await send(chatId, t(lang, 'bridge.progress.reasoningOnly'), threadId);
488
477
  return;
489
478
  }
490
- await send(chatId, result.text || t(lang, 'bridge.progress.emptyReply'), threadId);
479
+ await send(chatId, reply.text || t(lang, 'bridge.progress.emptyReply'), threadId);
491
480
  // A refusal explains the turn that just ended, so it goes after the answer.
492
481
  await reportRefusals({
493
482
  refusals,
@@ -12,12 +12,12 @@ const SECTION = {
12
12
  cd: 'Work', new: 'Work', stop: 'Work', send: 'Work', seed: 'Work', diff: 'Work',
13
13
  goal: 'Goals', task: 'Goals', tasks: 'Goals',
14
14
  status: 'Sessions', sessions: 'Sessions', rewind: 'Sessions', profile: 'Sessions',
15
- agents: 'Agents', model: 'Models', prices: 'Models', cost: 'Models', thoughts: 'Models', fallback: 'Models',
16
- effort: 'Tuning', permissions: 'Tuning', preset: 'Tuning', crew: 'Tuning', plan: 'Tuning', jobs: 'Tuning', remind: 'Tuning',
15
+ agents: 'Agents', model: 'Models', prices: 'Models', cost: 'Models', thoughts: 'Models', fallback: 'Models', endpoint: 'Models',
16
+ effort: 'Tuning', permissions: 'Tuning', preset: 'Tuning', crew: 'Tuning', plan: 'Tuning', jobs: 'Tuning', remind: 'Tuning', every: 'Tuning',
17
17
  skills: 'Extensions', plugins: 'Extensions', soul: 'Extensions',
18
18
  update: 'Versions', subscribe: 'Versions',
19
19
  load: 'Models', settings: 'Other', lang: 'Other', reasoning: 'Other', pin: 'Other', doctor: 'Other', logs: 'Other', report: 'Other',
20
- app: 'Other', restart: 'Other', help: 'Other', menu: 'Panels',
20
+ app: 'Other', restart: 'Other', help: 'Other', menu: 'Panels', dsh: 'Versions', compact: 'Versions',
21
21
  };
22
22
 
23
23
  /**
package/chat/media.mjs CHANGED
@@ -118,7 +118,12 @@ function transcribeLocal(file, voice, useScript) {
118
118
  log(`voice: python=${command} script=${voice.script} — both must be absolute`);
119
119
  return Promise.resolve({ text: '', error: 'voice.python and voice.script must be absolute paths' });
120
120
  }
121
- const cwd = voice.cwd || DIR;
121
+ const cwd = voice.cwd || (existsSync(DIR) ? DIR : tmpdir());
122
+ // `DIR` is the live install, and it exists on every machine that finished
123
+ // `init`. It does not exist before that — CI included — and spawning with a
124
+ // missing cwd fails with ENOENT, so the engine answered nothing and the
125
+ // transcript came back empty. Falling back to the temp directory keeps the
126
+ // engine runnable wherever the package is checked out.
122
127
  // A cwd that does not exist is a typo, and a spawn error names the file rather
123
128
  // than the setting that is actually wrong.
124
129
  if (voice.cwd && !(existsSync(cwd) && statSync(cwd).isDirectory())) {
@@ -144,7 +149,7 @@ function transcribeLocal(file, voice, useScript) {
144
149
  if (!useScript && !(voice.args ?? []).some((arg) => String(arg).includes('{file}'))) args.push(file);
145
150
  return new Promise((resolve) => {
146
151
  const child = spawn(command, args, {
147
- cwd: voice.cwd || DIR,
152
+ cwd,
148
153
  windowsHide: true,
149
154
  env: { ...process.env },
150
155
  });
@@ -17,10 +17,10 @@ import { CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from './commands-registry.mjs';
17
17
  const SECTIONS = {
18
18
  work: ['cd', 'seed', 'send', 'diff'],
19
19
  session: ['sessions', 'rewind', 'profile', 'agents'],
20
- goals: ['goal', 'task', 'tasks', 'plan', 'jobs', 'remind'],
20
+ goals: ['goal', 'task', 'tasks', 'plan', 'jobs', 'remind', 'every'],
21
21
  talk: ['effort', 'reasoning', 'pin', 'thoughts', 'prices', 'cost', 'lang', 'endpoint', 'fallback'],
22
22
  ext: ['plugins', 'skills', 'soul', 'preset', 'permissions', 'crew'],
23
- house: ['load', 'settings', 'update', 'subscribe', 'doctor', 'logs', 'report', 'restart', 'app', 'help'],
23
+ house: ['load', 'settings', 'update', 'dsh', 'compact', 'subscribe', 'doctor', 'logs', 'report', 'restart', 'app', 'help'],
24
24
  };
25
25
 
26
26
  /**
@@ -71,6 +71,7 @@ const LABELS = {
71
71
  plan: '/plan',
72
72
  jobs: '/jobs',
73
73
  remind: '/remind +15m',
74
+ every: '/every 09:00',
74
75
  model: '/model ▸ this topic',
75
76
  effort: '/effort <level>',
76
77
  reasoning: '/reasoning ▸ this topic',
package/chat/panel.mjs CHANGED
@@ -31,6 +31,25 @@ function tailOf(text, room) {
31
31
  return { text: text.slice(-room), cut: true };
32
32
  }
33
33
 
34
+ /**
35
+ * Remove the model's own thinking markers from a reply.
36
+ *
37
+ * Some routes stream reasoning into the text channel, and the marker survives
38
+ * into the answer: a reply begins with a literal `<thinking` and continues with
39
+ * the model's notes (`<thinkingAll done. Now the final answer.`). Two shapes are
40
+ * handled — a closed `<thinking>…</thinking>` block, and the unclosed marker the
41
+ * routes actually emit, where only the marker itself can be removed because the
42
+ * end of the notes is not knowable from the text alone. The comparison against
43
+ * the panel's reasoning decides what remains.
44
+ */
45
+ export function stripThinkingBlocks(text) {
46
+ return String(text ?? '')
47
+ .replace(/<think(?:ing)?>[\s\S]*?<\/think(?:ing)?>/gi, ' ')
48
+ .replace(/<\/?think(?:ing)?>/gi, ' ')
49
+ .replace(/^\s*<think(?:ing)?/i, ' ')
50
+ .trim();
51
+ }
52
+
34
53
  /**
35
54
  * Is this "answer" the reasoning the panel already holds?
36
55
  *
@@ -40,15 +59,37 @@ function tailOf(text, room) {
40
59
  * person reads it as "the bot answers with its own notes". Matching is on
41
60
  * whitespace-normalised text, and the answer must be long enough that a one-word
42
61
  * reply cannot be swallowed by coincidence.
62
+ *
63
+ * The marker is stripped first: a leaked `<thinking…` prefix made the answer a
64
+ * string the reasoning does not contain, so the guard missed exactly the case it
65
+ * exists for.
43
66
  */
44
67
  export function looksLikeReasoning(answer, thinking) {
45
68
  const norm = (value) => String(value ?? '').replace(/\s+/g, ' ').trim().toLowerCase();
46
- const said = norm(answer);
69
+ const raw = norm(answer);
70
+ const said = norm(stripThinkingBlocks(answer));
47
71
  const thought = norm(thinking);
48
- if (!said || !thought || said.length < 120) return false;
72
+ if (!thought || raw.length < 120) return false;
73
+ // A reply that is nothing but a thinking marker carries no answer.
74
+ if (!said) return /<think(?:ing)?/i.test(raw);
75
+ if (said.length < 120) return false;
49
76
  return thought.includes(said) || (said.includes(thought) && thought.length > said.length * 0.6);
50
77
  }
51
78
 
79
+ /**
80
+ * What to ask a model that answered with its notes instead of a reply.
81
+ *
82
+ * Sent as one more message in the same session: the work it did is still in
83
+ * context, so the second attempt is cheap and usually lands. It is a prompt, not
84
+ * chat copy, so it lives here and not in the locale tables.
85
+ */
86
+ export const REPLY_NUDGE = [
87
+ 'You sent your reasoning instead of the answer. The person is waiting.',
88
+ 'Answer now: the result of the work you just did, in the language of the',
89
+ 'conversation, as a finished reply. Do not narrate the plan, do not think out',
90
+ 'loud, and do not repeat the reasoning.',
91
+ ].join(' ');
92
+
52
93
  /**
53
94
  * One line for a tool call in the panel.
54
95
  *
@@ -0,0 +1,55 @@
1
+ // What the chat sends when the model hands back its own notes instead of a reply.
2
+ //
3
+ // The headless CLI's `final` text is the turn's last assistant text, and a turn
4
+ // that produced no answer reports the reasoning. Forwarding it reads as "the bot
5
+ // answers with its thinking", and suppressing it reads as "the turn died" — both
6
+ // were real, and both are the same defect seen from two sides. The guard here
7
+ // asks once more, in the same session, for a finished reply; only when that also
8
+ // comes back as notes does it send the honest sentence.
9
+ //
10
+ // Extracted from `handle-message.mjs`, which is at its size ceiling and whose
11
+ // subject is "one incoming message becomes one turn", not "what a reply is".
12
+ import { looksLikeReasoning, REPLY_NUDGE, stripThinkingBlocks } from './panel.mjs';
13
+ import { turnAttempt } from '../turn/turn.mjs';
14
+
15
+ /** Is this text the reasoning the panel already holds, markers included? */
16
+ export function isReasoningEcho(value, reasoning) {
17
+ return looksLikeReasoning(value, reasoning);
18
+ }
19
+
20
+ /**
21
+ * Produce the text the chat should send, asking the model once more if needed.
22
+ *
23
+ * @param {object} input
24
+ * @param {object} input.result the finished turn: `{ text, error }`, replaced in
25
+ * place when the second attempt produces a real answer
26
+ * @param {() => string} input.reasoning the reasoning this turn collected
27
+ * @param {string} input.key the topic key
28
+ * @param {object} input.turnOptions the options the first attempt ran with, so
29
+ * the second attempt cannot drift from it
30
+ * @param {string} input.sessionId the session the first attempt ran in
31
+ * @param {string} input.where the log label for this topic
32
+ * @param {(line: string) => void} input.log
33
+ * @param {Function} [input.retryTurn] builds the second attempt; defaults to the
34
+ * real one. Injectable because the guard's tests must not spawn a CLI.
35
+ * @returns {Promise<{ text: string, echoed: boolean }>} `echoed` means nothing
36
+ * the person should read was produced, and the caller sends its own sentence
37
+ */
38
+ export async function replyText({ result, reasoning, key, turnOptions, sessionId, where, log, retryTurn = turnAttempt }) {
39
+ const echoed = (value) => isReasoningEcho(value, reasoning());
40
+ if (echoed(result.text)) {
41
+ log(`reasoning echo for ${where} (${String(result.text).length} chars) — asking once more`);
42
+ const retry = await retryTurn(REPLY_NUDGE, key, turnOptions)(sessionId);
43
+ if (!retry.error && !echoed(retry.text) && stripThinkingBlocks(retry.text)) {
44
+ Object.assign(result, retry);
45
+ }
46
+ }
47
+ if (echoed(result.text)) {
48
+ log(`reasoning echo suppressed for ${where} (${String(result.text).length} chars)`);
49
+ return { text: '', echoed: true };
50
+ }
51
+ // The marker can survive inside an otherwise real reply; the chat never shows it.
52
+ return { text: stripThinkingBlocks(result.text), echoed: false };
53
+ }
54
+
55
+ export { REPLY_NUDGE };