@deepseek-insight/telegram-bot 0.0.0-stage → 0.1.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/README.md +95 -2
- package/bin/dsi-telegram.mjs +16 -0
- package/package.json +32 -4
- package/src/attachments.ts +122 -0
- package/src/chat-map.ts +86 -0
- package/src/commands.ts +37 -0
- package/src/dsi-client.ts +153 -0
- package/src/floor-cli.ts +433 -0
- package/src/index.ts +479 -0
- package/src/reply-stream.ts +148 -0
- package/src/slot.ts +73 -0
- package/src/status-listener.ts +67 -0
package/README.md
CHANGED
|
@@ -1,3 +1,96 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @deepseek-insight/telegram-bot
|
|
2
2
|
|
|
3
|
-
|
|
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 `src/floor-cli.ts` (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 src/index.ts` — 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]` runs the same `src/floor-cli.ts`. Both spellings need Node >= 22.19 and have **no build step and no `dist/`** — Node strips the TypeScript types itself, so the tarball *is* the source tree (ADR-0093 D2). `--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,16 @@
|
|
|
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. Node >= 22.19 strips the .ts types (D2): the tarball is the source.
|
|
6
|
+
import { main } from '../src/floor-cli.ts';
|
|
7
|
+
|
|
8
|
+
main(process.argv.slice(2))
|
|
9
|
+
.then((code) => {
|
|
10
|
+
process.exitCode = code;
|
|
11
|
+
})
|
|
12
|
+
.catch((err) => {
|
|
13
|
+
console.error(`[floor] fatal: ${err instanceof Error ? err.message : String(err)}`);
|
|
14
|
+
process.exit(1);
|
|
15
|
+
});
|
|
16
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deepseek-insight/telegram-bot",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"src",
|
|
14
|
+
"bin",
|
|
15
|
+
"README.md"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"start": "node src/index.ts",
|
|
19
|
+
"floor": "node src/floor-cli.ts",
|
|
20
|
+
"test": "vitest run",
|
|
21
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
22
|
+
"lint:package": "publint"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"grammy": "^1.38.0",
|
|
26
|
+
"yaml": "^2.9.0"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^24.0.0",
|
|
30
|
+
"publint": "^0.3.25",
|
|
31
|
+
"typescript": "^6.0.3",
|
|
32
|
+
"vitest": "^4.1.9"
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
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.ts';
|
|
11
|
+
import type { DsiClient, PromptImageMediaType, PromptImagePart } from './dsi-client.ts';
|
|
12
|
+
|
|
13
|
+
/** Telegram bot getFile download ceiling (platform limit). */
|
|
14
|
+
export const TELEGRAM_FILE_CAP_BYTES = 20 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
export interface PhotoInput {
|
|
17
|
+
/** file_id of the largest PhotoSize in the message. */
|
|
18
|
+
fileId: string;
|
|
19
|
+
}
|
|
20
|
+
export interface DocumentInput {
|
|
21
|
+
fileId: string;
|
|
22
|
+
mimeType?: string | undefined;
|
|
23
|
+
fileName?: string | undefined;
|
|
24
|
+
/** Telegram's file_size, when it sent one. */
|
|
25
|
+
fileSize?: number | undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Loads a Telegram file's bytes — owned by index.ts (grammY + file download). */
|
|
29
|
+
export type TelegramMediaLoader = (fileId: string) => Promise<{ bytes: Buffer; size: number }>;
|
|
30
|
+
|
|
31
|
+
export interface ShapeInput {
|
|
32
|
+
photo?: PhotoInput | undefined;
|
|
33
|
+
document?: DocumentInput | undefined;
|
|
34
|
+
caption: string;
|
|
35
|
+
client: Pick<DsiClient, 'file'>;
|
|
36
|
+
sessionId: string;
|
|
37
|
+
load: TelegramMediaLoader;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface ShapedPrompt {
|
|
41
|
+
images: PromptImagePart[];
|
|
42
|
+
text: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isPromptImageMediaType(value: string): value is PromptImageMediaType {
|
|
46
|
+
return (PROMPT_IMAGE_MEDIA_TYPES as readonly string[]).includes(value);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The inbox is flat (file route: basename only) — fold separators to '_'. */
|
|
50
|
+
export function inboxSafeName(name: string): string {
|
|
51
|
+
return name.length === 0 ? 'file' : name.replace(/\.\./g, '__').replace(/[/\\]/g, '_') || 'file';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function failureNote(err: unknown): string {
|
|
55
|
+
if (err instanceof Error && 'code' in err) return `(${String((err as { code: unknown }).code)})`;
|
|
56
|
+
return `(${err instanceof Error ? err.message : String(err)})`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function shapeAttachments(input: ShapeInput): Promise<ShapedPrompt> {
|
|
60
|
+
const images: PromptImagePart[] = [];
|
|
61
|
+
const landed: string[] = [];
|
|
62
|
+
const notes: string[] = [];
|
|
63
|
+
|
|
64
|
+
if (input.photo) {
|
|
65
|
+
try {
|
|
66
|
+
const { bytes } = await input.load(input.photo.fileId);
|
|
67
|
+
images.push({ mediaType: 'image/jpeg', data: bytes.toString('base64'), name: 'photo.jpg' });
|
|
68
|
+
} catch (err) {
|
|
69
|
+
notes.push(`photo could not be downloaded ${failureNote(err)}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const doc = input.document;
|
|
74
|
+
if (doc) {
|
|
75
|
+
const name = inboxSafeName(doc.fileName ?? 'file');
|
|
76
|
+
const type = doc.mimeType ?? '';
|
|
77
|
+
if (isPromptImageMediaType(type)) {
|
|
78
|
+
try {
|
|
79
|
+
const { bytes } = await input.load(doc.fileId);
|
|
80
|
+
images.push({ mediaType: type, data: bytes.toString('base64'), name });
|
|
81
|
+
} catch (err) {
|
|
82
|
+
notes.push(`image "${name}" could not be downloaded ${failureNote(err)}`);
|
|
83
|
+
}
|
|
84
|
+
} else {
|
|
85
|
+
let oversized = typeof doc.fileSize === 'number' && doc.fileSize > TELEGRAM_FILE_CAP_BYTES;
|
|
86
|
+
let bytes: Buffer | null = null;
|
|
87
|
+
if (!oversized) {
|
|
88
|
+
try {
|
|
89
|
+
const loaded = await input.load(doc.fileId);
|
|
90
|
+
bytes = loaded.bytes;
|
|
91
|
+
oversized =
|
|
92
|
+
loaded.size > TELEGRAM_FILE_CAP_BYTES || loaded.bytes.length > TELEGRAM_FILE_CAP_BYTES;
|
|
93
|
+
} catch (err) {
|
|
94
|
+
notes.push(`"${name}" could not be downloaded ${failureNote(err)}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (oversized) {
|
|
98
|
+
notes.push(`"${name}" is over 20 MB — not attached`);
|
|
99
|
+
} else if (bytes) {
|
|
100
|
+
try {
|
|
101
|
+
const out = await input.client.file(input.sessionId, {
|
|
102
|
+
name,
|
|
103
|
+
mediaType: type.length > 0 ? type : 'application/octet-stream',
|
|
104
|
+
data: bytes.toString('base64')
|
|
105
|
+
});
|
|
106
|
+
landed.push(out.path);
|
|
107
|
+
} catch (err) {
|
|
108
|
+
notes.push(`"${name}" could not be landed ${failureNote(err)}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
let text = input.caption;
|
|
115
|
+
if (landed.length > 0) {
|
|
116
|
+
text = `Attached files:\n${landed.map((p) => `- ${p}`).join('\n')}\n\n${text}`;
|
|
117
|
+
}
|
|
118
|
+
if (notes.length > 0) {
|
|
119
|
+
text = `${text}${text.length > 0 ? '\n\n' : ''}${notes.join('\n')}`;
|
|
120
|
+
}
|
|
121
|
+
return { images, text };
|
|
122
|
+
}
|
package/src/chat-map.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
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
|
+
|
|
11
|
+
/** Operator decision 2026-12-02: default workspace is ~/agentic-ai. */
|
|
12
|
+
export const DEFAULT_CWD = join(homedir(), 'agentic-ai');
|
|
13
|
+
export const CHAT_MAP_PATH = join(homedir(), '.dsi', 'telegram-chats.json');
|
|
14
|
+
|
|
15
|
+
export interface ChatRecord {
|
|
16
|
+
/** null until the chat's first /new or first prompt. */
|
|
17
|
+
sessionId: string | null;
|
|
18
|
+
/** cwd for the NEXT session create — never retroactive (D8). */
|
|
19
|
+
cwd: string;
|
|
20
|
+
}
|
|
21
|
+
export type ChatMap = Record<string, ChatRecord>;
|
|
22
|
+
export type ChatId = number | string;
|
|
23
|
+
|
|
24
|
+
export function loadChatMap(path = CHAT_MAP_PATH): ChatMap {
|
|
25
|
+
let text: string;
|
|
26
|
+
try {
|
|
27
|
+
text = readFileSync(path, 'utf-8');
|
|
28
|
+
} catch {
|
|
29
|
+
return {}; // missing → empty
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const parsed: unknown = JSON.parse(text);
|
|
33
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
34
|
+
throw new Error('not an object');
|
|
35
|
+
}
|
|
36
|
+
const out: ChatMap = {};
|
|
37
|
+
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
|
|
38
|
+
const r = (value ?? {}) as Partial<ChatRecord>;
|
|
39
|
+
out[key] = {
|
|
40
|
+
sessionId: typeof r.sessionId === 'string' ? r.sessionId : null,
|
|
41
|
+
cwd: typeof r.cwd === 'string' && r.cwd.length > 0 ? r.cwd : DEFAULT_CWD
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
} catch (err) {
|
|
46
|
+
console.warn(
|
|
47
|
+
`[telegram-bot] chat map at ${path} is corrupt (${err instanceof Error ? err.message : String(err)}) — starting empty`
|
|
48
|
+
);
|
|
49
|
+
return {};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Atomic: write a sibling tmp file, then rename over the target. */
|
|
54
|
+
export function saveChatMap(map: ChatMap, path = CHAT_MAP_PATH): void {
|
|
55
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
56
|
+
const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
|
|
57
|
+
writeFileSync(tmp, JSON.stringify(map, null, 2) + '\n', 'utf-8');
|
|
58
|
+
renameSync(tmp, path);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function keyOf(chatId: ChatId): string {
|
|
62
|
+
return String(chatId);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The chat's record, created with defaults ({sessionId:null}, DEFAULT_CWD) on first touch. */
|
|
66
|
+
export function get(map: ChatMap, chatId: ChatId): ChatRecord {
|
|
67
|
+
const key = keyOf(chatId);
|
|
68
|
+
const existing = map[key];
|
|
69
|
+
if (existing) return existing;
|
|
70
|
+
const fresh: ChatRecord = { sessionId: null, cwd: DEFAULT_CWD };
|
|
71
|
+
map[key] = fresh;
|
|
72
|
+
return fresh;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function setSession(map: ChatMap, chatId: ChatId, sessionId: string): ChatRecord {
|
|
76
|
+
const rec = get(map, chatId);
|
|
77
|
+
rec.sessionId = sessionId;
|
|
78
|
+
return rec;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** D8 — cwd only. The record's sessionId is left exactly as it was. */
|
|
82
|
+
export function setCwd(map: ChatMap, chatId: ChatId, cwd: string): ChatRecord {
|
|
83
|
+
const rec = get(map, chatId);
|
|
84
|
+
rec.cwd = cwd;
|
|
85
|
+
return rec;
|
|
86
|
+
}
|
package/src/commands.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* commands — THE command list (ADR-0092 D2). One owner, four readers, zero
|
|
3
|
+
* typists: the Telegram menu (pushed at boot by index.ts pushCommandMenu),
|
|
4
|
+
* the `unknown command` hint, the README table (pinned by tests/commands.test.ts)
|
|
5
|
+
* and the router's `switch` (pinned: every entry is routed). Pure — no grammy
|
|
6
|
+
* runtime, no side effects; nothing here knows Telegram's API beyond BotCommand's shape.
|
|
7
|
+
*/
|
|
8
|
+
import type { BotCommand } from 'grammy/types';
|
|
9
|
+
|
|
10
|
+
export interface CommandRow {
|
|
11
|
+
command: string;
|
|
12
|
+
description: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** README order. `/1` stands for the /N pattern (D3) — the hint and README keep the `/N` spelling. */
|
|
16
|
+
export const COMMANDS: readonly CommandRow[] = [
|
|
17
|
+
{ command: '/id', description: 'print the chat id and your user id' },
|
|
18
|
+
{ command: '/new', description: "fresh session in the chat's current cwd" },
|
|
19
|
+
{ command: '/ws', description: 'set the cwd for the next /new (never moves a live session)' },
|
|
20
|
+
{ command: '/status', description: 'is the agent running?' },
|
|
21
|
+
{ command: '/cancel', description: 'stop the running turn' },
|
|
22
|
+
{ command: '/1', description: 'answer the pending question with option 1 (/2, /3 …)' },
|
|
23
|
+
{ command: '/skills', description: "list the host's skills for this chat's session, or run one: /skills <name> [args] (ADR-0092)" }
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
export const PATTERN_COMMAND = '/N';
|
|
27
|
+
|
|
28
|
+
/** The rows as Telegram's setMyCommands takes them: the command without its slash (D1). */
|
|
29
|
+
export function menuCommands(): BotCommand[] {
|
|
30
|
+
return COMMANDS.map((c) => ({ command: c.command.slice(1), description: c.description }));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** `unknown command — /id /new … /N /skills` — derived, never typed (D2). */
|
|
34
|
+
export function unknownCommandHint(): string {
|
|
35
|
+
const names = COMMANDS.map((c) => c.command).filter((c) => c !== '/1');
|
|
36
|
+
return `unknown command — ${[...names.slice(0, -1), PATTERN_COMMAND, names[names.length - 1]].join(' ')}`;
|
|
37
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
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
|
+
|
|
10
|
+
export const API_ROOT = '/api/dsh';
|
|
11
|
+
|
|
12
|
+
export type FetchLike = typeof fetch;
|
|
13
|
+
|
|
14
|
+
export interface DsiClientOptions {
|
|
15
|
+
/** DSI origin, e.g. http://127.0.0.1:5201 (trailing slash tolerated). */
|
|
16
|
+
baseUrl: string;
|
|
17
|
+
/** settings.telegram.token — the bridge bearer (ADR-0090 D3). */
|
|
18
|
+
token: string;
|
|
19
|
+
/** Injected for tests; defaults to globalThis.fetch. */
|
|
20
|
+
fetch?: FetchLike;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class DsiClientError extends Error {
|
|
24
|
+
readonly status: number;
|
|
25
|
+
readonly code: string;
|
|
26
|
+
|
|
27
|
+
constructor(status: number, code: string, message: string) {
|
|
28
|
+
super(`DSI ${status} ${code}: ${message}`);
|
|
29
|
+
this.name = 'DsiClientError';
|
|
30
|
+
this.status = status;
|
|
31
|
+
this.code = code;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Host prompt-image whitelist (dsh-rpc.ts:595) — mirrored, never widened (ADR-0090 D2). */
|
|
36
|
+
export const PROMPT_IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'] as const;
|
|
37
|
+
export type PromptImageMediaType = (typeof PROMPT_IMAGE_MEDIA_TYPES)[number];
|
|
38
|
+
export interface PromptImagePart {
|
|
39
|
+
mediaType: PromptImageMediaType;
|
|
40
|
+
/** base64 */
|
|
41
|
+
data: string;
|
|
42
|
+
name?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The events poll's subset this package reads (types.ts DsiEntry / rpc-relay PendingAnswerFrame). */
|
|
46
|
+
export interface DsiAssistantEntry {
|
|
47
|
+
kind: 'assistant-message';
|
|
48
|
+
id: string;
|
|
49
|
+
seq: number;
|
|
50
|
+
time: number;
|
|
51
|
+
text: string;
|
|
52
|
+
streaming: boolean;
|
|
53
|
+
reasoning?: string;
|
|
54
|
+
}
|
|
55
|
+
export interface DsiPendingAnswer {
|
|
56
|
+
rpcId: string;
|
|
57
|
+
sessionId: string;
|
|
58
|
+
kind: 'approval' | 'question';
|
|
59
|
+
body: Record<string, unknown>;
|
|
60
|
+
receivedAt: number;
|
|
61
|
+
}
|
|
62
|
+
export interface DsiLiveStreamTail {
|
|
63
|
+
id: string;
|
|
64
|
+
turn: number;
|
|
65
|
+
step: number;
|
|
66
|
+
seq: number;
|
|
67
|
+
time: number;
|
|
68
|
+
text: string;
|
|
69
|
+
reasoning: string;
|
|
70
|
+
}
|
|
71
|
+
export interface DsiEventsResult {
|
|
72
|
+
ok: true;
|
|
73
|
+
entries: Array<Record<string, unknown>>;
|
|
74
|
+
lastSeq: number;
|
|
75
|
+
running: boolean;
|
|
76
|
+
gap?: boolean;
|
|
77
|
+
liveStream?: DsiLiveStreamTail | null;
|
|
78
|
+
pendingAnswers: DsiPendingAnswer[];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Mirror of dsh-rpc.ts DshSkillRow — the host's skill catalog row (ADR-0092 D5). */
|
|
82
|
+
export interface DsiSkillRow {
|
|
83
|
+
name: string;
|
|
84
|
+
description: string;
|
|
85
|
+
whenToUse?: string;
|
|
86
|
+
modelInvocable: boolean;
|
|
87
|
+
}
|
|
88
|
+
/** The catalog route's body: commands/list + skills/list for one session (either leg failing fails the whole catalog). */
|
|
89
|
+
export interface DsiCatalog {
|
|
90
|
+
ok: true;
|
|
91
|
+
commands: Array<Record<string, unknown>>;
|
|
92
|
+
skills: DsiSkillRow[];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface DsiClient {
|
|
96
|
+
createSession(cwd: string): Promise<{ sessionId: string }>;
|
|
97
|
+
prompt(sessionId: string, input: { text: string; images?: PromptImagePart[] }): Promise<{ accepted: boolean }>;
|
|
98
|
+
events(sessionId: string, since: number): Promise<DsiEventsResult>;
|
|
99
|
+
respond(sessionId: string, rpcId: string, payload: Record<string, unknown>): Promise<{ ok: boolean; accepted: boolean }>;
|
|
100
|
+
cancel(sessionId: string): Promise<{ ok: boolean; accepted: boolean }>;
|
|
101
|
+
/** The guarded landing route (ADR-0090 D2/D5). */
|
|
102
|
+
file(sessionId: string, input: { name: string; mediaType: string; data: string }): Promise<{ ok: boolean; path: string }>;
|
|
103
|
+
/** The guarded long-poll (ADR-0090 D2/D6). */
|
|
104
|
+
turn(sessionId: string): Promise<{ ok: boolean; running: boolean }>;
|
|
105
|
+
/** The composer's catalog route, read per invocation (ADR-0092 D5). */
|
|
106
|
+
catalog(sessionId: string): Promise<DsiCatalog>;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
type Method = 'GET' | 'POST';
|
|
110
|
+
|
|
111
|
+
export function createDsiClient(options: DsiClientOptions): DsiClient {
|
|
112
|
+
const baseUrl = options.baseUrl.replace(/\/+$/, '');
|
|
113
|
+
const doFetch = options.fetch ?? fetch;
|
|
114
|
+
|
|
115
|
+
/** The one HTTP door. `path` is always relative to API_ROOT. */
|
|
116
|
+
async function call<T>(method: Method, path: string, body?: unknown): Promise<T> {
|
|
117
|
+
const headers: Record<string, string> = { authorization: `Bearer ${options.token}` };
|
|
118
|
+
if (body !== undefined) headers['content-type'] = 'application/json';
|
|
119
|
+
const res = await doFetch(baseUrl + path, {
|
|
120
|
+
method,
|
|
121
|
+
headers,
|
|
122
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) })
|
|
123
|
+
});
|
|
124
|
+
let parsed: unknown = null;
|
|
125
|
+
try {
|
|
126
|
+
parsed = await res.json();
|
|
127
|
+
} catch {
|
|
128
|
+
parsed = null;
|
|
129
|
+
}
|
|
130
|
+
if (!res.ok) {
|
|
131
|
+
const rec = (parsed ?? {}) as { error?: { code?: unknown; message?: unknown } };
|
|
132
|
+
const code = typeof rec.error?.code === 'string' ? rec.error.code : `http-${res.status}`;
|
|
133
|
+
const message = typeof rec.error?.message === 'string' ? rec.error.message : res.statusText;
|
|
134
|
+
throw new DsiClientError(res.status, code, message);
|
|
135
|
+
}
|
|
136
|
+
return parsed as T;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const enc = encodeURIComponent;
|
|
140
|
+
const session = (id: string): string => `${API_ROOT}/session/${enc(id)}`;
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
createSession: (cwd) => call('POST', `${API_ROOT}/sessions`, { cwd }),
|
|
144
|
+
prompt: (id, { text, images }) =>
|
|
145
|
+
call('POST', `${session(id)}/prompt`, { text, ...(images === undefined ? {} : { images }) }),
|
|
146
|
+
events: (id, since) => call('GET', `${session(id)}/events?since=${since}`),
|
|
147
|
+
respond: (id, rpcId, payload) => call('POST', `${session(id)}/respond`, { rpcId, payload }),
|
|
148
|
+
cancel: (id) => call('POST', `${session(id)}/cancel`, {}),
|
|
149
|
+
file: (id, { name, mediaType, data }) => call('POST', `${session(id)}/file`, { name, mediaType, data }),
|
|
150
|
+
turn: (id) => call('GET', `${session(id)}/turn`),
|
|
151
|
+
catalog: (id) => call('GET', `${session(id)}/catalog`)
|
|
152
|
+
};
|
|
153
|
+
}
|