@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 CHANGED
@@ -1,3 +1,96 @@
1
- # Temporary Holding Version
1
+ # @deepseek-insight/telegram-bot
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Telegram as a simple chat client for DeepSeek Harness agents — text, photos, documents — bridged **through DSI** (ADR-0090, *The Side Door*). The bot is an ordinary HTTP client of the routes the browser already uses (`/api/dsh/*`) plus two guarded additions (`POST /api/dsh/session/:id/file`, `GET /api/dsh/session/:id/turn`). It never talks to the DSH host itself.
4
+
5
+ - Node-only ESM package, run as its own process beside DSI (ADR-0090 D7). DSI's Vite build does not bundle it; nothing under `src/` imports it. It ships as its **own npm package** — `@deepseek-insight/telegram-bot`, installed on its own (ADR-0093, *The Bot Ships Alone*).
6
+ - One session per Telegram chat, persisted in `~/.dsi/telegram-chats.json` (D4).
7
+ - Replies stream into **one edited message** (≈1 edit/s); long replies split at 4 096 chars; reasoning text is never forwarded (D6).
8
+ - The bot is a *declared citizen of its floor* (ADR-0091, *The Bot Slot*): floor k's bot answers its identity on `GET 127.0.0.1:4k90/`, is started detached by the `dsi-telegram` skill, and is found — never remembered.
9
+
10
+ ## Setup
11
+
12
+ ### 1. Create the bot with @BotFather
13
+
14
+ In Telegram, message [@BotFather](https://t.me/BotFather) → `/newbot` → copy the token it prints (shape `1234567890:AA...`).
15
+
16
+ ### 2. Add the `telegram:` section to `~/.dsi/settings.yaml`
17
+
18
+ ```yaml
19
+ telegram:
20
+ botToken: "1234567890:AA..." # from @BotFather
21
+ allowUserIds: [123456789] # your Telegram USER id (not the chat id)
22
+ token: "<random 48-hex secret>" # bearer for the two guarded DSI routes
23
+ ```
24
+
25
+ Generate the bridge token with `openssl rand -hex 24`. The same file is read by DSI's two guarded routes (`src/lib/server/telegram-config.ts`) — no second config.
26
+
27
+ ### 3. Find your Telegram user id
28
+
29
+ Message [@userinfobot](https://t.me/userinfobot) in Telegram; it replies with your `Id`. Put that number in `allowUserIds`. (Once you are allowed, the bot's `/id` also prints it.)
30
+
31
+ ### 4. Run — the sanctioned way is the `dsi-telegram` skill
32
+
33
+ Ask any session on the floor `/dsi-telegram`: bare shows the status table (every floor's bot: running, pid, uptime, upstream), `--on` starts this floor's bot, `--off` stops it. Behind the skill is ONE command (ADR-0091):
34
+
35
+ ```bash
36
+ dsi-telegram <status|on|off> [--slot k] # installed (npm i -g) — bare = status
37
+ # in a checkout: pnpm --dir packages/telegram-bot floor <status|on|off> [--slot k]
38
+ ```
39
+
40
+ There is no `dsi-telegram floor …`: `floor` is only the checkout's pnpm script name — installed, the verb comes first. Both spellings run the same `floor-cli`, compiled to `dist/` (ADR-0093 D3).
41
+
42
+ `--on` reads the floor's own `DSI_UI` stamp (every session `bin/dsi.mjs` spawns carries one), derives the slot from it, and spawns the bot **detached** — it outlives the terminal or agent session that started it — logging to `~/.dsi/logs/telegram-bot-<k>.log`. The bot answers its identity on the floor's Telegram port (`GET 127.0.0.1:4k90/` → `{ok, slot, pid, upstream, startedAt, allowCount}`); `--off` reads the pid from there and verifies the process before stopping it. Nothing is typed, remembered or scanned — which is why the skill is preferred over a manual run.
43
+
44
+ #### Manual run (debugging only)
45
+
46
+ `pnpm start` runs `node dist/index.js` (after `pnpm build`) — plain node, no loader.
47
+
48
+ ```bash
49
+ cd packages/telegram-bot
50
+ DSI_URL=<your DSI_UI stamp> DSI_TELEGRAM_PORT=<4k90> DSI_SLOT=k pnpm start
51
+ ```
52
+
53
+ There is **no default DSI_URL**: without it the bot prints one line naming `DSI_UI` and exits 1. The stamp's last digit says which mode runs (`…75` dev, `…74` build), so the bot dials exactly the port the stamp names. Without `DSI_TELEGRAM_PORT` no status listener runs — a manual bot is invisible to the skill's table, so stop it yourself.
54
+
55
+ On start it prints one line: `[telegram-bot] bridging Telegram → <DSI_URL> (…; status: http://127.0.0.1:<4k90>/)` then `[telegram-bot] long-polling — send /id to any chat to see your id`. If the `telegram:` section is missing or half-configured it prints **one** clear line naming the missing keys and exits 1 — never a crash loop.
56
+
57
+ On start the bot declares this command list to Telegram (setMyCommands), so the client's `/` menu matches this table after the first boot (ADR-0092 D1).
58
+
59
+ ### 5. Install the bot (outside a checkout)
60
+
61
+ The bot is its own npm package (ADR-0093) — it does **not** come with `@deepseek-insight/dsi`. Install it on its own, then drive it with the same command the skill uses:
62
+
63
+ ```bash
64
+ npm i -g @deepseek-insight/telegram-bot
65
+ dsi-telegram <status|on|off> [--slot k]
66
+ ```
67
+
68
+ In a repo checkout nothing is installed: `pnpm --dir packages/telegram-bot floor <status|on|off> [--slot k]` builds `dist/` (tsc, about a second) and runs the same `floor-cli`. The npm tarball ships **compiled JavaScript in `dist/`** — Node strips TypeScript types itself inside the checkout, but **refuses to do so for any file under `node_modules`** (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`), which is why 0.1.0 could not start from a global install and 0.1.1 ships `dist/` (ADR-0093 D2 as amended). `pnpm publish` runs the whole ritual by itself: `prepack` builds, `prepublishOnly` = typecheck → test → publint. `--on` works from anywhere on the machine; the slot still comes from the session's `DSI_UI` stamp (or `--slot k`), never from a guess.
69
+
70
+ ## Commands
71
+
72
+ | Command | What it does |
73
+ |---|---|
74
+ | `/id` | print the chat id and your user id |
75
+ | `/new` | fresh session in the chat's current cwd |
76
+ | `/ws <path>` | set the cwd for the next /new (never moves a live session) |
77
+ | `/status` | is the agent running? |
78
+ | `/cancel` | stop the running turn |
79
+ | `/N` | answer the pending question with option 1 (/2, /3 …) |
80
+ | `/skills` | list the host's skills for this chat's session, or run one: /skills <name> [args] (ADR-0092) |
81
+ | anything else | a prompt — text, photo, or document |
82
+
83
+ The table is **pinned by test** to `src/commands.ts` (`COMMANDS`), the one list the menu, the `unknown command` hint and this README all read; `/N` is one menu row (`/1`). Bare `/skill-name` is not a skill invocation here — the door is `/skills <name> (ADR-0092 D4)`.
84
+
85
+ Photos ride inline as `prompt.images[]` (the agent sees them). Any other document is landed by DSI under `<workspace>/.telegram-inbox/<ts>/<name>` and its path is prepended to the prompt as `Attached files:` — the agent reads it with its own tools (D5). Telegram's 20 MB download cap applies.
86
+
87
+ ## Tests
88
+
89
+ ```bash
90
+ pnpm test # vitest, node environment — one suite per module
91
+ pnpm typecheck # tsc --noEmit, NodeNext + strict
92
+ ```
93
+
94
+ Module map: `slot.ts` (the ONLY home of the port arithmetic — imported by `index.ts` and `floor-cli.ts`), `status-listener.ts` (the identity endpoint), `index.ts` (the bot), `floor-cli.ts` (the one command behind the skill).
95
+
96
+ Companion docs: ADR-0090 (the bot), ADR-0091 (the slot) and ADR-0093 (the second npm package) under `dev/architectural-decission/2026-12/`; KB `dev/kb/telegram-bridge.md`; `RELEASE.md` for the version history.
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ // dsi-telegram — the published spelling of `pnpm floor` (ADR-0093 D3): status | on | off [--slot k].
3
+ // No logic lives here. The shim calls floor-cli's exported main() EXPLICITLY: floor-cli's own
4
+ // isMain guard compares argv[1] with its URL and never fires from a shim — a shim that forgot
5
+ // this call would exit 0 silently. Points at dist/ — the COMPILED floor-cli (0.1.1): Node refuses to
6
+ // strip types from any file under node_modules (ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING), so an
7
+ // installed package could never import ../src/*.ts. dist/ is built by prepack / prepublishOnly.
8
+ import { main } from '../dist/floor-cli.js';
9
+
10
+ main(process.argv.slice(2))
11
+ .then((code) => {
12
+ process.exitCode = code;
13
+ })
14
+ .catch((err) => {
15
+ console.error(`[floor] fatal: ${err instanceof Error ? err.message : String(err)}`);
16
+ process.exit(1);
17
+ });
@@ -0,0 +1,91 @@
1
+ /**
2
+ * attachments — shape Telegram media into prompt parts (ADR-0090 D5).
3
+ * - photo / whitelisted image document → prompt.images[] as base64 (native sight)
4
+ * - any other document → the guarded file route, and the prompt text is
5
+ * prefixed with 'Attached files:' + one '- <path>' line per landing
6
+ * - over Telegram's 20 MB cap → skipped with a note in the text
7
+ * Pure shaping + injected loaders: this module never calls fetch (the DSI
8
+ * door is dsi-client; the Telegram download is injected by index.ts).
9
+ */
10
+ import { PROMPT_IMAGE_MEDIA_TYPES } from "./dsi-client.js";
11
+ /** Telegram bot getFile download ceiling (platform limit). */
12
+ export const TELEGRAM_FILE_CAP_BYTES = 20 * 1024 * 1024;
13
+ function isPromptImageMediaType(value) {
14
+ return PROMPT_IMAGE_MEDIA_TYPES.includes(value);
15
+ }
16
+ /** The inbox is flat (file route: basename only) — fold separators to '_'. */
17
+ export function inboxSafeName(name) {
18
+ return name.length === 0 ? 'file' : name.replace(/\.\./g, '__').replace(/[/\\]/g, '_') || 'file';
19
+ }
20
+ function failureNote(err) {
21
+ if (err instanceof Error && 'code' in err)
22
+ return `(${String(err.code)})`;
23
+ return `(${err instanceof Error ? err.message : String(err)})`;
24
+ }
25
+ export async function shapeAttachments(input) {
26
+ const images = [];
27
+ const landed = [];
28
+ const notes = [];
29
+ if (input.photo) {
30
+ try {
31
+ const { bytes } = await input.load(input.photo.fileId);
32
+ images.push({ mediaType: 'image/jpeg', data: bytes.toString('base64'), name: 'photo.jpg' });
33
+ }
34
+ catch (err) {
35
+ notes.push(`photo could not be downloaded ${failureNote(err)}`);
36
+ }
37
+ }
38
+ const doc = input.document;
39
+ if (doc) {
40
+ const name = inboxSafeName(doc.fileName ?? 'file');
41
+ const type = doc.mimeType ?? '';
42
+ if (isPromptImageMediaType(type)) {
43
+ try {
44
+ const { bytes } = await input.load(doc.fileId);
45
+ images.push({ mediaType: type, data: bytes.toString('base64'), name });
46
+ }
47
+ catch (err) {
48
+ notes.push(`image "${name}" could not be downloaded ${failureNote(err)}`);
49
+ }
50
+ }
51
+ else {
52
+ let oversized = typeof doc.fileSize === 'number' && doc.fileSize > TELEGRAM_FILE_CAP_BYTES;
53
+ let bytes = null;
54
+ if (!oversized) {
55
+ try {
56
+ const loaded = await input.load(doc.fileId);
57
+ bytes = loaded.bytes;
58
+ oversized =
59
+ loaded.size > TELEGRAM_FILE_CAP_BYTES || loaded.bytes.length > TELEGRAM_FILE_CAP_BYTES;
60
+ }
61
+ catch (err) {
62
+ notes.push(`"${name}" could not be downloaded ${failureNote(err)}`);
63
+ }
64
+ }
65
+ if (oversized) {
66
+ notes.push(`"${name}" is over 20 MB — not attached`);
67
+ }
68
+ else if (bytes) {
69
+ try {
70
+ const out = await input.client.file(input.sessionId, {
71
+ name,
72
+ mediaType: type.length > 0 ? type : 'application/octet-stream',
73
+ data: bytes.toString('base64')
74
+ });
75
+ landed.push(out.path);
76
+ }
77
+ catch (err) {
78
+ notes.push(`"${name}" could not be landed ${failureNote(err)}`);
79
+ }
80
+ }
81
+ }
82
+ }
83
+ let text = input.caption;
84
+ if (landed.length > 0) {
85
+ text = `Attached files:\n${landed.map((p) => `- ${p}`).join('\n')}\n\n${text}`;
86
+ }
87
+ if (notes.length > 0) {
88
+ text = `${text}${text.length > 0 ? '\n\n' : ''}${notes.join('\n')}`;
89
+ }
90
+ return { images, text };
91
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * chat-map — the ONLY reader/writer of ~/.dsi/telegram-chats.json (ADR-0090 D4).
3
+ * chatId → {sessionId, cwd}. `cwd` is the NEXT /new's argument (D8): /ws
4
+ * updates it and never touches a live session. Atomic write (tmp + rename).
5
+ * A corrupt file starts empty with one console line — never a crash loop.
6
+ */
7
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
8
+ import { homedir } from 'node:os';
9
+ import { dirname, join } from 'node:path';
10
+ /** Operator decision 2026-12-02: default workspace is ~/agentic-ai. */
11
+ export const DEFAULT_CWD = join(homedir(), 'agentic-ai');
12
+ export const CHAT_MAP_PATH = join(homedir(), '.dsi', 'telegram-chats.json');
13
+ export function loadChatMap(path = CHAT_MAP_PATH) {
14
+ let text;
15
+ try {
16
+ text = readFileSync(path, 'utf-8');
17
+ }
18
+ catch {
19
+ return {}; // missing → empty
20
+ }
21
+ try {
22
+ const parsed = JSON.parse(text);
23
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
24
+ throw new Error('not an object');
25
+ }
26
+ const out = {};
27
+ for (const [key, value] of Object.entries(parsed)) {
28
+ const r = (value ?? {});
29
+ out[key] = {
30
+ sessionId: typeof r.sessionId === 'string' ? r.sessionId : null,
31
+ cwd: typeof r.cwd === 'string' && r.cwd.length > 0 ? r.cwd : DEFAULT_CWD
32
+ };
33
+ }
34
+ return out;
35
+ }
36
+ catch (err) {
37
+ console.warn(`[telegram-bot] chat map at ${path} is corrupt (${err instanceof Error ? err.message : String(err)}) — starting empty`);
38
+ return {};
39
+ }
40
+ }
41
+ /** Atomic: write a sibling tmp file, then rename over the target. */
42
+ export function saveChatMap(map, path = CHAT_MAP_PATH) {
43
+ mkdirSync(dirname(path), { recursive: true });
44
+ const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
45
+ writeFileSync(tmp, JSON.stringify(map, null, 2) + '\n', 'utf-8');
46
+ renameSync(tmp, path);
47
+ }
48
+ export function keyOf(chatId) {
49
+ return String(chatId);
50
+ }
51
+ /** The chat's record, created with defaults ({sessionId:null}, DEFAULT_CWD) on first touch. */
52
+ export function get(map, chatId) {
53
+ const key = keyOf(chatId);
54
+ const existing = map[key];
55
+ if (existing)
56
+ return existing;
57
+ const fresh = { sessionId: null, cwd: DEFAULT_CWD };
58
+ map[key] = fresh;
59
+ return fresh;
60
+ }
61
+ export function setSession(map, chatId, sessionId) {
62
+ const rec = get(map, chatId);
63
+ rec.sessionId = sessionId;
64
+ return rec;
65
+ }
66
+ /** D8 — cwd only. The record's sessionId is left exactly as it was. */
67
+ export function setCwd(map, chatId, cwd) {
68
+ const rec = get(map, chatId);
69
+ rec.cwd = cwd;
70
+ return rec;
71
+ }
@@ -0,0 +1,20 @@
1
+ /** README order. `/1` stands for the /N pattern (D3) — the hint and README keep the `/N` spelling. */
2
+ export const COMMANDS = [
3
+ { command: '/id', description: 'print the chat id and your user id' },
4
+ { command: '/new', description: "fresh session in the chat's current cwd" },
5
+ { command: '/ws', description: 'set the cwd for the next /new (never moves a live session)' },
6
+ { command: '/status', description: 'is the agent running?' },
7
+ { command: '/cancel', description: 'stop the running turn' },
8
+ { command: '/1', description: 'answer the pending question with option 1 (/2, /3 …)' },
9
+ { command: '/skills', description: "list the host's skills for this chat's session, or run one: /skills <name> [args] (ADR-0092)" }
10
+ ];
11
+ export const PATTERN_COMMAND = '/N';
12
+ /** The rows as Telegram's setMyCommands takes them: the command without its slash (D1). */
13
+ export function menuCommands() {
14
+ return COMMANDS.map((c) => ({ command: c.command.slice(1), description: c.description }));
15
+ }
16
+ /** `unknown command — /id /new … /N /skills` — derived, never typed (D2). */
17
+ export function unknownCommandHint() {
18
+ const names = COMMANDS.map((c) => c.command).filter((c) => c !== '/1');
19
+ return `unknown command — ${[...names.slice(0, -1), PATTERN_COMMAND, names[names.length - 1]].join(' ')}`;
20
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * dsi-client — the ONLY module in this package that speaks HTTP to DSI
3
+ * (ADR-0090 D1: an ordinary client of /api/dsh/*; no Telegram namespace).
4
+ * Every call carries the bridge bearer; every non-2xx answer is a
5
+ * DsiClientError{status, code}. Nothing here knows Telegram; nothing else
6
+ * in the package knows DSI's URLs.
7
+ * ADR-0092 D5: `catalog()` reads the composer's own route per invocation — no cache, no retry.
8
+ */
9
+ export const API_ROOT = '/api/dsh';
10
+ export class DsiClientError extends Error {
11
+ status;
12
+ code;
13
+ constructor(status, code, message) {
14
+ super(`DSI ${status} ${code}: ${message}`);
15
+ this.name = 'DsiClientError';
16
+ this.status = status;
17
+ this.code = code;
18
+ }
19
+ }
20
+ /** Host prompt-image whitelist (dsh-rpc.ts:595) — mirrored, never widened (ADR-0090 D2). */
21
+ export const PROMPT_IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'];
22
+ export function createDsiClient(options) {
23
+ const baseUrl = options.baseUrl.replace(/\/+$/, '');
24
+ const doFetch = options.fetch ?? fetch;
25
+ /** The one HTTP door. `path` is always relative to API_ROOT. */
26
+ async function call(method, path, body) {
27
+ const headers = { authorization: `Bearer ${options.token}` };
28
+ if (body !== undefined)
29
+ headers['content-type'] = 'application/json';
30
+ const res = await doFetch(baseUrl + path, {
31
+ method,
32
+ headers,
33
+ ...(body === undefined ? {} : { body: JSON.stringify(body) })
34
+ });
35
+ let parsed = null;
36
+ try {
37
+ parsed = await res.json();
38
+ }
39
+ catch {
40
+ parsed = null;
41
+ }
42
+ if (!res.ok) {
43
+ const rec = (parsed ?? {});
44
+ const code = typeof rec.error?.code === 'string' ? rec.error.code : `http-${res.status}`;
45
+ const message = typeof rec.error?.message === 'string' ? rec.error.message : res.statusText;
46
+ throw new DsiClientError(res.status, code, message);
47
+ }
48
+ return parsed;
49
+ }
50
+ const enc = encodeURIComponent;
51
+ const session = (id) => `${API_ROOT}/session/${enc(id)}`;
52
+ return {
53
+ createSession: (cwd) => call('POST', `${API_ROOT}/sessions`, { cwd }),
54
+ prompt: (id, { text, images }) => call('POST', `${session(id)}/prompt`, { text, ...(images === undefined ? {} : { images }) }),
55
+ events: (id, since) => call('GET', `${session(id)}/events?since=${since}`),
56
+ respond: (id, rpcId, payload) => call('POST', `${session(id)}/respond`, { rpcId, payload }),
57
+ cancel: (id) => call('POST', `${session(id)}/cancel`, {}),
58
+ file: (id, { name, mediaType, data }) => call('POST', `${session(id)}/file`, { name, mediaType, data }),
59
+ turn: (id) => call('GET', `${session(id)}/turn`),
60
+ catalog: (id) => call('GET', `${session(id)}/catalog`)
61
+ };
62
+ }