@deepseek-insight/telegram-bot 0.1.0 → 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 +3 -3
- package/bin/dsi-telegram.mjs +4 -3
- 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 +8 -5
- package/src/attachments.ts +0 -122
- package/src/chat-map.ts +0 -86
- package/src/commands.ts +0 -37
- package/src/dsi-client.ts +0 -153
- package/src/floor-cli.ts +0 -433
- package/src/index.ts +0 -479
- package/src/reply-stream.ts +0 -148
- package/src/slot.ts +0 -73
- package/src/status-listener.ts +0 -67
package/README.md
CHANGED
|
@@ -37,13 +37,13 @@ dsi-telegram <status|on|off> [--slot k] # installed (npm i -g) — bare = stat
|
|
|
37
37
|
# in a checkout: pnpm --dir packages/telegram-bot floor <status|on|off> [--slot k]
|
|
38
38
|
```
|
|
39
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 `
|
|
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
41
|
|
|
42
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
43
|
|
|
44
44
|
#### Manual run (debugging only)
|
|
45
45
|
|
|
46
|
-
`pnpm start` runs `node
|
|
46
|
+
`pnpm start` runs `node dist/index.js` (after `pnpm build`) — plain node, no loader.
|
|
47
47
|
|
|
48
48
|
```bash
|
|
49
49
|
cd packages/telegram-bot
|
|
@@ -65,7 +65,7 @@ npm i -g @deepseek-insight/telegram-bot
|
|
|
65
65
|
dsi-telegram <status|on|off> [--slot k]
|
|
66
66
|
```
|
|
67
67
|
|
|
68
|
-
In a repo checkout nothing is installed: `pnpm --dir packages/telegram-bot floor <status|on|off> [--slot k]` runs the same `
|
|
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
69
|
|
|
70
70
|
## Commands
|
|
71
71
|
|
package/bin/dsi-telegram.mjs
CHANGED
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
// dsi-telegram — the published spelling of `pnpm floor` (ADR-0093 D3): status | on | off [--slot k].
|
|
3
3
|
// No logic lives here. The shim calls floor-cli's exported main() EXPLICITLY: floor-cli's own
|
|
4
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.
|
|
6
|
-
|
|
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';
|
|
7
9
|
|
|
8
10
|
main(process.argv.slice(2))
|
|
9
11
|
.then((code) => {
|
|
@@ -13,4 +15,3 @@ main(process.argv.slice(2))
|
|
|
13
15
|
console.error(`[floor] fatal: ${err instanceof Error ? err.message : String(err)}`);
|
|
14
16
|
process.exit(1);
|
|
15
17
|
});
|
|
16
|
-
|
|
@@ -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
|
+
}
|
package/dist/chat-map.js
ADDED
|
@@ -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
|
+
}
|
package/dist/commands.js
ADDED
|
@@ -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
|
+
}
|