telecoder 0.0.0-stage → 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 (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,282 @@
1
+ /**
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`).
10
+ */
11
+ import { config, BOT_ID, getBotNameSource } from '../config.js';
12
+ import * as path from 'path';
13
+ import { z } from 'zod';
14
+ import { GrammyError } from 'grammy';
15
+ import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
16
+ const SETTINGS_DIR = getStateDir();
17
+ // ---------------------------------------------------------------------------
18
+ // Rate-limited setMyName wrapper
19
+ // ---------------------------------------------------------------------------
20
+ const MIN_NAME_UPDATE_INTERVAL_MS = 60_000; // 1 minute soft cooldown
21
+ // One file per bot, like the rest of the per-bot state. Each bot is its own
22
+ // process, and when they shared a file each one rewrote it from the copy it
23
+ // loaded at startup, undoing what the others had saved since. A wrong last-sent
24
+ // name makes a real rename look like no change, and a lost block sends a call
25
+ // Telegram has already refused. The old shared setmyname-cooldowns.json and
26
+ // setmyname-lastsent.json are deliberately not read: their entries can't be
27
+ // trusted, and starting without them costs at most one extra call per bot.
28
+ const COOLDOWN_FILE = path.join(SETTINGS_DIR, `setmyname-cooldown-${BOT_ID}.json`);
29
+ const LAST_SENT_FILE = path.join(SETTINGS_DIR, `setmyname-lastsent-${BOT_ID}.json`);
30
+ const cooldownSchema = z.object({ blockedUntil: z.number() });
31
+ const lastSentSchema = z.object({ name: z.string() });
32
+ // Persistent 429 cooldown. Telegram's setMyName limit is much stricter than our
33
+ // soft local interval, and the local state is reset on every restart — so we
34
+ // honor any retry_after Telegram returns and persist the "do not call before"
35
+ // timestamp to disk.
36
+ ensureStateDir(SETTINGS_DIR, 'BotName');
37
+ let cooldownUntil = readJsonFile(COOLDOWN_FILE, cooldownSchema, 'BotName')?.blockedUntil ?? 0;
38
+ function getBlockedUntil() {
39
+ return cooldownUntil;
40
+ }
41
+ function setBlockedUntil(blockedUntil) {
42
+ cooldownUntil = blockedUntil;
43
+ ensureStateDir(SETTINGS_DIR, 'BotName');
44
+ writeJsonFile(COOLDOWN_FILE, { blockedUntil }, 'BotName');
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
+ }
57
+ // The last successfully-sent display name, persisted to disk. The in-memory
58
+ // dedup (`state.lastSentName`) is reset on every restart, so without this the
59
+ // first name push after a restart always hits Telegram even when the name is
60
+ // unchanged. Persisting it lets the `no_change` short-circuit survive restarts.
61
+ function getPersistedLastSentName() {
62
+ return readJsonFile(LAST_SENT_FILE, lastSentSchema, 'BotName')?.name ?? null;
63
+ }
64
+ function setPersistedLastSentName(name) {
65
+ ensureStateDir(SETTINGS_DIR, 'BotName');
66
+ writeJsonFile(LAST_SENT_FILE, { name }, 'BotName');
67
+ }
68
+ /** Parse Telegram's retry_after (seconds) from a Grammy/HTTP error. */
69
+ function extractRetryAfterMs(err) {
70
+ if (err instanceof GrammyError && err.error_code === 429) {
71
+ const sec = err.parameters?.retry_after;
72
+ if (typeof sec === 'number' && sec > 0)
73
+ return sec * 1000;
74
+ }
75
+ // Fallback: parse "(429: Too Many Requests: retry after N)" out of the message.
76
+ if (err instanceof Error) {
77
+ const m = err.message.match(/429:[^)]*retry after (\d+)/i);
78
+ if (m) {
79
+ const sec = Number.parseInt(m[1], 10);
80
+ if (Number.isFinite(sec) && sec > 0)
81
+ return sec * 1000;
82
+ }
83
+ }
84
+ return undefined;
85
+ }
86
+ // Per-bot soft-throttle state. Keyed by the bot's `api` object (stable per
87
+ // bot) so multiple bots running in the same process don't collide on a
88
+ // shared slot. WeakMap lets state get GC'd if a bot is torn down.
89
+ const nameRateStates = new WeakMap();
90
+ function getRateState(key) {
91
+ let state = nameRateStates.get(key);
92
+ if (!state) {
93
+ // Seed lastSentName from disk so the `no_change` dedup survives restarts —
94
+ // otherwise the first push after every restart re-sends an unchanged name.
95
+ state = { lastUpdateTime: 0, lastSentName: getPersistedLastSentName(), pendingName: null, pendingApiCall: null, pendingTimer: null };
96
+ nameRateStates.set(key, state);
97
+ }
98
+ return state;
99
+ }
100
+ async function callAndHandle429(state, apiCall, name, source) {
101
+ try {
102
+ await apiCall(name);
103
+ state.lastSentName = name;
104
+ setPersistedLastSentName(name);
105
+ return { kind: 'sent' };
106
+ }
107
+ catch (err) {
108
+ const retryAfterMs = extractRetryAfterMs(err);
109
+ if (retryAfterMs !== undefined) {
110
+ const until = Date.now() + retryAfterMs;
111
+ setBlockedUntil(until);
112
+ const mins = Math.round(retryAfterMs / 60000);
113
+ console.warn(`[BotName] ${source}: setMyName rate-limited by Telegram, blocked for ~${mins}m (until ${new Date(until).toISOString()})`);
114
+ return { kind: 'newly_blocked', blockedUntilMs: until };
115
+ }
116
+ throw err;
117
+ }
118
+ }
119
+ /**
120
+ * Rate-limited wrapper around `bot.api.setMyName()`.
121
+ *
122
+ * Two layers of throttling:
123
+ * 1. A persistent server-side cooldown — when Telegram returns 429 with a
124
+ * `retry_after`, we record `now + retry_after` to disk and refuse all
125
+ * further calls until that timestamp passes. Survives bot restarts.
126
+ * 2. A soft 1-minute local interval — at most one outbound call per minute
127
+ * per bot; if called more frequently the latest name is queued and
128
+ * applied when the cooldown expires.
129
+ *
130
+ * `botKey` must be a stable object identifying the bot (typically `ctx.api`
131
+ * or `bot.api`). State is tracked per-key so multiple bots in the same
132
+ * process don't share a throttle slot.
133
+ */
134
+ export async function rateLimitedSetMyName(botKey, apiCall, name) {
135
+ const blockedUntil = getBlockedUntil();
136
+ const now = Date.now();
137
+ if (blockedUntil > now) {
138
+ const mins = Math.round((blockedUntil - now) / 60000);
139
+ console.debug(`[BotName] Skipping setMyName — Telegram cooldown for ~${mins}m more.`);
140
+ return { status: 'still_blocked', blockedUntilMs: blockedUntil };
141
+ }
142
+ const state = getRateState(botKey);
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.
145
+ if (state.lastSentName === name) {
146
+ // A queued (different) name from an earlier call is now superseded — the
147
+ // currently-desired name already matches what's shown. Cancel the stale
148
+ // timer so it doesn't fire a wasted setMyName for a name we've moved past
149
+ // (e.g. A→B→A within the soft interval).
150
+ if (state.pendingTimer) {
151
+ clearTimeout(state.pendingTimer);
152
+ state.pendingTimer = null;
153
+ }
154
+ state.pendingName = null;
155
+ state.pendingApiCall = null;
156
+ return { status: 'no_change' };
157
+ }
158
+ const elapsed = now - state.lastUpdateTime;
159
+ if (elapsed >= MIN_NAME_UPDATE_INTERVAL_MS) {
160
+ state.lastUpdateTime = now;
161
+ state.pendingName = null;
162
+ state.pendingApiCall = null;
163
+ if (state.pendingTimer) {
164
+ clearTimeout(state.pendingTimer);
165
+ state.pendingTimer = null;
166
+ }
167
+ const r = await callAndHandle429(state, apiCall, name, 'immediate');
168
+ if (r.kind === 'newly_blocked') {
169
+ return { status: 'newly_blocked', blockedUntilMs: r.blockedUntilMs };
170
+ }
171
+ return { status: 'sent' };
172
+ }
173
+ state.pendingName = name;
174
+ state.pendingApiCall = apiCall;
175
+ if (!state.pendingTimer) {
176
+ const delay = MIN_NAME_UPDATE_INTERVAL_MS - elapsed;
177
+ state.pendingTimer = setTimeout(async () => {
178
+ state.pendingTimer = null;
179
+ const queuedName = state.pendingName;
180
+ const queuedCall = state.pendingApiCall;
181
+ state.pendingName = null;
182
+ state.pendingApiCall = null;
183
+ if (queuedName === null || !queuedCall)
184
+ return;
185
+ if (state.lastSentName === queuedName)
186
+ return;
187
+ // Re-check the persistent cooldown — it may have been set since this
188
+ // timer was scheduled (e.g. a sibling immediate call hit 429).
189
+ if (getBlockedUntil() > Date.now())
190
+ return;
191
+ state.lastUpdateTime = Date.now();
192
+ try {
193
+ await callAndHandle429(state, queuedCall, queuedName, 'deferred');
194
+ }
195
+ catch (err) {
196
+ console.error('[BotName] Deferred name update failed:', err instanceof Error ? err.message : err);
197
+ }
198
+ }, delay);
199
+ }
200
+ return { status: 'queued' };
201
+ }
202
+ let retryTimer = null;
203
+ /**
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.
236
+ *
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.
239
+ *
240
+ * Deliberately bypasses the `lastSentName` dedup in `rateLimitedSetMyName`:
241
+ * `getMyName()` is authoritative about what Telegram actually shows, and the
242
+ * case worth catching here is exactly the one where our cached name and the
243
+ * live name disagree (BOT_NAME edited between runs, or a BotFather rename).
244
+ * The persistent 429 cooldown still applies.
245
+ *
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.
249
+ */
250
+ export async function syncBotNameOnStartup(api) {
251
+ if (getBotNameSource() === 'default')
252
+ return { status: 'no_change' };
253
+ const wanted = config.BOT_NAME;
254
+ let current;
255
+ try {
256
+ current = (await api.getMyName()).name;
257
+ }
258
+ catch (err) {
259
+ console.debug('[BotName] Startup sync: getMyName failed:', err instanceof Error ? err.message : err);
260
+ return { status: 'no_change' };
261
+ }
262
+ if (current === wanted)
263
+ return { status: 'no_change' };
264
+ const blockedUntil = getBlockedUntil();
265
+ const now = Date.now();
266
+ if (blockedUntil > now) {
267
+ const mins = Math.round((blockedUntil - now) / 60000);
268
+ console.warn(`[BotName] Startup sync: "${current}" → "${wanted}" skipped, Telegram cooldown for ~${mins}m more.`);
269
+ armRetryAfterCooldown(api, blockedUntil);
270
+ return { status: 'still_blocked', blockedUntilMs: blockedUntil };
271
+ }
272
+ console.log(`[BotName] Startup sync: renaming "${current}" → "${wanted}"`);
273
+ const state = getRateState(api);
274
+ state.lastUpdateTime = now;
275
+ const result = await callAndHandle429(state, (n) => api.setMyName(n), wanted, 'startup sync');
276
+ if (result.kind === 'newly_blocked') {
277
+ armRetryAfterCooldown(api, result.blockedUntilMs);
278
+ return { status: 'newly_blocked', blockedUntilMs: result.blockedUntilMs };
279
+ }
280
+ return { status: 'sent' };
281
+ }
282
+ //# sourceMappingURL=botname-settings.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * How wide inline-button text may be before Telegram clips it.
3
+ *
4
+ * An inline button is a single line the client ellipsises, and there is no way
5
+ * for the reader to expand it — text past the clip is not buried, it is gone.
6
+ * So anything the user has to *read* in order to decide belongs in a message
7
+ * body, and the button carries at most a label short enough to survive whole.
8
+ *
9
+ * The number is deliberately conservative: a full-width button on a narrow
10
+ * phone is the case that clips first, and a label that stops short of the cut
11
+ * costs nothing. Both features that put model-written text on a button —
12
+ * `telecoder_ask_user` options and the predicted next prompt — measure
13
+ * against this one constant so they clip at the same place.
14
+ */
15
+ export const MAX_BUTTON_TEXT_LEN = 30;
16
+ /**
17
+ * True when `text` renders on a button without being ellipsised.
18
+ *
19
+ * Length is counted in UTF-16 units rather than code points on purpose: an
20
+ * emoji costs 2 there and renders about twice as wide as a letter, so the
21
+ * cheap count tracks the rendered width better than a "correct" one would.
22
+ */
23
+ export function fitsOnButton(text) {
24
+ return text.length <= MAX_BUTTON_TEXT_LEN;
25
+ }
26
+ //# sourceMappingURL=button-text.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * How the bot reaches api.telegram.org: the proxy, if any, and the timeout.
3
+ *
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.
8
+ */
9
+ import { HttpsProxyAgent } from 'https-proxy-agent';
10
+ import { config } from '../config.js';
11
+ import { findProxy } from '../utils/telegram-proxy.js';
12
+ /** TELEGRAM_PROXY_URL, falling back to the usual proxy variables. */
13
+ export function telegramProxyUrl() {
14
+ return findProxy((setting) => (setting === 'TELEGRAM_PROXY_URL' ? config.TELEGRAM_PROXY_URL : process.env[setting]))?.url;
15
+ }
16
+ export function telegramClientOptions() {
17
+ const proxyUrl = telegramProxyUrl();
18
+ return {
19
+ // Default is 500s which causes long hangs on network interruptions.
20
+ // 60s is enough for long polling (30s) + file uploads while recovering
21
+ // from stuck connections much faster.
22
+ timeoutSeconds: 60,
23
+ baseFetchConfig: proxyUrl ? { agent: new HttpsProxyAgent(proxyUrl) } : undefined,
24
+ };
25
+ }
26
+ //# sourceMappingURL=client-options.js.map
@@ -0,0 +1,33 @@
1
+ const processedMessages = new Map();
2
+ const MESSAGE_TTL = 60000; // 1 minute
3
+ let cleanupInterval = null;
4
+ export function isDuplicate(messageId) {
5
+ return processedMessages.has(messageId);
6
+ }
7
+ export function markProcessed(messageId) {
8
+ processedMessages.set(messageId, Date.now());
9
+ ensureCleanupRunning();
10
+ }
11
+ function ensureCleanupRunning() {
12
+ if (cleanupInterval)
13
+ return;
14
+ cleanupInterval = setInterval(() => {
15
+ const now = Date.now();
16
+ for (const [id, timestamp] of processedMessages) {
17
+ if (now - timestamp > MESSAGE_TTL) {
18
+ processedMessages.delete(id);
19
+ }
20
+ }
21
+ if (processedMessages.size === 0 && cleanupInterval) {
22
+ clearInterval(cleanupInterval);
23
+ cleanupInterval = null;
24
+ }
25
+ }, 30000); // Cleanup every 30 seconds
26
+ }
27
+ export function stopCleanup() {
28
+ if (cleanupInterval) {
29
+ clearInterval(cleanupInterval);
30
+ cleanupInterval = null;
31
+ }
32
+ }
33
+ //# sourceMappingURL=deduplication.js.map
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Plain-text messages carrying explicit Telegram entities.
3
+ *
4
+ * Every message TeleCoder sends is formatted this way; nothing goes out with a
5
+ * parse mode. MarkdownV2 meant escaping, and escaping is exactly what fails
6
+ * when the text being formatted came from the model or from a shell command — a
7
+ * stray underscore in a URL parameter or an unbalanced backtick in a `sed`
8
+ * script turned a `sendMessage` into a 400. It also could not be split: a long
9
+ * reply cut in the middle of a bold run or a link broke both halves.
10
+ *
11
+ * Entities sidestep that: the text is sent verbatim with no parse mode, and the
12
+ * formatting rides alongside as offsets. Nothing in the payload can be
13
+ * misparsed, because nothing is parsed.
14
+ *
15
+ * It also buys the one thing MarkdownV2 cannot express — `text_mention`, a
16
+ * mention of a user by numeric id. That is what makes an approval prompt raise
17
+ * a notification for the admin who has to answer it, even in a muted group,
18
+ * and even for an admin who has no @username.
19
+ *
20
+ * Offsets are UTF-16 code units, which is what `String.length` counts, so the
21
+ * running length below is the offset Telegram expects — including for emoji,
22
+ * which occupy two units each.
23
+ */
24
+ /**
25
+ * Accumulates text and the entities that describe it. Every method returns
26
+ * `this` so a message reads top-to-bottom in the order it renders.
27
+ */
28
+ export class EntityText {
29
+ parts = [];
30
+ offset = 0;
31
+ entities = [];
32
+ /** Append unstyled text. */
33
+ add(text) {
34
+ if (text) {
35
+ this.parts.push(text);
36
+ this.offset += text.length;
37
+ }
38
+ return this;
39
+ }
40
+ /** Append a newline (or several). */
41
+ newline(count = 1) {
42
+ return this.add('\n'.repeat(count));
43
+ }
44
+ styled(text, entity) {
45
+ if (!text)
46
+ return this;
47
+ this.entities.push(entity(this.offset, text.length));
48
+ return this.add(text);
49
+ }
50
+ bold(text) {
51
+ return this.styled(text, (offset, length) => ({ type: 'bold', offset, length }));
52
+ }
53
+ italic(text) {
54
+ return this.styled(text, (offset, length) => ({ type: 'italic', offset, length }));
55
+ }
56
+ /** Inline monospace — for a tool name, a path, a flag. */
57
+ code(text) {
58
+ return this.styled(text, (offset, length) => ({ type: 'code', offset, length }));
59
+ }
60
+ /**
61
+ * A monospace block, for a shell command or other multi-line verbatim text.
62
+ * Telegram renders `pre` with its own trailing newline, so callers should not
63
+ * add one inside `text`.
64
+ */
65
+ pre(text, language) {
66
+ return this.styled(text, (offset, length) => ({
67
+ type: 'pre',
68
+ offset,
69
+ length,
70
+ ...(language ? { language } : {}),
71
+ }));
72
+ }
73
+ strikethrough(text) {
74
+ return this.styled(text, (offset, length) => ({ type: 'strikethrough', offset, length }));
75
+ }
76
+ underline(text) {
77
+ return this.styled(text, (offset, length) => ({ type: 'underline', offset, length }));
78
+ }
79
+ spoiler(text) {
80
+ return this.styled(text, (offset, length) => ({ type: 'spoiler', offset, length }));
81
+ }
82
+ /**
83
+ * `text` as a link to `url`, which the reader doesn't have to see spelled out.
84
+ *
85
+ * Telegram refuses the whole message over a link it won't accept — one to
86
+ * `http://localhost:3000`, say, which has no TLD. Such a link goes out as
87
+ * plain text instead, with the address after it when the label hides it.
88
+ */
89
+ link(text, url) {
90
+ if (!isLinkableUrl(url))
91
+ return this.add(text === url || !text ? url : `${text} (${url})`);
92
+ return this.styled(text || url, (offset, length) => ({ type: 'text_link', offset, length, url }));
93
+ }
94
+ /**
95
+ * A quote; `expandable` collapses it to its first lines until tapped. Telegram
96
+ * does not nest quotes, so callers must not open one inside another.
97
+ */
98
+ quote(text, expandable = false) {
99
+ const type = expandable ? 'expandable_blockquote' : 'blockquote';
100
+ return this.wrap(type, (b) => (typeof text === 'string' ? b.add(text) : b.append(text)));
101
+ }
102
+ /**
103
+ * Wrap whatever `build` appends in one entity of `type`, so it can carry
104
+ * entities of its own: bold inside a link, code inside a quote.
105
+ */
106
+ wrap(type, build, extra = {}) {
107
+ const start = this.offset;
108
+ const at = this.entities.length;
109
+ build(this);
110
+ const length = this.offset - start;
111
+ if (length > 0) {
112
+ // Before the entities appended inside it, so a reader of the list meets
113
+ // the outer one first, as Telegram itself orders them.
114
+ this.entities.splice(at, 0, { type, offset: start, length, ...extra });
115
+ }
116
+ return this;
117
+ }
118
+ /**
119
+ * Mention a user by numeric id. Telegram notifies them if they are a member
120
+ * of the chat, whether or not they have a @username, and renders `label` as
121
+ * a link to their profile.
122
+ */
123
+ mention(label, userId) {
124
+ return this.styled(label, (offset, length) => ({
125
+ type: 'text_mention',
126
+ offset,
127
+ length,
128
+ // Telegram only reads `id` off this object; the rest of grammy's User
129
+ // shape is required by the type but ignored on the wire.
130
+ user: { id: userId, is_bot: false, first_name: label },
131
+ }));
132
+ }
133
+ /**
134
+ * A moment in time, which Telegram shows in the reader's own timezone and
135
+ * format — Bot API 9.5's `date_time` entity. The bot runs on a server whose
136
+ * clock can be hours off the reader's, so a time it writes out itself can be
137
+ * too. `text` is what a client too old for the entity shows instead.
138
+ *
139
+ * `format` is Telegram's: `t` a short time (22:45), `T` one with seconds.
140
+ */
141
+ dateTime(text, unixMs, format = 't') {
142
+ return this.styled(text, (offset, length) => ({
143
+ type: 'date_time',
144
+ offset,
145
+ length,
146
+ unix_time: Math.floor(unixMs / 1000),
147
+ date_time_format: format,
148
+ // grammy's MessageEntity predates Bot API 9.5 and has no `date_time`.
149
+ }));
150
+ }
151
+ /** Append another built message, its entities shifted to where it lands. */
152
+ append(message) {
153
+ for (const entity of message.entities) {
154
+ this.entities.push({ ...entity, offset: entity.offset + this.offset });
155
+ }
156
+ return this.add(message.text);
157
+ }
158
+ /** Current length in UTF-16 code units — the unit Telegram's 4096 cap counts. */
159
+ get length() {
160
+ return this.offset;
161
+ }
162
+ build() {
163
+ return { text: this.parts.join(''), entities: this.entities };
164
+ }
165
+ }
166
+ /**
167
+ * Clip text to `max` code units, marking the cut. Entity offsets are computed
168
+ * from the text as appended, so anything long has to be shortened *before* it
169
+ * goes into the builder rather than after.
170
+ */
171
+ export function clip(text, max) {
172
+ if (text.length <= max)
173
+ return text;
174
+ // Never between the halves of a surrogate pair: half an emoji is invalid
175
+ // UTF-16, which Telegram refuses.
176
+ let cut = Math.max(0, max - 1);
177
+ if (cut > 0 && isHighSurrogate(text.charCodeAt(cut - 1)))
178
+ cut--;
179
+ return text.slice(0, cut) + '…';
180
+ }
181
+ export function isHighSurrogate(code) {
182
+ return code >= 0xd800 && code <= 0xdbff;
183
+ }
184
+ /**
185
+ * Whether Telegram accepts `url` on a `text_link`. It wants a web address with
186
+ * a real top-level domain (no `localhost`, no bare IP, no single-label
187
+ * intranet host) or one of its own `tg:` links; anything else makes it refuse
188
+ * the entire message.
189
+ */
190
+ export function isLinkableUrl(url) {
191
+ let parsed;
192
+ try {
193
+ parsed = new URL(url);
194
+ }
195
+ catch {
196
+ return false;
197
+ }
198
+ if (parsed.protocol === 'tg:')
199
+ return true;
200
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
201
+ return false;
202
+ const labels = parsed.hostname.split('.');
203
+ if (labels.length < 2 || labels.some((l) => !l))
204
+ return false;
205
+ const tld = labels[labels.length - 1];
206
+ return /^(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/i.test(tld);
207
+ }
208
+ /** Plain text, no formatting. */
209
+ export function plain(text) {
210
+ return { text, entities: [] };
211
+ }
212
+ /** Join messages with `separator`, shifting each one's entities into place. */
213
+ export function joinMessages(messages, separator = '\n\n') {
214
+ const b = new EntityText();
215
+ messages.forEach((m, i) => {
216
+ if (i > 0)
217
+ b.add(separator);
218
+ b.append(m);
219
+ });
220
+ return b.build();
221
+ }
222
+ /**
223
+ * The slice `[start, end)` of a message, with its entities cut to fit. An
224
+ * entity running across either edge keeps the part inside, which is what lets
225
+ * a long reply be split in the middle of a bold run or a code block and keep
226
+ * the formatting on both sides.
227
+ */
228
+ export function sliceMessage(message, start, end = message.text.length) {
229
+ const entities = [];
230
+ for (const e of message.entities) {
231
+ const from = Math.max(e.offset, start);
232
+ const to = Math.min(e.offset + e.length, end);
233
+ if (to <= from)
234
+ continue;
235
+ entities.push({ ...e, offset: from - start, length: to - from });
236
+ }
237
+ return { text: message.text.slice(start, end), entities: dropBlankEntities(message.text.slice(start, end), entities) };
238
+ }
239
+ /**
240
+ * Strip leading and trailing whitespace, as Telegram does to every message on
241
+ * arrival. It strips it *before* applying the offsets, so a message that
242
+ * starts with a newline would otherwise have all its formatting shifted one
243
+ * character to the left — or refused, when an entity then runs off the end.
244
+ */
245
+ export function trimMessage(message) {
246
+ const start = message.text.length - message.text.trimStart().length;
247
+ const end = message.text.trimEnd().length;
248
+ if (start === 0 && end === message.text.length)
249
+ return message;
250
+ if (end <= start)
251
+ return plain('');
252
+ return sliceMessage(message, start, end);
253
+ }
254
+ /**
255
+ * Drop entities with nothing visible in them. Telegram rejects a message with
256
+ * an entity over whitespace alone ("text must be non-empty") for some types,
257
+ * and a slice can leave one behind at either edge.
258
+ */
259
+ function dropBlankEntities(text, entities) {
260
+ return entities.filter((e) => e.length > 0 && (e.type === 'pre' || text.slice(e.offset, e.offset + e.length).trim() !== ''));
261
+ }
262
+ /**
263
+ * Prefix every line of `message` with `prefix`, keeping its entities on the
264
+ * same characters. For list items: a nested paragraph or sub-list lines up
265
+ * under its bullet.
266
+ */
267
+ export function indentMessage(message, prefix, skipFirstLine = false) {
268
+ if (!prefix)
269
+ return message;
270
+ const { text } = message;
271
+ // shift[i] is how far character i moves: one prefix for every line start at
272
+ // or before it.
273
+ const shift = new Array(text.length + 1);
274
+ let added = 0;
275
+ let out = '';
276
+ for (let i = 0; i <= text.length; i++) {
277
+ const lineStart = i === 0 ? !skipFirstLine : text[i - 1] === '\n';
278
+ if (lineStart && i < text.length && text[i] !== '\n') {
279
+ out += prefix;
280
+ added += prefix.length;
281
+ }
282
+ shift[i] = added;
283
+ if (i < text.length)
284
+ out += text[i];
285
+ }
286
+ const entities = message.entities.map((e) => {
287
+ const from = e.offset + shift[e.offset];
288
+ // The end keeps the shift of the last character inside the entity, so a
289
+ // prefix inserted at the next line's start stays outside it.
290
+ const lastShift = e.length > 0 ? shift[e.offset + e.length - 1] : shift[e.offset];
291
+ return { ...e, offset: from, length: e.offset + e.length + lastShift - from };
292
+ });
293
+ return { text: out, entities };
294
+ }
295
+ //# sourceMappingURL=entities.js.map