@deepseek-insight/telegram-bot 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -2
- package/bin/dsi-telegram.mjs +17 -0
- package/dist/attachments.js +91 -0
- package/dist/chat-map.js +71 -0
- package/dist/commands.js +20 -0
- package/dist/dsi-client.js +62 -0
- package/dist/floor-cli.js +398 -0
- package/dist/index.js +405 -0
- package/dist/reply-stream.js +116 -0
- package/dist/slot.js +56 -0
- package/dist/status-listener.js +39 -0
- package/package.json +35 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* telegram-bot entry (ADR-0090 D3/D4) — grammY long-poll, allow-list gate,
|
|
3
|
+
* command router. The ONLY module that knows grammY. `routeUpdate` is pure
|
|
4
|
+
* over injected deps so the behaviour is testable without Telegram.
|
|
5
|
+
*
|
|
6
|
+
* The command vocabulary lives in commands.ts (ADR-0092 D2 — the one list,
|
|
7
|
+
* pushed to Telegram at boot and mirrored by the README table):
|
|
8
|
+
* /id /new /ws /status /cancel /N as before (ADR-0090 D4/D8)
|
|
9
|
+
* /skills [name [args]] the skill door: bare lists the host catalog; with a
|
|
10
|
+
* name it forwards /name args as a prompt (ADR-0092 D4-D8)
|
|
11
|
+
* any other slash the unknown-command hint
|
|
12
|
+
* anything else a prompt (text, photo, document)
|
|
13
|
+
*/
|
|
14
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
15
|
+
import { homedir } from 'node:os';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { Bot } from 'grammy';
|
|
19
|
+
import YAML from 'yaml';
|
|
20
|
+
import { shapeAttachments } from "./attachments.js";
|
|
21
|
+
import { CHAT_MAP_PATH, get, loadChatMap, saveChatMap, setCwd, setSession } from "./chat-map.js";
|
|
22
|
+
import { menuCommands, unknownCommandHint } from "./commands.js";
|
|
23
|
+
import { createDsiClient, DsiClientError } from "./dsi-client.js";
|
|
24
|
+
import { splitMessage, streamReply } from "./reply-stream.js";
|
|
25
|
+
import { peekSlotFromStamp } from "./slot.js";
|
|
26
|
+
import { startStatusListener } from "./status-listener.js";
|
|
27
|
+
export const DEFAULT_SETTINGS_PATH = join(homedir(), '.dsi', 'settings.yaml');
|
|
28
|
+
/**
|
|
29
|
+
* No default DSI_URL (ADR-0091 D3): the stamp names the floor — a bot without
|
|
30
|
+
* one is a bot guessing. This line is the boot error when DSI_URL is missing.
|
|
31
|
+
*/
|
|
32
|
+
export const MISSING_DSI_URL_LINE = '[telegram-bot] not starting: DSI_URL is unset — your floor stamps every session with DSI_UI (http://127.0.0.1:5x75 dev / 5x74 build); start the bot with the dsi-telegram skill (--on), or pass DSI_URL=<DSI_UI> explicitly';
|
|
33
|
+
export const NOT_AUTHORIZED = 'Not authorized.';
|
|
34
|
+
export const NOTHING_TO_ANSWER = 'nothing to answer';
|
|
35
|
+
/** Missing file/section → empty defaults; the boot step owns the clear error. */
|
|
36
|
+
export function readTelegramSettings(path = DEFAULT_SETTINGS_PATH) {
|
|
37
|
+
let doc = {};
|
|
38
|
+
try {
|
|
39
|
+
doc = (YAML.parse(readFileUtf8(path)) ?? {});
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
doc = {};
|
|
43
|
+
}
|
|
44
|
+
const rec = (doc['telegram'] ?? {});
|
|
45
|
+
// Parity with DSI's telegram-config.ts: numeric strings are coerced (YAML
|
|
46
|
+
// quotes around an id are common), anything else is dropped — never guessed.
|
|
47
|
+
const ids = Array.isArray(rec['allowUserIds'])
|
|
48
|
+
? rec['allowUserIds'].flatMap((v) => {
|
|
49
|
+
const n = typeof v === 'number'
|
|
50
|
+
? v
|
|
51
|
+
: typeof v === 'string' && v.trim().length > 0
|
|
52
|
+
? Number(v.trim())
|
|
53
|
+
: NaN;
|
|
54
|
+
return Number.isFinite(n) ? [n] : [];
|
|
55
|
+
})
|
|
56
|
+
: [];
|
|
57
|
+
return {
|
|
58
|
+
botToken: typeof rec['botToken'] === 'string' ? rec['botToken'] : '',
|
|
59
|
+
allowUserIds: ids,
|
|
60
|
+
token: typeof rec['token'] === 'string' ? rec['token'] : ''
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function readFileUtf8(path) {
|
|
64
|
+
// Imported lazily so the pure router never touches the fs.
|
|
65
|
+
return readFileSync(path, 'utf-8');
|
|
66
|
+
}
|
|
67
|
+
function replyText(deps, text) {
|
|
68
|
+
return deps.out.sendMessage(text);
|
|
69
|
+
}
|
|
70
|
+
/** A reply that may exceed Telegram's limit: splitMessage parts, sent in order (D8). */
|
|
71
|
+
async function replyLong(deps, text) {
|
|
72
|
+
for (const part of splitMessage(text))
|
|
73
|
+
await deps.out.sendMessage(part);
|
|
74
|
+
}
|
|
75
|
+
/** The host's busy code (dsh-rpc SUBAGENT_REJECTION_CODES) → one honest line, no retry. */
|
|
76
|
+
function busyLine(err) {
|
|
77
|
+
if (err instanceof DsiClientError && (err.code === 'session/agent-busy' || err.status === 502)) {
|
|
78
|
+
return 'The agent is busy — try again shortly, or /cancel.';
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
/** Build the /N payload for the first pending QUESTION: its Nth option's label. */
|
|
83
|
+
export function optionAnswerPayload(pending, n) {
|
|
84
|
+
for (const frame of pending) {
|
|
85
|
+
if (frame.kind !== 'question')
|
|
86
|
+
continue;
|
|
87
|
+
const questions = Array.isArray(frame.body['questions']) ? frame.body['questions'] : [];
|
|
88
|
+
const q = questions[0];
|
|
89
|
+
if (!q)
|
|
90
|
+
return null;
|
|
91
|
+
const options = Array.isArray(q.options) ? q.options : [];
|
|
92
|
+
const opt = options[n - 1];
|
|
93
|
+
const label = opt && typeof opt.label === 'string' ? opt.label : undefined;
|
|
94
|
+
if (label === undefined)
|
|
95
|
+
return null;
|
|
96
|
+
const id = typeof q.id === 'string' ? q.id : '';
|
|
97
|
+
return { rpcId: frame.rpcId, payload: { answers: [{ id, selected: [label] }] }, label };
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
/** The skill list, one line per skill: `/name — description` (first line, cut at 120), host order (ADR-0092 D8). */
|
|
102
|
+
export const SKILL_LINE_MAX = 120;
|
|
103
|
+
export function formatSkillList(skills) {
|
|
104
|
+
if (skills.length === 0)
|
|
105
|
+
return 'no skills available';
|
|
106
|
+
return skills
|
|
107
|
+
.map((s) => {
|
|
108
|
+
const firstLine = s.description.split('\n')[0] ?? '';
|
|
109
|
+
return `/${s.name} — ${firstLine.slice(0, SKILL_LINE_MAX)}`;
|
|
110
|
+
})
|
|
111
|
+
.join('\n');
|
|
112
|
+
}
|
|
113
|
+
/** Exact, case-insensitive name match against the catalog — the host's own semantics (ADR-0092 D6). */
|
|
114
|
+
export function matchSkill(skills, name) {
|
|
115
|
+
const wanted = name.toLowerCase();
|
|
116
|
+
return skills.find((s) => s.name.toLowerCase() === wanted);
|
|
117
|
+
}
|
|
118
|
+
/** The prompt tail the plain-prompt path and a skill run share: prompt → busy line → stream (ADR-0090 D6 / ADR-0092 D6). */
|
|
119
|
+
async function promptAndStream(deps, sessionId, input) {
|
|
120
|
+
try {
|
|
121
|
+
await deps.client.prompt(sessionId, input);
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
const busy = busyLine(err);
|
|
125
|
+
if (busy) {
|
|
126
|
+
await replyText(deps, busy);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
throw err;
|
|
130
|
+
}
|
|
131
|
+
await (deps.stream ?? streamReply)({ client: deps.client, sessionId, out: deps.out });
|
|
132
|
+
}
|
|
133
|
+
/** `/skills` — the single door (ADR-0092 D4-D8): lazy session, catalog per invocation, list or run. */
|
|
134
|
+
async function skillsCommand(deps, arg) {
|
|
135
|
+
const { client, map } = deps;
|
|
136
|
+
// D7: no session → create one in the chat's cwd before the catalog read (the prompt path's own rule).
|
|
137
|
+
const rec = get(map, deps.chatId);
|
|
138
|
+
let sessionId = rec.sessionId;
|
|
139
|
+
if (sessionId === null) {
|
|
140
|
+
sessionId = (await client.createSession(rec.cwd)).sessionId;
|
|
141
|
+
setSession(map, deps.chatId, sessionId);
|
|
142
|
+
deps.save(map);
|
|
143
|
+
}
|
|
144
|
+
// D5: one read per invocation through the composer's own route; a failure is one line, no retry.
|
|
145
|
+
let cat;
|
|
146
|
+
try {
|
|
147
|
+
cat = await client.catalog(sessionId);
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
if (err instanceof DsiClientError) {
|
|
151
|
+
await replyText(deps, `skills unavailable (DSI ${err.status} ${err.code})`);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
throw err;
|
|
155
|
+
}
|
|
156
|
+
if (arg.length === 0) {
|
|
157
|
+
await replyLong(deps, formatSkillList(cat.skills));
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const [name = '', ...rest] = arg.split(/\s+/);
|
|
161
|
+
const skill = matchSkill(cat.skills, name);
|
|
162
|
+
if (!skill) {
|
|
163
|
+
await replyText(deps, 'unknown skill — /skills to list');
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
// D6: forward verbatim in the catalog's spelling; the host injects the body.
|
|
167
|
+
await promptAndStream(deps, sessionId, { text: `/${skill.name}${rest.length > 0 ? ` ${rest.join(' ')}` : ''}` });
|
|
168
|
+
}
|
|
169
|
+
/** Pure router: one update → zero or more DSI calls → zero or more replies. */
|
|
170
|
+
export async function routeUpdate(update, deps) {
|
|
171
|
+
if (!deps.settings.allowUserIds.includes(update.from.id)) {
|
|
172
|
+
await replyText(deps, NOT_AUTHORIZED);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const { client, map } = deps;
|
|
176
|
+
const rec = get(map, deps.chatId);
|
|
177
|
+
const raw = (update.text ?? update.caption ?? '').trim();
|
|
178
|
+
const hasMedia = update.photo !== undefined || update.document !== undefined;
|
|
179
|
+
if (raw.startsWith('/')) {
|
|
180
|
+
const [head = '', ...rest] = raw.split(/\s+/);
|
|
181
|
+
const arg = rest.join(' ').trim();
|
|
182
|
+
const command = head.replace(/@\S+$/, '').toLowerCase(); // strip @botname
|
|
183
|
+
switch (command) {
|
|
184
|
+
case '/id':
|
|
185
|
+
await replyText(deps, `chat id: ${deps.chatId}\nuser id: ${update.from.id}`);
|
|
186
|
+
return;
|
|
187
|
+
case '/new': {
|
|
188
|
+
const { sessionId } = await client.createSession(rec.cwd);
|
|
189
|
+
setSession(map, deps.chatId, sessionId);
|
|
190
|
+
deps.save(map);
|
|
191
|
+
await replyText(deps, `new session in ${rec.cwd}`);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
case '/ws': {
|
|
195
|
+
if (arg.length === 0) {
|
|
196
|
+
await replyText(deps, `usage: /ws <path> (current: ${rec.cwd})`);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
setCwd(map, deps.chatId, arg); // D8: cwd only — the live session is untouched
|
|
200
|
+
deps.save(map);
|
|
201
|
+
await replyText(deps, `workspace set to ${arg} — applies to /new`);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
case '/status': {
|
|
205
|
+
if (rec.sessionId === null) {
|
|
206
|
+
await replyText(deps, 'no session yet — send a message or /new');
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const poll = await client.events(rec.sessionId, -1);
|
|
210
|
+
await replyText(deps, `running: ${poll.running}`);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
case '/cancel': {
|
|
214
|
+
if (rec.sessionId === null) {
|
|
215
|
+
await replyText(deps, 'no session yet');
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const r = await client.cancel(rec.sessionId);
|
|
219
|
+
await replyText(deps, r.accepted ? 'cancel sent' : 'nothing to cancel');
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
case '/skills':
|
|
223
|
+
await skillsCommand(deps, arg);
|
|
224
|
+
return;
|
|
225
|
+
default: {
|
|
226
|
+
const m = /^\/(\d{1,2})$/.exec(command);
|
|
227
|
+
if (!m) {
|
|
228
|
+
await replyText(deps, unknownCommandHint());
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (rec.sessionId === null) {
|
|
232
|
+
await replyText(deps, NOTHING_TO_ANSWER);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const poll = await client.events(rec.sessionId, -1);
|
|
236
|
+
const answer = optionAnswerPayload(poll.pendingAnswers, Number(m[1]));
|
|
237
|
+
if (!answer) {
|
|
238
|
+
await replyText(deps, NOTHING_TO_ANSWER);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
await client.respond(rec.sessionId, answer.rpcId, answer.payload);
|
|
242
|
+
await replyText(deps, `answered: ${answer.label}`);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (raw.length === 0 && !hasMedia) {
|
|
248
|
+
await replyText(deps, 'empty message');
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
// Ensure a session (first touch creates one in the chat's cwd).
|
|
252
|
+
let sessionId = rec.sessionId;
|
|
253
|
+
if (sessionId === null) {
|
|
254
|
+
sessionId = (await client.createSession(rec.cwd)).sessionId;
|
|
255
|
+
setSession(map, deps.chatId, sessionId);
|
|
256
|
+
deps.save(map);
|
|
257
|
+
}
|
|
258
|
+
let images = [];
|
|
259
|
+
let text = raw;
|
|
260
|
+
if (hasMedia) {
|
|
261
|
+
const photoSizes = update.photo ?? [];
|
|
262
|
+
const shaped = await shapeAttachments({
|
|
263
|
+
photo: photoSizes.length > 0 ? { fileId: photoSizes[photoSizes.length - 1].file_id } : undefined,
|
|
264
|
+
document: update.document
|
|
265
|
+
? {
|
|
266
|
+
fileId: update.document.file_id,
|
|
267
|
+
mimeType: update.document.mime_type,
|
|
268
|
+
fileName: update.document.file_name,
|
|
269
|
+
fileSize: update.document.file_size
|
|
270
|
+
}
|
|
271
|
+
: undefined,
|
|
272
|
+
caption: raw,
|
|
273
|
+
client,
|
|
274
|
+
sessionId,
|
|
275
|
+
load: deps.load
|
|
276
|
+
});
|
|
277
|
+
images = shaped.images;
|
|
278
|
+
text = shaped.text;
|
|
279
|
+
}
|
|
280
|
+
await promptAndStream(deps, sessionId, { text, ...(images.length > 0 ? { images } : {}) });
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Declare the command list to Telegram (ADR-0092 D1): ONE setMyCommands per boot, default
|
|
284
|
+
* scope, before bot.start. A failed push logs one line and resolves false — it never
|
|
285
|
+
* throws, so a Telegram hiccup cannot keep the phone door from opening.
|
|
286
|
+
*/
|
|
287
|
+
export async function pushCommandMenu(api, log = console.error) {
|
|
288
|
+
try {
|
|
289
|
+
await api.setMyCommands(menuCommands());
|
|
290
|
+
return true;
|
|
291
|
+
}
|
|
292
|
+
catch (err) {
|
|
293
|
+
log(`[telegram-bot] menu push failed (${err instanceof Error ? err.message : String(err)})`);
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/** grammY Message → the router's update shape. */
|
|
298
|
+
export function toBotUpdate(ctx) {
|
|
299
|
+
const msg = ctx.msg;
|
|
300
|
+
if (!msg || !msg.from)
|
|
301
|
+
return null;
|
|
302
|
+
return {
|
|
303
|
+
from: { id: msg.from.id },
|
|
304
|
+
chat: { id: msg.chat.id },
|
|
305
|
+
...(msg.text === undefined ? {} : { text: msg.text }),
|
|
306
|
+
...(msg.caption === undefined ? {} : { caption: msg.caption }),
|
|
307
|
+
...(msg.photo === undefined ? {} : { photo: msg.photo }),
|
|
308
|
+
...(msg.document === undefined ? {} : { document: msg.document })
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
/** Telegram file download (Telegram's API — the DSI door is dsi-client). Cap 20 MB. */
|
|
312
|
+
export function telegramMediaLoader(bot, token) {
|
|
313
|
+
return async (fileId) => {
|
|
314
|
+
const file = await bot.api.getFile(fileId);
|
|
315
|
+
if (!file.file_path)
|
|
316
|
+
throw new Error('Telegram returned no file_path');
|
|
317
|
+
const res = await fetch(`https://api.telegram.org/file/bot${token}/${file.file_path}`);
|
|
318
|
+
if (!res.ok)
|
|
319
|
+
throw new Error(`Telegram file download failed (${res.status})`);
|
|
320
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
321
|
+
return { bytes, size: file.file_size ?? bytes.length };
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
/** Boot: clear error line + exit 1 on a missing/half telegram section — no crash loop. */
|
|
325
|
+
export async function main(env = process.env) {
|
|
326
|
+
const settingsPath = env['DSI_CONFIG_PATH'] ?? DEFAULT_SETTINGS_PATH;
|
|
327
|
+
const settings = readTelegramSettings(settingsPath);
|
|
328
|
+
const missing = [];
|
|
329
|
+
if (settings.botToken.length === 0)
|
|
330
|
+
missing.push('telegram.botToken');
|
|
331
|
+
if (settings.allowUserIds.length === 0)
|
|
332
|
+
missing.push('telegram.allowUserIds');
|
|
333
|
+
if (settings.token.length === 0)
|
|
334
|
+
missing.push('telegram.token');
|
|
335
|
+
if (missing.length > 0) {
|
|
336
|
+
console.error(`[telegram-bot] not starting: ${settingsPath} is missing ${missing.join(', ')} — add the telegram: section (see packages/telegram-bot/README.md)`);
|
|
337
|
+
process.exit(1);
|
|
338
|
+
}
|
|
339
|
+
const baseUrl = env['DSI_URL'];
|
|
340
|
+
if (baseUrl === undefined || baseUrl.trim() === '') {
|
|
341
|
+
console.error(MISSING_DSI_URL_LINE);
|
|
342
|
+
process.exit(1);
|
|
343
|
+
}
|
|
344
|
+
// DSI_SLOT is the floor's own word, reported verbatim; absent → derived from
|
|
345
|
+
// the stamp only if DSI_URL is one, else null. The arithmetic is slot.ts's.
|
|
346
|
+
const slotEnv = env['DSI_SLOT'];
|
|
347
|
+
const slot = slotEnv !== undefined && slotEnv.trim() !== '' && /^[1-9]$/.test(slotEnv.trim())
|
|
348
|
+
? Number(slotEnv)
|
|
349
|
+
: (peekSlotFromStamp(baseUrl)?.slot ?? null);
|
|
350
|
+
const client = createDsiClient({ baseUrl, token: settings.token });
|
|
351
|
+
const map = loadChatMap(CHAT_MAP_PATH);
|
|
352
|
+
const save = (m) => saveChatMap(m, CHAT_MAP_PATH);
|
|
353
|
+
// Identity endpoint first (ADR-0091 D2): the floor can find this bot the
|
|
354
|
+
// moment it exists. Port 0/unset → no listener (ADR-0090 behaviour).
|
|
355
|
+
const status = startStatusListener({
|
|
356
|
+
port: env['DSI_TELEGRAM_PORT'],
|
|
357
|
+
status: { slot, pid: process.pid, upstream: baseUrl, startedAt: new Date().toISOString(), allowCount: settings.allowUserIds.length }
|
|
358
|
+
});
|
|
359
|
+
const statusLine = status.port === null ? 'status: off' : `status: http://127.0.0.1:${status.port}/`;
|
|
360
|
+
const bot = new Bot(settings.botToken);
|
|
361
|
+
const load = telegramMediaLoader(bot, settings.botToken);
|
|
362
|
+
await pushCommandMenu(bot.api); // ADR-0092 D1 — before the first poll, never fatal
|
|
363
|
+
bot.on('message', async (ctx) => {
|
|
364
|
+
const update = toBotUpdate(ctx);
|
|
365
|
+
if (!update)
|
|
366
|
+
return;
|
|
367
|
+
const chatId = update.chat.id;
|
|
368
|
+
const out = {
|
|
369
|
+
sendMessage: async (text) => {
|
|
370
|
+
const m = await ctx.api.sendMessage(chatId, text);
|
|
371
|
+
return { messageId: m.message_id };
|
|
372
|
+
},
|
|
373
|
+
editMessage: async (messageId, text) => {
|
|
374
|
+
await ctx.api.editMessageText(chatId, messageId, text);
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
const deps = { settings, client, map, save, chatId, out, load };
|
|
378
|
+
try {
|
|
379
|
+
await routeUpdate(update, deps);
|
|
380
|
+
}
|
|
381
|
+
catch (err) {
|
|
382
|
+
console.error('[telegram-bot] update failed:', err);
|
|
383
|
+
await out.sendMessage(`Something went wrong: ${err instanceof DsiClientError ? `${err.status} ${err.code}` : 'unknown error'}`).catch(() => { });
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
bot.catch((err) => console.error('[telegram-bot] bot error:', err));
|
|
387
|
+
console.log(`[telegram-bot] bridging Telegram → ${baseUrl} (chats: ${CHAT_MAP_PATH}; ${statusLine})`);
|
|
388
|
+
await bot.start({
|
|
389
|
+
onStart: () => console.log('[telegram-bot] long-polling — send /id to any chat to see your id')
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
const isMain = (() => {
|
|
393
|
+
try {
|
|
394
|
+
return process.argv[1] !== undefined && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
return false;
|
|
398
|
+
}
|
|
399
|
+
})();
|
|
400
|
+
if (isMain) {
|
|
401
|
+
main().catch((err) => {
|
|
402
|
+
console.error('[telegram-bot] fatal:', err);
|
|
403
|
+
process.exit(1);
|
|
404
|
+
});
|
|
405
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/** Telegram's edit budget: ~1 edit/s per message. */
|
|
2
|
+
export const EDIT_THROTTLE_MS = 1_000;
|
|
3
|
+
/** Telegram's hard message limit. */
|
|
4
|
+
export const TELEGRAM_MESSAGE_LIMIT = 4_096;
|
|
5
|
+
export const PLACEHOLDER = '…';
|
|
6
|
+
export const NO_REPLY = '(no reply text)';
|
|
7
|
+
/** Split on the limit, preferring the last newline before the cut. */
|
|
8
|
+
export function splitMessage(text, limit = TELEGRAM_MESSAGE_LIMIT) {
|
|
9
|
+
if (text.length <= limit)
|
|
10
|
+
return [text];
|
|
11
|
+
const chunks = [];
|
|
12
|
+
let rest = text;
|
|
13
|
+
while (rest.length > limit) {
|
|
14
|
+
const window = rest.slice(0, limit);
|
|
15
|
+
const nl = window.lastIndexOf('\n');
|
|
16
|
+
const cut = nl > limit / 2 ? nl + 1 : limit;
|
|
17
|
+
chunks.push(rest.slice(0, cut));
|
|
18
|
+
rest = rest.slice(cut);
|
|
19
|
+
}
|
|
20
|
+
if (rest.length > 0)
|
|
21
|
+
chunks.push(rest);
|
|
22
|
+
return chunks;
|
|
23
|
+
}
|
|
24
|
+
/** The latest assistant-message text — reasoning is a sibling field and is never read. */
|
|
25
|
+
export function latestAssistantText(entries) {
|
|
26
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
27
|
+
const e = entries[i];
|
|
28
|
+
if (e && e['kind'] === 'assistant-message') {
|
|
29
|
+
const text = e['text'];
|
|
30
|
+
return typeof text === 'string' ? text : '';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return '';
|
|
34
|
+
}
|
|
35
|
+
/** grammY's GrammyError carries error_code; tolerate a few common spellings. */
|
|
36
|
+
export function telegramErrorCode(err) {
|
|
37
|
+
if (err === null || typeof err !== 'object')
|
|
38
|
+
return undefined;
|
|
39
|
+
const e = err;
|
|
40
|
+
for (const key of ['error_code', 'errorCode', 'status', 'code']) {
|
|
41
|
+
const v = e[key];
|
|
42
|
+
if (typeof v === 'number')
|
|
43
|
+
return v;
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
export function telegramRetryAfterMs(err) {
|
|
48
|
+
if (err !== null && typeof err === 'object') {
|
|
49
|
+
const params = err.parameters;
|
|
50
|
+
const ra = params?.retry_after;
|
|
51
|
+
if (typeof ra === 'number' && ra >= 0)
|
|
52
|
+
return ra * 1_000;
|
|
53
|
+
}
|
|
54
|
+
return EDIT_THROTTLE_MS;
|
|
55
|
+
}
|
|
56
|
+
export async function streamReply(opts) {
|
|
57
|
+
const now = opts.now ?? (() => Date.now());
|
|
58
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
59
|
+
const throttleMs = opts.throttleMs ?? EDIT_THROTTLE_MS;
|
|
60
|
+
const limit = opts.limit ?? TELEGRAM_MESSAGE_LIMIT;
|
|
61
|
+
const { client, sessionId, out } = opts;
|
|
62
|
+
let lastEditAt = Number.NEGATIVE_INFINITY;
|
|
63
|
+
let shown = '';
|
|
64
|
+
let retried429 = false;
|
|
65
|
+
async function edit(messageId, text) {
|
|
66
|
+
try {
|
|
67
|
+
await out.editMessage(messageId, text);
|
|
68
|
+
lastEditAt = now();
|
|
69
|
+
shown = text;
|
|
70
|
+
retried429 = false;
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
if (telegramErrorCode(err) === 429 && !retried429) {
|
|
74
|
+
retried429 = true;
|
|
75
|
+
await sleep(telegramRetryAfterMs(err));
|
|
76
|
+
await edit(messageId, text); // exactly one retry
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
throw err;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const { messageId } = await out.sendMessage(PLACEHOLDER);
|
|
83
|
+
let since = -1;
|
|
84
|
+
let finalText = '';
|
|
85
|
+
for (;;) {
|
|
86
|
+
const { running } = await client.turn(sessionId);
|
|
87
|
+
const poll = await client.events(sessionId, since);
|
|
88
|
+
since = poll.lastSeq;
|
|
89
|
+
const durable = latestAssistantText(poll.entries);
|
|
90
|
+
const live = poll.liveStream?.text ?? '';
|
|
91
|
+
finalText = durable.length > 0 ? durable : live;
|
|
92
|
+
if (!running)
|
|
93
|
+
break;
|
|
94
|
+
if (finalText.length > 0 && finalText !== shown && now() - lastEditAt >= throttleMs) {
|
|
95
|
+
await edit(messageId, finalText);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const chunks = splitMessage(finalText.length > 0 ? finalText : NO_REPLY, limit);
|
|
99
|
+
// The final edit obeys the same budget: wait out the remainder of the throttle window.
|
|
100
|
+
async function finalEdit(messageId, text) {
|
|
101
|
+
const remaining = throttleMs - (now() - lastEditAt);
|
|
102
|
+
if (lastEditAt !== Number.NEGATIVE_INFINITY && remaining > 0)
|
|
103
|
+
await sleep(remaining);
|
|
104
|
+
await edit(messageId, text);
|
|
105
|
+
}
|
|
106
|
+
if (chunks.length === 1) {
|
|
107
|
+
if (chunks[0] !== shown)
|
|
108
|
+
await finalEdit(messageId, chunks[0] ?? NO_REPLY);
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
await finalEdit(messageId, chunks[0] ?? NO_REPLY);
|
|
112
|
+
for (const chunk of chunks.slice(1))
|
|
113
|
+
await out.sendMessage(chunk);
|
|
114
|
+
}
|
|
115
|
+
return { messageId, chunks };
|
|
116
|
+
}
|
package/dist/slot.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* slot — the ONLY home of the slot arithmetic (ADR-0091 D1/D3/D7, beside
|
|
3
|
+
* ADR-0089 D1). Floor k owns host 3k80, UI 5k74 (build) / 5k75 (dev) and
|
|
4
|
+
* Telegram 4k90. Pure: no env, no fs. Both the bot's main() and floor-cli
|
|
5
|
+
* import it, so the two can never disagree.
|
|
6
|
+
*/
|
|
7
|
+
/** Floors are 1–9; there is no DSI-0 (ADR-0091 D7). */
|
|
8
|
+
export function assertSlot(k) {
|
|
9
|
+
if (!Number.isInteger(k) || k < 1 || k > 9) {
|
|
10
|
+
throw new Error(`slot must be an integer 1–9 (got ${k}) — there is no DSI-0 (ADR-0091 D7)`);
|
|
11
|
+
}
|
|
12
|
+
return k;
|
|
13
|
+
}
|
|
14
|
+
/** Telegram status port of floor k: 4k90 → 4190 … 4990 (ADR-0091 D1). */
|
|
15
|
+
export function telegramPortForSlot(k) {
|
|
16
|
+
return 4000 + 100 * assertSlot(k) + 90;
|
|
17
|
+
}
|
|
18
|
+
/** `http://127.0.0.1:4k90/` — the only address anything needs to find floor k's bot. */
|
|
19
|
+
export function statusUrl(k) {
|
|
20
|
+
return `http://127.0.0.1:${telegramPortForSlot(k)}/`;
|
|
21
|
+
}
|
|
22
|
+
/** 5k75 (dev) / 5k74 (build), k = 1–9 — e.g. http://127.0.0.1:5175 */
|
|
23
|
+
const STAMP_RE = /^http:\/\/127\.0\.0\.1:5([1-9])7([45])\/?$/;
|
|
24
|
+
function stampHint(got) {
|
|
25
|
+
return (`${got} — expected the floor stamp http://127.0.0.1:5x75 (dev) or 5x74 (build) with x = 1–9. ` +
|
|
26
|
+
'Your floor stamps every session with DSI_UI (bin/dsi.mjs): launch through the floor, or set DSI_UI, or pass --slot k.');
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* DSI_UI → {slot, mode, upstream}. The stamp's last digit says which mode runs,
|
|
30
|
+
* so the bot dials exactly the port the stamp names — never a guess between the
|
|
31
|
+
* pair (ADR-0091 D3; ADR-0089 D2: read the stamp, never probe). Dies loud
|
|
32
|
+
* naming DSI_UI when unset or not a stamp.
|
|
33
|
+
*/
|
|
34
|
+
export function slotFromStamp(url) {
|
|
35
|
+
if (url === undefined || url.trim() === '') {
|
|
36
|
+
throw new Error(`DSI_UI is unset — ${stampHint('nothing')}`);
|
|
37
|
+
}
|
|
38
|
+
const m = STAMP_RE.exec(url.trim());
|
|
39
|
+
if (!m) {
|
|
40
|
+
throw new Error(`DSI_UI is not a floor stamp: ${stampHint(JSON.stringify(url))}`);
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
slot: Number(m[1]),
|
|
44
|
+
mode: m[2] === '5' ? 'dev' : 'build',
|
|
45
|
+
upstream: url.trim().replace(/\/$/, '')
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** Like slotFromStamp but a non-stamp is `null`, not an error — for reporting only. */
|
|
49
|
+
export function peekSlotFromStamp(url) {
|
|
50
|
+
try {
|
|
51
|
+
return slotFromStamp(url);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* status-listener — the bot's identity endpoint (ADR-0091 D2). node:http on
|
|
3
|
+
* 127.0.0.1 ONLY; `GET /` answers who the bot is; every other path or method
|
|
4
|
+
* is 404. It is a status endpoint, never a control channel: nothing can be
|
|
5
|
+
* started, stopped or prompted through it.
|
|
6
|
+
*/
|
|
7
|
+
import { createServer } from 'node:http';
|
|
8
|
+
export function startStatusListener(options) {
|
|
9
|
+
const port = typeof options.port === 'string' ? Number(options.port) : (options.port ?? 0);
|
|
10
|
+
if (!Number.isInteger(port) || port <= 0) {
|
|
11
|
+
return { port: null, close: async () => { } };
|
|
12
|
+
}
|
|
13
|
+
const body = JSON.stringify({ ok: true, ...options.status });
|
|
14
|
+
let server;
|
|
15
|
+
server = createServer((req, res) => {
|
|
16
|
+
if (req.method === 'GET' && req.url === '/') {
|
|
17
|
+
res.writeHead(200, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) });
|
|
18
|
+
res.end(body);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
// No other route exists — status only, no control (D2).
|
|
22
|
+
res.writeHead(404, { 'content-type': 'text/plain' });
|
|
23
|
+
res.end('not found');
|
|
24
|
+
});
|
|
25
|
+
server.on('error', (err) => {
|
|
26
|
+
(options.log ?? console.error)(`[telegram-bot] status listener on 127.0.0.1:${port} failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
27
|
+
});
|
|
28
|
+
server.listen(port, '127.0.0.1');
|
|
29
|
+
return {
|
|
30
|
+
port,
|
|
31
|
+
close: () => new Promise((resolve) => {
|
|
32
|
+
if (!server)
|
|
33
|
+
return resolve();
|
|
34
|
+
server.close(() => resolve());
|
|
35
|
+
server.closeAllConnections();
|
|
36
|
+
server = undefined;
|
|
37
|
+
})
|
|
38
|
+
};
|
|
39
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deepseek-insight/telegram-bot",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Telegram bridge for DeepSeek Insight — an HTTP client of the existing /api/dsh/* routes plus the two guarded bridge routes (ADR-0090). Node-only; never bundled by DSI's Vite build.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=22.19"
|
|
8
|
+
},
|
|
9
|
+
"bin": {
|
|
10
|
+
"dsi-telegram": "bin/dsi-telegram.mjs"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist",
|
|
14
|
+
"bin",
|
|
15
|
+
"README.md"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -p tsconfig.build.json",
|
|
19
|
+
"start": "node dist/index.js",
|
|
20
|
+
"floor": "pnpm run build && node dist/floor-cli.js",
|
|
21
|
+
"test": "pnpm run build && vitest run",
|
|
22
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
23
|
+
"prepack": "pnpm run build",
|
|
24
|
+
"prepublishOnly": "pnpm typecheck && pnpm test && pnpm lint:package",
|
|
25
|
+
"lint:package": "publint"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"grammy": "^1.38.0",
|
|
29
|
+
"yaml": "^2.9.0"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "^24.0.0",
|
|
33
|
+
"publint": "^0.3.25",
|
|
34
|
+
"typescript": "^6.0.3",
|
|
35
|
+
"vitest": "^4.1.9"
|
|
36
|
+
}
|
|
37
|
+
}
|