telecoder 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +363 -0
- package/CHANGELOG.md +1186 -0
- package/LICENSE +22 -0
- package/README.md +126 -2
- package/dist/audio/transcribe.js +50 -0
- package/dist/bin/mcp-server.js +378 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +592 -0
- package/dist/bot/file-access.js +141 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +827 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/btw.js +224 -0
- package/dist/bot/handlers/command/cost.js +409 -0
- package/dist/bot/handlers/command/media.js +197 -0
- package/dist/bot/handlers/command/model.js +305 -0
- package/dist/bot/handlers/command/prefs-scope.js +197 -0
- package/dist/bot/handlers/command/project.js +536 -0
- package/dist/bot/handlers/command/resume.js +321 -0
- package/dist/bot/handlers/command/session.js +438 -0
- package/dist/bot/handlers/command/settings.js +1012 -0
- package/dist/bot/handlers/command/shared.js +210 -0
- package/dist/bot/handlers/command/streaming-mode.js +16 -0
- package/dist/bot/handlers/command/tasks.js +513 -0
- package/dist/bot/handlers/command/topic-store.js +113 -0
- package/dist/bot/handlers/command/topic.js +80 -0
- package/dist/bot/handlers/command.handler.js +772 -0
- package/dist/bot/handlers/fork.handler.js +1109 -0
- package/dist/bot/handlers/media-fallback.js +121 -0
- package/dist/bot/handlers/message/replies.js +133 -0
- package/dist/bot/handlers/message/shared.js +117 -0
- package/dist/bot/handlers/message/throttle.js +49 -0
- package/dist/bot/handlers/message/turn-notify.js +169 -0
- package/dist/bot/handlers/message/turn-runner.js +141 -0
- package/dist/bot/handlers/message.handler.js +107 -0
- package/dist/bot/handlers/newbot.handler.js +221 -0
- package/dist/bot/handlers/photo.handler.js +327 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/schedule.handler.js +303 -0
- package/dist/bot/handlers/session-guard.js +78 -0
- package/dist/bot/handlers/suggestion.handler.js +84 -0
- package/dist/bot/handlers/tree.handler.js +480 -0
- package/dist/bot/handlers/view.js +41 -0
- package/dist/bot/handlers/voice.handler.js +209 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +139 -0
- package/dist/bot/middleware/group-role.middleware.js +75 -0
- package/dist/bot/middleware/message-batcher.js +87 -0
- package/dist/bot/middleware/queued-messages.js +971 -0
- package/dist/bot/middleware/stale-filter.js +31 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/agent-watchdog.js +162 -0
- package/dist/claude/agent.js +1458 -0
- package/dist/claude/ask-user.js +295 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +126 -0
- package/dist/claude/available-commands.js +153 -0
- package/dist/claude/carry-over.js +27 -0
- package/dist/claude/ccr-shim.js +46 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +121 -0
- package/dist/claude/command-parser.js +200 -0
- package/dist/claude/cost-overlay-scraper.js +129 -0
- package/dist/claude/enabled-plugins.js +56 -0
- package/dist/claude/fork-tree.js +393 -0
- package/dist/claude/held-query.js +190 -0
- package/dist/claude/in-flight-tracker.js +61 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +453 -0
- package/dist/claude/mcp-tools.js +354 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +450 -0
- package/dist/claude/model-catalog.js +85 -0
- package/dist/claude/monitor-relay.js +597 -0
- package/dist/claude/pending-forks.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +337 -0
- package/dist/claude/permission-mode.js +178 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/project-commands.js +69 -0
- package/dist/claude/prompt-hold.js +124 -0
- package/dist/claude/prompt-suggestion-scraper.js +89 -0
- package/dist/claude/pty-provider.js +2214 -0
- package/dist/claude/pty-spawn-config.js +296 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/request-queue.js +135 -0
- package/dist/claude/scheduled-runner.js +91 -0
- package/dist/claude/scheduler.js +237 -0
- package/dist/claude/scope-guard.js +274 -0
- package/dist/claude/sdk-permission-gate.js +77 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-cost.js +41 -0
- package/dist/claude/session-history.js +286 -0
- package/dist/claude/session-jsonl.js +920 -0
- package/dist/claude/session-manager.js +195 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +249 -0
- package/dist/claude/stage-images.js +62 -0
- package/dist/claude/subagent-tools.js +12 -0
- package/dist/claude/synthetic-ctx.js +51 -0
- package/dist/claude/system-prompt.js +162 -0
- package/dist/claude/tasks-overlay-scraper.js +94 -0
- package/dist/claude/tip-scraper.js +78 -0
- package/dist/claude/tui-modal.js +501 -0
- package/dist/claude/tui-state.js +384 -0
- package/dist/claude/turn-end.js +91 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +305 -0
- package/dist/cli/commands/help.js +25 -0
- package/dist/cli/commands/init.js +123 -0
- package/dist/cli/commands/service.js +678 -0
- package/dist/cli/commands/start.js +53 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/dispatch.js +79 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +638 -0
- package/dist/cli/init/prompter.js +116 -0
- package/dist/cli/init/telegram.js +94 -0
- package/dist/cli/service/render.js +212 -0
- package/dist/cli.js +18 -0
- package/dist/config-report.js +107 -0
- package/dist/config.js +500 -0
- package/dist/index.js +367 -0
- package/dist/launcher.js +933 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +149 -0
- package/dist/providers/ccr-provider.js +60 -0
- package/dist/providers/claude-provider.js +63 -0
- package/dist/providers/prefs-sync.js +164 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +127 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/sdk-provider.js +37 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +214 -0
- package/dist/restart-when-idle.js +153 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +173 -0
- package/dist/startup/notices.js +120 -0
- package/dist/startup/shared.js +44 -0
- package/dist/startup/verify-token.js +31 -0
- package/dist/telegram/access-request.js +153 -0
- package/dist/telegram/action-logger.js +684 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +336 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +27 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +57 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1287 -0
- package/dist/telegram/prompt-label.js +142 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +105 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +209 -0
- package/dist/telegram/telegraph-settings.js +31 -0
- package/dist/telegram/telegraph.js +453 -0
- package/dist/telegram/terminal-renderer.js +671 -0
- package/dist/telegram/terminal-settings.js +25 -0
- package/dist/telegram/thread-titles.js +190 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/tts/tts-settings.js +62 -0
- package/dist/tts/tts.js +245 -0
- package/dist/tts/voice-reply.js +78 -0
- package/dist/utils/admins.js +143 -0
- package/dist/utils/agent-timer.js +55 -0
- package/dist/utils/atomic-write.js +24 -0
- package/dist/utils/bot-token.js +74 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +50 -0
- package/dist/utils/claude-env.js +54 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/debug-agent.js +117 -0
- package/dist/utils/debug-watchdog.js +121 -0
- package/dist/utils/download.js +111 -0
- package/dist/utils/exit-codes.js +48 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +81 -0
- package/dist/utils/home-project.js +30 -0
- package/dist/utils/host-stall.js +51 -0
- package/dist/utils/id-list.js +44 -0
- package/dist/utils/idle-restart.js +92 -0
- package/dist/utils/install-mode.js +63 -0
- package/dist/utils/instance-config.js +148 -0
- package/dist/utils/instances.js +95 -0
- package/dist/utils/json-store.js +140 -0
- package/dist/utils/keyed-settings.js +62 -0
- package/dist/utils/legacy-env.js +35 -0
- package/dist/utils/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/project-data-dir.js +33 -0
- package/dist/utils/reasoning-summary.js +12 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +63 -0
- package/dist/utils/respawn-backoff.js +19 -0
- package/dist/utils/sanitize.js +91 -0
- package/dist/utils/session-key.js +37 -0
- package/dist/utils/stale-launcher.js +109 -0
- package/dist/utils/state-dir-migration.js +92 -0
- package/dist/utils/systemd.js +126 -0
- package/dist/utils/user-roster.js +275 -0
- package/dist/utils/verbosity.js +118 -0
- package/dist/utils/version-check.js +166 -0
- package/dist/utils/workspace-guard.js +44 -0
- package/dist/worker-restart.js +141 -0
- package/instances.json.example +41 -0
- package/package.json +76 -4
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dynamic bot name settings per chat.
|
|
3
|
+
* When enabled, the Telegram bot display name updates to include the active project.
|
|
4
|
+
*/
|
|
5
|
+
import { config, BOT_ID, explicitFlags } from '../config.js';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import { GrammyError } from 'grammy';
|
|
9
|
+
import { createKeyedSettings } from '../utils/keyed-settings.js';
|
|
10
|
+
import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
|
|
11
|
+
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
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Rate-limited setMyName wrapper
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
const MIN_NAME_UPDATE_INTERVAL_MS = 60_000; // 1 minute soft cooldown
|
|
33
|
+
// One file per bot, like the rest of the per-bot state. Each bot is its own
|
|
34
|
+
// process, and when they shared a file each one rewrote it from the copy it
|
|
35
|
+
// loaded at startup, undoing what the others had saved since. A wrong last-sent
|
|
36
|
+
// name makes a real rename look like no change, and a lost block sends a call
|
|
37
|
+
// Telegram has already refused. The old shared setmyname-cooldowns.json and
|
|
38
|
+
// setmyname-lastsent.json are deliberately not read: their entries can't be
|
|
39
|
+
// trusted, and starting without them costs at most one extra call per bot.
|
|
40
|
+
const COOLDOWN_FILE = path.join(SETTINGS_DIR, `setmyname-cooldown-${BOT_ID}.json`);
|
|
41
|
+
const LAST_SENT_FILE = path.join(SETTINGS_DIR, `setmyname-lastsent-${BOT_ID}.json`);
|
|
42
|
+
const cooldownSchema = z.object({ blockedUntil: z.number() });
|
|
43
|
+
const lastSentSchema = z.object({ name: z.string() });
|
|
44
|
+
// Persistent 429 cooldown. Telegram's setMyName limit is much stricter than our
|
|
45
|
+
// soft local interval, and the local state is reset on every restart — so we
|
|
46
|
+
// honor any retry_after Telegram returns and persist the "do not call before"
|
|
47
|
+
// timestamp to disk.
|
|
48
|
+
ensureStateDir(SETTINGS_DIR, 'BotName');
|
|
49
|
+
let cooldownUntil = readJsonFile(COOLDOWN_FILE, cooldownSchema, 'BotName')?.blockedUntil ?? 0;
|
|
50
|
+
function getBlockedUntil() {
|
|
51
|
+
return cooldownUntil;
|
|
52
|
+
}
|
|
53
|
+
function setBlockedUntil(blockedUntil) {
|
|
54
|
+
cooldownUntil = blockedUntil;
|
|
55
|
+
ensureStateDir(SETTINGS_DIR, 'BotName');
|
|
56
|
+
writeJsonFile(COOLDOWN_FILE, { blockedUntil }, 'BotName');
|
|
57
|
+
}
|
|
58
|
+
// The last successfully-sent display name, persisted to disk. The in-memory
|
|
59
|
+
// dedup (`state.lastSentName`) is reset on every restart, so without this the
|
|
60
|
+
// 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.
|
|
64
|
+
function getPersistedLastSentName() {
|
|
65
|
+
return readJsonFile(LAST_SENT_FILE, lastSentSchema, 'BotName')?.name ?? null;
|
|
66
|
+
}
|
|
67
|
+
function setPersistedLastSentName(name) {
|
|
68
|
+
ensureStateDir(SETTINGS_DIR, 'BotName');
|
|
69
|
+
writeJsonFile(LAST_SENT_FILE, { name }, 'BotName');
|
|
70
|
+
}
|
|
71
|
+
/** Parse Telegram's retry_after (seconds) from a Grammy/HTTP error. */
|
|
72
|
+
function extractRetryAfterMs(err) {
|
|
73
|
+
if (err instanceof GrammyError && err.error_code === 429) {
|
|
74
|
+
const sec = err.parameters?.retry_after;
|
|
75
|
+
if (typeof sec === 'number' && sec > 0)
|
|
76
|
+
return sec * 1000;
|
|
77
|
+
}
|
|
78
|
+
// Fallback: parse "(429: Too Many Requests: retry after N)" out of the message.
|
|
79
|
+
if (err instanceof Error) {
|
|
80
|
+
const m = err.message.match(/429:[^)]*retry after (\d+)/i);
|
|
81
|
+
if (m) {
|
|
82
|
+
const sec = Number.parseInt(m[1], 10);
|
|
83
|
+
if (Number.isFinite(sec) && sec > 0)
|
|
84
|
+
return sec * 1000;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
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
|
+
// Per-bot soft-throttle state. Keyed by the bot's `api` object (stable per
|
|
96
|
+
// bot) so multiple bots running in the same process don't collide on a
|
|
97
|
+
// shared slot. WeakMap lets state get GC'd if a bot is torn down.
|
|
98
|
+
const nameRateStates = new WeakMap();
|
|
99
|
+
function getRateState(key) {
|
|
100
|
+
let state = nameRateStates.get(key);
|
|
101
|
+
if (!state) {
|
|
102
|
+
// Seed lastSentName from disk so the `no_change` dedup survives restarts —
|
|
103
|
+
// otherwise the first push after every restart re-sends an unchanged name.
|
|
104
|
+
state = { lastUpdateTime: 0, lastSentName: getPersistedLastSentName(), pendingName: null, pendingApiCall: null, pendingTimer: null };
|
|
105
|
+
nameRateStates.set(key, state);
|
|
106
|
+
}
|
|
107
|
+
return state;
|
|
108
|
+
}
|
|
109
|
+
async function callAndHandle429(state, apiCall, name, source) {
|
|
110
|
+
try {
|
|
111
|
+
await apiCall(name);
|
|
112
|
+
state.lastSentName = name;
|
|
113
|
+
setPersistedLastSentName(name);
|
|
114
|
+
return { kind: 'sent' };
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
const retryAfterMs = extractRetryAfterMs(err);
|
|
118
|
+
if (retryAfterMs !== undefined) {
|
|
119
|
+
const until = Date.now() + retryAfterMs;
|
|
120
|
+
setBlockedUntil(until);
|
|
121
|
+
const mins = Math.round(retryAfterMs / 60000);
|
|
122
|
+
console.warn(`[BotName] ${source}: setMyName rate-limited by Telegram, blocked for ~${mins}m (until ${new Date(until).toISOString()})`);
|
|
123
|
+
return { kind: 'newly_blocked', blockedUntilMs: until };
|
|
124
|
+
}
|
|
125
|
+
throw err;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Rate-limited wrapper around `bot.api.setMyName()`.
|
|
130
|
+
*
|
|
131
|
+
* Two layers of throttling:
|
|
132
|
+
* 1. A persistent server-side cooldown — when Telegram returns 429 with a
|
|
133
|
+
* `retry_after`, we record `now + retry_after` to disk and refuse all
|
|
134
|
+
* further calls until that timestamp passes. Survives bot restarts.
|
|
135
|
+
* 2. A soft 1-minute local interval — at most one outbound call per minute
|
|
136
|
+
* per bot; if called more frequently the latest name is queued and
|
|
137
|
+
* applied when the cooldown expires.
|
|
138
|
+
*
|
|
139
|
+
* `botKey` must be a stable object identifying the bot (typically `ctx.api`
|
|
140
|
+
* or `bot.api`). State is tracked per-key so multiple bots in the same
|
|
141
|
+
* process don't share a throttle slot.
|
|
142
|
+
*/
|
|
143
|
+
export async function rateLimitedSetMyName(botKey, apiCall, name) {
|
|
144
|
+
nameClaimedThisProcess = true;
|
|
145
|
+
const blockedUntil = getBlockedUntil();
|
|
146
|
+
const now = Date.now();
|
|
147
|
+
if (blockedUntil > now) {
|
|
148
|
+
const mins = Math.round((blockedUntil - now) / 60000);
|
|
149
|
+
console.debug(`[BotName] Skipping setMyName — Telegram cooldown for ~${mins}m more.`);
|
|
150
|
+
return { status: 'still_blocked', blockedUntilMs: blockedUntil };
|
|
151
|
+
}
|
|
152
|
+
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.
|
|
156
|
+
if (state.lastSentName === name) {
|
|
157
|
+
// A queued (different) name from an earlier switch is now superseded — the
|
|
158
|
+
// currently-desired name already matches what's shown. Cancel the stale
|
|
159
|
+
// 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).
|
|
161
|
+
if (state.pendingTimer) {
|
|
162
|
+
clearTimeout(state.pendingTimer);
|
|
163
|
+
state.pendingTimer = null;
|
|
164
|
+
}
|
|
165
|
+
state.pendingName = null;
|
|
166
|
+
state.pendingApiCall = null;
|
|
167
|
+
return { status: 'no_change' };
|
|
168
|
+
}
|
|
169
|
+
const elapsed = now - state.lastUpdateTime;
|
|
170
|
+
if (elapsed >= MIN_NAME_UPDATE_INTERVAL_MS) {
|
|
171
|
+
state.lastUpdateTime = now;
|
|
172
|
+
state.pendingName = null;
|
|
173
|
+
state.pendingApiCall = null;
|
|
174
|
+
if (state.pendingTimer) {
|
|
175
|
+
clearTimeout(state.pendingTimer);
|
|
176
|
+
state.pendingTimer = null;
|
|
177
|
+
}
|
|
178
|
+
const r = await callAndHandle429(state, apiCall, name, 'immediate');
|
|
179
|
+
if (r.kind === 'newly_blocked') {
|
|
180
|
+
return { status: 'newly_blocked', blockedUntilMs: r.blockedUntilMs };
|
|
181
|
+
}
|
|
182
|
+
return { status: 'sent' };
|
|
183
|
+
}
|
|
184
|
+
state.pendingName = name;
|
|
185
|
+
state.pendingApiCall = apiCall;
|
|
186
|
+
if (!state.pendingTimer) {
|
|
187
|
+
const delay = MIN_NAME_UPDATE_INTERVAL_MS - elapsed;
|
|
188
|
+
state.pendingTimer = setTimeout(async () => {
|
|
189
|
+
state.pendingTimer = null;
|
|
190
|
+
const queuedName = state.pendingName;
|
|
191
|
+
const queuedCall = state.pendingApiCall;
|
|
192
|
+
state.pendingName = null;
|
|
193
|
+
state.pendingApiCall = null;
|
|
194
|
+
if (queuedName === null || !queuedCall)
|
|
195
|
+
return;
|
|
196
|
+
if (state.lastSentName === queuedName)
|
|
197
|
+
return;
|
|
198
|
+
// Re-check the persistent cooldown — it may have been set since this
|
|
199
|
+
// timer was scheduled (e.g. a sibling immediate call hit 429).
|
|
200
|
+
if (getBlockedUntil() > Date.now())
|
|
201
|
+
return;
|
|
202
|
+
state.lastUpdateTime = Date.now();
|
|
203
|
+
try {
|
|
204
|
+
await callAndHandle429(state, queuedCall, queuedName, 'deferred');
|
|
205
|
+
}
|
|
206
|
+
catch (err) {
|
|
207
|
+
console.error('[BotName] Deferred name update failed:', err instanceof Error ? err.message : err);
|
|
208
|
+
}
|
|
209
|
+
}, delay);
|
|
210
|
+
}
|
|
211
|
+
return { status: 'queued' };
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Reconcile the Telegram display name with `BOT_NAME` once at startup.
|
|
215
|
+
*
|
|
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.
|
|
220
|
+
*
|
|
221
|
+
* Deliberately bypasses the `lastSentName` dedup in `rateLimitedSetMyName`:
|
|
222
|
+
* `getMyName()` is authoritative about what Telegram actually shows, and the
|
|
223
|
+
* case worth catching here is exactly the one where our cached name and the
|
|
224
|
+
* live name disagree (BOT_NAME edited between runs, or a BotFather rename).
|
|
225
|
+
* The persistent 429 cooldown still applies.
|
|
226
|
+
*
|
|
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.
|
|
231
|
+
*/
|
|
232
|
+
export async function syncBotNameOnStartup(api) {
|
|
233
|
+
if (nameClaimedThisProcess)
|
|
234
|
+
return { status: 'no_change' };
|
|
235
|
+
if (!explicitFlags.BOT_NAME && !config.DYNAMIC_BOT_NAME)
|
|
236
|
+
return { status: 'no_change' };
|
|
237
|
+
const base = config.BOT_NAME;
|
|
238
|
+
let current;
|
|
239
|
+
try {
|
|
240
|
+
current = (await api.getMyName()).name;
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
console.debug('[BotName] Startup sync: getMyName failed:', err instanceof Error ? err.message : err);
|
|
244
|
+
return { status: 'no_change' };
|
|
245
|
+
}
|
|
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} — `))
|
|
250
|
+
return { status: 'no_change' };
|
|
251
|
+
const blockedUntil = getBlockedUntil();
|
|
252
|
+
const now = Date.now();
|
|
253
|
+
if (blockedUntil > now) {
|
|
254
|
+
const mins = Math.round((blockedUntil - now) / 60000);
|
|
255
|
+
console.warn(`[BotName] Startup sync: "${current}" → "${base}" skipped, Telegram cooldown for ~${mins}m more.`);
|
|
256
|
+
return { status: 'still_blocked', blockedUntilMs: blockedUntil };
|
|
257
|
+
}
|
|
258
|
+
console.log(`[BotName] Startup sync: renaming "${current}" → "${base}"`);
|
|
259
|
+
const state = getRateState(api);
|
|
260
|
+
state.lastUpdateTime = now;
|
|
261
|
+
const result = await callAndHandle429(state, (n) => api.setMyName(n), base, 'startup sync');
|
|
262
|
+
if (result.kind === 'newly_blocked') {
|
|
263
|
+
return { status: 'newly_blocked', blockedUntilMs: result.blockedUntilMs };
|
|
264
|
+
}
|
|
265
|
+
nameClaimedThisProcess = true;
|
|
266
|
+
return { status: 'sent' };
|
|
267
|
+
}
|
|
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
|
+
//# 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,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the bot reaches api.telegram.org: the proxy, if any, and the timeout.
|
|
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.
|
|
7
|
+
*/
|
|
8
|
+
import { HttpsProxyAgent } from 'https-proxy-agent';
|
|
9
|
+
import { config } from '../config.js';
|
|
10
|
+
/** TELEGRAM_PROXY_URL, falling back to the usual proxy variables. */
|
|
11
|
+
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;
|
|
16
|
+
}
|
|
17
|
+
export function telegramClientOptions() {
|
|
18
|
+
const proxyUrl = telegramProxyUrl();
|
|
19
|
+
return {
|
|
20
|
+
// Default is 500s which causes long hangs on network interruptions.
|
|
21
|
+
// 60s is enough for long polling (30s) + file uploads while recovering
|
|
22
|
+
// from stuck connections much faster.
|
|
23
|
+
timeoutSeconds: 60,
|
|
24
|
+
baseFetchConfig: proxyUrl ? { agent: new HttpsProxyAgent(proxyUrl) } : undefined,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
//# 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
|