dsh-tg-bridge 1.21.1 → 1.23.0

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
@@ -113,6 +113,8 @@ Optional provider settings live in `config.json`:
113
113
  | `vision.patch` | opt-in overlay profile for photo turns; default `""` — the turn's own model reads images |
114
114
  | `vision.enabled` | set `true` to run photo turns on `vision.patch` instead of the topic profile |
115
115
  | `fallbackModels` | free-model fallbacks; default `[]` |
116
+ | `maxParallel` | how many topics run at once, 1–8, default `3`; also `/jobs 5` in the chat |
117
+ | `replayWindowMs` | how old a journaled update may be and still be replayed after a restart; default `600000` (10 min) |
116
118
 
117
119
  Get your id from [@userinfobot](https://t.me/userinfobot), the token from
118
120
  [@BotFather](https://t.me/BotFather).
package/bridge.mjs CHANGED
@@ -32,7 +32,7 @@ import { turnArgs } from './cli-args.mjs';
32
32
  import { chunk, markdownParts, toPlainText, toTelegramHtml } from './format.mjs';
33
33
  import { mediaPrompt, readVoiceIntoText } from './media.mjs';
34
34
  import { busyNotices, clearBusyNotice, steerAvailable, steerMediaMessage, steerRunningTurn } from './steer.mjs';
35
- import { MAX_PARALLEL, approvals, bufferAlbum, enqueue, lastPrompt, queues, rewindUsed, setMessageHandler } from './queue.mjs';
35
+ import { MAX_PARALLEL, approvals, bufferAlbum, enqueue, lastPrompt, queues, redeliver, rewindUsed, setMessageHandler } from './queue.mjs';
36
36
  import { applyAsetJob, settingsChipOf, turnProfileOf } from './profile-view.mjs';
37
37
  import { handleMessage } from './handle-message.mjs';
38
38
  import { boundSetOf, handleCallback, handleCardPress, renderTaskCard, taskRows } from './callbacks.mjs';
@@ -204,7 +204,23 @@ async function main() {
204
204
  Promise.resolve()
205
205
  .then(() => handleMessage(msg))
206
206
  .then(() => ack(update.update_id))
207
- .catch((error) => log(`command ${immediate} failed: ${error.message}`));
207
+ // A command that threw is answered by the log, not by a replay. Leaving
208
+ // it pending meant every restart ran it again: `/update` installed the
209
+ // release, died on an undefined name, was never acked, and the journal
210
+ // replayed it four times — the chat got "already on 1.22.0" three times
211
+ // for one typed command.
212
+ .catch(async (error) => {
213
+ log(`command ${immediate} failed: ${error.message}`);
214
+ // The person typed a command and got nothing back: silence reads as
215
+ // "still working". One line, then the update is done with.
216
+ const lang = resolveLang(state, queueKey, msg, config);
217
+ await send(
218
+ msg.chat.id,
219
+ t(lang, 'msg.commandFailed', { cmd: immediate, err: String(error.message).slice(0, 200) }),
220
+ thread,
221
+ ).catch(() => {});
222
+ ack(update.update_id);
223
+ });
208
224
  return;
209
225
  }
210
226
  // Telegram splits an album into one update per file, all sharing a
@@ -229,7 +245,7 @@ async function main() {
229
245
  if (activeTurns.has(queueKey) && sessionId) {
230
246
  if (steerText && !steerMedia) {
231
247
  try {
232
- const job = steerRunningTurn(msg, steerText, sessionId, thread, deliverTurn);
248
+ const job = steerRunningTurn(msg, steerText, sessionId, thread, redeliver);
233
249
  log(`steer handled outside the queue: ${job.id}`);
234
250
  ack(update.update_id);
235
251
  } catch (error) {
@@ -243,7 +259,7 @@ async function main() {
243
259
  // the voicemail in a directory nobody reads again.
244
260
  ack(update.update_id);
245
261
  const lang = resolveLang(state, queueKey, msg, config);
246
- void steerMediaMessage(msg, sessionId, queueKey, thread, lang, deliverTurn).catch((error) => {
262
+ void steerMediaMessage(msg, sessionId, queueKey, thread, lang, redeliver).catch((error) => {
247
263
  // The attachment could not be prepared (download, transcription). It
248
264
  // still deserves an answer, so let the normal path take it: it retries
249
265
  // the same work and reports the failure itself.
@@ -263,8 +279,11 @@ async function main() {
263
279
  ack(update.update_id);
264
280
  if (replay) log(`replayed update ${update.update_id} after restart`);
265
281
  } catch (error) {
266
- // Keep the pending file: the next start retries it once.
267
- log(`turn error for update ${update.update_id}: ${error.message}`);
282
+ // One retry, then the answer is owed by nobody: a turn that throws the
283
+ // same way on every start would otherwise be replayed on every restart
284
+ // until the TTL, filling the chat with identical failures.
285
+ log(`turn error for update ${update.update_id}: ${error.message}${replay ? ' (already a retry, dropping)' : ''}`);
286
+ if (replay) ack(update.update_id);
268
287
  }
269
288
  },
270
289
  // Only plain text prompts can queue behind a turn; commands are
@@ -308,10 +327,27 @@ async function main() {
308
327
  // leave the update pending forever, so the bridge replayed it, died, and was
309
328
  // restarted by the supervisor — every ninety seconds, with a stack trace and
310
329
  // nothing else. Drop the entry after reporting it.
330
+ //
331
+ // And a replay is only for what was genuinely mid-flight. After a bad release
332
+ // left nineteen updates unacked, the next start would have re-run a whole
333
+ // evening of turns the owner had already been answered for — the same money
334
+ // twice, in messages he had read. Age is the only signal the journal carries
335
+ // that separates "we died under this" from "this was answered or abandoned
336
+ // long ago", so anything older than the window is dropped and said out loud.
337
+ const replayWindowMs = Number(config.replayWindowMs) > 0
338
+ ? Number(config.replayWindowMs)
339
+ : 10 * 60 * 1000;
311
340
  const owed = pendingUpdates();
312
- if (owed.length > 0) {
313
- log(`replaying ${owed.length} pending update(s) from the journal`);
314
- for (const { update } of owed) {
341
+ const now = Date.now();
342
+ const fresh = owed.filter(({ at }) => !at || now - at <= replayWindowMs);
343
+ const stale = owed.filter(({ at }) => at && now - at > replayWindowMs);
344
+ if (stale.length > 0) {
345
+ log(`dropping ${stale.length} pending update(s) older than ${Math.round(replayWindowMs / 60000)} min: ${stale.map(({ id }) => id).join(', ')}`);
346
+ for (const { id } of stale) ack(id);
347
+ }
348
+ if (fresh.length > 0) {
349
+ log(`replaying ${fresh.length} pending update(s) from the journal`);
350
+ for (const { update } of fresh) {
315
351
  try {
316
352
  accept(update, true);
317
353
  } catch (error) {
package/callbacks.mjs CHANGED
@@ -9,13 +9,13 @@ import { resolveLang, t } from './i18n.mjs';
9
9
  import { sessionKey } from './keys.mjs';
10
10
  import { commandForName, isMenuPress, menuTarget, renderPanel, runsUnasked } from './menu-card.mjs';
11
11
  import { DIR, DSH_HOME, LOG } from './paths.mjs';
12
- import { MAX_PARALLEL, approvals, enqueue, lastPrompt, rewindUsed } from './queue.mjs';
12
+ import { approvals, enqueue, lastPrompt, maxParallel, rewindUsed } from './queue.mjs';
13
13
  import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.mjs';
14
14
  import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
15
15
  import { runCommandFromButton } from './run-command.mjs';
16
16
  import { commandFor, renderSettingsCard, settingsCurrent } from './settings-card.mjs';
17
17
  import { config, done, log, saveState, state } from './state.mjs';
18
- import { send, sendFile, tg } from './telegram.mjs';
18
+ import { inlineKeyboard, send, sendFile, tg } from './telegram.mjs';
19
19
  import { sessionFile } from './thoughts.mjs';
20
20
  import { activeTurns, killTurn, profileOf } from './turn.mjs';
21
21
  import { readFileSync } from 'node:fs';
@@ -142,6 +142,16 @@ export async function handleCallback(query) {
142
142
  return;
143
143
  }
144
144
 
145
+ // A parallel-slot button from the /jobs card. It runs the command the card
146
+ // advertises, so validation and storage live in one place and a tap cannot
147
+ // write a value `/jobs <n>` would refuse. The command redraws the card, so the
148
+ // answer to the press is the new state, not a second message about it.
149
+ if (data.startsWith('jb:')) {
150
+ await clearKeyboard();
151
+ await runCommandFromButton(`/jobs ${data.slice(3)}`, { chatId, threadId, key });
152
+ return;
153
+ }
154
+
145
155
  if (isMenuPress(data)) {
146
156
  // The panel is a set of cards: the hub, then one page per section. Moving
147
157
  // between them edits this message, so browsing costs no new messages. A
@@ -154,7 +164,7 @@ export async function handleCallback(query) {
154
164
  chat_id: chatId,
155
165
  message_id: messageId,
156
166
  text: card.text,
157
- reply_markup: { inline_keyboard: card.keyboard },
167
+ reply_markup: { inline_keyboard: inlineKeyboard(card.keyboard) },
158
168
  ...(threadId > 0 ? { message_thread_id: threadId } : {}),
159
169
  }).catch(() => {});
160
170
  await answer(t(lang, 'bridge.cb.done'));
@@ -262,7 +272,7 @@ export async function handleCallback(query) {
262
272
  chat_id: chatId,
263
273
  message_id: messageId,
264
274
  text,
265
- reply_markup: { inline_keyboard: taskRows(goal) },
275
+ reply_markup: { inline_keyboard: inlineKeyboard(taskRows(goal)) },
266
276
  }).catch(() => {});
267
277
  await answer(t(lang, goal.tasks[n - 1]?.done ? 'bridge.cb.taskDone' : 'bridge.cb.taskUndone'));
268
278
  log(`task ${n} toggled for ${key}`);
@@ -315,7 +325,7 @@ export async function handleCardPress(query, ctx) {
315
325
  chat_id: chatId,
316
326
  message_id: messageId,
317
327
  text: card.text,
318
- reply_markup: { inline_keyboard: card.keyboard },
328
+ reply_markup: { inline_keyboard: inlineKeyboard(card.keyboard) },
319
329
  ...(threadId > 0 ? { message_thread_id: threadId } : {}),
320
330
  }).catch((error) => log(`settings card redraw failed: ${error.message}`));
321
331
  await tg('answerCallbackQuery', { callback_query_id: query.id }).catch(() => {});
@@ -348,7 +358,7 @@ export async function handleCardPress(query, ctx) {
348
358
  replies.push(String(text ?? ''));
349
359
  return Promise.resolve(0);
350
360
  },
351
- jobs: () => ({ active: [], queued: 0, max: MAX_PARALLEL }),
361
+ jobs: () => ({ active: [], queued: 0, max: maxParallel() }),
352
362
  api: tg,
353
363
  sendFile: () => Promise.resolve(0),
354
364
  profile: profileOf(key),
@@ -4,10 +4,11 @@
4
4
  "profile": "headless",
5
5
  "cwd": "",
6
6
  "providerKeys": [],
7
- "pricesUrl": "",
8
7
  "turnIdleMs": 120000,
9
8
  "turnTimeoutMs": 0,
10
9
  "busyNoticeMs": 45000,
10
+ "maxParallel": 3,
11
+ "replayWindowMs": 600000,
11
12
  "approvalTimeoutMs": 600000,
12
13
  "generalLobby": true,
13
14
  "topicLog": true,
@@ -30,4 +31,4 @@
30
31
  "patch": "",
31
32
  "model": ""
32
33
  }
33
- }
34
+ }
@@ -63,7 +63,7 @@ function versionCard(lang) {
63
63
  }
64
64
 
65
65
  export async function handleBridgeCommands(ctx) {
66
- const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang } = ctx;
66
+ const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang, saveState } = ctx;
67
67
  // The topic's language, then the config default, then English. Never Russian:
68
68
  // a group that has no opinion still must not guess a language.
69
69
  const lang = normalizeLang(rawLang) || normalizeLang(config?.lang) || 'en';
@@ -34,7 +34,7 @@ import { taskKeyboard, goalView, taskView, reasoningOf, filterLogLines } from '.
34
34
  import { updatePolicy, bridgeRoot, copyRelease, installRelease, bridgeVersion, newestModuleMtime, npmLatest, npmLatestAsync } from './release.mjs';
35
35
 
36
36
  export async function handlePluginCommands(ctx) {
37
- const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang } = ctx;
37
+ const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang, saveState } = ctx;
38
38
  // The topic's language, then the config default, then English. Never Russian:
39
39
  // a group that has no opinion still must not guess a language.
40
40
  const lang = normalizeLang(rawLang) || normalizeLang(config?.lang) || 'en';
@@ -32,6 +32,7 @@ import { agentsOf, fleetOf, patchRows, skillsOf, AGENTS, PERSONA_HEADING, soulOf
32
32
  import { fmt, AGENTSETS, agentset, agentsetOf, profileRowOf, bindAgentset, agentsetCard, agentsetKeyboard } from './agentsets.mjs';
33
33
  import { taskKeyboard, goalView, taskView, reasoningOf, filterLogLines } from './tasks.mjs';
34
34
  import { updatePolicy, bridgeRoot, copyRelease, installRelease, bridgeVersion, newestModuleMtime, npmLatest, npmLatestAsync } from './release.mjs';
35
+ import { CAP_CHOICES, CAP_MAX, CAP_MIN, setParallel } from '../jobs-cap.mjs';
35
36
 
36
37
  export async function handleTaskCommands(ctx) {
37
38
  const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang } = ctx;
@@ -155,8 +156,27 @@ export async function handleTaskCommands(ctx) {
155
156
  // What survives — and what a person waiting on a reply actually needs —
156
157
  // is the bridge's queue: which topics are running now, for how long, and
157
158
  // how many waits behind them.
159
+ //
160
+ // The card also owns the ceiling. It was a config-file key nobody could
161
+ // reach from the chat, and a wrong value showed up as "your message is
162
+ // waiting for a free slot" with no way to widen it. `/jobs 5` sets it, and
163
+ // so does a button — both through `setParallel`, so they cannot disagree,
164
+ // and the card is redrawn either way, so the answer is the new state.
165
+ const asked = String(arg || '').trim();
166
+ let set = null;
167
+ if (asked) {
168
+ set = setParallel(asked, { config, saveConfig: ctx.saveConfig, log });
169
+ if (!set.ok) {
170
+ say(t(lang, 'ctrl.jobs.capRange', { min: CAP_MIN, max: CAP_MAX }));
171
+ return true;
172
+ }
173
+ }
158
174
  const snapshot = ctx.jobs ? ctx.jobs() : { active: [], queued: 0, max: 0 };
159
- const lines = [t(lang, 'ctrl.jobs.title')];
175
+ const lines = [];
176
+ // One message: what changed, then the state it changed to. Two messages
177
+ // for one tap is noise in a chat that is already long.
178
+ if (set) lines.push(t(lang, set.saved ? 'ctrl.jobs.capSet' : 'ctrl.jobs.capUnsaved', { n: set.n }), '');
179
+ lines.push(t(lang, 'ctrl.jobs.title'));
160
180
  if (snapshot.active.length === 0) {
161
181
  lines.push(t(lang, 'ctrl.jobs.idle'));
162
182
  } else {
@@ -168,7 +188,15 @@ export async function handleTaskCommands(ctx) {
168
188
  }
169
189
  lines.push(t(lang, 'ctrl.jobs.queued', { n: snapshot.queued, max: snapshot.max }));
170
190
  lines.push(t(lang, 'ctrl.jobs.hint'));
171
- say(lines.join('\n'));
191
+ const cap = Number(snapshot.max) || 0;
192
+ lines.push(t(lang, 'ctrl.jobs.cap', { n: cap }));
193
+ // The numbers a person actually picks from. `jb:` is answered in
194
+ // callbacks.mjs by running `/jobs <n>`, the same command this argument runs.
195
+ const rows = [CAP_CHOICES.map((n) => ({
196
+ text: n === cap ? `• ${n}` : String(n),
197
+ data: `jb:${n}`,
198
+ }))];
199
+ say(lines.join('\n'), { keyboard: rows });
172
200
  return true;
173
201
  }
174
202
  case '/remind': {
@@ -20,9 +20,9 @@ import { renderPrices } from './prices.mjs';
20
20
  import { settingsChipOf, turnProfileOf } from './profile-view.mjs';
21
21
  import { ensureProfile } from './profiles.mjs';
22
22
  import { startProgress } from './progress.mjs';
23
- import { MAX_PARALLEL, lastPrompt, queues } from './queue.mjs';
23
+ import { lastPrompt, maxParallel, queues } from './queue.mjs';
24
24
  import { token } from './secrets.mjs';
25
- import { config, done, log, saveState, state } from './state.mjs';
25
+ import { config, done, log, saveConfig, saveState, state } from './state.mjs';
26
26
  import { send, sendEphemeral, sendFile, sendWithMarkup, tg } from './telegram.mjs';
27
27
  import { ensureTopicSeed, logTopicToGeneral, newestBoundTopic, startTopicFromMessage, topicName, topicSeeded, topicSeededRecently, touchTopic } from './topics.mjs';
28
28
  import { activeTurns, killTurn, liveSessions, profileOf, runTurnLive, turnStartedAt, typingLoop } from './turn.mjs';
@@ -226,15 +226,15 @@ ${t(lang, 'help.body')}`,
226
226
  config,
227
227
  activeTurns,
228
228
  saveState,
229
+ saveConfig,
229
230
  log,
230
231
  send,
231
- // What `/jobs` shows: the turns that hold a slot right now and how many
232
- // wait behind them. `queues` counts a topic that is running too, so the
233
- // waiters are the keys without an active turn.
232
+ // What `/jobs` shows: the turns holding a slot, and the keys without an
233
+ // active turn waiting behind them.
234
234
  jobs: () => ({
235
235
  active: [...activeTurns.keys()].map((topic) => ({ key: topic, startedAt: turnStartedAt.get(topic) || 0 })),
236
236
  queued: [...queues.keys()].filter((topic) => !activeTurns.has(topic)).length,
237
- max: MAX_PARALLEL,
237
+ max: maxParallel(),
238
238
  }),
239
239
  api: tg,
240
240
  sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
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\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: /model · /model \u003cid\u003e · /prices · /thoughts\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs · /remind\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off\nOther: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /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\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: /model · /model \u003cid\u003e · /prices · /thoughts\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off\nOther: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /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)',
@@ -84,6 +84,7 @@ export default {
84
84
  'err.generic': 'something went wrong',
85
85
  'msg.busy.since': '⏳ The previous turn has been running for {min} min — your message is queued.\nIf it stalls, /stop interrupts it and I take yours right away.',
86
86
  'msg.busy.now': '⏳ The previous turn is still running — your message is queued.\nIf it stalls, /stop interrupts it and I take yours right away.',
87
+ 'msg.slotWait': '⏳ {max} turns are already running in other topics — your message is waiting for a free slot.\nI take it the moment one frees up; /stop in another topic speeds that up.',
87
88
  'steer.queued': '↪ Addition received — I will fold it in at the next step of this turn.',
88
89
  'steer.ackFallback': '↪ Got the addition — folding it into this turn.',
89
90
  'msg.started': 'Telegram bridge for DSH is running (headless). Send a task; /help for commands.',
@@ -92,6 +93,7 @@ export default {
92
93
  'cmd.restart.started': 'Restarting the bridge…',
93
94
  'msg.generalGuard': "This is the General topic, where topics are started. {cmd} changes “{topic}”, so open that topic and send it there. Reading works here: /status, /sessions, /stop.",
94
95
  'msg.unknownCommand': 'Unknown command: {cmd}. Open /help — it lists everything this bot can do.',
96
+ 'msg.commandFailed': '⚠️ /{cmd} failed: {err}\nNothing was half-done on purpose — check /logs before running it again.',
95
97
  'msg.langSet': 'Language set to English.',
96
98
  'msg.reasoningOn': 'Working notes on: 💭 lines will appear in the progress message.\nOff: /reasoning off',
97
99
  'msg.reasoningOff': 'Working notes off. The progress message keeps the step list only.\nOn: /reasoning on',
@@ -112,7 +114,7 @@ export default {
112
114
  'profile.badName': 'Name it with lowercase letters, digits and dashes: /profile new my-space from web',
113
115
  'profile.set': 'Topic profile → {name} ({route}). Applies from the next turn.',
114
116
  'msg.reasoningState': 'Working notes: {state}. Switch with /reasoning on or /reasoning off.',
115
- 'prompt.reasoning': 'Working notes: at each meaningful step — the task is clear, the cause is found, something risky is about to change, the result is checked — append one line of at most 90 characters with `node {say} --thought "..."`. It shows up as 💭 in the progress message: write the decision, not a retelling. Skip it for one-step work. When a decision changes what the person should expect — a release shipped, a cause found, a blocker — send it to the chat as one plain line: `node {say} --note "..."`. The chat line is for what they must know now, not for every step.',
117
+ 'prompt.reasoning': 'Working notes: in every turn, at each meaningful step — the task is clear, the cause is found, something risky is about to change, the result is checked — append one line of at most 90 characters with `node {say} --thought "..."`. It shows up as 💭 in the progress message: write the decision, not a retelling. Only a turn that is a single tool call may skip it. When a decision changes what the person should expect — a release shipped, a cause found, a blocker, a turn running long — send it to the chat as one plain line: `node {say} --note "..."`. The chat line is for what they must know now, not for every step.',
116
118
  'cmd.help.title': 'Commands',
117
119
  'cmd.help.hint': 'Send any text to start a task. In a forum topic: /cd <project> binds the topic to that project.',
118
120
  'cmd.cd.bound': 'Topic bound to project:\n{path}\n\nAll turns run from this directory.',
package/i18n/en/ctrl.mjs CHANGED
@@ -390,6 +390,10 @@ export default {
390
390
  'ctrl.jobs.thisTopic': 'this topic',
391
391
  'ctrl.jobs.queued': 'Waiting behind: {n} (up to {max} turns run at once)',
392
392
  'ctrl.jobs.hint': 'A turn is one DSH process: its own background jobs die with it. /stop ends this topic\'s turn.',
393
+ 'ctrl.jobs.cap': 'Parallel turns at once: {n}. Tap a number below, or send /jobs 5.',
394
+ 'ctrl.jobs.capSet': 'Parallel turns at once: {n}. Saved to config.json — it applies to the next turn that starts, no restart needed.',
395
+ 'ctrl.jobs.capUnsaved': 'Parallel turns at once: {n} for this process only — config.json could not be written, so a restart goes back to the old value. Check /logs.',
396
+ 'ctrl.jobs.capRange': 'A number from 1 to 8. Each parallel turn is a full DSH process, so more than 8 on one machine makes every turn slower, not faster.',
393
397
  'ctrl.remind.title': '⏰ Reminders',
394
398
  'ctrl.remind.empty': 'Nothing scheduled.',
395
399
  'ctrl.remind.line': '{n}. {when} ({left}) — {text}',
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\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 · /prices · /thoughts\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs · /remind\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off\nПрочее: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
17
+ 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e\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 · /prices · /thoughts\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off\nПрочее: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
18
18
  'settings.reply.title': 'Что бот говорит',
19
19
  'settings.agent.title': 'Кто отвечает и как старается',
20
20
  'settings.updates.title': 'Новые версии (эта установка, не тема)',
@@ -84,6 +84,7 @@ export default {
84
84
  'err.generic': 'что-то пошло не так',
85
85
  'msg.busy.since': '⏳ Предыдущий ход идёт уже {min} мин — твоё сообщение в очереди.\nЕсли это затянулось, /stop прервёт ход, и я сразу возьмусь за твоим.',
86
86
  'msg.busy.now': '⏳ Предыдущий ход ещё идёт — твоё сообщение в очереди.\nЕсли это затянулось, /stop прервёт ход, и я сразу возьмусь за твоим.',
87
+ 'msg.slotWait': '⏳ Сейчас идут {max} хода в других темах — твоё сообщение ждёт свободный слот.\nВозьмусь за него сразу, как освободится; /stop в другой теме ускорит.',
87
88
  'steer.queued': '↪ Дополнение принято — передам его на следующем шаге этого хода.',
88
89
  'steer.ackFallback': '↪ Принял дополнение — учту его в этом же ходе.',
89
90
  'msg.started': 'Telegram-мост DSH запущен (headless). Пиши задачу; /help — команды.',
@@ -92,6 +93,7 @@ export default {
92
93
  'cmd.restart.started': 'Перезапускаю мост…',
93
94
  'msg.generalGuard': "Это общая тема «Все» — здесь темы начинаются. {cmd} меняет «{topic}», поэтому откройте ту тему и отправьте команду там. Читать можно и здесь: /status, /sessions, /stop.",
94
95
  'msg.unknownCommand': 'Неизвестная команда: {cmd}. Открой /help — там всё, что умеет бот.',
96
+ 'msg.commandFailed': '⚠️ /{cmd} не сработала: {err}\nНичего не сделано наполовину намеренно — посмотри /logs, прежде чем повторять.',
95
97
  'msg.langSet': 'Язык переключён на русский.',
96
98
  'msg.reasoningOn': 'Заметки по ходу включены: 💭 будут появляться в сообщении прогресса.\nВыключить: /reasoning off',
97
99
  'msg.reasoningOff': 'Заметки по ходу выключены. В прогрессе остаётся только список шагов.\nВключить: /reasoning on',
@@ -112,7 +114,7 @@ export default {
112
114
  'profile.badName': 'Имя — строчные буквы, цифры и дефис: /profile new my-space from web',
113
115
  'profile.set': 'Профиль темы → {name} ({route}). Действует со следующего хода.',
114
116
  'msg.reasoningState': 'Заметки по ходу: {state}. Переключить: /reasoning on или /reasoning off.',
115
- 'prompt.reasoning': 'Заметки по ходу: на каждом значимом шаге — задача ясна, причина найдена, сейчас изменю рискованное, результат проверен — дописывай одну строку до 90 символов через `node {say} --thought "..."`. Она видна как 💭 в сообщении прогресса: пиши решение, а не пересказ. Для работы в один шаг не зови. Когда решение меняет то, что человек должен знать сразу — выпущена версия, найдена причина, упёрся в блокер — отправь это в чат одной строкой без разметки: `node {say} --note "..."`. В чат — только то, что важно сейчас, не каждый шаг.',
117
+ 'prompt.reasoning': 'Заметки по ходу: в каждом ходе, на каждом значимом шаге — задача ясна, причина найдена, сейчас изменю рискованное, результат проверен — дописывай одну строку до 90 символов через `node {say} --thought "..."`. Она видна как 💭 в сообщении прогресса: пиши решение, а не пересказ. Пропускать можно только если весь ход — один вызов инструмента. Когда решение меняет то, что человек должен знать сразу — выпущена версия, найдена причина, упёрся в блокер, ход идёт долго — отправь это в чат одной строкой без разметки: `node {say} --note "..."`. В чат — только то, что важно сейчас, не каждый шаг.',
116
118
  'cmd.help.title': 'Команды',
117
119
  'cmd.help.hint': 'Любой текст — задача агенту. В теме форума: /cd <проект> привяжет тему к проекту.',
118
120
  'cmd.cd.bound': 'Тема привязана к проекту:\n{path}\n\nДальше все команды идут отсюда.',
package/i18n/ru/ctrl.mjs CHANGED
@@ -390,6 +390,10 @@ export default {
390
390
  'ctrl.jobs.thisTopic': 'эта тема',
391
391
  'ctrl.jobs.queued': 'Ждут позади: {n} (одновременно идёт до {max} ходов)',
392
392
  'ctrl.jobs.hint': 'Ход — это один процесс DSH: его фоновые задачи умирают вместе с ним. /stop завершает ход этой темы.',
393
+ 'ctrl.jobs.cap': 'Одновременных ходов: {n}. Нажми число ниже или отправь /jobs 5.',
394
+ 'ctrl.jobs.capSet': 'Одновременных ходов: {n}. Записано в config.json — применится к следующему начатому ходу, перезапуск не нужен.',
395
+ 'ctrl.jobs.capUnsaved': 'Одновременных ходов: {n} только для этого процесса — config.json не записался, после перезапуска вернётся старое значение. Посмотри /logs.',
396
+ 'ctrl.jobs.capRange': 'Число от 1 до 8. Каждый параллельный ход — отдельный процесс DSH, поэтому больше 8 на одной машине замедляет все ходы, а не ускоряет.',
393
397
  'ctrl.remind.title': '⏰ Напоминания',
394
398
  'ctrl.remind.empty': 'Ничего не запланировано.',
395
399
  'ctrl.remind.line': '{n}. {when} ({left}) — {text}',
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\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 · /prices · /thoughts\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs · /remind\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off\n其他: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
17
+ 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e\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 · /prices · /thoughts\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off\n其他: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
18
18
  'settings.reply.title': '机器人怎么说',
19
19
  'settings.agent.title': '谁来回答、投入多少',
20
20
  'settings.updates.title': '新版本(针对本次安装,而非话题)',
@@ -84,6 +84,7 @@ export default {
84
84
  'err.generic': '出现错误',
85
85
  'msg.busy.since': '⏳ 上一轮已运行 {min} 分钟 —— 你的消息在队列中。\n如果太久,/stop 会中断它,我马上处理你的消息。',
86
86
  'msg.busy.now': '⏳ 上一轮还在运行 —— 你的消息在队列中。\n如果太久,/stop 会中断它,我马上处理你的消息。',
87
+ 'msg.slotWait': '⏳ 其他话题已有 {max} 轮在运行 —— 你的消息在等待空位。\n一旦有空位我就接手;在别的话题里 /stop 可以加快。',
87
88
  'steer.queued': '↪ 已收到补充 — 会在这一轮的下一步并入。',
88
89
  'steer.ackFallback': '↪ 收到补充,会在本轮里一并处理。',
89
90
  'msg.started': 'DSH 的 Telegram 桥已启动(headless)。直接发送任务;/help 查看命令。',
@@ -92,6 +93,7 @@ export default {
92
93
  'cmd.restart.started': '正在重启桥…',
93
94
  'msg.generalGuard': "这里是「全部」主题,用来开新话题。{cmd} 会改动「{topic}」,请打开那个话题再发送。这里可以直接读:/status、/sessions、/stop。",
94
95
  'msg.unknownCommand': '未知命令:{cmd}。打开 /help 查看机器人支持的全部命令。',
96
+ 'msg.commandFailed': '⚠️ /{cmd} 执行失败:{err}\n不会故意留下做了一半的状态——重试前先看 /logs。',
95
97
  'msg.langSet': '界面语言已切换为中文。',
96
98
  'msg.reasoningOn': '工作记录已开启:💭 会显示在进度消息里。\n关闭:/reasoning off',
97
99
  'msg.reasoningOff': '工作记录已关闭,进度消息只保留步骤列表。\n开启:/reasoning on',
@@ -112,7 +114,7 @@ export default {
112
114
  'profile.badName': '名称只能用小写字母、数字和连字符:/profile new my-space from web',
113
115
  'profile.set': '话题配置档 → {name}({route})。下一轮生效。',
114
116
  'msg.reasoningState': '工作记录:{state}。切换:/reasoning on 或 /reasoning off。',
115
- 'prompt.reasoning': '工作记录:在每个有意义的节点——任务已清楚、原因已找到、即将改动有风险的地方、结果已验证——用 `node {say} --thought "..."` 追加一行,不超过 90 个字符。它会以 💭 出现在进度消息里:写结论,不要复述。一步就能完成的工作不必调用。当某个决定改变对方需要预期的事——版本已发布、找到原因、遇到阻塞——用一行纯文本发到聊天:`node {say} --note "..."`。聊天里只发此刻重要的内容,不是每一步。',
117
+ 'prompt.reasoning': '工作记录:每一轮在每个有意义的节点——任务已清楚、原因已找到、即将改动有风险的地方、结果已验证——用 `node {say} --thought "..."` 追加一行,不超过 90 个字符。它会以 💭 出现在进度消息里:写结论,不要复述。只有整轮只是一次工具调用时才可以跳过。当某个决定改变对方需要预期的事——版本已发布、找到原因、遇到阻塞、这一轮跑得很久——用一行纯文本发到聊天:`node {say} --note "..."`。聊天里只发此刻重要的内容,不是每一步。',
116
118
  'cmd.help.title': '命令',
117
119
  'cmd.help.hint': '发送任意文本即可开始任务。在论坛话题中:/cd <项目> 将该话题绑定到项目目录。',
118
120
  'cmd.cd.bound': '话题已绑定到项目:\n{path}\n\n之后所有操作都在此目录执行。',
package/i18n/zh/ctrl.mjs CHANGED
@@ -390,6 +390,10 @@ export default {
390
390
  'ctrl.jobs.thisTopic': '本话题',
391
391
  'ctrl.jobs.queued': '后面等待:{n}(同时最多 {max} 轮)',
392
392
  'ctrl.jobs.hint': '一轮就是一个 DSH 进程:它的后台任务随进程结束。 /stop 结束本话题的轮次。',
393
+ 'ctrl.jobs.cap': '同时运行的轮次:{n}。点下面的数字,或发送 /jobs 5。',
394
+ 'ctrl.jobs.capSet': '同时运行的轮次:{n}。已写入 config.json——下一轮开始时生效,无需重启。',
395
+ 'ctrl.jobs.capUnsaved': '同时运行的轮次:{n},仅本进程有效——config.json 未能写入,重启后会回到旧值。请看 /logs。',
396
+ 'ctrl.jobs.capRange': '数字范围 1 到 8。每个并行轮次都是一个完整的 DSH 进程,所以同一台机器上超过 8 会让所有轮次变慢,而不是变快。',
393
397
  'ctrl.remind.title': '⏰ 提醒',
394
398
  'ctrl.remind.empty': '没有安排。',
395
399
  'ctrl.remind.line': '{n}. {when}({left})— {text}',
package/jobs-cap.mjs ADDED
@@ -0,0 +1,29 @@
1
+ // The parallel-turn ceiling: one rule, two ways in.
2
+ //
3
+ // `/jobs 5` and the buttons under the `/jobs` card write the same number, and a
4
+ // tap must not be able to store a value the command would refuse. The ceiling is
5
+ // a real machine limit — every parallel turn is a whole DSH process — so the
6
+ // range is closed at eight and the refusal says why instead of clamping.
7
+ //
8
+ // The live config changes first and is persisted second: a failed write costs
9
+ // the setting after a restart, not the setting now, and the caller reports which
10
+ // of the two happened rather than claiming a save it did not make.
11
+ export const CAP_MIN = 1;
12
+ export const CAP_MAX = 8;
13
+
14
+ /** The values the card offers. Five rows of buttons is already a lot of thumb. */
15
+ export const CAP_CHOICES = [1, 2, 3, 4, 5, 8];
16
+
17
+ /**
18
+ * Apply a ceiling. Returns `{ ok:false }` for anything outside the range, and
19
+ * `{ ok:true, n, saved }` otherwise, with `saved` false when config.json could
20
+ * not be written.
21
+ */
22
+ export function setParallel(value, { config, saveConfig, log }) {
23
+ const n = Number(String(value).trim());
24
+ if (!Number.isInteger(n) || n < CAP_MIN || n > CAP_MAX) return { ok: false };
25
+ config.maxParallel = n;
26
+ const saved = Boolean(saveConfig && saveConfig());
27
+ if (log) log(`maxParallel set to ${n}${saved ? '' : ' (config.json write failed)'}`);
28
+ return { ok: true, n, saved };
29
+ }
package/notes.mjs ADDED
@@ -0,0 +1,55 @@
1
+ // Reading the 💭 notes a turn writes with `say.mjs --thought`.
2
+ //
3
+ // Two files exist for one topic and both are written in practice:
4
+ //
5
+ // <chat>_<thread>_<turn>.jsonl the turn's own file, named by the bridge and
6
+ // exported as DSH_TG_THOUGHT — unique per turn,
7
+ // so two turns in one topic never mix;
8
+ // <chat>_<thread>.jsonl the stable per-topic file, used whenever the
9
+ // tool shell lost the environment (it usually
10
+ // does) or the agent passed explicit ids.
11
+ //
12
+ // The progress card used to read only the first, so a note written through the
13
+ // second was invisible: the 💭 block stayed empty while the file on disk kept
14
+ // growing. This module reads both and keeps only the lines that belong to the
15
+ // turn being displayed — an older line from the previous turn in the same topic
16
+ // is not this turn's progress.
17
+ import { readFileSync } from 'node:fs';
18
+
19
+ /** Every note in one file, as `{ at, text }`, oldest first. Missing file = []. */
20
+ export function readNotes(file) {
21
+ try {
22
+ return readFileSync(file, 'utf8')
23
+ .split('\n')
24
+ .filter(Boolean)
25
+ .map((line) => {
26
+ try {
27
+ const row = JSON.parse(line);
28
+ const text = String(row.text || '').trim();
29
+ return text ? { at: Number(row.at) || 0, text: text.slice(0, 140) } : null;
30
+ } catch { return null; }
31
+ })
32
+ .filter(Boolean);
33
+ } catch { return []; }
34
+ }
35
+
36
+ /**
37
+ * The last `limit` note texts across `files`, written at or after `since`.
38
+ *
39
+ * `since` is the turn's start time: it is what separates "this turn said X" from
40
+ * "a previous turn in this topic said X". Notes without a timestamp are dropped
41
+ * rather than shown at the wrong moment.
42
+ */
43
+ export function recentThoughts(files, since = 0, limit = 2) {
44
+ const seen = new Set();
45
+ return files
46
+ .filter(Boolean)
47
+ .flatMap(readNotes)
48
+ .filter((row) => row.at > 0 && row.at >= since && row.text)
49
+ // The same note can sit in both files when `say.mjs` wrote to each; a
50
+ // duplicated 💭 line reads as two decisions instead of one.
51
+ .filter((row) => (seen.has(`${row.at}:${row.text}`) ? false : seen.add(`${row.at}:${row.text}`)))
52
+ .sort((a, b) => a.at - b.at)
53
+ .slice(-limit)
54
+ .map((row) => row.text);
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.21.1",
3
+ "version": "1.23.0",
4
4
  "description": "Telegram bridge for DeepSeek Harness: text, voice, photos and project-per-topic sessions without opening the desktop app",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
@@ -54,6 +54,7 @@
54
54
  "keys.mjs",
55
55
  "keyboards.mjs",
56
56
  "progress.mjs",
57
+ "notes.mjs",
57
58
  "turn.mjs",
58
59
  "control.mjs",
59
60
  "control/release.mjs",
@@ -141,6 +142,7 @@
141
142
  "handle-message.mjs",
142
143
  "callbacks.mjs",
143
144
  "run-command.mjs",
145
+ "jobs-cap.mjs",
144
146
  "job-loops.mjs"
145
147
  ],
146
148
  "homepage": "https://github.com/aleksvega/dsh-tg-bridge#readme",
package/progress.mjs CHANGED
@@ -14,6 +14,7 @@ import { tg } from './telegram.mjs';
14
14
  import { topicName } from './topics.mjs';
15
15
  import { t } from './i18n.mjs';
16
16
  import { addStep, progressPanel, stepLine } from './panel.mjs';
17
+ import { recentThoughts } from './notes.mjs';
17
18
  import { continueKeyboard, errorKeyboard } from './keyboards.mjs';
18
19
 
19
20
  /**
@@ -60,26 +61,27 @@ export async function startProgress(chatId, threadId, lang = config.lang || 'en'
60
61
  // message shows the last two, so the person sees the decision trail without
61
62
  // a second stream of chat messages. The path is unique per turn (see
62
63
  // startTurn) so two turns never share one file.
64
+ //
65
+ // Two writers exist and they do not agree on the path. The turn's own file
66
+ // (`DSH_TG_THOUGHT`) is only reachable when the tool shell inherits the
67
+ // bridge's environment, and tool shells usually do not — so `say.mjs` falls
68
+ // back to the stable per-topic file. Reading only the first path silently
69
+ // dropped every note: the 💭 block stayed empty for a whole session while the
70
+ // topic file on disk kept growing. Read both, keep this turn's lines only.
63
71
  const notes = thoughtFile || join(THOUGHT_DIR, `${chatId}_${threadId || 0}.jsonl`);
72
+ const topicNotes = join(THOUGHT_DIR, `${chatId}_${threadId || 0}.jsonl`);
64
73
  let thoughts = [];
65
74
  try {
66
75
  mkdirSync(THOUGHT_DIR, { recursive: true });
67
- writeFileSync(notes, '');
76
+ // Start this turn's file empty — but never truncate the stable per-topic
77
+ // file, which is shared history and the only record when a turn wrote
78
+ // through the fallback path.
79
+ if (thoughtFile) writeFileSync(notes, '');
68
80
  } catch {}
69
81
  const thoughtTimer = setInterval(() => {
70
- let next = [];
71
- try {
72
- next = readFileSync(notes, 'utf8')
73
- .split('\n')
74
- .filter(Boolean)
75
- .slice(-2)
76
- .map((line) => {
77
- try { return String(JSON.parse(line).text || '').slice(0, 140); } catch { return ''; }
78
- })
79
- .filter(Boolean);
80
- } catch {}
81
- if (next.join('\n') !== thoughts.join('\n')) {
82
- thoughts = next;
82
+ const merged = recentThoughts([notes, topicNotes], started);
83
+ if (merged.join('\n') !== thoughts.join('\n')) {
84
+ thoughts = merged;
83
85
  schedule();
84
86
  }
85
87
  }, 3000);
package/queue.mjs CHANGED
@@ -11,9 +11,9 @@ import { langFor } from './commands.mjs';
11
11
  import { resolveLang, t } from './i18n.mjs';
12
12
  import { sessionKey, threadOf } from './keys.mjs';
13
13
  import { RESTART_MARKER } from './paths.mjs';
14
- import { config, log, state } from './state.mjs';
15
- import { clearBusyNotice, steerAvailable, steerMediaMessage } from './steer.mjs';
16
- import { tg } from './telegram.mjs';
14
+ import { config, log, saveConfig, state } from './state.mjs';
15
+ import { busyNotices, clearBusyNotice, steerAvailable, steerMediaMessage } from './steer.mjs';
16
+ import { send, tg } from './telegram.mjs';
17
17
  import { liveSessions, profileOf, turnStartedAt } from './turn.mjs';
18
18
 
19
19
  /** The message handler is wired in by the entry module: it owns the turn. */
@@ -21,16 +21,31 @@ let handle = () => { throw new Error('queue: message handler is not wired'); };
21
21
  export function setMessageHandler(fn) { handle = fn; }
22
22
 
23
23
  /** A steer that outlived its turn becomes a turn of its own. */
24
- const redeliver = (key, message) => enqueue(key, () => handle(message));
24
+ export const redeliver = (key, message) => enqueue(key, () => handle(message));
25
25
  // Per-topic turn queues: one turn at a time inside a topic, different topics run
26
26
  // in parallel. Bounded, because every turn is a full Electron process.
27
27
  export const queues = new Map();
28
28
  export const waiting = [];
29
29
  export let running = 0;
30
+ /** Default cap; `config.maxParallel` overrides it for one install. */
30
31
  export const MAX_PARALLEL = 3;
31
32
 
33
+ /**
34
+ * How many turns may run at once.
35
+ *
36
+ * Three was a guess that fit a small machine, and it is a real ceiling: with
37
+ * three long turns in flight a fourth topic waited with no message at all, so a
38
+ * prompt in a fresh topic looked exactly like a dead bot. The number is a
39
+ * setting now, and waiting for a slot is announced (see `enqueue`).
40
+ */
41
+ export function maxParallel() {
42
+ const raw = Number(config?.maxParallel);
43
+ if (!Number.isFinite(raw)) return MAX_PARALLEL;
44
+ return Math.min(8, Math.max(1, Math.round(raw)));
45
+ }
46
+
32
47
  export function acquire() {
33
- if (running < MAX_PARALLEL) {
48
+ if (running < maxParallel()) {
34
49
  running += 1;
35
50
  return Promise.resolve();
36
51
  }
@@ -112,7 +127,21 @@ export function enqueue(key, task, onBusy) {
112
127
  const prev = queues.get(key) || Promise.resolve();
113
128
  const queued = queues.has(key);
114
129
  const run = prev
115
- .then(() => acquire())
130
+ .then(() => {
131
+ // A turn waiting for a free slot used to wait in total silence: with three
132
+ // long turns running, a prompt in a fourth topic showed nothing at all —
133
+ // not even "queued" — so the bot looked dead in that topic. Say it once,
134
+ // in the topic that is waiting; `clearBusyNotice` removes it when the turn
135
+ // actually starts.
136
+ if (!queued && running >= maxParallel()) {
137
+ const [chatId, threadId] = String(key).split(':');
138
+ const lang = resolveLang(state, key, null, config);
139
+ Promise.resolve(send(chatId, t(lang, 'msg.slotWait', { max: maxParallel() }), Number(threadId) || 0))
140
+ .then((messageId) => { if (messageId) busyNotices.set(key, { chatId, messageId }); })
141
+ .catch(() => {});
142
+ }
143
+ return acquire();
144
+ })
116
145
  .then(async () => {
117
146
  // The person was told "your message is queued"; that notice has done its
118
147
  // job the moment the turn starts and must not linger in the chat.
package/run-command.mjs CHANGED
@@ -3,8 +3,8 @@
3
3
  import { langFor } from './commands.mjs';
4
4
  import { handleControl } from './control.mjs';
5
5
  import { t } from './i18n.mjs';
6
- import { MAX_PARALLEL } from './queue.mjs';
7
- import { config, log, saveState, state } from './state.mjs';
6
+ import { maxParallel, queues } from './queue.mjs';
7
+ import { config, log, saveConfig, saveState, state } from './state.mjs';
8
8
  import { send, sendEphemeral, sendFile, sendWithMarkup, tg } from './telegram.mjs';
9
9
  import { ensureTopicSeed } from './topics.mjs';
10
10
  import { activeTurns, profileOf, turnStartedAt } from './turn.mjs';
@@ -25,12 +25,13 @@ export async function runCommandFromButton(typed, { chatId, threadId, key }) {
25
25
  config,
26
26
  activeTurns,
27
27
  saveState,
28
+ saveConfig,
28
29
  log,
29
30
  send,
30
31
  jobs: () => ({
31
32
  active: [...activeTurns.keys()].map((topic) => ({ key: topic, startedAt: turnStartedAt.get(topic) || 0 })),
32
33
  queued: [...queues.keys()].filter((topic) => !activeTurns.has(topic)).length,
33
- max: MAX_PARALLEL,
34
+ max: maxParallel(),
34
35
  }),
35
36
  api: tg,
36
37
  sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
package/say.mjs CHANGED
@@ -123,7 +123,16 @@ async function main() {
123
123
  if (args.thought) {
124
124
  try {
125
125
  mkdirSync(THOUGHTS, { recursive: true });
126
- const file = join(THOUGHTS, `${chatId}_${threadId || 0}.jsonl`);
126
+ // The turn's own file when the bridge exported one: two turns in the same
127
+ // topic then never mix, and the panel reads that file directly. The stable
128
+ // per-topic name stays the fallback for a shell that lost the env, and the
129
+ // panel reads both — so a note never lands in a file nobody reads, which
130
+ // 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`);
127
136
  appendFileSync(file, `${JSON.stringify({ at: Date.now(), text: args.text })}\n`, 'utf8');
128
137
  console.log(file);
129
138
  } catch (error) {
package/state.mjs CHANGED
@@ -76,6 +76,28 @@ export function saveDone() {
76
76
  }
77
77
  }
78
78
 
79
+ /**
80
+ * Write config.json back.
81
+ *
82
+ * Only for a setting the owner changed from the chat: `config` is the live
83
+ * object every module reads, so mutating it first and persisting second means a
84
+ * failed write costs the restart, not the current setting. Re-reads the file so
85
+ * keys written by hand (tokens, profiles) are not dropped by a stale copy.
86
+ */
87
+ export function saveConfig() {
88
+ try {
89
+ let onDisk = {};
90
+ try {
91
+ onDisk = JSON.parse(readFileSync(join(DIR, 'config.json'), 'utf8').replace(/^\uFEFF/, ''));
92
+ } catch {}
93
+ writeAtomic(join(DIR, 'config.json'), `${JSON.stringify({ ...onDisk, ...config }, null, 2)}\n`);
94
+ return true;
95
+ } catch (error) {
96
+ log(`config.json write failed: ${error.message}`);
97
+ return false;
98
+ }
99
+ }
100
+
79
101
  export function pendingPath(updateId) {
80
102
  return join(PENDING_DIR, `${updateId}.json`);
81
103
  }
@@ -127,7 +149,10 @@ export function pendingUpdates() {
127
149
  continue;
128
150
  }
129
151
  try {
130
- out.push({ update: JSON.parse(readFileSync(full, 'utf8')), id });
152
+ // `at` is the moment the update arrived, which is what the replay loop
153
+ // needs to tell "this was mid-flight when we died" from "this has been
154
+ // sitting here for hours and the person has long since moved on".
155
+ out.push({ update: JSON.parse(readFileSync(full, 'utf8')), id, at: stat.mtimeMs });
131
156
  } catch {
132
157
  try { unlinkSync(full); } catch {}
133
158
  }
package/steer.mjs CHANGED
@@ -13,7 +13,7 @@ import { config, log, state } from './state.mjs';
13
13
  import { resolveLang, t } from './i18n.mjs';
14
14
  import { sessionKey } from './keys.mjs';
15
15
  import { activeTurns } from './turn.mjs';
16
- import { send } from './telegram.mjs';
16
+ import { send, tg } from './telegram.mjs';
17
17
  import { mediaPrompt } from './media.mjs';
18
18
  /**
19
19
  * Queue notices, one per topic. A notice exists only while the person is
package/telegram.mjs CHANGED
@@ -84,6 +84,40 @@ export async function downloadFile(fileId, fileName) {
84
84
  * shapes a person can end up with, so every call site hands its intent here
85
85
  * instead of building `reply_markup` itself.
86
86
  */
87
+ /**
88
+ * Rows of buttons, in the one shape Telegram accepts.
89
+ *
90
+ * The cards build buttons as `{ text, data }` — a payload, not a Telegram field,
91
+ * because the card does not know or care where it will be drawn. Telegram wants
92
+ * `callback_data` and rejects the *whole message* with "Text buttons are not
93
+ * allowed in the inline keyboard" when it sees `data` instead. That rejection was
94
+ * swallowed by the `.catch(() => {})` on every send, so `/menu`, `/settings` and
95
+ * the task card drew nothing at all and said nothing about it.
96
+ *
97
+ * One conversion here, at the edge, so a card can keep its own vocabulary.
98
+ */
99
+ export function inlineKeyboard(rows) {
100
+ if (!Array.isArray(rows)) return rows;
101
+ const out = [];
102
+ for (const row of rows) {
103
+ if (!Array.isArray(row)) { out.push(row); continue; }
104
+ const buttons = [];
105
+ for (const button of row) {
106
+ if (!button || typeof button !== 'object') { buttons.push(button); continue; }
107
+ const { data, ...rest } = button;
108
+ const payload = rest.callback_data ?? rest.url ?? rest.web_app ?? data;
109
+ // A button with neither a payload nor a link is a label Telegram refuses —
110
+ // and it refuses the whole message, not the button.
111
+ if (payload === undefined) continue;
112
+ buttons.push(rest.callback_data !== undefined || rest.url !== undefined || rest.web_app !== undefined
113
+ ? rest
114
+ : { ...rest, callback_data: String(payload) });
115
+ }
116
+ if (buttons.length > 0) out.push(buttons);
117
+ }
118
+ return out;
119
+ }
120
+
87
121
  export async function sendWithMarkup(chatId, threadId, text, extra = {}) {
88
122
  const thread = threadId > 0 ? { message_thread_id: threadId } : {};
89
123
  if (extra.removeKeyboard) {
@@ -107,9 +141,15 @@ export async function sendWithMarkup(chatId, threadId, text, extra = {}) {
107
141
  chat_id: chatId,
108
142
  text,
109
143
  disable_web_page_preview: true,
110
- reply_markup: { inline_keyboard: extra.keyboard },
144
+ reply_markup: { inline_keyboard: inlineKeyboard(extra.keyboard) },
111
145
  ...thread,
112
- }).catch(() => {});
146
+ }).catch((error) => {
147
+ // Silence here cost a release: the card never appeared and the log said
148
+ // nothing. A keyboard Telegram refuses is a bug in this repo, so say which
149
+ // button it was and still deliver the text without buttons.
150
+ log(`inline keyboard rejected (${String(error.message).slice(0, 160)}); sending without buttons`);
151
+ return tg('sendMessage', { chat_id: chatId, text, disable_web_page_preview: true, ...thread }).catch(() => {});
152
+ });
113
153
  }
114
154
  return send(chatId, text, threadId);
115
155
  }