telecoder 1.2.0 → 1.3.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 (197) hide show
  1. package/.env.example +142 -130
  2. package/CHANGELOG.md +683 -2
  3. package/README.md +36 -32
  4. package/dist/audio/transcribe.js +0 -9
  5. package/dist/bin/mcp-server.js +46 -61
  6. package/dist/bot/bot.js +162 -181
  7. package/dist/bot/command-catalog.js +263 -0
  8. package/dist/bot/deleted-threads.js +103 -0
  9. package/dist/bot/file-access.js +35 -26
  10. package/dist/bot/handlers/album.handler.js +128 -0
  11. package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
  12. package/dist/bot/handlers/command/access.js +1 -1
  13. package/dist/bot/handlers/command/admin.js +86 -110
  14. package/dist/bot/handlers/command/all-view.js +33 -0
  15. package/dist/bot/handlers/command/auto-approve.js +3 -3
  16. package/dist/bot/handlers/command/background.js +37 -0
  17. package/dist/bot/handlers/command/botname.js +76 -0
  18. package/dist/bot/handlers/command/btw.js +20 -69
  19. package/dist/bot/handlers/command/cleanup.js +329 -0
  20. package/dist/bot/handlers/command/model.js +40 -119
  21. package/dist/bot/handlers/command/prefs-scope.js +255 -90
  22. package/dist/bot/handlers/command/project.js +31 -109
  23. package/dist/bot/handlers/command/resume.js +8 -4
  24. package/dist/bot/handlers/command/session.js +74 -213
  25. package/dist/bot/handlers/command/settings.js +92 -447
  26. package/dist/bot/handlers/command/shared.js +32 -35
  27. package/dist/bot/handlers/command/tasks.js +263 -95
  28. package/dist/bot/handlers/command/thread.js +128 -0
  29. package/dist/bot/handlers/command/topic-store.js +14 -53
  30. package/dist/bot/handlers/command/topic.js +8 -61
  31. package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
  32. package/dist/bot/handlers/command-fallback.js +179 -0
  33. package/dist/bot/handlers/command.handler.js +96 -422
  34. package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
  35. package/dist/bot/handlers/media-fallback.js +12 -7
  36. package/dist/bot/handlers/message/replies.js +10 -87
  37. package/dist/bot/handlers/message/shared.js +9 -31
  38. package/dist/bot/handlers/message/turn-notify.js +15 -49
  39. package/dist/bot/handlers/message/turn-runner.js +18 -103
  40. package/dist/bot/handlers/message.handler.js +59 -52
  41. package/dist/bot/handlers/newbot.handler.js +13 -4
  42. package/dist/bot/handlers/photo.handler.js +88 -129
  43. package/dist/bot/handlers/prompts.handler.js +11 -11
  44. package/dist/bot/handlers/running-note.js +2 -2
  45. package/dist/bot/handlers/session-guard.js +4 -4
  46. package/dist/bot/handlers/suggestion.handler.js +2 -2
  47. package/dist/bot/handlers/tree.handler.js +20 -20
  48. package/dist/bot/handlers/voice.handler.js +23 -85
  49. package/dist/bot/kept-threads.js +51 -0
  50. package/dist/bot/middleware/album-collector.js +69 -0
  51. package/dist/bot/middleware/auth.middleware.js +1 -1
  52. package/dist/bot/middleware/group-mention.middleware.js +11 -5
  53. package/dist/bot/middleware/queued-messages.js +143 -32
  54. package/dist/bot/middleware/stale-filter.js +0 -22
  55. package/dist/build-info.json +5 -5
  56. package/dist/claude/ask-user-form.js +517 -0
  57. package/dist/claude/ask-user.js +94 -26
  58. package/dist/claude/auto-topic-haiku.js +17 -0
  59. package/dist/claude/available-commands.js +22 -19
  60. package/dist/claude/background-hint.js +91 -0
  61. package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
  62. package/dist/claude/carry-over.js +0 -2
  63. package/dist/claude/ccr-shim.js +12 -10
  64. package/dist/claude/claude-auth.js +6 -10
  65. package/dist/claude/command-parser.js +49 -43
  66. package/dist/claude/cost-overlay-scraper.js +7 -2
  67. package/dist/claude/effort-level.js +5 -0
  68. package/dist/claude/enabled-plugins.js +12 -16
  69. package/dist/claude/in-flight-tracker.js +21 -0
  70. package/dist/claude/mcp-bridge.js +86 -58
  71. package/dist/claude/memory-guard.js +400 -0
  72. package/dist/claude/message-offsets.js +5 -5
  73. package/dist/claude/modal-relay.js +401 -34
  74. package/dist/claude/model-catalog.js +20 -3
  75. package/dist/claude/monitor-relay.js +130 -15
  76. package/dist/claude/native-commands.js +40 -0
  77. package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
  78. package/dist/claude/permission-gate.js +11 -10
  79. package/dist/claude/permission-mode.js +19 -45
  80. package/dist/claude/prewarm.js +70 -0
  81. package/dist/claude/pty-idle-reaper.js +96 -0
  82. package/dist/claude/pty-provider.js +473 -188
  83. package/dist/claude/pty-spawn-config.js +79 -32
  84. package/dist/claude/pty-watch.js +201 -0
  85. package/dist/claude/request-queue.js +7 -35
  86. package/dist/claude/rewind.js +111 -0
  87. package/dist/claude/scheduled-runner.js +1 -3
  88. package/dist/claude/scheduler.js +6 -2
  89. package/dist/claude/scope-guard.js +8 -3
  90. package/dist/claude/screen-marks.js +83 -0
  91. package/dist/claude/screen-render.js +96 -0
  92. package/dist/claude/session-history.js +4 -2
  93. package/dist/claude/session-jsonl.js +162 -15
  94. package/dist/claude/session-manager.js +29 -8
  95. package/dist/claude/session-move.js +70 -0
  96. package/dist/claude/shell-mode-gate.js +60 -0
  97. package/dist/claude/side-question.js +20 -17
  98. package/dist/claude/stage-images.js +5 -5
  99. package/dist/claude/tasks-overlay-scraper.js +143 -20
  100. package/dist/claude/thread-judge-haiku.js +88 -0
  101. package/dist/claude/tip-scraper.js +3 -4
  102. package/dist/claude/tui-modal.js +272 -27
  103. package/dist/claude/tui-state.js +74 -2
  104. package/dist/claude/turn-end.js +15 -1
  105. package/dist/claude/turn-prose.js +1 -1
  106. package/dist/claude/typed-answer.js +104 -0
  107. package/dist/claude/update-banner-relay.js +1 -1
  108. package/dist/cli/commands/doctor.js +48 -15
  109. package/dist/cli/commands/help.js +11 -2
  110. package/dist/cli/commands/init.js +16 -13
  111. package/dist/cli/commands/service.js +40 -8
  112. package/dist/cli/commands/start.js +10 -0
  113. package/dist/cli/commands/watch.js +322 -0
  114. package/dist/cli/dispatch.js +5 -0
  115. package/dist/cli/init/env-file.js +1 -1
  116. package/dist/cli/init/flow.js +114 -47
  117. package/dist/cli/init/prompter.js +8 -0
  118. package/dist/cli/init/telegram.js +35 -9
  119. package/dist/cli/service/render.js +3 -3
  120. package/dist/config.js +156 -131
  121. package/dist/index.js +107 -31
  122. package/dist/launcher.js +34 -7
  123. package/dist/providers/ccr-introspect.js +1 -8
  124. package/dist/providers/ccr-provider.js +19 -20
  125. package/dist/providers/claude-provider.js +4 -57
  126. package/dist/providers/prefs-sync.js +16 -59
  127. package/dist/providers/provider-router.js +24 -23
  128. package/dist/providers/spawn-settings.js +45 -0
  129. package/dist/providers/user-preferences.js +127 -19
  130. package/dist/restart-when-idle.js +27 -7
  131. package/dist/startup/auto-continue.js +2 -2
  132. package/dist/startup/auto-resume.js +3 -15
  133. package/dist/startup/notices.js +1 -1
  134. package/dist/startup/verify-token.js +4 -4
  135. package/dist/telegram/action-logger.js +3 -165
  136. package/dist/telegram/background-activity-card.js +1 -1
  137. package/dist/telegram/botname-settings.js +71 -125
  138. package/dist/telegram/client-options.js +6 -7
  139. package/dist/telegram/force-reply-tracker.js +55 -16
  140. package/dist/telegram/message-sender.js +92 -360
  141. package/dist/telegram/prompt-label.js +11 -5
  142. package/dist/telegram/streaming-turn.js +5 -7
  143. package/dist/telegram/table-lists.js +56 -0
  144. package/dist/telegram/task-list.js +4 -4
  145. package/dist/telegram/task-tracker.js +45 -126
  146. package/dist/telegram/terminal-renderer.js +1 -5
  147. package/dist/telegram/thread-titles.js +74 -2
  148. package/dist/telegram/threads-setup.js +1 -1
  149. package/dist/utils/admins.js +2 -2
  150. package/dist/utils/bot-icon.js +248 -0
  151. package/dist/utils/bot-token.js +8 -5
  152. package/dist/utils/build-info.js +3 -3
  153. package/dist/utils/caffeinate.js +6 -3
  154. package/dist/utils/claude-env.js +0 -1
  155. package/dist/utils/claude-version.js +2 -2
  156. package/dist/utils/config-home.js +3 -3
  157. package/dist/utils/download.js +41 -15
  158. package/dist/utils/exit-codes.js +11 -0
  159. package/dist/utils/format.js +3 -6
  160. package/dist/utils/home-project.js +1 -1
  161. package/dist/utils/idle-restart.js +1 -1
  162. package/dist/utils/install-mode.js +1 -1
  163. package/dist/utils/instance-config.js +1 -1
  164. package/dist/utils/instances.js +1 -1
  165. package/dist/utils/keyed-settings.js +2 -2
  166. package/dist/utils/memory-pressure.js +60 -0
  167. package/dist/utils/npm-version.js +2 -2
  168. package/dist/utils/resolve-claude-bin.js +13 -24
  169. package/dist/utils/respawn-backoff.js +9 -0
  170. package/dist/utils/stale-launcher.js +1 -1
  171. package/dist/utils/systemd.js +8 -8
  172. package/dist/utils/telegram-proxy.js +72 -0
  173. package/dist/utils/uploads-dir.js +27 -0
  174. package/dist/utils/verbosity.js +8 -8
  175. package/dist/utils/version-check.js +5 -5
  176. package/package.json +3 -4
  177. package/dist/bot/handlers/command/media.js +0 -197
  178. package/dist/bot/handlers/command/streaming-mode.js +0 -16
  179. package/dist/bot/handlers/message/throttle.js +0 -49
  180. package/dist/claude/agent-watchdog.js +0 -162
  181. package/dist/claude/agent.js +0 -1458
  182. package/dist/claude/held-query.js +0 -190
  183. package/dist/claude/mcp-tools.js +0 -354
  184. package/dist/claude/sdk-permission-gate.js +0 -77
  185. package/dist/claude/session-cost.js +0 -41
  186. package/dist/claude/system-prompt.js +0 -162
  187. package/dist/providers/sdk-provider.js +0 -37
  188. package/dist/telegram/telegraph-settings.js +0 -31
  189. package/dist/telegram/telegraph.js +0 -453
  190. package/dist/telegram/terminal-settings.js +0 -25
  191. package/dist/tts/tts-settings.js +0 -62
  192. package/dist/tts/tts.js +0 -245
  193. package/dist/tts/voice-reply.js +0 -78
  194. package/dist/utils/debug-agent.js +0 -117
  195. package/dist/utils/debug-watchdog.js +0 -121
  196. package/dist/utils/project-data-dir.js +0 -33
  197. package/dist/utils/reasoning-summary.js +0 -12
@@ -20,9 +20,6 @@ import { GrammyError } from 'grammy';
20
20
  import { EntityText } from './entities.js';
21
21
  import { promptLabel, cutLabel } from './prompt-label.js';
22
22
  import { getToolIcon, extractToolDetail, elideToolOutput, stripAnsi } from './terminal-renderer.js';
23
- import { createTelegraphPage, fitsTelegraphPage } from './telegraph.js';
24
- import { editFormatted } from './send.js';
25
- import { isTelegraphEnabled } from './telegraph-settings.js';
26
23
  import { getSessionKeyFromCtx } from '../utils/session-key.js';
27
24
  // Constants
28
25
  const MIN_EDIT_INTERVAL_MS = 10000; // Minimum time between message edits (~5 edits/min safe zone)
@@ -183,66 +180,6 @@ export class ActionLogger {
183
180
  state.entries.push(entry);
184
181
  await this.requestDraw(state);
185
182
  }
186
- /**
187
- * Add a monitor event to the action log
188
- */
189
- async addMonitorEvent(sessionKey, task, eventText) {
190
- const state = this.logStates.get(sessionKey);
191
- if (!state || task.skipTranscript)
192
- return;
193
- const cleaned = stripAnsi(eventText);
194
- const truncated = cleaned.length > 500
195
- ? cleaned.substring(0, 497) + '...'
196
- : cleaned;
197
- const entry = {
198
- id: `monitor-${Date.now()}-${Math.random()}`,
199
- timestamp: Date.now(),
200
- type: 'monitor_event',
201
- icon: '📡',
202
- title: 'Monitor event',
203
- content: truncated,
204
- status: 'completed'
205
- };
206
- state.entries.push(entry);
207
- await this.requestDraw(state);
208
- }
209
- /**
210
- * Add a task completion to the action log
211
- */
212
- async addTaskCompletion(sessionKey, task) {
213
- const state = this.logStates.get(sessionKey);
214
- if (!state || task.skipTranscript || !task.isBackgrounded)
215
- return;
216
- const isMonitor = task.taskType === 'monitor_mcp';
217
- const statusIcon = task.status === 'completed'
218
- ? (isMonitor ? '📡' : '✅')
219
- : task.status === 'stopped' ? '🛑' : '❌';
220
- const verb = task.status === 'completed'
221
- ? (isMonitor ? 'stream ended' : 'completed')
222
- : task.status === 'stopped' ? 'stopped' : 'failed';
223
- const elapsedMs = (task.endedAt ?? Date.now()) - task.startedAt;
224
- const seconds = Math.round(elapsedMs / 1000);
225
- const duration = seconds >= 60
226
- ? `${Math.floor(seconds / 60)}m ${seconds % 60}s`
227
- : `${seconds}s`;
228
- const description = task.description.length > 100
229
- ? task.description.substring(0, 97) + '...'
230
- : task.description;
231
- const title = isMonitor
232
- ? `Monitor "${description}" ${verb} after ${duration}`
233
- : `Background task "${description}" ${verb} in ${duration}`;
234
- const entry = {
235
- id: `task-${Date.now()}-${Math.random()}`,
236
- timestamp: Date.now(),
237
- type: 'task_completion',
238
- icon: statusIcon,
239
- title,
240
- content: task.error,
241
- status: task.status === 'completed' ? 'completed' : 'error'
242
- };
243
- state.entries.push(entry);
244
- await this.requestDraw(state);
245
- }
246
183
  /**
247
184
  * Whether the turn's status line is showing at the bottom of the log: from
248
185
  * the log's first post until its turn ends. MessageSender stops updating the
@@ -534,11 +471,8 @@ export class ActionLogger {
534
471
  });
535
472
  }
536
473
  /**
537
- * Collapse the in-chat action log into a Telegraph link at the end of a turn.
538
- * Renders all entries (no 10-entry cap) onto a Telegraph page, then edits
539
- * the existing action-log message into a brief "📋 N actions · view full
540
- * log" summary. If Telegraph is disabled or fails, the log is drawn one last
541
- * time as it stands, without the live marker and status line.
474
+ * Close the in-chat action log at the end of a turn: draw it one last time
475
+ * as it stands, without the live marker and status line.
542
476
  */
543
477
  async finalize(state) {
544
478
  if (state.finalized)
@@ -548,19 +482,7 @@ export class ActionLogger {
548
482
  this.cancelDraw(state);
549
483
  if (!state.messageId || state.entries.length === 0)
550
484
  return;
551
- // Telegraph creation can fail (rate limit, network); the full log then
552
- // stays in the chat instead.
553
- const pageUrl = isTelegraphEnabled(state.sessionKey)
554
- ? await createTelegraphPage('Action log', this.renderTelegraphPage(state.entries))
555
- : null;
556
485
  try {
557
- if (pageUrl) {
558
- const summary = this.renderCollapsedSummary(state.entries, pageUrl);
559
- await editFormatted(state.api, state.chatId, state.messageId, summary, {
560
- link_preview_options: { is_disabled: true },
561
- });
562
- return;
563
- }
564
486
  const view = { live: false };
565
487
  const { text, entities } = this.renderActionLog(state.entries, this.entriesThatFit(state.entries, view), view);
566
488
  if (JSON.stringify({ text, entities }) === state.lastDrawn)
@@ -573,92 +495,8 @@ export class ActionLogger {
573
495
  if (msg.includes('message is not modified'))
574
496
  return;
575
497
  }
576
- console.error('[ActionLogger] Failed to collapse message:', error);
577
- }
578
- }
579
- /**
580
- * The full action log as markdown for a Telegraph page, cut down until it
581
- * fits on one.
582
- *
583
- * Telegraph refuses a page over 64 KB, and a long turn's log passes that
584
- * easily — 40 results at the verbose tier's 2,000 characters is 80 KB — which
585
- * left the live log standing uncollapsed. Output goes first: each pass
586
- * halves how much of an entry's input and output the page keeps, so every
587
- * action stays listed. Only once the title lines alone are too much do the
588
- * oldest actions drop off.
589
- */
590
- renderTelegraphPage(entries) {
591
- const longest = entries.reduce((max, e) => Math.max(max, e.subtitle?.length ?? 0, e.content?.length ?? 0), 0);
592
- for (let cap = longest; cap > 0; cap = Math.floor(cap / 2)) {
593
- const markdown = this.renderTelegraphMarkdown(entries, cap);
594
- if (fitsTelegraphPage(markdown))
595
- return markdown;
596
- }
597
- let keep = entries.length;
598
- let markdown = this.renderTelegraphMarkdown(entries, 0);
599
- while (keep > 1 && !fitsTelegraphPage(markdown)) {
600
- keep = Math.ceil(keep / 2);
601
- markdown = this.renderTelegraphMarkdown(entries, 0, entries.length - keep);
602
- }
603
- return markdown;
604
- }
605
- /**
606
- * Render the action log as markdown for a Telegraph page, from the entries
607
- * as captured — no attempt to recover untruncated content. Each entry's
608
- * input and output are cut to `bodyCap` characters, and left off at 0; the
609
- * first `skip` entries are left off entirely.
610
- */
611
- renderTelegraphMarkdown(entries, bodyCap, skip = 0) {
612
- const sections = [];
613
- if (skip > 0) {
614
- sections.push(`_${skip} earlier action${skip === 1 ? '' : 's'} left off to fit the page._`);
498
+ console.error('[ActionLogger] Failed to close the log:', error);
615
499
  }
616
- entries.slice(skip).forEach((entry, index) => {
617
- const statusEmoji = entry.status === 'completed' ? '✅' :
618
- entry.status === 'error' ? '❌' : '⏳';
619
- const time = new Date(entry.timestamp).toLocaleTimeString('en-US', {
620
- hour12: false,
621
- hour: '2-digit',
622
- minute: '2-digit',
623
- second: '2-digit',
624
- });
625
- const cut = (text) => text && bodyCap > 0
626
- ? elideToolOutput(text, Infinity, bodyCap, { isError: entry.status === 'error' })
627
- : undefined;
628
- const subtitle = cut(entry.subtitle);
629
- const content = cut(entry.content);
630
- const headerLines = [];
631
- headerLines.push(`## ${skip + index + 1}. ${entry.icon} ${statusEmoji} ${entry.title}`);
632
- headerLines.push(`_${time}_`);
633
- if (subtitle) {
634
- headerLines.push('');
635
- headerLines.push('```');
636
- headerLines.push(subtitle);
637
- headerLines.push('```');
638
- }
639
- if (content) {
640
- headerLines.push('');
641
- headerLines.push('```');
642
- headerLines.push(content);
643
- headerLines.push('```');
644
- }
645
- sections.push(headerLines.join('\n'));
646
- });
647
- return sections.join('\n\n---\n\n');
648
- }
649
- /**
650
- * Render the collapsed in-chat summary line that replaces the live log.
651
- */
652
- renderCollapsedSummary(entries, pageUrl) {
653
- const completed = entries.filter(e => e.status === 'completed').length;
654
- const errors = entries.filter(e => e.status === 'error').length;
655
- const counts = [`${entries.length} action${entries.length === 1 ? '' : 's'}`];
656
- if (errors > 0)
657
- counts.push(`${errors} error${errors === 1 ? '' : 's'}`);
658
- else if (completed < entries.length)
659
- counts.push(`${completed} completed`);
660
- const summary = counts.join(' · ');
661
- return new EntityText().add('📋 ').italic(summary).add(' · ').link('view full log', pageUrl).build();
662
500
  }
663
501
  /**
664
502
  * Check if action logging is active for a session
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * One live "background activity" card per session.
3
3
  *
4
- * PTY-mode async work (monitors, backgrounded Bash, subagents, workflows)
4
+ * Async work (monitors, backgrounded Bash, subagents, workflows)
5
5
  * reports in from outside any user turn, so every arm, event and completion
6
6
  * used to arrive as its own Telegram message — a monitor that fires ten times
7
7
  * produced ten messages. This module folds all of it into a single message
@@ -1,31 +1,19 @@
1
1
  /**
2
- * Dynamic bot name settings per chat.
3
- * When enabled, the Telegram bot display name updates to include the active project.
2
+ * The bot's Telegram display name: a rate-limited `setMyName`, the startup
3
+ * reconcile with the configured name, and the cooldown Telegram imposes.
4
+ *
5
+ * The name is static. It used to follow the active project (and before that
6
+ * the topic), but Telegram throttles `setMyName` so hard that a rename could
7
+ * silently fail and leave the wrong project showing for hours. The project is
8
+ * in the status line and the thread names instead, and a bot made for one
9
+ * project carries it in its name from the start (`/newbot`).
4
10
  */
5
- import { config, BOT_ID, explicitFlags } from '../config.js';
11
+ import { config, BOT_ID, getBotNameSource } from '../config.js';
6
12
  import * as path from 'path';
7
13
  import { z } from 'zod';
8
14
  import { GrammyError } from 'grammy';
9
- import { createKeyedSettings } from '../utils/keyed-settings.js';
10
15
  import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
11
16
  const SETTINGS_DIR = getStateDir();
12
- const store = createKeyedSettings({
13
- file: 'botname-settings.json',
14
- label: 'BotName',
15
- entrySchema: z.object({ enabled: z.boolean().optional() }),
16
- normalize: (stored) => ({
17
- enabled: typeof stored?.enabled === 'boolean' ? stored.enabled : config.DYNAMIC_BOT_NAME,
18
- }),
19
- });
20
- export function getBotNameSettings(sessionKey) {
21
- return store.get(sessionKey);
22
- }
23
- export function setBotNameEnabled(sessionKey, enabled) {
24
- store.update(sessionKey, { enabled });
25
- }
26
- export function isBotNameEnabled(sessionKey) {
27
- return getBotNameSettings(sessionKey).enabled;
28
- }
29
17
  // ---------------------------------------------------------------------------
30
18
  // Rate-limited setMyName wrapper
31
19
  // ---------------------------------------------------------------------------
@@ -55,12 +43,21 @@ function setBlockedUntil(blockedUntil) {
55
43
  ensureStateDir(SETTINGS_DIR, 'BotName');
56
44
  writeJsonFile(COOLDOWN_FILE, { blockedUntil }, 'BotName');
57
45
  }
46
+ /** When Telegram will accept a rename again, or undefined when it does now. */
47
+ export function getBotNameCooldownUntil() {
48
+ const until = getBlockedUntil();
49
+ return until > Date.now() ? until : undefined;
50
+ }
51
+ /** "~5m" or "~2h": how long a cooldown has left, for a message. */
52
+ export function formatCooldownLeft(blockedUntilMs) {
53
+ const remainingMs = Math.max(0, blockedUntilMs - Date.now());
54
+ const mins = Math.round(remainingMs / 60000);
55
+ return mins >= 60 ? `~${Math.round(mins / 60)}h` : `~${Math.max(mins, 1)}m`;
56
+ }
58
57
  // The last successfully-sent display name, persisted to disk. The in-memory
59
58
  // dedup (`state.lastSentName`) is reset on every restart, so without this the
60
59
  // first name push after a restart always hits Telegram even when the name is
61
- // unchanged — and since the topic moved to the status line the name is now
62
- // effectively static, making nearly every post-restart push a wasted quota
63
- // slot. Persisting it lets the `no_change` short-circuit survive restarts.
60
+ // unchanged. Persisting it lets the `no_change` short-circuit survive restarts.
64
61
  function getPersistedLastSentName() {
65
62
  return readJsonFile(LAST_SENT_FILE, lastSentSchema, 'BotName')?.name ?? null;
66
63
  }
@@ -86,12 +83,6 @@ function extractRetryAfterMs(err) {
86
83
  }
87
84
  return undefined;
88
85
  }
89
- // Set as soon as anything in this process asks for a name update. The startup
90
- // sync uses it to tell "nobody has claimed the display name yet" from
91
- // "auto-resume already pushed a name built from BOT_NAME" — in the latter case
92
- // the name is current by construction and re-checking it would race against a
93
- // deferred (soft-throttled) push that hasn't reached Telegram yet.
94
- let nameClaimedThisProcess = false;
95
86
  // Per-bot soft-throttle state. Keyed by the bot's `api` object (stable per
96
87
  // bot) so multiple bots running in the same process don't collide on a
97
88
  // shared slot. WeakMap lets state get GC'd if a bot is torn down.
@@ -141,7 +132,6 @@ async function callAndHandle429(state, apiCall, name, source) {
141
132
  * process don't share a throttle slot.
142
133
  */
143
134
  export async function rateLimitedSetMyName(botKey, apiCall, name) {
144
- nameClaimedThisProcess = true;
145
135
  const blockedUntil = getBlockedUntil();
146
136
  const now = Date.now();
147
137
  if (blockedUntil > now) {
@@ -150,14 +140,13 @@ export async function rateLimitedSetMyName(botKey, apiCall, name) {
150
140
  return { status: 'still_blocked', blockedUntilMs: blockedUntil };
151
141
  }
152
142
  const state = getRateState(botKey);
153
- // No-op if the name we already sent matches — most auto-topic calls re-emit
154
- // the same topic for follow-up messages, and Telegram counts those toward
155
- // the rate limit even though the visible name doesn't change.
143
+ // No-op if the name we already sent matches — Telegram counts a call that
144
+ // changes nothing toward the rate limit all the same.
156
145
  if (state.lastSentName === name) {
157
- // A queued (different) name from an earlier switch is now superseded — the
146
+ // A queued (different) name from an earlier call is now superseded — the
158
147
  // currently-desired name already matches what's shown. Cancel the stale
159
148
  // timer so it doesn't fire a wasted setMyName for a name we've moved past
160
- // (e.g. switch A→B→A within the soft interval).
149
+ // (e.g. A→B→A within the soft interval).
161
150
  if (state.pendingTimer) {
162
151
  clearTimeout(state.pendingTimer);
163
152
  state.pendingTimer = null;
@@ -210,13 +199,43 @@ export async function rateLimitedSetMyName(botKey, apiCall, name) {
210
199
  }
211
200
  return { status: 'queued' };
212
201
  }
202
+ let retryTimer = null;
213
203
  /**
214
- * Reconcile the Telegram display name with `BOT_NAME` once at startup.
204
+ * Once the cooldown is over, send the name the bot wants by then. Read at fire
205
+ * time, so a `/botname` given in the meantime is what lands. One timer per bot;
206
+ * a new block replaces it.
207
+ */
208
+ function armRetryAfterCooldown(api, blockedUntilMs) {
209
+ if (retryTimer)
210
+ clearTimeout(retryTimer);
211
+ retryTimer = setTimeout(async () => {
212
+ retryTimer = null;
213
+ try {
214
+ const r = await rateLimitedSetMyName(api, (n) => api.setMyName(n), config.BOT_NAME);
215
+ console.log(`[BotName] Retry after cooldown: ${r.status}`);
216
+ }
217
+ catch (err) {
218
+ console.error('[BotName] Retry after cooldown failed:', err instanceof Error ? err.message : err);
219
+ }
220
+ }, Math.max(0, blockedUntilMs - Date.now()) + 1000);
221
+ retryTimer.unref?.();
222
+ }
223
+ /**
224
+ * Rename the bot on Telegram, and when Telegram refuses, try again as soon as
225
+ * it allows. The result says which happened, for the reply to the user.
226
+ */
227
+ export async function pushBotName(api, name) {
228
+ const result = await rateLimitedSetMyName(api, (n) => api.setMyName(n), name);
229
+ if (result.status === 'newly_blocked' || result.status === 'still_blocked') {
230
+ armRetryAfterCooldown(api, result.blockedUntilMs);
231
+ }
232
+ return result;
233
+ }
234
+ /**
235
+ * Reconcile the Telegram display name with the configured name once at startup.
215
236
  *
216
- * Every other `setMyName` path is event-driven (project switch, topic
217
- * clear/restore, `/botname` toggle), so a `BOT_NAME` change in `instances.json`
218
- * used to sit invisible until one of those fired — a rebrand could leave the
219
- * old name showing for days.
237
+ * A `BOT_NAME` edited between runs, or a `/botname` whose cooldown retry was
238
+ * lost to a restart, would otherwise sit invisible: nothing else renames the bot.
220
239
  *
221
240
  * Deliberately bypasses the `lastSentName` dedup in `rateLimitedSetMyName`:
222
241
  * `getMyName()` is authoritative about what Telegram actually shows, and the
@@ -224,17 +243,14 @@ export async function rateLimitedSetMyName(botKey, apiCall, name) {
224
243
  * live name disagree (BOT_NAME edited between runs, or a BotFather rename).
225
244
  * The persistent 429 cooldown still applies.
226
245
  *
227
- * Without an explicit BOT_NAME the name chosen in BotFather is kept: the
228
- * "TeleCoder" default would otherwise overwrite it on a fresh install's first
229
- * start. Dynamic naming builds every name from BOT_NAME anyway, so it still
230
- * syncs.
246
+ * Without a name of its own (neither `/botname` nor `BOT_NAME`) the name chosen
247
+ * in BotFather is kept: the "TeleCoder" default would otherwise overwrite it on
248
+ * a fresh install's first start.
231
249
  */
232
250
  export async function syncBotNameOnStartup(api) {
233
- if (nameClaimedThisProcess)
234
- return { status: 'no_change' };
235
- if (!explicitFlags.BOT_NAME && !config.DYNAMIC_BOT_NAME)
251
+ if (getBotNameSource() === 'default')
236
252
  return { status: 'no_change' };
237
- const base = config.BOT_NAME;
253
+ const wanted = config.BOT_NAME;
238
254
  let current;
239
255
  try {
240
256
  current = (await api.getMyName()).name;
@@ -243,94 +259,24 @@ export async function syncBotNameOnStartup(api) {
243
259
  console.debug('[BotName] Startup sync: getMyName failed:', err instanceof Error ? err.message : err);
244
260
  return { status: 'no_change' };
245
261
  }
246
- // Dynamic names carry a " — project" suffix. Anything already rooted at
247
- // BOT_NAME is in sync; rewriting it to the bare base would clobber the
248
- // project the user last switched to.
249
- if (current === base || current.startsWith(`${base} — `))
262
+ if (current === wanted)
250
263
  return { status: 'no_change' };
251
264
  const blockedUntil = getBlockedUntil();
252
265
  const now = Date.now();
253
266
  if (blockedUntil > now) {
254
267
  const mins = Math.round((blockedUntil - now) / 60000);
255
- console.warn(`[BotName] Startup sync: "${current}" → "${base}" skipped, Telegram cooldown for ~${mins}m more.`);
268
+ console.warn(`[BotName] Startup sync: "${current}" → "${wanted}" skipped, Telegram cooldown for ~${mins}m more.`);
269
+ armRetryAfterCooldown(api, blockedUntil);
256
270
  return { status: 'still_blocked', blockedUntilMs: blockedUntil };
257
271
  }
258
- console.log(`[BotName] Startup sync: renaming "${current}" → "${base}"`);
272
+ console.log(`[BotName] Startup sync: renaming "${current}" → "${wanted}"`);
259
273
  const state = getRateState(api);
260
274
  state.lastUpdateTime = now;
261
- const result = await callAndHandle429(state, (n) => api.setMyName(n), base, 'startup sync');
275
+ const result = await callAndHandle429(state, (n) => api.setMyName(n), wanted, 'startup sync');
262
276
  if (result.kind === 'newly_blocked') {
277
+ armRetryAfterCooldown(api, result.blockedUntilMs);
263
278
  return { status: 'newly_blocked', blockedUntilMs: result.blockedUntilMs };
264
279
  }
265
- nameClaimedThisProcess = true;
266
280
  return { status: 'sent' };
267
281
  }
268
- // ---------------------------------------------------------------------------
269
- // Cooldown notification (surface 429 blackouts to the user)
270
- // ---------------------------------------------------------------------------
271
- // Dedup keyed on `${BOT_ID}:${chatId}:${blockedUntilMs}` so a fresh 429
272
- // (different blockedUntilMs) re-notifies, but repeated drops inside the same
273
- // cooldown window do not. Lives in-memory only — after restart, the cooldown
274
- // reloads from disk and the next attempt re-notifies, which is fine UX.
275
- const notifiedCooldowns = new Set();
276
- function makeCooldownKey(chatId, blockedUntilMs) {
277
- return `${BOT_ID}:${chatId}:${blockedUntilMs}`;
278
- }
279
- function formatCooldownMessage(blockedUntilMs) {
280
- const remainingMs = Math.max(0, blockedUntilMs - Date.now());
281
- const mins = Math.round(remainingMs / 60000);
282
- const when = mins >= 60
283
- ? `~${Math.round(mins / 60)}h`
284
- : `~${Math.max(mins, 1)}m`;
285
- return `⚠️ Bot name update skipped — Telegram rate-limited setMyName. Will retry in ${when}.`;
286
- }
287
- /**
288
- * Shared dedup gate: returns true exactly once per (bot, chat, cooldown window)
289
- * so multiple dropped updates inside the same window stay quiet.
290
- */
291
- function shouldNotifyCooldown(chatId, blockedUntilMs) {
292
- const key = makeCooldownKey(chatId, blockedUntilMs);
293
- if (notifiedCooldowns.has(key))
294
- return false;
295
- notifiedCooldowns.add(key);
296
- return true;
297
- }
298
- /**
299
- * If `result` indicates a 429 cooldown, send a one-time notice to the chat in
300
- * `ctx`. Deduped per (bot, chat, cooldown window) so repeated dropped updates
301
- * inside the same window don't spam the user.
302
- */
303
- export async function notifyBotNameBlock(ctx, result) {
304
- if (result.status !== 'newly_blocked' && result.status !== 'still_blocked')
305
- return;
306
- const chatId = ctx.chat?.id;
307
- if (chatId === undefined)
308
- return;
309
- if (!shouldNotifyCooldown(chatId, result.blockedUntilMs))
310
- return;
311
- try {
312
- await ctx.reply(formatCooldownMessage(result.blockedUntilMs));
313
- }
314
- catch (err) {
315
- console.debug('[BotName] Failed to send cooldown notice:', err instanceof Error ? err.message : err);
316
- }
317
- }
318
- /**
319
- * Same as `notifyBotNameBlock` but takes a raw `bot.api` reference plus chat /
320
- * thread IDs — for paths that don't have a grammy `Context` (e.g. auto-resume
321
- * loops over sessions and sends through `bot.api.sendMessage`).
322
- */
323
- export async function notifyBotNameBlockToChat(api, chatId, result, threadId) {
324
- if (result.status !== 'newly_blocked' && result.status !== 'still_blocked')
325
- return;
326
- if (!shouldNotifyCooldown(chatId, result.blockedUntilMs))
327
- return;
328
- try {
329
- const opts = threadId !== undefined ? { message_thread_id: threadId } : undefined;
330
- await api.sendMessage(chatId, formatCooldownMessage(result.blockedUntilMs), opts);
331
- }
332
- catch (err) {
333
- console.debug('[BotName] Failed to send cooldown notice:', err instanceof Error ? err.message : err);
334
- }
335
- }
336
282
  //# sourceMappingURL=botname-settings.js.map
@@ -1,18 +1,17 @@
1
1
  /**
2
2
  * How the bot reaches api.telegram.org: the proxy, if any, and the timeout.
3
3
  *
4
- * Shared by the bot itself and the token check that runs before it is built
5
- * (startup/verify-token.ts), so a bot behind a proxy checks its token through
6
- * that same proxy instead of failing the check on a direct connection.
4
+ * Shared by the bot itself, the token check that runs before it is built
5
+ * (startup/verify-token.ts) and the download of a file sent to the bot, so a
6
+ * bot behind a proxy does all three through that same proxy instead of
7
+ * failing on a direct connection.
7
8
  */
8
9
  import { HttpsProxyAgent } from 'https-proxy-agent';
9
10
  import { config } from '../config.js';
11
+ import { findProxy } from '../utils/telegram-proxy.js';
10
12
  /** TELEGRAM_PROXY_URL, falling back to the usual proxy variables. */
11
13
  export function telegramProxyUrl() {
12
- return config.TELEGRAM_PROXY_URL
13
- || process.env.HTTPS_PROXY || process.env.https_proxy
14
- || process.env.HTTP_PROXY || process.env.http_proxy
15
- || undefined;
14
+ return findProxy((setting) => (setting === 'TELEGRAM_PROXY_URL' ? config.TELEGRAM_PROXY_URL : process.env[setting]))?.url;
16
15
  }
17
16
  export function telegramClientOptions() {
18
17
  const proxyUrl = telegramProxyUrl();
@@ -1,31 +1,40 @@
1
1
  /**
2
- * Remembers which of the bot's own messages were ForceReply prompts.
2
+ * Remembers which of the bot's own messages were ForceReply prompts, and which
3
+ * flow each one opened.
3
4
  *
4
- * In a group the bot only answers when it is @mentioned, but the ForceReply
5
- * flows (`/project`, `/plan`, `/file`, …) are answered by replying to the
6
- * prompt — Telegram pops the composer open with the reply already attached,
7
- * and there is nowhere to put a mention. Those replies have to stay
8
- * addressed, so the gate needs to tell "answering a prompt" apart from
9
- * "quoting something the bot said".
5
+ * A ForceReply flow (`/dir`) posts a question and
6
+ * takes the user's reply to it as the answer: Telegram pops the composer open
7
+ * with the reply already attached. Two things need to know a reply answers a
8
+ * prompt:
10
9
  *
11
- * Rather than re-deriving that from the prompt's wording (a list that would
12
- * drift from the handlers), a transformer watches outgoing sendMessage calls
13
- * and records the id of any message sent with a force_reply keyboard.
10
+ * - the message handlers, to route the answer to the flow that asked, which
11
+ * {@link forceReplyFlow} tells them from the prompt's id rather than from
12
+ * its wording — a list of phrases that would drift from the handlers;
13
+ * - the group mention gate, since in a group the bot only answers when it is
14
+ * @mentioned and a reply to a prompt has nowhere to put a mention. A
15
+ * transformer watches outgoing sendMessage calls and records every message
16
+ * sent with a force_reply keyboard, so that gate holds for a prompt sent
17
+ * any other way too.
14
18
  *
15
19
  * The ids live in memory only: these prompts are answered within seconds, and
16
20
  * a prompt left hanging across a restart is better re-opened than resurrected.
17
21
  */
18
- /** Plenty for any realistic number of prompts open at once; bounds the set. */
22
+ import { replyFormatted } from './send.js';
23
+ /** Plenty for any realistic number of prompts open at once; bounds the map. */
19
24
  const MAX_TRACKED = 200;
20
- const prompts = new Set();
25
+ /** Prompt → the flow it opened, or undefined for one sent outside {@link sendForceReplyPrompt}. */
26
+ const prompts = new Map();
21
27
  const key = (chatId, messageId) => `${chatId}:${messageId}`;
22
- export function rememberForceReplyPrompt(chatId, messageId) {
28
+ export function rememberForceReplyPrompt(chatId, messageId, flow) {
23
29
  const k = key(chatId, messageId);
24
30
  // Re-inserting moves it to the end, so the oldest entry is always first out.
31
+ // The transformer records a prompt first, without its flow; the sender then
32
+ // names the flow, which must not be lost to a later nameless record.
33
+ const known = prompts.get(k);
25
34
  prompts.delete(k);
26
- prompts.add(k);
35
+ prompts.set(k, flow ?? known);
27
36
  while (prompts.size > MAX_TRACKED) {
28
- const oldest = prompts.values().next();
37
+ const oldest = prompts.keys().next();
29
38
  if (oldest.done)
30
39
  break;
31
40
  prompts.delete(oldest.value);
@@ -34,7 +43,37 @@ export function rememberForceReplyPrompt(chatId, messageId) {
34
43
  export function isForceReplyPrompt(chatId, messageId) {
35
44
  return prompts.has(key(chatId, messageId));
36
45
  }
37
- /** Test seam — the set is module state that would otherwise leak between cases. */
46
+ /** The flow a reply to `messageId` answers, or undefined when it answers no open prompt. */
47
+ export function forceReplyFlow(chatId, messageId) {
48
+ return prompts.get(key(chatId, messageId));
49
+ }
50
+ /**
51
+ * The flow the message being replied to opened, if it is one of this bot's
52
+ * prompts. Undefined for a message that isn't a reply, replies to a user, or
53
+ * replies to a bot message that was no prompt (or one from before a restart).
54
+ */
55
+ export function repliedForceReplyFlow(ctx) {
56
+ const replyTo = ctx.message?.reply_to_message;
57
+ const chatId = ctx.chat?.id;
58
+ if (!replyTo?.from?.is_bot || chatId === undefined)
59
+ return undefined;
60
+ return forceReplyFlow(chatId, replyTo.message_id);
61
+ }
62
+ /**
63
+ * Post a ForceReply prompt for `flow` and remember which flow it opened.
64
+ * `selective` keeps the composer from opening for everyone else in a group.
65
+ */
66
+ export async function sendForceReplyPrompt(ctx, flow, text, placeholder) {
67
+ const sent = await replyFormatted(ctx, text, {
68
+ reply_markup: {
69
+ force_reply: true,
70
+ input_field_placeholder: placeholder,
71
+ selective: true,
72
+ },
73
+ });
74
+ rememberForceReplyPrompt(sent.chat.id, sent.message_id, flow);
75
+ }
76
+ /** Test seam — the map is module state that would otherwise leak between cases. */
38
77
  export function clearForceReplyPrompts() {
39
78
  prompts.clear();
40
79
  }