dsh-tg-bridge 1.38.6 → 1.38.8

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.
@@ -17,6 +17,7 @@ import { diffPressRouter } from '../control/cmd-diff.mjs';
17
17
  import { handleModelPress, MODEL_PREFIX, modelPressRouter } from '../control/model-card.mjs';
18
18
  import { runCommandFromButton } from '../core/run-command.mjs';
19
19
  import { handleCardPress } from '../profile/settings-press.mjs';
20
+ import { cardBlocks, cardKeyboard, renderCardSettings, toggleCardBlock } from '../turn/card.mjs';
20
21
  import { config, done, log, saveState, state } from '../core/state.mjs';
21
22
  import { inlineKeyboard, send, sendFile, tg, tgFast } from './telegram.mjs';
22
23
  import { sessionFile } from './thoughts.mjs';
@@ -343,6 +344,29 @@ export async function handleCallback(query) {
343
344
  if (await modelPressRouter({ chatId, threadId, messageId, key, lang, answer, log })(data)) return;
344
345
  }
345
346
 
347
+ if (data.startsWith('tc:')) {
348
+ // The turn card's own switches. Redrawn from state like the task card, so a
349
+ // double tap settles on one truth; an id this build does not know answers
350
+ // "stale" instead of writing a key nothing reads.
351
+ const next = toggleCardBlock(state, key, data.slice(3));
352
+ if (!next) {
353
+ await answer(t(lang, 'card.stale'));
354
+ return;
355
+ }
356
+ state.cardBlocks = { ...(state.cardBlocks || {}), [key]: next };
357
+ saveState();
358
+ const blocks = cardBlocks(state, key);
359
+ await tg('editMessageText', {
360
+ chat_id: chatId,
361
+ message_id: messageId,
362
+ text: renderCardSettings(blocks, lang),
363
+ reply_markup: { inline_keyboard: inlineKeyboard(cardKeyboard(blocks, lang)) },
364
+ }).catch(() => {});
365
+ await answer(t(lang, next.includes(data.slice(3)) ? 'card.cbOn' : 'card.cbOff'));
366
+ log(`card block ${data.slice(3)} toggled for ${key}`);
367
+ return;
368
+ }
369
+
346
370
  if (data.startsWith('t:')) {
347
371
  // A task card. The whole message is redrawn from state, so a double tap or
348
372
  // two people pressing converge on one truth instead of stacking ✅ marks.
@@ -12,7 +12,7 @@ export const CONTROL_COMMANDS = [
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', 'dsh', 'compact',
15
+ 'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card',
16
16
  ];
17
17
 
18
18
  /**
package/chat/control.mjs CHANGED
@@ -29,6 +29,7 @@ import { COMMAND_ALIASES, CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from './comman
29
29
 
30
30
  import { handleAgentCommands } from '../control/cmd-agents.mjs';
31
31
  import { handleBridgeCommands } from '../control/cmd-bridge.mjs';
32
+ import { handleCardCommands } from '../control/cmd-card.mjs';
32
33
  import { handleFallbackCommands } from '../control/cmd-fallback.mjs';
33
34
  import { handleDiffCommands } from '../control/cmd-diff.mjs';
34
35
  import { handleLoadCommands } from '../control/cmd-load.mjs';
@@ -112,7 +113,7 @@ export async function handleControl(ctx) {
112
113
  // that is not its job. The order is alphabetical, not meaningful: no two
113
114
  // groups claim the same command, so a miss falls through to `default` below.
114
115
  const child = { ...ctx, effective, command, arg: effectiveArgText, send, reply, log, profile, state, key, config, lang };
115
- for (const handler of [handleAgentCommands, handleBridgeCommands, handleCompactCommands, handleDiffCommands, handleEveryCommands, handleDshCommands, handleFallbackCommands, handleLoadCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands]) {
116
+ for (const handler of [handleAgentCommands, handleBridgeCommands, handleCardCommands, handleCompactCommands, handleDiffCommands, handleEveryCommands, handleDshCommands, handleFallbackCommands, handleLoadCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleTaskCommands, handleViewCommands, handleEndpointCommands]) {
116
117
  if (await handler(child)) return true;
117
118
  }
118
119
  // Nothing claimed it: the bridge answers an unknown `/` command itself, with
@@ -17,7 +17,7 @@ const SECTION = {
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', dsh: 'Versions', compact: 'Versions',
20
+ app: 'Other', restart: 'Other', help: 'Other', menu: 'Panels', dsh: 'Versions', compact: 'Versions', card: 'Models',
21
21
  };
22
22
 
23
23
  /**
@@ -20,7 +20,7 @@ const SECTIONS = {
20
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', 'dsh', 'compact', 'subscribe', 'doctor', 'logs', 'report', 'restart', 'app', 'help'],
23
+ house: ['load', 'settings', 'card', 'update', 'dsh', 'compact', 'subscribe', 'doctor', 'logs', 'report', 'restart', 'app', 'help'],
24
24
  };
25
25
 
26
26
  /**
package/chat/panel.mjs CHANGED
@@ -173,21 +173,29 @@ export function progressPanel({
173
173
  // no rate for this model. Only ever on the final card: a running turn has no
174
174
  // final bill, and a figure that climbs is read as a meter, not as a receipt.
175
175
  money = '',
176
+ // Which blocks this topic keeps, as a Set of ids from `turn/card.mjs`.
177
+ // `null` means "no choice recorded", and the card keeps every block — the
178
+ // shape it had before `/card` existed, so an old topic does not shrink.
179
+ blocks = null,
176
180
  } = {}) {
181
+ const on = (id) => !blocks || blocks.has(id);
177
182
  const snippet = String(task).replace(/\s+/g, ' ').trim().slice(0, 48);
178
183
  const mark = String(chip).trim() ? ` · ${String(chip).trim()}` : '';
179
184
  const where = String(topic || '').trim() ? `\n${String(topic).trim()}` : '';
180
185
  // The speed sits right after the clock so the two read as one measurement.
181
- const rate = Number(speed) > 0 ? ` · ${Math.round(Number(speed))} ${t(lang, 'status.speed')}` : '';
186
+ const rate = Number(speed) > 0 && on('speed') ? ` · ${Math.round(Number(speed))} ${t(lang, 'status.speed')}` : '';
182
187
  const head = final
183
188
  ? `✅ ${t(lang, 'status.done')} · ${seconds} ${secondsUnit(lang)}${rate}${mark}${where}`
184
189
  : snippet
185
190
  ? `⏳ ${t(lang, 'status.accepted')}: «${snippet}${String(task).trim().length > 48 ? '…' : ''}» · ${seconds} ${secondsUnit(lang)}${rate}${mark}${where}`
186
191
  : `⏳ ${t(lang, 'status.working')}… ${seconds} ${secondsUnit(lang)}${rate}${mark}${where}`;
187
- const mind = thoughts.map((line) => `💭 ${line}`);
188
- const ctx = String(context || '').trim();
189
- const paid = String(money || '').trim();
190
- const base = [head, ...mind, ctx, paid, cache].filter(Boolean).join('\n').length;
192
+ // Every block below is a row `/card` can switch off for this topic. The head
193
+ // always stays: a card with no duration is not a summary of a turn.
194
+ const mind = on('thoughts') ? thoughts.map((line) => `💭 ${line}`) : [];
195
+ const ctx = on('context') ? String(context || '').trim() : '';
196
+ const paid = on('cost') ? String(money || '').trim() : '';
197
+ const cacheLine = on('cache') ? cache : '';
198
+ const base = [head, ...mind, ctx, paid, cacheLine].filter(Boolean).join('\n').length;
191
199
 
192
200
  // While the turn runs this message is rewritten every few seconds, and
193
201
  // Telegram drops an expanded block on every edit — which is what yanks the
@@ -196,16 +204,19 @@ export function progressPanel({
196
204
  // all. The two blocks arrive once, in the final edit, which nothing touches
197
205
  // again, so a block can be opened and read in peace.
198
206
  const many = steps.length > 3;
199
- const inline = many
200
- ? (final ? [] : steps.slice(-3).map((line) => `• ${line}`))
201
- : steps.map((line) => `• ${line}`);
202
- const more = !final && many ? t(lang, 'status.more', { n: steps.length - 3 }) : '';
203
- const text = String(thinking || '').trim();
207
+ const showSteps = on('steps');
208
+ const inline = !showSteps
209
+ ? []
210
+ : many
211
+ ? (final ? [] : steps.slice(-3).map((line) => `• ${line}`))
212
+ : steps.map((line) => `• ${line}`);
213
+ const more = showSteps && !final && many ? t(lang, 'status.more', { n: steps.length - 3 }) : '';
214
+ const text = on('reasoning') ? String(thinking || '').trim() : '';
204
215
  const live = (reasoning === 'counter' && final)
205
216
  ? (text ? `🧠 ${t(lang, 'status.thinkTitle')} · ${text.length} · /thoughts file` : '')
206
217
  : (!final && text ? `🧠 ${t(lang, 'status.thinkTitle')} · ${text.length}` : '');
207
218
  const stepsRoom = Math.max(0, Math.min(STEPS_MAX, PANEL_MAX - base - 1200));
208
- const all = many && final
219
+ const all = showSteps && many && final
209
220
  ? tailOf(steps.map((line) => `• ${line}`).join('\n'), stepsRoom)
210
221
  : { text: '', cut: false };
211
222
  const stepsLabel = `🛠 ${t(lang, 'status.stepsTitle')} · ${steps.length}`
@@ -231,7 +242,7 @@ export function progressPanel({
231
242
  escapeHtml(ctx),
232
243
  escapeHtml(paid),
233
244
  all.text ? `<blockquote expandable>${escapeHtml(stepsLabel)}\n${escapeHtml(all.text)}</blockquote>` : '',
234
- escapeHtml(cache),
245
+ escapeHtml(cacheLine),
235
246
  ].filter(Boolean).join('\n');
236
247
  const plain = [
237
248
  head,
@@ -243,7 +254,7 @@ export function progressPanel({
243
254
  ctx,
244
255
  paid,
245
256
  all.text ? `${stepsLabel}\n${all.text}` : '',
246
- cache,
257
+ cacheLine,
247
258
  ].filter(Boolean).join('\n');
248
259
  return { html, plain };
249
260
  }
@@ -0,0 +1,19 @@
1
+ // `/card`: what the finished-turn card carries, chosen with buttons.
2
+ //
3
+ // The card used to be the same for everyone — speed, steps, reasoning, context,
4
+ // cost and cache in one message — and the only way to have less was to scroll.
5
+ // The choice is per topic, because the topic is where the reading happens.
6
+ import { cardBlocks, cardKeyboard, renderCardSettings } from '../turn/card.mjs';
7
+
8
+ export async function handleCardCommands(ctx) {
9
+ const { effective, state, key, lang, reply } = ctx;
10
+ switch (effective) {
11
+ case '/card': {
12
+ const blocks = cardBlocks(state, key);
13
+ await reply(renderCardSettings(blocks, lang), { keyboard: cardKeyboard(blocks, lang) });
14
+ return true;
15
+ }
16
+ default:
17
+ return false;
18
+ }
19
+ }
package/docs/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # CHANGELOG — DSH Telegram bridge
2
2
 
3
+ ## 1.38.8
4
+
5
+ - **A 💭 line is no longer lost when the sandbox forbids the write.** A turn that
6
+ runs in a project folder may have `~/.dsh` outside its writable area: the note
7
+ file refused the append with `EPERM`, `say.mjs --thought` exited 6, and the
8
+ decision never reached the chat. It now falls back to sending the line as a
9
+ real `💭` message — the person sees it, the stderr line says why it did not go
10
+ into the card, and the exit code is a failure only when both paths fail.
11
+ - `DSH_TG_THOUGHTS` overrides the thoughts directory, so the fallback is
12
+ testable without breaking a real installation.
13
+
14
+ ## 1.38.7
15
+
16
+ - **The turn card is now a choice, not a wall.** Every turn ends with one card,
17
+ and it used to carry everything the bridge knew: speed, thoughts, steps,
18
+ context, cost, cache and reasoning, in that order, for everyone. `/card` lists
19
+ those rows as buttons: tap one and that block stops appearing in this topic
20
+ from the next turn. The choice is per topic and survives a restart.
21
+ A topic that never chose keeps the full card, so an update never shortens a
22
+ card someone was reading. The head stays either way: a card without a duration
23
+ is not a summary of a turn.
24
+ - **The renderer reads the same switch the command writes.** `chat/panel.mjs`
25
+ takes the chosen set and drops the rows it excludes, instead of deciding for
26
+ itself what a card carries — the drift that would otherwise make `/card` a
27
+ promise the card does not keep.
28
+ - **A press answers.** Toggling redraws the card from state (a double tap settles
29
+ on one truth), answers «Включено»/«Выключено», and an id this build does not
30
+ know says the button is stale instead of writing a key nothing reads.
31
+ - `/help` documents `/card` next to `/model`, `/cost` and `/thoughts`, in all
32
+ three locales, with a sentence of its own.
33
+
3
34
  ## 1.38.6
4
35
 
5
36
  - **A refused key is no longer reported as an unrecognised voice message.** A
package/i18n/en/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': 'on',
15
15
  'settings.state.off': 'off',
16
16
  'settings.state.auto': 'auto',
17
- 'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e · /diff [stat]\nGoals: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (tap to tick)\nSessions: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cname\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels per topic: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nOther: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nPanels: /menu — the same commands as buttons, page by page. /menu on puts four keys under the message field.",
17
+ 'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e · /diff [stat]\nGoals: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (tap to tick)\nSessions: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cname\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels per topic: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nOther: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nPanels: /menu — the same commands as buttons, page by page. /menu on puts four keys under the message field.",
18
18
  'settings.reply.title': 'What the bot says',
19
19
  'settings.agent.title': 'Who answers, and how hard it works',
20
20
  'settings.updates.title': 'New releases (this install, not this topic)',
@@ -207,6 +207,21 @@ export default {
207
207
  'msg.voiceNotRecognized': 'Could not make out the voice message{detail}',
208
208
  'msg.voiceRefused': 'The speech engine refused the request (status {status}) — the key was not accepted. Check voice.apiKey or voice.apiKeyEnv.',
209
209
  'msg.voiceRefusedRest': 'The rest of the clips in this batch were not sent: the engine would answer the same way.',
210
+ 'card.title': 'Turn card: what to show after the answer',
211
+ 'ctrl.help.about.card': 'The turn card is the message every turn ends with. `/card` opens its rows as buttons: time, speed, thoughts, steps, context, cost, cache, reasoning. The choice is per topic and applies from the next turn.',
212
+ 'card.b.time': 'Time',
213
+ 'card.b.speed': 'Speed',
214
+ 'card.b.thoughts': 'Thoughts',
215
+ 'card.b.steps': 'Steps',
216
+ 'card.b.context': 'Context',
217
+ 'card.b.cost': 'Cost',
218
+ 'card.b.cache': 'Cache',
219
+ 'card.b.reasoning': 'Reasoning',
220
+ 'card.none': 'Nothing is selected — the card will stay empty.',
221
+ 'card.hint': 'Tap a row to turn it on or off. The choice is per topic and applies from the next turn.',
222
+ 'card.stale': 'That button is stale: this build has no such row.',
223
+ 'card.cbOn': 'On',
224
+ 'card.cbOff': 'Off',
210
225
  'msg.voiceOff': '🎤 Voice transcription is not set up here. `voice` takes any engine: a local script (`voice.python` + `voice.script`), any CLI (`voice.command` + `voice.args`), or an OpenAI-compatible API (`voice.baseUrl` + `voice.model` + a key). Ready-made blocks are in docs/VOICE.md.',
211
226
  'prompt.photo': 'Look at the image at {path} and describe it in detail: text (verbatim, keeping its language), interface elements, objects.',
212
227
  'prompt.file': 'The user sent a file: {path} ({type}, {size} bytes).',
package/i18n/ru/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': 'вкл',
15
15
  'settings.state.off': 'выкл',
16
16
  'settings.state.auto': 'авто',
17
- 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e · /diff [stat]\nЦели: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (нажать, чтобы отметить)\nСессии: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cимя\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодель у каждой темы: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nПрочее: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
17
+ 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e · /diff [stat]\nЦели: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (нажать, чтобы отметить)\nСессии: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cимя\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодель у каждой темы: /model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\nПрочее: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
18
18
  'settings.reply.title': 'Что бот говорит',
19
19
  'settings.agent.title': 'Кто отвечает и как старается',
20
20
  'settings.updates.title': 'Новые версии (эта установка, не тема)',
@@ -207,6 +207,21 @@ export default {
207
207
  'msg.voiceNotRecognized': 'Не распознал голосовое{detail}',
208
208
  'msg.voiceRefused': 'Движок распознавания отказал (код {status}) — ключ не принят. Проверьте voice.apiKey или voice.apiKeyEnv.',
209
209
  'msg.voiceRefusedRest': 'Остальные голосовые из этой пачки не отправлял: ответ движка был бы тот же.',
210
+ 'card.title': 'Карточка хода: что показывать после ответа',
211
+ 'ctrl.help.about.card': 'Карточка хода — это сообщение, которым заканчивается каждый ход. `/card` открывает её строки кнопками: время, скорость, мысли, шаги, контекст, стоимость, кэш, рассуждение. Выбор свой у каждой темы и действует со следующего хода.',
212
+ 'card.b.time': 'Время',
213
+ 'card.b.speed': 'Скорость',
214
+ 'card.b.thoughts': 'Мысли',
215
+ 'card.b.steps': 'Шаги',
216
+ 'card.b.context': 'Контекст',
217
+ 'card.b.cost': 'Стоимость',
218
+ 'card.b.cache': 'Кэш',
219
+ 'card.b.reasoning': 'Рассуждение',
220
+ 'card.none': 'Сейчас не выбрано ничего — карточка останется пустой.',
221
+ 'card.hint': 'Нажмите строку, чтобы включить или выключить. Настройка своя у каждой темы и действует со следующего хода.',
222
+ 'card.stale': 'Кнопка устарела: такой строки в этой версии нет.',
223
+ 'card.cbOn': 'Включено',
224
+ 'card.cbOff': 'Выключено',
210
225
  'msg.voiceOff': '🎤 Расшифровка голоса здесь не настроена. В `voice` подойдёт любой движок: локальный скрипт (`voice.python` + `voice.script`), любая CLI (`voice.command` + `voice.args`) или OpenAI-совместимый API (`voice.baseUrl` + `voice.model` + ключ). Готовые блоки — в docs/VOICE.md.',
211
226
  'prompt.photo': 'Посмотри изображение по пути {path} и подробно опиши, что на нём: текст (дословно, с сохранением языка), элементы интерфейса, объекты.',
212
227
  'prompt.file': 'Пользователь прислал файл: {path} ({type}, {size} байт).',
package/i18n/zh/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': '开',
15
15
  'settings.state.off': '关',
16
16
  'settings.state.auto': '自动',
17
- 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e · /diff [stat]\n目标: /goal · /tasks [\u003ctext\u003e|done N] · /tasks(点击勾选)\n会话: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003c名称\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n每个话题各自的模型:/model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\n其他: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
17
+ 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e · /diff [stat]\n目标: /goal · /tasks [\u003ctext\u003e|done N] · /tasks(点击勾选)\n会话: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003c名称\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n每个话题各自的模型:/model · /model \u003cid\u003e · /model \u003cid\u003e all · /endpoint [list|add|rm] · /fallback · /load · /prices · /cost · /thoughts · /card\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind · /every\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off · /dsh · /compact\n其他: /settings · /lang · /reasoning · /pin · /doctor · /logs [errors|N] · /report · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
18
18
  'settings.reply.title': '机器人怎么说',
19
19
  'settings.agent.title': '谁来回答、投入多少',
20
20
  'settings.updates.title': '新版本(针对本次安装,而非话题)',
@@ -207,6 +207,21 @@ export default {
207
207
  'msg.voiceNotRecognized': '没能识别这条语音{detail}',
208
208
  'msg.voiceRefused': '语音引擎拒绝了请求(状态码 {status})——密钥未被接受。请检查 voice.apiKey 或 voice.apiKeyEnv。',
209
209
  'msg.voiceRefusedRest': '这批里其余语音没有发送:引擎的答复会一样。',
210
+ 'card.title': '回合卡片:回答之后显示什么',
211
+ 'ctrl.help.about.card': '回合卡片是每个回合结束时的那条消息。`/card` 把它的各行做成按钮:耗时、速度、思路、步骤、上下文、费用、缓存、推理。每个主题各有一套,从下一回合生效。',
212
+ 'card.b.time': '耗时',
213
+ 'card.b.speed': '速度',
214
+ 'card.b.thoughts': '思路',
215
+ 'card.b.steps': '步骤',
216
+ 'card.b.context': '上下文',
217
+ 'card.b.cost': '费用',
218
+ 'card.b.cache': '缓存',
219
+ 'card.b.reasoning': '推理',
220
+ 'card.none': '目前一项都没选——卡片会是空的。',
221
+ 'card.hint': '点一行即可开关。每个主题各有一套,从下一回合生效。',
222
+ 'card.stale': '这个按钮已过期:当前版本没有这一行。',
223
+ 'card.cbOn': '已开启',
224
+ 'card.cbOff': '已关闭',
210
225
  'msg.voiceOff': '🎤 这里还没有配置语音转写。`voice` 可以接任意引擎:本地脚本(`voice.python` + `voice.script`)、任意命令行(`voice.command` + `voice.args`),或 OpenAI 兼容接口(`voice.baseUrl` + `voice.model` + 密钥)。现成配置见 docs/VOICE.md。',
211
226
  'prompt.photo': '查看路径 {path} 的图片并详细描述:文字(逐字,保留原语言)、界面元素、物体。',
212
227
  'prompt.file': '用户发来文件:{path}({type},{size} 字节)。',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.38.6",
3
+ "version": "1.38.8",
4
4
  "description": "Drive DeepSeek Harness from Telegram: one project, model and session per forum topic",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
package/say.mjs CHANGED
@@ -26,7 +26,7 @@ import { join } from 'node:path';
26
26
  const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh');
27
27
  const STEER = join(DSH_HOME, 'tg-bridge', 'steer');
28
28
  const ACKS = join(STEER, 'acks');
29
- const THOUGHTS = join(DSH_HOME, 'tg-bridge', 'thoughts');
29
+ const THOUGHTS = (process.env.DSH_TG_THOUGHTS || '').trim() || join(DSH_HOME, 'tg-bridge', 'thoughts');
30
30
 
31
31
  function findToken() {
32
32
  const env = (process.env.DSH_TELEGRAM_BOT_TOKEN || '').trim();
@@ -85,6 +85,31 @@ function activeThoughtFile() {
85
85
  return { chatId, threadId: Number(base.slice(cut + 1)) || 0 };
86
86
  }
87
87
 
88
+ /**
89
+ * Send one plain chat line and report the message id, or null.
90
+ *
91
+ * Used by the thought fallback: a 💭 line that cannot be written into the card
92
+ * file still has to arrive somewhere, and a failed send must not look like a
93
+ * successful one.
94
+ */
95
+ async function sendLine(chatId, threadId, text) {
96
+ const token = findToken();
97
+ if (!token) return null;
98
+ const body = { chat_id: chatId, text, disable_web_page_preview: true };
99
+ if (threadId > 0) body.message_thread_id = threadId;
100
+ try {
101
+ const res = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
102
+ method: 'POST',
103
+ headers: { 'content-type': 'application/json' },
104
+ body: JSON.stringify(body),
105
+ });
106
+ const data = await res.json().catch(() => ({}));
107
+ return data.ok ? data.result.message_id : null;
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+
88
113
  async function main() {
89
114
  const args = parse(process.argv.slice(2));
90
115
  if (!args.text) usage();
@@ -121,6 +146,11 @@ async function main() {
121
146
  if (!chatId) usage();
122
147
 
123
148
  if (args.thought) {
149
+ const explicit = (process.env.DSH_TG_THOUGHT || '').trim();
150
+ const own = explicit && explicit.split(/[\\/]/).pop()?.startsWith(`${chatId}_${threadId || 0}_`)
151
+ ? explicit
152
+ : '';
153
+ const file = own || join(THOUGHTS, `${chatId}_${threadId || 0}.jsonl`);
124
154
  try {
125
155
  mkdirSync(THOUGHTS, { recursive: true });
126
156
  // The turn's own file when the bridge exported one: two turns in the same
@@ -128,18 +158,22 @@ async function main() {
128
158
  // per-topic name stays the fallback for a shell that lost the env, and the
129
159
  // panel reads both — so a note never lands in a file nobody reads, which
130
160
  // is exactly what made 💭 stay empty while the file on disk kept growing.
131
- const explicit = (process.env.DSH_TG_THOUGHT || '').trim();
132
- const own = explicit && explicit.split(/[\\/]/).pop()?.startsWith(`${chatId}_${threadId || 0}_`)
133
- ? explicit
134
- : '';
135
- const file = own || join(THOUGHTS, `${chatId}_${threadId || 0}.jsonl`);
136
161
  appendFileSync(file, `${JSON.stringify({ at: Date.now(), text: args.text })}\n`, 'utf8');
137
162
  console.log(file);
163
+ return;
138
164
  } catch (error) {
139
- console.error(String(error?.message ?? error));
140
- process.exit(6);
165
+ // A workspace sandbox can forbid writes under ~/.dsh while the turn runs
166
+ // in a project folder. The line must still reach the person: fall back to
167
+ // a real 💭 message and say why, instead of losing the decision silently.
168
+ const why = String(error?.message ?? error).replace(/\s+/g, ' ').slice(0, 120);
169
+ const sent = await sendLine(chatId, threadId, `💭 ${args.text}`);
170
+ if (!sent) {
171
+ console.error(`${why}; and the fallback message did not go through`);
172
+ process.exit(6);
173
+ }
174
+ console.error(`${why}; sent as a 💭 message instead of a card line`);
175
+ return;
141
176
  }
142
- return;
143
177
  }
144
178
 
145
179
  const token = findToken();
@@ -159,8 +193,7 @@ async function main() {
159
193
  if (!data.ok) {
160
194
  console.error(`telegram: ${data.description || res.status}`);
161
195
  process.exit(4);
162
- }
163
- if (args.steer) {
196
+ } if (args.steer) {
164
197
  try {
165
198
  mkdirSync(ACKS, { recursive: true });
166
199
  writeFileSync(join(ACKS, `${args.steer}.json`), JSON.stringify({ at: Date.now(), messageId: data.result.message_id, job: jobPath }), 'utf8');
package/turn/card.mjs ADDED
@@ -0,0 +1,71 @@
1
+ // Which blocks the finished-turn card shows, and the card that chooses them.
2
+ //
3
+ // The card is one message per turn, and what belongs in it is a matter of taste:
4
+ // someone chasing a slow provider wants the speed and the cache line, someone
5
+ // reading answers wants the step list gone. The choice is per topic and lives in
6
+ // `state`, so the next turn reads it back without a command.
7
+ import { t } from '../core/i18n.mjs';
8
+
9
+ /**
10
+ * Every block the card can carry, in the order the card shows them.
11
+ *
12
+ * `time` is not optional: a card without a duration is not a summary of a turn,
13
+ * and turning it off would leave the card with no head at all — so `/card`
14
+ * offers it like any other row and the renderer keeps the head either way.
15
+ */
16
+ export const CARD_BLOCKS = ['time', 'speed', 'thoughts', 'steps', 'context', 'cost', 'cache', 'reasoning'];
17
+
18
+ /**
19
+ * The blocks this topic keeps.
20
+ *
21
+ * A topic that never chose gets every block: that is what the card looked like
22
+ * before the choice existed, and an update must not silently shorten it. An id
23
+ * this build no longer knows is dropped rather than rendered as an empty row.
24
+ */
25
+ export function cardBlocks(state, key) {
26
+ const chosen = state?.cardBlocks?.[key];
27
+ if (!Array.isArray(chosen)) return new Set(CARD_BLOCKS);
28
+ // Canonical order, not the stored one: the card is read top to bottom, and a
29
+ // list that depends on the order buttons were pressed in would be a different
30
+ // card after every restart.
31
+ return new Set(CARD_BLOCKS.filter((id) => chosen.includes(id)));
32
+ }
33
+
34
+ /**
35
+ * Flip one block and return the list to store, in the card's own order.
36
+ *
37
+ * `null` for an id this build does not know: the caller answers "stale card"
38
+ * instead of writing a key nobody reads.
39
+ */
40
+ export function toggleCardBlock(state, key, id) {
41
+ if (!CARD_BLOCKS.includes(id)) return null;
42
+ const blocks = cardBlocks(state, key);
43
+ if (blocks.has(id)) blocks.delete(id);
44
+ else blocks.add(id);
45
+ return CARD_BLOCKS.filter((block) => blocks.has(block));
46
+ }
47
+
48
+ /** One button per block: a tick means the block is on. Two per row. */
49
+ export function cardKeyboard(blocks, lang) {
50
+ const rows = [];
51
+ for (const id of CARD_BLOCKS) {
52
+ const on = blocks.has(id);
53
+ const button = { text: `${on ? '✅' : '⬜'} ${t(lang, `card.b.${id}`)}`, callback_data: `tc:${id}` };
54
+ const last = rows[rows.length - 1];
55
+ if (last && last.length === 1) last.push(button);
56
+ else rows.push([button]);
57
+ }
58
+ return rows;
59
+ }
60
+
61
+ /** The card itself: what the next finished turn will show. */
62
+ export function renderCardSettings(blocks, lang) {
63
+ const on = CARD_BLOCKS.filter((id) => blocks.has(id));
64
+ return [
65
+ `🗂 ${t(lang, 'card.title')}`,
66
+ '',
67
+ on.length ? on.map((id) => `• ${t(lang, `card.b.${id}`)}`).join('\n') : t(lang, 'card.none'),
68
+ '',
69
+ t(lang, 'card.hint'),
70
+ ].join('\n');
71
+ }
package/turn/progress.mjs CHANGED
@@ -15,6 +15,7 @@ import { topicName } from '../chat/topics.mjs';
15
15
  import { t } from '../core/i18n.mjs';
16
16
  import { addStep, progressPanel, stepLine } from '../chat/panel.mjs';
17
17
  import { reasoningMode, thoughtRows } from '../chat/notes.mjs';
18
+ import { cardBlocks } from './card.mjs';
18
19
  import { cardPin } from '../profile/settings-card.mjs';
19
20
  import { continueKeyboard, errorKeyboard } from '../chat/keyboards.mjs';
20
21
  import { contextFill, contextRow, contextUsed } from './context-meter.mjs';
@@ -181,6 +182,9 @@ export async function startProgress(chatId, threadId, lang = config.lang || 'en'
181
182
  : '';
182
183
  return progressPanel({
183
184
  lang,
185
+ // Which blocks this topic asked for with `/card`. A topic that never chose
186
+ // gets the full card, which is what it had before the choice existed.
187
+ blocks: cardBlocks(state, panelKey),
184
188
  // Two topics run at once in a group, so a card that does not name its topic
185
189
  // is unattributable the moment it scrolls: the same 💭 line in the wrong
186
190
  // place looks like a cross-topic bug, and half the time it is one. The