@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.
@@ -0,0 +1,398 @@
1
+ /**
2
+ * floor-cli — the ONE command behind the dsi-telegram skill (ADR-0091 D3–D6).
3
+ *
4
+ * floor status [--slot k] every floor's bot: running · pid · uptime · upstream — exit 0 always (D6)
5
+ * floor on [--slot k] slot from the DSI_UI stamp (or --slot), spawn the bot detached, poll its port (D3/D4)
6
+ * floor off [--slot k] ask the port for the pid, verify the command line, SIGTERM (SIGKILL after 3 s, reported) (D5)
7
+ *
8
+ * All arithmetic is slot.ts's. Decisions are pure and exported; the side effects
9
+ * (probe, spawn, ps, kill, clock) are injected. Nothing is scanned, nothing is
10
+ * remembered, nothing is typed — and nothing is ever killed unverified.
11
+ */
12
+ import { execFileSync, spawn } from 'node:child_process';
13
+ import { closeSync, mkdirSync, openSync, realpathSync, writeSync } from 'node:fs';
14
+ import { get as httpGetRaw } from 'node:http';
15
+ import { homedir } from 'node:os';
16
+ import { dirname, join } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { assertSlot, slotFromStamp, statusUrl, telegramPortForSlot } from "./slot.js";
19
+ const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
20
+ export class UsageError extends Error {
21
+ }
22
+ const USAGE = 'usage: pnpm --dir packages/telegram-bot floor <status|on|off> [--slot k]';
23
+ /** Bare = status. Slot 0 / 10 / junk → a die-loud UsageError (ADR-0091 D7). */
24
+ export function parseArgs(argv) {
25
+ const [head, ...rest] = argv;
26
+ let verb;
27
+ if (head === undefined)
28
+ verb = 'status';
29
+ else if (head === 'status' || head === 'on' || head === 'off')
30
+ verb = head;
31
+ else
32
+ throw new UsageError(`unknown command "${head}" — ${USAGE}`);
33
+ let slot = null;
34
+ for (let i = 0; i < rest.length; i++) {
35
+ const arg = rest[i];
36
+ let raw;
37
+ if (arg === '--slot')
38
+ raw = rest[++i];
39
+ else if (arg.startsWith('--slot='))
40
+ raw = arg.slice('--slot='.length);
41
+ else
42
+ throw new UsageError(`unexpected argument "${arg}" — ${USAGE}`);
43
+ if (raw === undefined || !/^\d+$/.test(raw))
44
+ throw new UsageError(`--slot needs a number 1–9 (got ${raw ?? 'nothing'}) — ${USAGE}`);
45
+ try {
46
+ slot = assertSlot(Number(raw));
47
+ }
48
+ catch (err) {
49
+ throw new UsageError(err instanceof Error ? err.message : String(err));
50
+ }
51
+ }
52
+ return { verb, slot };
53
+ }
54
+ /**
55
+ * on: DSI_UI is ALWAYS the upstream (unset → die loud, naming the stamp).
56
+ * --slot overrides only WHICH slot/port the bot is filed under.
57
+ */
58
+ export function planOn(env, slotArg, logPathFor) {
59
+ const upstream = env['DSI_UI'];
60
+ if (upstream === undefined || upstream.trim() === '') {
61
+ // Reuse slot.ts's die-loud line — no second copy of the message.
62
+ slotFromStamp(upstream);
63
+ throw new Error('unreachable');
64
+ }
65
+ const slot = slotArg ?? slotFromStamp(upstream).slot;
66
+ return { slot, port: telegramPortForSlot(slot), upstream: upstream.trim(), logPath: logPathFor(slot) };
67
+ }
68
+ /** off/status --slot absent: the stamp says which floor. Unstamped → die loud. */
69
+ export function slotForThisFloor(env, slotArg) {
70
+ return slotArg ?? slotFromStamp(env['DSI_UI']).slot;
71
+ }
72
+ /**
73
+ * GET over node:http — deliberately NOT fetch(): 4190 (slot 1) is on the WHATWG
74
+ * bad-port blocklist, so fetch() fails with "bad port" before any connection is
75
+ * made (found live 2026-12-03; ADR-0091 amendment). Resolves with the status and
76
+ * body; rejects on connection refused / timeout / any error.
77
+ */
78
+ export function httpGet(url, timeoutMs = 1000) {
79
+ return new Promise((resolve, reject) => {
80
+ const req = httpGetRaw(url, (res) => {
81
+ const chunks = [];
82
+ res.on('data', (c) => chunks.push(c));
83
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString('utf8') }));
84
+ res.on('error', reject);
85
+ });
86
+ req.setTimeout(timeoutMs, () => req.destroy(new Error(`timeout after ${timeoutMs} ms`)));
87
+ req.on('error', reject);
88
+ req.end();
89
+ });
90
+ }
91
+ /** Strict shape check: anything that is not exactly the identity body is foreign. */
92
+ export function parseStatusBody(text) {
93
+ let v;
94
+ try {
95
+ v = JSON.parse(text);
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ if (v === null || typeof v !== 'object')
101
+ return null;
102
+ const b = v;
103
+ if (b['ok'] !== true)
104
+ return null;
105
+ if (typeof b['pid'] !== 'number' || !Number.isInteger(b['pid']) || b['pid'] <= 0)
106
+ return null;
107
+ if (typeof b['upstream'] !== 'string' || typeof b['startedAt'] !== 'string')
108
+ return null;
109
+ if (!(b['slot'] === null || (typeof b['slot'] === 'number' && Number.isInteger(b['slot']))))
110
+ return null;
111
+ if (typeof b['allowCount'] !== 'number')
112
+ return null;
113
+ return {
114
+ ok: true,
115
+ slot: b['slot'],
116
+ pid: b['pid'],
117
+ upstream: b['upstream'],
118
+ startedAt: b['startedAt'],
119
+ allowCount: b['allowCount']
120
+ };
121
+ }
122
+ /**
123
+ * D5 — the only pid we may signal: `ps -o command= -p <pid>` must contain
124
+ * "telegram-bot" AND the entry path "dist/index.js" (spawned by absolute path, so it does;
125
+ * "src/index.ts" also qualifies — a 0.1.0 bot still running from the source tree, 0.1.1 RELEASE D4).
126
+ * floor-cli itself is excluded so the CLI can never qualify as the bot.
127
+ */
128
+ export function isBotCommand(command) {
129
+ if (!command)
130
+ return false;
131
+ return (command.includes('telegram-bot') &&
132
+ (command.includes('dist/index.js') || command.includes('src/index.ts')) &&
133
+ !command.includes('floor-cli'));
134
+ }
135
+ export const OFF_TIMEOUT_MS = 3000;
136
+ export const ON_POLL_MS = 5000;
137
+ export const SLOTS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
138
+ /** Verified = the port says it is the bot AND the pid command line agrees. */
139
+ async function verifiedBot(e, status) {
140
+ return isBotCommand(e.psCommand(status.pid));
141
+ }
142
+ export function formatUptime(ms) {
143
+ if (ms < 0)
144
+ return '0s';
145
+ const s = Math.floor(ms / 1000);
146
+ if (s < 60)
147
+ return `${s}s`;
148
+ const m = Math.floor(s / 60);
149
+ if (m < 60)
150
+ return `${m}m${String(s % 60).padStart(2, '0')}s`;
151
+ const h = Math.floor(m / 60);
152
+ return `${h}h${String(m % 60).padStart(2, '0')}m`;
153
+ }
154
+ export async function rowFor(e, slot) {
155
+ const p = await e.probe(slot);
156
+ if (p.kind === 'down')
157
+ return { slot, state: 'down', pid: null, uptimeMs: null, upstream: null, note: '' };
158
+ if (p.kind === 'foreign') {
159
+ return { slot, state: 'foreign', pid: null, uptimeMs: null, upstream: null, note: `port held by something that is not the bot: ${p.detail}` };
160
+ }
161
+ const cmd = e.psCommand(p.status.pid);
162
+ if (!isBotCommand(cmd)) {
163
+ return {
164
+ slot,
165
+ state: 'foreign',
166
+ pid: p.status.pid,
167
+ uptimeMs: null,
168
+ upstream: p.status.upstream,
169
+ note: `status port names pid ${p.status.pid} but its command is not the bot command (${cmd ?? 'no such process'}) -- --off will refuse`
170
+ };
171
+ }
172
+ const started = Date.parse(p.status.startedAt);
173
+ return {
174
+ slot,
175
+ state: 'up',
176
+ pid: p.status.pid,
177
+ uptimeMs: Number.isNaN(started) ? 0 : Math.max(0, e.now() - started),
178
+ upstream: p.status.upstream,
179
+ note: ''
180
+ };
181
+ }
182
+ export function renderTable(rows) {
183
+ const head = ['slot', 'running', 'pid', 'uptime', 'upstream'];
184
+ const cells = rows.map((r) => [
185
+ String(r.slot),
186
+ r.state,
187
+ r.pid === null ? '—' : String(r.pid),
188
+ r.uptimeMs === null ? '—' : formatUptime(r.uptimeMs),
189
+ r.upstream ?? '—'
190
+ ]);
191
+ const widths = head.map((h, i) => Math.max(h.length, ...cells.map((c) => c[i].length)));
192
+ const line = (c) => c.map((v, i) => v.padEnd(widths[i])).join(' ').trimEnd();
193
+ const out = [line(head), line(widths.map((w) => '-'.repeat(w))), ...cells.map(line)];
194
+ for (const r of rows)
195
+ if (r.note)
196
+ out.push(`slot ${r.slot}: ${r.note}`);
197
+ return out.join('\n');
198
+ }
199
+ export async function runStatus(e, slotArg) {
200
+ const slots = slotArg === null ? [...SLOTS] : [slotArg];
201
+ const rows = await Promise.all(slots.map((s) => rowFor(e, s)));
202
+ e.say(renderTable(rows));
203
+ const here = e.env['DSI_UI'];
204
+ if (slotArg === null) {
205
+ let k = null;
206
+ if (here !== undefined && here.trim() !== '') {
207
+ try {
208
+ k = slotFromStamp(here).slot;
209
+ }
210
+ catch {
211
+ k = null;
212
+ }
213
+ }
214
+ e.say(k === null ? 'this floor: unstamped (no DSI_UI) -- pass --slot k to act on a floor' : `this floor: slot ${k} (DSI_UI ${here})`);
215
+ }
216
+ return 0; // D6: a report, never a gate
217
+ }
218
+ export async function runOn(e, slotArg) {
219
+ let plan;
220
+ try {
221
+ plan = planOn(e.env, slotArg, e.logPathFor);
222
+ }
223
+ catch (err) {
224
+ e.say(`not starting: ${err instanceof Error ? err.message : String(err)}`);
225
+ return 1;
226
+ }
227
+ const at = statusUrl(plan.slot);
228
+ // Own port first.
229
+ const own = await e.probe(plan.slot);
230
+ if (own.kind === 'foreign') {
231
+ e.say(`not starting: ${at} is held by something that is not the bot (${own.detail}) -- stop it yourself`);
232
+ return 1;
233
+ }
234
+ if (own.kind === 'status') {
235
+ if (await verifiedBot(e, own.status)) {
236
+ e.say(`already running (slot ${plan.slot}, pid ${own.status.pid}, upstream ${own.status.upstream})`);
237
+ return 0;
238
+ }
239
+ const cmd = e.psCommand(own.status.pid);
240
+ e.say(`not starting: ${at} names pid ${own.status.pid} but that process is not the bot (${cmd ?? 'no such process'}) -- stop it yourself`);
241
+ return 1;
242
+ }
243
+ // Weakest point (ADR-0091 D6 give-up): one Telegram token = one live bot.
244
+ const others = await Promise.all(SLOTS.filter((s) => s !== plan.slot).map(async (s) => ({ s, p: await e.probe(s) })));
245
+ for (const { s, p } of others) {
246
+ if (p.kind === 'status' && (await verifiedBot(e, p.status))) {
247
+ e.say(`not starting: another floor's bot is already running -- slot ${s}, pid ${p.status.pid}, upstream ${p.status.upstream}. One Telegram token = one live bot (ADR-0091 D6); --off slot ${s} first.`);
248
+ return 1;
249
+ }
250
+ }
251
+ const pid = e.spawnBot(plan);
252
+ e.say(`spawned pid ${pid} (slot ${plan.slot}, upstream ${plan.upstream}, log ${plan.logPath}) -- waiting for ${at}`);
253
+ const deadline = e.now() + ON_POLL_MS;
254
+ for (;;) {
255
+ const p = await e.probe(plan.slot);
256
+ if (p.kind === 'status' && (await verifiedBot(e, p.status))) {
257
+ e.say(`running (slot ${plan.slot}, pid ${p.status.pid}, upstream ${p.status.upstream}, log ${plan.logPath})`);
258
+ return 0;
259
+ }
260
+ if (e.now() >= deadline)
261
+ break;
262
+ await e.sleep(200);
263
+ }
264
+ e.say(`spawned pid ${pid} but ${at} did not answer within ${ON_POLL_MS / 1000} s -- read ${plan.logPath}`);
265
+ return 1;
266
+ }
267
+ export async function runOff(e, slotArg) {
268
+ let slot;
269
+ try {
270
+ slot = slotForThisFloor(e.env, slotArg);
271
+ }
272
+ catch (err) {
273
+ e.say(`which floor? ${err instanceof Error ? err.message : String(err)}`);
274
+ return 1;
275
+ }
276
+ const at = statusUrl(slot);
277
+ const p = await e.probe(slot);
278
+ if (p.kind === 'down') {
279
+ e.say(`no bot for this floor (slot ${slot} -- ${at} closed)`);
280
+ return 0; // D5: a no-op, exit 0
281
+ }
282
+ if (p.kind === 'foreign') {
283
+ e.say(`refusing: ${at} is held by something that is not the bot (${p.detail}) -- left alone`);
284
+ return 1;
285
+ }
286
+ const { pid } = p.status;
287
+ const cmd = e.psCommand(pid);
288
+ if (!isBotCommand(cmd)) {
289
+ e.say(`refusing: ${at} names pid ${pid} but that process is not the bot -- ${cmd ?? 'no such process'} (ADR-0091 D5)`);
290
+ return 1;
291
+ }
292
+ e.kill(pid, 'SIGTERM');
293
+ const deadline = e.now() + OFF_TIMEOUT_MS;
294
+ while (e.isAlive(pid) && e.now() < deadline)
295
+ await e.sleep(100);
296
+ if (e.isAlive(pid)) {
297
+ e.kill(pid, 'SIGKILL');
298
+ e.say(`SIGTERM was ignored for ${OFF_TIMEOUT_MS / 1000} s -- sent SIGKILL to pid ${pid}`);
299
+ }
300
+ e.say(`stopped (slot ${slot}, pid ${pid})`);
301
+ return 0;
302
+ }
303
+ /** The production effects: real http/spawn/ps/kill. */
304
+ export function defaultEffects(env = process.env) {
305
+ return {
306
+ env,
307
+ probe: async (slot) => {
308
+ try {
309
+ const res = await httpGet(statusUrl(slot), 1000);
310
+ const text = res.text;
311
+ const status = parseStatusBody(text);
312
+ return status === null
313
+ ? { kind: 'foreign', detail: `HTTP ${res.status}: ${text.slice(0, 80).replace(/\s+/g, ' ')}` }
314
+ : { kind: 'status', status };
315
+ }
316
+ catch {
317
+ return { kind: 'down' };
318
+ }
319
+ },
320
+ spawnBot: (plan) => {
321
+ mkdirSync(dirname(plan.logPath), { recursive: true });
322
+ const fd = openSync(plan.logPath, 'a');
323
+ writeSync(fd, `\n--- floor on ${new Date().toISOString()} (slot ${plan.slot}, upstream ${plan.upstream}) ---\n`);
324
+ // One node process, no wrapper — plain node on the COMPILED entry (0.1.1 RELEASE D4; Node
325
+ // refuses to strip types under node_modules, so an installed package cannot run src/*.ts):
326
+ // its pid IS the bot process.pid, and the absolute entry path puts "telegram-bot" and
327
+ // "dist/index.js" on its command line for --off, in a checkout and in an installed package alike.
328
+ const child = spawn(process.execPath, [join(PKG_ROOT, 'dist', 'index.js')], {
329
+ cwd: PKG_ROOT,
330
+ detached: true, // ppid 1: the bot outlives this session (D4)
331
+ stdio: ['ignore', fd, fd],
332
+ env: { ...env, DSI_URL: plan.upstream, DSI_SLOT: String(plan.slot), DSI_TELEGRAM_PORT: String(plan.port) }
333
+ });
334
+ child.on('error', (err) => console.error(`[floor] spawn failed: ${err.message}`));
335
+ child.unref();
336
+ closeSync(fd);
337
+ return child.pid ?? -1;
338
+ },
339
+ psCommand: (pid) => {
340
+ try {
341
+ return execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' }).trim() || null;
342
+ }
343
+ catch {
344
+ return null;
345
+ }
346
+ },
347
+ kill: (pid, signal) => process.kill(pid, signal),
348
+ isAlive: (pid) => {
349
+ try {
350
+ process.kill(pid, 0);
351
+ return true;
352
+ }
353
+ catch (err) {
354
+ return err.code === 'EPERM';
355
+ }
356
+ },
357
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
358
+ now: () => Date.now(),
359
+ logPathFor: (slot) => join(homedir(), '.dsi', 'logs', `telegram-bot-${slot}.log`),
360
+ say: (line) => console.log(line)
361
+ };
362
+ }
363
+ export async function main(argv, e = defaultEffects()) {
364
+ let args;
365
+ try {
366
+ args = parseArgs(argv);
367
+ }
368
+ catch (err) {
369
+ e.say(err instanceof Error ? err.message : String(err));
370
+ return 1;
371
+ }
372
+ switch (args.verb) {
373
+ case 'status':
374
+ return runStatus(e, args.slot);
375
+ case 'on':
376
+ return runOn(e, args.slot);
377
+ case 'off':
378
+ return runOff(e, args.slot);
379
+ }
380
+ }
381
+ const isMain = (() => {
382
+ try {
383
+ return process.argv[1] !== undefined && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
384
+ }
385
+ catch {
386
+ return false;
387
+ }
388
+ })();
389
+ if (isMain) {
390
+ main(process.argv.slice(2))
391
+ .then((code) => {
392
+ process.exitCode = code;
393
+ })
394
+ .catch((err) => {
395
+ console.error(`[floor] fatal: ${err instanceof Error ? err.message : String(err)}`);
396
+ process.exitCode = 1;
397
+ });
398
+ }