dsh-tg-bridge 1.47.1 → 1.49.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.
Files changed (66) hide show
  1. package/chat/branch-press.mjs +47 -0
  2. package/chat/callbacks.mjs +3 -0
  3. package/chat/commands-registry.mjs +3 -3
  4. package/chat/file-press.mjs +28 -1
  5. package/chat/handle-message.mjs +4 -4
  6. package/chat/help-explain.mjs +37 -2
  7. package/chat/help-sections.mjs +3 -3
  8. package/chat/media-text.mjs +6 -1
  9. package/chat/menu-card.mjs +6 -3
  10. package/chat/panel.mjs +13 -1
  11. package/chat/topics.mjs +45 -0
  12. package/control/agents.mjs +99 -4
  13. package/control/cmd-balance.mjs +89 -0
  14. package/control/cmd-model.mjs +15 -5
  15. package/control/cmd-session.mjs +110 -9
  16. package/control/cmd-skills.mjs +56 -2
  17. package/control/cmd-views.mjs +7 -0
  18. package/control/model-card.mjs +6 -2
  19. package/control/models.mjs +36 -1
  20. package/control/sessions.mjs +30 -10
  21. package/core/run-command.mjs +4 -3
  22. package/docs/CHANGELOG.md +118 -0
  23. package/docs/COMMANDS.md +15 -3
  24. package/docs/MARKETPLACE.md +24 -0
  25. package/i18n/en/balance.mjs +12 -0
  26. package/i18n/en/branch.mjs +19 -0
  27. package/i18n/en/core.mjs +5 -1
  28. package/i18n/en/ctrl.mjs +499 -498
  29. package/i18n/en/files.mjs +9 -0
  30. package/i18n/en/history.mjs +17 -0
  31. package/i18n/en/model.mjs +1 -0
  32. package/i18n/en/remember.mjs +17 -0
  33. package/i18n/en.mjs +6 -1
  34. package/i18n/ru/balance.mjs +12 -0
  35. package/i18n/ru/branch.mjs +19 -0
  36. package/i18n/ru/core.mjs +5 -1
  37. package/i18n/ru/ctrl.mjs +499 -498
  38. package/i18n/ru/files.mjs +9 -0
  39. package/i18n/ru/history.mjs +17 -0
  40. package/i18n/ru/model.mjs +1 -0
  41. package/i18n/ru/remember.mjs +17 -0
  42. package/i18n/ru.mjs +6 -1
  43. package/i18n/zh/balance.mjs +12 -0
  44. package/i18n/zh/branch.mjs +19 -0
  45. package/i18n/zh/core.mjs +6 -2
  46. package/i18n/zh/ctrl.mjs +499 -498
  47. package/i18n/zh/files.mjs +9 -0
  48. package/i18n/zh/history.mjs +17 -0
  49. package/i18n/zh/model.mjs +1 -0
  50. package/i18n/zh/remember.mjs +17 -0
  51. package/i18n/zh.mjs +6 -1
  52. package/model/balance.mjs +102 -0
  53. package/model/fallback.mjs +28 -1
  54. package/package.json +1 -1
  55. package/plugin-bridge.mjs +6 -0
  56. package/profile/agents.mjs +54 -0
  57. package/profile/profiles.mjs +19 -1
  58. package/turn/failures.mjs +6 -0
  59. package/turn/files.mjs +95 -0
  60. package/turn/progress.mjs +51 -27
  61. package/turn/task-arg.mjs +27 -0
  62. package/turn/turn.mjs +7 -1
  63. package/work/branch-buttons.mjs +65 -0
  64. package/work/history.mjs +42 -0
  65. package/work/rewind-card.mjs +8 -0
  66. package/work/rewind.mjs +23 -0
@@ -0,0 +1,47 @@
1
+ // The 🌿 picker's router half. Kept out of the callback router because the
2
+ // router sits at the size ceiling, and because the picker is one idea: a
3
+ // press names a turn, the plan is rebuilt from the live session, and the
4
+ // action types the very command that does the work — `/fork` and
5
+ // `/branch new` stay the only implementations of a branch.
6
+ import { answerBranchPress, isBranchPress } from '../work/branch-buttons.mjs';
7
+ import { t } from '../core/i18n.mjs';
8
+ import { DSH_HOME } from '../core/paths.mjs';
9
+ import { state } from '../core/state.mjs';
10
+ import { tg } from './telegram.mjs';
11
+ import { sessionFile } from './thoughts.mjs';
12
+ import { activeTurns } from '../turn/turn.mjs';
13
+ import { join } from 'node:path';
14
+
15
+ /**
16
+ * Handle one `bf:` press.
17
+ *
18
+ * @returns {Promise<boolean>} true when the press was this module's to answer.
19
+ */
20
+ export async function handleBranchPress({ data, key, lang, chatId, threadId, messageId, answer, clearKeyboard, runCommandFromButton, log }) {
21
+ if (!isBranchPress(data)) return false;
22
+ const sessionId = state.sessions[key] || '';
23
+ const sessionPath = sessionId ? sessionFile(join(DSH_HOME, 'sessions'), sessionId) : '';
24
+ const done = answerBranchPress(data, {
25
+ t: (k, vars) => t(lang, k, vars),
26
+ ctx: { sessionId, busy: activeTurns.has(key), file: sessionPath },
27
+ });
28
+ if (done.command) {
29
+ await clearKeyboard();
30
+ await answer(t(lang, 'bridge.cb.done'));
31
+ await runCommandFromButton(done.command, { chatId, threadId, key, lang });
32
+ } else {
33
+ // Either a confirm card replaces the picker, or one line replaces it —
34
+ // a refused press leaves nothing clickable behind.
35
+ const card = done.card || { text: done.line, keyboard: [] };
36
+ await tg('editMessageText', {
37
+ chat_id: chatId,
38
+ message_id: messageId,
39
+ text: card.text,
40
+ reply_markup: { inline_keyboard: card.keyboard },
41
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
42
+ }).catch(() => {});
43
+ await answer(t(lang, 'bridge.cb.done'));
44
+ }
45
+ log(`branch press ${data} for ${key}`);
46
+ return true;
47
+ }
@@ -11,6 +11,7 @@ import { sessionKey } from '../core/keys.mjs';
11
11
  import { commandForName, isMenuPress, menuTarget, renderPanel, runsUnasked } from './menu-card.mjs';
12
12
  import { DSH_HOME, LOG } from '../core/paths.mjs';
13
13
  import { approvals, enqueue, lastPrompt, redeliver, rewindUsed } from '../turn/queue.mjs';
14
+ import { handleBranchPress } from './branch-press.mjs';
14
15
  import { answerRewindPress, cutSession, isRewindPress } from '../work/rewind-buttons.mjs';
15
16
  import { applyRewind, newestBackup, restoreBackup } from '../work/rewind.mjs';
16
17
  import { diffPressRouter } from '../control/cmd-diff.mjs';
@@ -177,6 +178,8 @@ export async function handleCallback(query) {
177
178
  return;
178
179
  }
179
180
 
181
+ if (await handleBranchPress({ data, key, lang, chatId, threadId, messageId, answer, clearKeyboard, runCommandFromButton, log })) return;
182
+
180
183
  // A search result's plus button. The name came from the registry and the
181
184
  // command is the one the hint under the list names, so a tap installs exactly
182
185
  // what was read — no hidden second path into pnpm.
@@ -16,10 +16,10 @@ export const EXTERNAL_COMMANDS = ['setinline'];
16
16
  export const CONTROL_COMMANDS = [
17
17
  'status', 'models', 'model', 'effort', 'profile', 'agents', 'preset', 'permissions', 'plan',
18
18
  'jobs', 'remind', 'every', 'sessions', 'resume', 'plugins', 'plugin', 'mcp',
19
- 'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
20
- 'prices', 'cost', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
19
+ 'skills', 'soul', 'remember', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
20
+ 'prices', 'cost', 'balance', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'pin', 'goal', 'task', 'tasks',
21
21
  'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
22
- 'rewind', 'fork', 'branches', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card', 'find', 'start',
22
+ 'rewind', 'fork', 'branches', 'branch', 'history', 'menu', 'fallback', 'load', 'diff', 'endpoint', 'dsh', 'compact', 'card', 'find', 'start',
23
23
  'ls', 'view', 'edit', 'subagents',
24
24
  ];
25
25
 
@@ -8,7 +8,7 @@ import { previewWindow } from './file-preview.mjs';
8
8
  import { listDir, listingCard } from './file-listing.mjs';
9
9
  import { t } from '../core/i18n.mjs';
10
10
  import { saveState, state } from '../core/state.mjs';
11
- import { inlineKeyboard, tg } from './telegram.mjs';
11
+ import { inlineKeyboard, sendFile, tg } from './telegram.mjs';
12
12
 
13
13
  /**
14
14
  * Handle one `fs:` or `fv:` press.
@@ -16,6 +16,9 @@ import { inlineKeyboard, tg } from './telegram.mjs';
16
16
  * @returns {Promise<boolean>} true when the press was this module's to answer.
17
17
  */
18
18
  export async function handleFilePress({ data, key, lang, chatId, threadId, messageId, answer }) {
19
+ if (String(data || '').startsWith('tf:')) {
20
+ return sendTurnFile({ index: Number(String(data).slice(3)) || 0, key, lang, chatId, threadId, answer });
21
+ }
19
22
  if (String(data || '').startsWith('fv:')) {
20
23
  return pressEntry({ data: String(data).slice(3), key, lang, chatId, threadId, messageId, answer });
21
24
  }
@@ -71,6 +74,30 @@ export async function handleFilePress({ data, key, lang, chatId, threadId, messa
71
74
  return true;
72
75
  }
73
76
 
77
+ /**
78
+ * An `tf:` press: send one file the finished turn wrote, as a document.
79
+ *
80
+ * The row comes from `state.turnFiles`, written when the card was drawn, so the
81
+ * button can only send something that turn actually produced. A newer turn
82
+ * replaces the list; a press on the old card then finds no row and answers
83
+ * "stale" instead of sending whatever moved into that slot.
84
+ */
85
+ async function sendTurnFile({ index, key, lang, chatId, threadId, answer }) {
86
+ const rows = state.turnFiles?.[key];
87
+ const row = rows?.[index];
88
+ if (!row) {
89
+ await answer(t(lang, 'card.files.stale'));
90
+ return true;
91
+ }
92
+ try {
93
+ await sendFile(chatId, threadId, row.path, row.name);
94
+ await answer(t(lang, 'card.files.sent', { name: row.name }));
95
+ } catch (error) {
96
+ await answer(t(lang, 'card.files.failed', { err: String(error.message).slice(0, 80) }));
97
+ }
98
+ return true;
99
+ }
100
+
74
101
  /** A `/ls` row pressed: walk into a folder, or open the file it named. */
75
102
  async function pressEntry({ data, key, lang, chatId, threadId, messageId, answer }) {
76
103
  const cur = state.listing?.[key];
@@ -30,11 +30,11 @@ import { rememberRuns } from '../work/subagents.mjs';
30
30
  import { reportRefusals } from '../profile/sandbox-note.mjs';
31
31
  import { noteTurn } from '../core/stability.mjs';
32
32
  import { makeTurnEvents, newTelemetry, noteAnswered } from '../turn/turn-events.mjs';
33
- import { lastPrompt, maxParallel, queues } from '../turn/queue.mjs';
33
+ import { lastPrompt, maxParallel, queues, redeliver } from '../turn/queue.mjs';
34
34
  import { token } from '../core/secrets.mjs';
35
35
  import { config, done, log, saveConfig, saveState, state } from '../core/state.mjs';
36
36
  import { send, sendEphemeral, sendFile, sendWithMarkup, tg } from './telegram.mjs';
37
- import { ensureTopicSeed, logTopicToGeneral, newestBoundTopic, startTopicFromMessage, topicName, topicSeeded, topicSeededRecently, touchTopic } from './topics.mjs';
37
+ import { ensureTopicSeed, logTopicToGeneral, newestBoundTopic, openBranchTopic, startTopicFromMessage, topicName, topicSeeded, topicSeededRecently, touchTopic } from './topics.mjs';
38
38
  import { activeTurns, killTurn, liveSessions, profileOf, runTurnLive, turnAttempt, turnStartedAt, typingLoop } from '../turn/turn.mjs';
39
39
  import { join } from 'node:path';
40
40
  import { existsSync } from 'node:fs';
@@ -246,9 +246,9 @@ ${helpLines((k, vars) => t(lang, k, vars)).join('\n')}`,
246
246
  queued: [...queues.keys()].filter((topic) => !activeTurns.has(topic)).length,
247
247
  max: maxParallel(),
248
248
  }),
249
- api: tg,
249
+ api: tg, redeliver,
250
250
  sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
251
- seedTopic: ensureTopicSeed,
251
+ seedTopic: ensureTopicSeed, openTopic: openBranchTopic,
252
252
  profile: profileOf(key),
253
253
  prices: (filter) => {
254
254
  const route = modelOf(profileOf(key));
@@ -6,10 +6,39 @@
6
6
  // `Models:` line, so every question about a command without an entry of its own
7
7
  // answered with a heading and nothing under it. Now both come from the same
8
8
  // table: the section says which commands it holds, and the answer quotes it.
9
- import { COMMAND_ALIASES, CONTROL_COMMANDS } from './commands-registry.mjs';
9
+ import { COMMAND_ALIASES, CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from './commands-registry.mjs';
10
10
  import { commandsOf, DOC_URL, sectionFor } from './help-sections.mjs';
11
11
  import { t } from '../core/i18n.mjs';
12
12
 
13
+ /** How many commands a word search may list before it stops being an answer. */
14
+ const SEARCH_LIMIT = 3;
15
+
16
+ /** A CJK word is two characters where a Latin one needs three. */
17
+ const CJK = /[\u3400-\u9fff\uf900-\ufaff]/;
18
+
19
+ /**
20
+ * Commands whose own sentence mentions this word.
21
+ *
22
+ * `/help ветка` answered "no command /ветка" while the sentence explaining
23
+ * branching sat one line away: the lookup matched command names only. The
24
+ * sentences are the bot's own text in the chat's language, so searching them
25
+ * searches what the person would read. Three characters is the floor — a shorter
26
+ * word matches half the list and answers nothing — and two for a CJK word, where
27
+ * two characters are a word and not a fragment.
28
+ */
29
+ export function findCommands(word, lang, t) {
30
+ const needle = String(word || '').trim().toLowerCase();
31
+ if (needle.length < (CJK.test(needle) ? 2 : 3)) return [];
32
+ const hits = [];
33
+ for (const name of DOCUMENTED_COMMANDS) {
34
+ const about = String(t(lang, `ctrl.help.about.${name}`) || '');
35
+ if (about.startsWith('ctrl.help.about.')) continue;
36
+ if (about.toLowerCase().includes(needle)) hits.push(name);
37
+ if (hits.length >= SEARCH_LIMIT) break;
38
+ }
39
+ return hits;
40
+ }
41
+
13
42
  /**
14
43
  * The explanation for one command, or '' when there is no such command.
15
44
  * A command with a sentence of its own gets it; the rest get the line from
@@ -17,7 +46,13 @@ import { t } from '../core/i18n.mjs';
17
46
  */
18
47
  export function explainCommand(name, lang, t) {
19
48
  const typed = String(name || '').trim().toLowerCase().replace(/^\//, '');
20
- if (!CONTROL_COMMANDS.includes(typed)) return '';
49
+ if (!CONTROL_COMMANDS.includes(typed)) {
50
+ // Not a name — but it may be the word somebody actually has in mind.
51
+ const hits = findCommands(typed, lang, t);
52
+ if (!hits.length) return '';
53
+ const body = hits.map((hit) => `/${hit} — ${t(lang, `ctrl.help.about.${hit}`)}`).join('\n\n');
54
+ return `${t(lang, 'help.found', { word: typed })}\n\n${body}`;
55
+ }
21
56
  // An old spelling answers as the command that owns the job. Saying "that one
22
57
  // is the same as /task" would teach the alias back, which is the confusion
23
58
  // this file exists to end.
@@ -20,11 +20,11 @@ export const DOC_URL = 'https://github.com/aleksvega/dsh-tg-bridge/blob/master/d
20
20
  export const HELP_SECTIONS = [
21
21
  { id: 'work', commands: ['start', 'cd', 'ls', 'view', 'edit', 'new', 'stop', 'send', 'seed', 'diff', 'find'] },
22
22
  { id: 'goals', commands: ['goal', 'tasks'] },
23
- { id: 'sessions', commands: ['status', 'sessions', 'rewind', 'profile', 'compact', 'card'] },
24
- { id: 'model', commands: ['model', 'effort', 'prices', 'cost', 'thoughts', 'fallback', 'endpoint', 'load'] },
23
+ { id: 'sessions', commands: ['status', 'sessions', 'rewind', 'branch', 'history', 'profile', 'compact', 'card'] },
24
+ { id: 'model', commands: ['model', 'effort', 'prices', 'cost', 'balance', 'thoughts', 'fallback', 'endpoint', 'load'] },
25
25
  { id: 'agents', commands: ['agents', 'crew', 'subagents', 'preset', 'plan', 'permissions'] },
26
26
  { id: 'tuning', commands: ['jobs', 'remind', 'every'] },
27
- { id: 'extensions', commands: ['skills', 'plugins', 'mcp', 'soul'] },
27
+ { id: 'extensions', commands: ['skills', 'plugins', 'mcp', 'soul', 'remember'] },
28
28
  { id: 'versions', commands: ['update', 'subscribe', 'dsh'] },
29
29
  { id: 'settings', commands: ['settings', 'lang', 'reasoning', 'pin'] },
30
30
  { id: 'panels', commands: ['menu', 'help'] },
@@ -12,7 +12,12 @@ export const TEXTUAL_EXT = new Set([
12
12
  'bat', 'cmd', 'sql', 'env', 'properties', 'srt', 'vtt', 'diff', 'patch',
13
13
  ]);
14
14
 
15
- export const INLINE_LIMIT = 60_000;
15
+ // Two attached documents at the old 60 000-char cap made one 72 000-char
16
+ // prompt, and the OS refused to launch the turn at all: the task travels on
17
+ // the command line, and Windows cuts that at 32 767. An excerpt of a few
18
+ // kilobytes is still a whole screen of steer context, and the full file
19
+ // waits on disk with its path already in the message.
20
+ export const INLINE_LIMIT = 8_000;
16
21
 
17
22
  /**
18
23
  * Text body of a small text file, or '' when the file is not worth inlining.
@@ -16,10 +16,10 @@ import { CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from './commands-registry.mjs';
16
16
  */
17
17
  const SECTIONS = {
18
18
  work: ['cd', 'ls', 'view', 'edit', 'seed', 'send', 'diff'],
19
- session: ['sessions', 'rewind', 'profile', 'agents', 'subagents'],
19
+ session: ['sessions', 'rewind', 'branch', 'history', 'profile', 'agents', 'subagents'],
20
20
  goals: ['goal', 'task', 'tasks', 'plan', 'jobs', 'remind', 'every'],
21
- talk: ['effort', 'reasoning', 'pin', 'thoughts', 'prices', 'cost', 'lang', 'endpoint', 'fallback'],
22
- ext: ['plugins', 'mcp', 'skills', 'soul', 'preset', 'permissions', 'crew'],
21
+ talk: ['effort', 'reasoning', 'pin', 'thoughts', 'prices', 'cost', 'balance', 'lang', 'endpoint', 'fallback'],
22
+ ext: ['plugins', 'mcp', 'skills', 'soul', 'remember', 'preset', 'permissions', 'crew'],
23
23
  house: ['load', 'settings', 'card', 'find', 'update', 'dsh', 'compact', 'subscribe', 'doctor', 'logs', 'report', 'restart', 'app', 'start', 'help'],
24
24
  };
25
25
 
@@ -63,6 +63,7 @@ const LABELS = {
63
63
  stop: '/stop',
64
64
  sessions: '/sessions [<id>]',
65
65
  rewind: '/rewind [n|fork|branches]',
66
+ branch: '/branch [<id>|new]',
66
67
  profile: '/profile <name>',
67
68
  agents: '/agents',
68
69
  goal: '/goal <text>',
@@ -77,6 +78,7 @@ const LABELS = {
77
78
  reasoning: '/reasoning ▸ this topic',
78
79
  thoughts: '/thoughts',
79
80
  prices: '/prices',
81
+ balance: '/balance',
80
82
  fallback: '/fallback',
81
83
  endpoint: '/endpoint [list|add|rm]',
82
84
  lang: '/lang en|ru|zh',
@@ -84,6 +86,7 @@ const LABELS = {
84
86
  mcp: '/mcp add|rm',
85
87
  skills: '/skills',
86
88
  soul: '/soul',
89
+ remember: '/remember <fact>',
87
90
  preset: '/preset <id>',
88
91
  permissions: '/permissions',
89
92
  crew: '/crew use <id>',
package/chat/panel.mjs CHANGED
@@ -216,6 +216,11 @@ export function progressPanel({
216
216
  // `null` means "no choice recorded", and the card keeps every block — the
217
217
  // shape it had before `/card` existed, so an old topic does not shrink.
218
218
  blocks = null,
219
+ // Files this turn wrote, already rendered as rows by `turn/files.mjs`, plus a
220
+ // notice when there were more than the card carries. They are buttons, not
221
+ // lines: the whole point is one tap from "готово" to the document in hand.
222
+ files = [],
223
+ moreFiles = '',
219
224
  } = {}) {
220
225
  const on = (id) => !blocks || blocks.has(id);
221
226
  const snippet = String(task).replace(/\s+/g, ' ').trim().slice(0, 48);
@@ -234,7 +239,12 @@ export function progressPanel({
234
239
  const ctx = on('context') ? String(context || '').trim() : '';
235
240
  const paid = on('cost') ? String(money || '').trim() : '';
236
241
  const cacheLine = on('cache') ? cache : '';
237
- const base = [head, ...mind, ctx, paid, cacheLine].filter(Boolean).join('\n').length;
242
+ // One line, not a list: the files themselves are the buttons underneath, and a
243
+ // row of names above them would say the same thing twice.
244
+ const attached = final && files.length
245
+ ? `📎 ${t(lang, 'card.files.line', { n: files.length })}${moreFiles ? ` · ${moreFiles}` : ''}`
246
+ : '';
247
+ const base = [head, ...mind, ctx, paid, cacheLine, attached].filter(Boolean).join('\n').length;
238
248
 
239
249
  // While the turn runs this message is rewritten every few seconds, and
240
250
  // Telegram drops an expanded block on every edit — which is what yanks the
@@ -282,6 +292,7 @@ export function progressPanel({
282
292
  escapeHtml(paid),
283
293
  all.text ? `<blockquote expandable>${escapeHtml(stepsLabel)}\n${escapeHtml(all.text)}</blockquote>` : '',
284
294
  escapeHtml(cacheLine),
295
+ escapeHtml(attached),
285
296
  ].filter(Boolean).join('\n');
286
297
  const plain = [
287
298
  head,
@@ -294,6 +305,7 @@ export function progressPanel({
294
305
  paid,
295
306
  all.text ? `${stepsLabel}\n${all.text}` : '',
296
307
  cacheLine,
308
+ attached,
297
309
  ].filter(Boolean).join('\n');
298
310
  return { html, plain };
299
311
  }
package/chat/topics.mjs CHANGED
@@ -213,6 +213,51 @@ export async function startTopicFromMessage(chatId, msg, text) {
213
213
  return threadId;
214
214
  }
215
215
 
216
+ /**
217
+ * Open a new topic that starts from a copy of another one, and seed it.
218
+ *
219
+ * `/branch new` from inside a topic: the person wants the same work in a place
220
+ * of its own, without the new conversation landing in the topic they were
221
+ * reading. The copy of the session is made by the caller before this runs — a
222
+ * topic that opens onto nothing is a worse failure than a copy nobody points at
223
+ * yet — so this only talks to Telegram: create the topic, write the seed line
224
+ * that says where it came from, and pin it.
225
+ *
226
+ * Returns the new thread id, or 0 when Telegram refused (a group without topic
227
+ * permissions, a rate limit). The caller then removes the copy it made.
228
+ */
229
+ export async function openBranchTopic(chatId, name, seedText) {
230
+ let threadId = 0;
231
+ try {
232
+ const created = await tg('createForumTopic', { chat_id: chatId, name: String(name).slice(0, 128) });
233
+ threadId = Number(created?.message_thread_id || 0);
234
+ } catch (error) {
235
+ log(`branch topic could not be created: ${error.message}`);
236
+ return 0;
237
+ }
238
+ if (!(threadId > 0)) return 0;
239
+ log(`branch topic ${threadId} opened as "${name}"`);
240
+ let messageId = 0;
241
+ try {
242
+ const sent = await tg('sendMessage', { chat_id: chatId, message_thread_id: threadId, text: seedText });
243
+ messageId = Number(sent?.message_id || 0);
244
+ } catch (error) {
245
+ log(`branch topic ${threadId} seed failed: ${error.message}`);
246
+ }
247
+ if (!messageId) return threadId;
248
+ state.seededTopics = state.seededTopics ?? {};
249
+ state.seededTopics[String(threadId)] = messageId;
250
+ saveState();
251
+ if (config.pinTopicSeed !== false) {
252
+ try {
253
+ await tg('pinChatMessage', { chat_id: chatId, message_id: messageId, disable_notification: false });
254
+ } catch (error) {
255
+ log(`branch topic ${threadId} pin failed: ${error.message}`);
256
+ }
257
+ }
258
+ return threadId;
259
+ }
260
+
216
261
  /**
217
262
  * Write one line about a new topic into the General chat, so the main stream
218
263
  * reads as a log of what was started instead of a wall of prompts. The full
@@ -2,7 +2,7 @@
2
2
  //
3
3
  // Split out of `control.mjs` by the 500-line plan: the command handlers that
4
4
  // follow call these, and none of them needs the dispatcher to do it.
5
- import { copyFileSync, existsSync, readdirSync, writeFileSync } from 'node:fs';
5
+ import { copyFileSync, existsSync, readdirSync, renameSync, writeFileSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { parseModelSelection, parseSubagentFleet, parseSubagentRows } from '../profile/agents.mjs';
8
8
  import { DSH_HOME } from '../core/paths.mjs';
@@ -81,11 +81,106 @@ export function setSoul(text) {
81
81
  const rest = end === -1 ? '' : after.slice(end);
82
82
  next = `${body.slice(0, at).trimEnd()}\n\n${PERSONA_HEADING}\n\n${text.trim()}\n${rest}`;
83
83
  }
84
+ writeAside(AGENTS, next);
85
+ }
86
+
87
+ /** The bot-owned section `/remember` appends dated facts to. */
88
+ export const LEARNED_HEADING = '## Learned (DSH memory)';
89
+
90
+ /** How many notes the learned section may hold: the file is paid for on every request. */
91
+ export const MAX_LEARNED = 60;
92
+
93
+ /** The learned section, or '' when the file has none yet. */
94
+ export function learnedOf() {
95
+ const body = read(AGENTS);
96
+ const at = body.indexOf(LEARNED_HEADING);
97
+ if (at === -1) return '';
98
+ const after = body.slice(at + LEARNED_HEADING.length);
99
+ const end = after.search(/\n## /);
100
+ return (end === -1 ? after : after.slice(0, end)).replace(/^\s*\n/, '').trim();
101
+ }
102
+
103
+ /**
104
+ * The file with the learned section replaced by `lines` (a no-op when there is
105
+ * nothing to add and no section to change), or null.
106
+ *
107
+ * Everything around the section — the person's own hand-written text, the
108
+ * persona, whatever came after — is moved, not rewritten: the section ends at
109
+ * the next `## ` heading, and what follows it is reattached verbatim.
110
+ */
111
+ function withLearned(lines) {
112
+ const body = read(AGENTS);
113
+ const at = body.indexOf(LEARNED_HEADING);
114
+ if (at === -1) {
115
+ if (lines.length === 0) return null;
116
+ return `${body.trimEnd()}\n\n${LEARNED_HEADING}\n\n${lines.join('\n')}\n`;
117
+ }
118
+ const before = at === 0 ? '' : `${body.slice(0, at).trimEnd()}\n\n`;
119
+ const after = body.slice(at + LEARNED_HEADING.length);
120
+ const end = after.search(/\n## /);
121
+ const following = end === -1 ? '' : after.slice(end).replace(/^\n+/, '').replace(/\n+$/, '');
122
+ if (lines.length === 0) {
123
+ const head = before.replace(/\n+$/, '');
124
+ if (!head && !following) return '';
125
+ return following ? `${head ? `${head}\n\n` : ''}${following}\n` : `${head}\n`;
126
+ }
127
+ return `${before}${LEARNED_HEADING}\n\n${lines.join('\n')}${following ? `\n\n${following}\n` : '\n'}`;
128
+ }
129
+
130
+ /** The learned section as note lines, oldest first. */
131
+ function learnedLines() {
132
+ const list = learnedOf();
133
+ return list ? list.split('\n').map((line) => line.trim()).filter(Boolean) : [];
134
+ }
135
+
136
+ /**
137
+ * Add one dated note to the learned section, dropping the oldest past the cap.
138
+ *
139
+ * The write goes through a temp file renamed into place: the harness re-reads
140
+ * this file, and a half-written one would be instructions for exactly one
141
+ * request.
142
+ *
143
+ * @returns {{ dropped: number, count: number }}
144
+ */
145
+ export function appendLearned(note, { max = MAX_LEARNED, now = new Date() } = {}) {
146
+ const text = String(note || '').trim();
147
+ const added = `- ${now.toISOString().slice(0, 10)} — ${text}`;
148
+ const lines = learnedLines();
149
+ lines.push(added);
150
+ const dropped = Math.max(0, lines.length - Math.max(1, max));
151
+ const kept = lines.slice(dropped);
152
+ writeAside(AGENTS, withLearned(kept));
153
+ return { dropped, count: kept.length };
154
+ }
155
+
156
+ /**
157
+ * Replace the whole learned section (the caller supplies every surviving line),
158
+ * or remove it when the new text is empty.
159
+ *
160
+ * `/remember forget` works on whole lines because a note is one line: no edit
161
+ * can stop halfway through a fact and leave a sentence that says two things.
162
+ *
163
+ * @returns {boolean} whether the file changed
164
+ */
165
+ export function setLearned(text) {
166
+ const lines = String(text || '').split('\n').map((line) => line.trim()).filter(Boolean);
167
+ const next = withLearned(lines);
168
+ if (next === null) return false;
169
+ writeAside(AGENTS, next);
170
+ return true;
171
+ }
172
+
173
+ /**
174
+ * Write the instructions file: a copy first, then a rename, never in place.
175
+ * A copy that cannot be written must not block the write it was made for.
176
+ */
177
+ function writeAside(file, next) {
84
178
  try {
85
- if (existsSync(AGENTS)) copyFileSync(AGENTS, `${AGENTS}.bak`);
179
+ if (existsSync(file)) copyFileSync(file, `${file}.bak`);
86
180
  } catch {
87
- // A backup that cannot be written must not block the person's edit.
181
+ // Nothing to recover from — the write itself is the record.
88
182
  }
89
- writeFileSync(AGENTS, next, 'utf8');
183
+ writeFileSync(`${file}.tmp`, next, 'utf8');
184
+ renameSync(`${file}.tmp`, file);
90
185
  }
91
186
 
@@ -0,0 +1,89 @@
1
+ // `/balance`: what is left on each provider key, from the provider's own answer.
2
+ import { readFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { endpointRows } from './endpoint.mjs';
6
+ import { fetchBalance } from '../model/balance.mjs';
7
+
8
+ const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh');
9
+ const CRED = join(DSH_HOME, '.credentials.yaml');
10
+
11
+ /** Read a key from env first, then from the credentials store. Returns '' when missing. */
12
+ function keyOf(name) {
13
+ const fromEnv = (process.env[name] || '').trim();
14
+ if (fromEnv) return fromEnv;
15
+ try {
16
+ const yaml = readFileSync(CRED, 'utf8');
17
+ const m = yaml.match(new RegExp(`^\\s*${name}:\\s*["']?([^"'\\s]+)`, 'm'));
18
+ return m ? m[1] : '';
19
+ } catch {
20
+ return '';
21
+ }
22
+ }
23
+
24
+ /** Format a dollar amount: 4 decimals for small, 2 for large, sign before the symbol. */
25
+ const money = (usd) => {
26
+ const abs = Math.abs(usd);
27
+ return `${usd < 0 ? '-' : ''}$${abs < 1 ? abs.toFixed(4) : abs.toFixed(2)}`;
28
+ };
29
+
30
+ /**
31
+ * The `/balance` card: remaining balance per provider, from each provider's own API.
32
+ *
33
+ * Returns a plain-text card listing each provider with its balance, or a hint when empty.
34
+ * Accepts optional `rowsOf`, `keyOfImpl` and `fetchImpl` so a test can hand it a
35
+ * profile of its own instead of reading the machine's.
36
+ */
37
+ export async function balanceCard({ profile, lang, t, rowsOf = endpointRows, keyOfImpl = keyOf, fetchImpl } = {}) {
38
+ let rows;
39
+ try {
40
+ rows = rowsOf(profile).filter((row) => row.baseURL);
41
+ } catch {
42
+ return t(lang, 'balance.none');
43
+ }
44
+ if (!rows.length) return t(lang, 'balance.none');
45
+ const answers = await Promise.all(
46
+ rows.map(async (row) => {
47
+ const key = keyOfImpl(row.keyEnv);
48
+ if (!key) return { row, kind: 'nokey' };
49
+ const got = await fetchBalance({ baseUrl: row.baseURL, key, fetchImpl });
50
+ return { row, kind: got.ok ? 'ok' : 'failed', got };
51
+ }),
52
+ );
53
+ const lines = [t(lang, 'balance.head')];
54
+ let anyEmpty = 0;
55
+ let anyFailed = 0;
56
+ for (const { row, kind, got } of answers) {
57
+ if (kind === 'nokey') {
58
+ lines.push(t(lang, 'balance.noKey', { provider: row.id }));
59
+ continue;
60
+ }
61
+ if (kind === 'failed') {
62
+ anyFailed += 1;
63
+ lines.push(t(lang, 'balance.failed', { provider: row.id }));
64
+ continue;
65
+ }
66
+ // The account is what actually pays. A key that ran past its own grant shows a
67
+ // negative number while the account still serves, and calling that "empty" is
68
+ // the mistake this card exists to stop. So when the router reports both, both
69
+ // are printed and the account decides the verdict.
70
+ const account = got.account && Number.isFinite(got.account.usd) ? got.account.usd : null;
71
+ const effective = account === null ? got.usd : account;
72
+ if (effective <= 0) {
73
+ anyEmpty += 1;
74
+ lines.push(t(lang, 'balance.empty', { provider: row.id }));
75
+ continue;
76
+ }
77
+ if (account !== null) {
78
+ lines.push(t(lang, 'balance.rowAccount', { provider: row.id, amount: money(account), key: money(got.usd) }));
79
+ continue;
80
+ }
81
+ if (got.unlimited) {
82
+ lines.push(t(lang, 'balance.unlimited', { provider: row.id }));
83
+ continue;
84
+ }
85
+ lines.push(t(lang, 'balance.row', { provider: row.id, amount: money(effective) }));
86
+ }
87
+ if (anyEmpty || anyFailed) lines.push('', t(lang, 'balance.hint'));
88
+ return lines.join('\n');
89
+ }
@@ -8,7 +8,7 @@
8
8
  // Extracted from `cmd-views.mjs` by the 500-line ceiling, and it holds together
9
9
  // on its own: one card, one command, one idea of scope.
10
10
  import { t } from '../core/i18n.mjs';
11
- import { modelOf, routesOf, setModel } from './models.mjs';
11
+ import { effortThatWouldDrop, modelOf, patchPath, read, routesOf, setModel } from './models.mjs';
12
12
  import { modelCard } from './model-card.mjs';
13
13
  import { clearTopicRoute, routeExists, setTopicRoute, topicRoute } from './topic-route.mjs';
14
14
 
@@ -53,7 +53,8 @@ export async function handleModelCommand(ctx) {
53
53
  if (scope === 'both' || scope === 'all' || scope === 'global') {
54
54
  // The default every topic without a choice reads. Same word as `/reasoning
55
55
  // off all`, so one habit covers both settings.
56
- if (!setModel(activeProfile, wanted)) {
56
+ const applied = setModel(activeProfile, wanted);
57
+ if (!applied) {
57
58
  say(t(lang, 'ctrl.model.failed', { name: activeProfile, model: wanted }));
58
59
  return true;
59
60
  }
@@ -65,9 +66,13 @@ export async function handleModelCommand(ctx) {
65
66
  model: `${route.provider}/${route.model}`,
66
67
  desktop: desktop ? t(lang, 'ctrl.model.withDesktop', { model: wanted }) : '',
67
68
  });
69
+ const dropped = (applied && applied.dropped) || (desktop && desktop.dropped) || '';
70
+ const line = dropped
71
+ ? `${answer}\n${t(lang, 'ctrl.model.effortDropped', { value: dropped })}`
72
+ : answer;
68
73
  // A default that does not reach every topic has to say so in the same breath,
69
74
  // or "now every topic" is a promise the next turn breaks.
70
- say(kept > 0 ? `${answer}\n${t(lang, 'ctrl.model.topicKept', { n: kept })}` : answer);
75
+ say(kept > 0 ? `${line}\n${t(lang, 'ctrl.model.topicKept', { n: kept })}` : line);
71
76
  return true;
72
77
  }
73
78
 
@@ -88,9 +93,14 @@ export async function handleModelCommand(ctx) {
88
93
  save();
89
94
  const now = topicRoute({ state, config, key });
90
95
  const head = modelOf(activeProfile);
91
- say(t(lang, 'ctrl.model.topicSet', {
96
+ const said = t(lang, 'ctrl.model.topicSet', {
92
97
  route: `${now.provider}/${now.model}`,
93
98
  default: `${head.provider}/${head.model}`,
94
- }));
99
+ });
100
+ // The copy rewrites the level away when this model does not declare it, so the
101
+ // answer has to say so: the person set it, and a setting that disappears
102
+ // without a word is indistinguishable from a bug.
103
+ const dropped = effortThatWouldDrop(read(patchPath(activeProfile)), route);
104
+ say(dropped ? `${said}\n${t(lang, 'ctrl.model.effortDropped', { value: dropped })}` : said);
95
105
  return true;
96
106
  }