@shliamb/dsh-telegram-bot 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +310 -2
- package/README.ru.md +311 -0
- package/cordis.patch.yml +6 -0
- package/lib/client.js +275 -0
- package/lib/client.js.map +1 -0
- package/lib/index.d.ts +106 -0
- package/lib/index.js +2020 -0
- package/lib/logging/index.d.ts +28 -0
- package/lib/logging/index.js +106 -0
- package/lib/state/index.d.ts +69 -0
- package/lib/state/index.js +94 -0
- package/package.json +83 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-telegram-bot contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,311 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-telegram-bot
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**English** | [Русский](README.ru.md)
|
|
4
|
+
|
|
5
|
+
Package: [`@shliamb/dsh-telegram-bot`](https://www.npmjs.com/package/@shliamb/dsh-telegram-bot)
|
|
6
|
+
|
|
7
|
+
Telegram bridge for **DeepSeek Harness**. The plugin runs inside the Harness Host as an external bundle: you talk to the agent from a private Telegram chat, choose a workspace and session, follow long turns with a live progress message, and manage the Host remotely.
|
|
8
|
+
|
|
9
|
+
> **Status:** Phase 2.2, early alpha. The bundle targets DeepSeek Harness `0.2.2-alpha.3` and the `web` profile.
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- Text conversation with the agent from Telegram.
|
|
14
|
+
- Workspace and session (branch) picker. A session is created on the first message when the workspace has none.
|
|
15
|
+
- Rich final answers: Markdown with tables, headings, lists and code; falls back to rich HTML and then to plain text.
|
|
16
|
+
- One editable progress message per turn (`💭 thinking`, `🔧 tool`, `✍️ writing`, `✅ done`) instead of a stream of bash output.
|
|
17
|
+
- Parallel turns: switch to another workspace while an older turn keeps updating. Its final answer still arrives in the same chat.
|
|
18
|
+
- Tool approvals and agent questions as inline buttons.
|
|
19
|
+
- Main menu with account balance, workspace, session, context usage and colored buttons.
|
|
20
|
+
- Sound on/off per chat, history compaction via `/compact`, and a confirmed stop.
|
|
21
|
+
- Admin screen with log download and remote Harness restart.
|
|
22
|
+
- Russian or English UI, chosen from the Telegram client language (`ru*` → Russian, otherwise English).
|
|
23
|
+
|
|
24
|
+
## Requirements
|
|
25
|
+
|
|
26
|
+
- DeepSeek Harness with the `web` profile. The bundle declares `engines.dsh >=0.2.2-alpha.3 <0.3.0`, so installation is refused on an incompatible Host.
|
|
27
|
+
- Node.js `>= 24.9` and pnpm.
|
|
28
|
+
- A Telegram bot token from [@BotFather](https://t.me/BotFather).
|
|
29
|
+
- Your numeric Telegram user ID, for example from [@userinfobot](https://t.me/userinfobot).
|
|
30
|
+
- A running Host. One bot token can be polled by only one Host process at a time (otherwise Telegram returns `409 Conflict`).
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
The package is published on npm as **`@shliamb/dsh-telegram-bot`**. The short name `dsh-telegram-bot` is already used by another project, so use the scoped name.
|
|
35
|
+
|
|
36
|
+
### Option 1 — from npm (recommended)
|
|
37
|
+
|
|
38
|
+
With the `dsh` CLI on your `PATH`:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
dsh plugin --profile web add @shliamb/dsh-telegram-bot
|
|
42
|
+
dsh web
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
From a Harness source checkout:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
cd /path/to/deepseek-harness
|
|
49
|
+
pnpm dsh plugin --profile web add @shliamb/dsh-telegram-bot
|
|
50
|
+
pnpm dsh web
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The in-app path is **Plugins → Add plugin**. Enter `@shliamb/dsh-telegram-bot` and confirm the install.
|
|
54
|
+
|
|
55
|
+
Adding a new bundle requires a Host restart. Chat sessions and bindings survive the restart; the new plugin row and its settings page are loaded on boot.
|
|
56
|
+
|
|
57
|
+
### Option 2 — prebuilt archive
|
|
58
|
+
|
|
59
|
+
The repository also contains a ready-to-install archive:
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
dist/shliamb-dsh-telegram-bot-0.2.0.tgz
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
If the `dsh` CLI is on your `PATH`, run this from the repository root:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.0.tgz
|
|
69
|
+
dsh web
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
If you run Harness from a source checkout, use `pnpm dsh` from that checkout and pass an absolute path to the archive:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
cd /path/to/deepseek-harness
|
|
76
|
+
pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.0.tgz
|
|
77
|
+
pnpm dsh web
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`dsh plugin` forwards its arguments to pnpm inside the profile directory. Relative paths are resolved from the directory where you run the command, so absolute paths are the safest option when in doubt.
|
|
81
|
+
|
|
82
|
+
### Option 3 — from source
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
cd /path/to/HarnessBot
|
|
86
|
+
pnpm install
|
|
87
|
+
pnpm build
|
|
88
|
+
|
|
89
|
+
cd /path/to/deepseek-harness
|
|
90
|
+
pnpm dsh plugin --profile web add /path/to/HarnessBot
|
|
91
|
+
pnpm dsh web
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
A linked checkout keeps its own `node_modules`. After changing the source, run `pnpm build` again and restart the Host. HMR updates the plugin configuration, but it does not reload the host code of a linked bundle or register a new client entry.
|
|
95
|
+
|
|
96
|
+
### First start
|
|
97
|
+
|
|
98
|
+
The bot does not start long polling until a token is configured. Open the Web UI, go to **Plugins → @shliamb/dsh-telegram-bot**, and set the token and your Telegram ID as described below.
|
|
99
|
+
|
|
100
|
+
DeepSeek Harness has no official plugin marketplace. Community directories such as FindHarness index packages published on npm, so publishing the scoped package makes the plugin discoverable without a separate store submission.
|
|
101
|
+
|
|
102
|
+
## Configuration
|
|
103
|
+
|
|
104
|
+
### Web UI
|
|
105
|
+
|
|
106
|
+
1. Open the Harness Web UI.
|
|
107
|
+
2. Go to **Plugins → @shliamb/dsh-telegram-bot**.
|
|
108
|
+
3. Click **Configure** in the top-right corner of the bundle card, or click the `telegram-bot` row in the row list.
|
|
109
|
+
4. Paste the bot token and enter your numeric Telegram user ID.
|
|
110
|
+
5. Click **Save**.
|
|
111
|
+
|
|
112
|
+
The token field is write-only:
|
|
113
|
+
|
|
114
|
+
- the saved token is never sent back to the browser;
|
|
115
|
+
- the page only shows **configured** or **not configured**;
|
|
116
|
+
- an empty field keeps the current token, so you can change only the admin ID;
|
|
117
|
+
- to replace the token, paste a new one and save.
|
|
118
|
+
|
|
119
|
+
The admin ID is stored in the plugin configuration. When `allowedUserIds` is empty, the admin is also the only user allowed to talk to the bot. The admin is always added to the allowlist.
|
|
120
|
+
|
|
121
|
+
Saving the form restarts polling automatically, so a Host restart is not required after configuration.
|
|
122
|
+
|
|
123
|
+
### Config file (advanced)
|
|
124
|
+
|
|
125
|
+
The same settings can be provided through the profile's `cordis.patch.yml`:
|
|
126
|
+
|
|
127
|
+
```yaml
|
|
128
|
+
- id: telegram-bot
|
|
129
|
+
config:
|
|
130
|
+
adminUserId: 123456789
|
|
131
|
+
allowedUserIds: [123456789]
|
|
132
|
+
botTokenRef: DSH_TELEGRAM_BOT_TOKEN
|
|
133
|
+
lowBalanceUsd: 1 # warn when the USD balance is <= 1
|
|
134
|
+
rich: true # false disables rich messages
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`adminUserId` is the administrator and is always added to the allowlist. `allowedUserIds` is optional; when it is empty, only the admin is allowed. Only private chats are accepted.
|
|
138
|
+
|
|
139
|
+
The token itself still belongs in `credentials` under the `DSH_TELEGRAM_BOT_TOKEN` ref. The Web settings page is the simplest way to store it. `apiRoot` can point at a self-hosted Telegram Bot API server.
|
|
140
|
+
|
|
141
|
+
### Getting a token and your Telegram ID
|
|
142
|
+
|
|
143
|
+
1. Open [@BotFather](https://t.me/BotFather), send `/newbot`, and follow the prompts. Copy the token it returns.
|
|
144
|
+
2. Open [@userinfobot](https://t.me/userinfobot), send any message, and copy your numeric ID.
|
|
145
|
+
3. Paste both into the plugin settings.
|
|
146
|
+
|
|
147
|
+
## Using the bot
|
|
148
|
+
|
|
149
|
+
### Main menu
|
|
150
|
+
|
|
151
|
+
`/start` and `/menu` open the main menu. It shows:
|
|
152
|
+
|
|
153
|
+
- the account balance as an H1 heading with two decimal places;
|
|
154
|
+
- the active workspace, session and context usage;
|
|
155
|
+
- buttons for workspaces, sessions, a new session, compaction, sound and stop.
|
|
156
|
+
|
|
157
|
+
The buttons use Telegram's `success`, `primary`, `danger` and `link` styles where the client supports them. If no workspace is selected, **New session** opens the workspace picker first.
|
|
158
|
+
|
|
159
|
+
On a fresh Host start the bot sends the admin a single **“Harness is online”** message with a **Menu** button. A plugin HMR reload does not send it again.
|
|
160
|
+
|
|
161
|
+
### Commands
|
|
162
|
+
|
|
163
|
+
Only `/start` is shown in Telegram's command menu. The other commands are hidden but still work when typed manually.
|
|
164
|
+
|
|
165
|
+
| Command | Description |
|
|
166
|
+
| --- | --- |
|
|
167
|
+
| `/start`, `/menu` | Main menu with balance and buttons. |
|
|
168
|
+
| `/admin` | Admin only: send logs as a document and restart Harness with confirmation. |
|
|
169
|
+
| `/new` | Create a new session in the active workspace. |
|
|
170
|
+
| `/compact` | Compact the current session history. |
|
|
171
|
+
| `/stop` | Stop the current turn (the menu asks for confirmation). |
|
|
172
|
+
| `/status` | Show balance, active workspace/session, agent state, context and sound. |
|
|
173
|
+
| `/logs` | Send the log tail as a document (admin only). |
|
|
174
|
+
|
|
175
|
+
Final answers are sent as separate rich messages. Long text is split into parts that fit Telegram's message limit. If rich formatting fails, the plugin retries with rich HTML and then with plain text, so the answer is not lost.
|
|
176
|
+
|
|
177
|
+
### Workspaces and sessions
|
|
178
|
+
|
|
179
|
+
After you choose a workspace:
|
|
180
|
+
|
|
181
|
+
- if it has one session, that session is selected automatically;
|
|
182
|
+
- if it has several, an inline picker with `🟢`/`⚪` and session titles appears;
|
|
183
|
+
- if it has none, a session is created when you send the first message.
|
|
184
|
+
|
|
185
|
+
Text sent before a session is selected is not lost: it waits in `pendingPrompt` and is submitted after the selection.
|
|
186
|
+
|
|
187
|
+
### Progress and parallel turns
|
|
188
|
+
|
|
189
|
+
Each turn has its own progress message, tracked by `sessionId`. The message is edited in place and shows the current stage:
|
|
190
|
+
|
|
191
|
+
```text
|
|
192
|
+
💭 thinking
|
|
193
|
+
🔧 bash: <short command>
|
|
194
|
+
✍️ writing
|
|
195
|
+
✅ done
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
You can start a turn in one workspace, switch to another, and start a second turn. Both progress messages keep updating, and both final answers arrive in the same chat even after the active workspace has changed. The last progress stage is delayed and applied after 1.5 seconds instead of being dropped by throttling.
|
|
199
|
+
|
|
200
|
+
Turn tracking lives in Host memory. If the Host is restarted in the middle of a turn, the old progress message may remain at its last stage.
|
|
201
|
+
|
|
202
|
+
### Approvals and questions
|
|
203
|
+
|
|
204
|
+
When the agent requests a tool approval, the bot sends an inline **Allow** / **Deny** keyboard. When the agent asks a question with predefined options, the answers are inline buttons as well. Requests time out after 10 minutes.
|
|
205
|
+
|
|
206
|
+
Approvals and questions are answered for the bound session. Questions that need multi-select or free-form text are left to the Web UI.
|
|
207
|
+
|
|
208
|
+
### Compaction, sound and stop
|
|
209
|
+
|
|
210
|
+
- **Compact** shows the current context percentage and asks for confirmation. The plugin calls the preset-scoped `/compact` command through the `commands` service and reports the localized result and the new percentage. If the agent is busy, compaction is refused.
|
|
211
|
+
- **Sound** is stored per chat. When it is off, answers, progress edits and the startup greeting use `disable_notification`.
|
|
212
|
+
- **Stop** asks for confirmation, then cancels the current turn with `agent.cancel({ kind: 'user' })`.
|
|
213
|
+
|
|
214
|
+
### Admin and remote restart
|
|
215
|
+
|
|
216
|
+
`/admin` is available only to the configured admin. It can:
|
|
217
|
+
|
|
218
|
+
- send the bot log as a Telegram document;
|
|
219
|
+
- restart the Harness Host after confirmation.
|
|
220
|
+
|
|
221
|
+
The restart runs in the background through `pnpm dsh web --no-open` and writes its output to `$DSH_HOME/logs/harness-restart.log`. The bot reconnects after a few seconds. A restart creates a new Web launch URL, so refresh the page or open the URL printed by the new process. The browser cookie usually survives the restart.
|
|
222
|
+
|
|
223
|
+
## Data and privacy
|
|
224
|
+
|
|
225
|
+
- The bot token is stored in DeepSeek Harness `credentials` under `DSH_TELEGRAM_BOT_TOKEN`. It is write-only from the settings page and is never returned to the browser.
|
|
226
|
+
- Logs are written to `$DSH_HOME/logs/telegram-bot.log` as JSONL with `0600` permissions and 2 MB × 3 rotation. The token is replaced with `<redacted-token>`; message text is not logged.
|
|
227
|
+
- Chat bindings are stored in the `telegram_bridge` storage domain (JSON backend, `$DSH_HOME/storages/telegram_bridge.json`). If storage is unavailable, the plugin keeps bindings in memory and logs a warning.
|
|
228
|
+
- Only private chats are accepted. The admin is always allowed; `allowedUserIds` narrows access to the listed accounts.
|
|
229
|
+
- The repository contains no real bot token or Telegram ID. The install archive is built without local credentials.
|
|
230
|
+
|
|
231
|
+
## Troubleshooting
|
|
232
|
+
|
|
233
|
+
### The bot does not respond
|
|
234
|
+
|
|
235
|
+
1. Open **Plugins → @shliamb/dsh-telegram-bot → Configure** and check that the token status is **configured** and the admin ID is correct.
|
|
236
|
+
2. Make sure you write to the bot in a private chat from the admin account (or from an account in `allowedUserIds`).
|
|
237
|
+
3. Check `$DSH_HOME/logs/telegram-bot.log` for `token-missing`, `polling-unauthorized`, `409` or `state-open-failed`.
|
|
238
|
+
4. If another Host process is polling the same token, stop it; Telegram allows only one long-polling consumer.
|
|
239
|
+
|
|
240
|
+
### The Configure button is missing
|
|
241
|
+
|
|
242
|
+
- Hard-refresh the Web UI (`Ctrl+Shift+R`).
|
|
243
|
+
- Make sure the installed package contains `lib/client.js`.
|
|
244
|
+
- Restart the Host after installing a new bundle. A new client entry is registered at boot.
|
|
245
|
+
- Run `pnpm check` and `pnpm build` in the plugin checkout if you installed from source.
|
|
246
|
+
|
|
247
|
+
### The Web page does not open after a restart
|
|
248
|
+
|
|
249
|
+
The restarted Host prints a new launch URL with a fresh token. Open that URL, or refresh the existing page if the Host is already back. The old URL is not reused.
|
|
250
|
+
|
|
251
|
+
### Rich formatting is missing
|
|
252
|
+
|
|
253
|
+
The plugin automatically falls back to rich HTML and then to plain text. If a particular table or heading is not supported by your Telegram client, the plain-text version is still delivered.
|
|
254
|
+
|
|
255
|
+
### The restart failed
|
|
256
|
+
|
|
257
|
+
Read `$DSH_HOME/logs/harness-restart.log`. If the Host did not come back, start it manually from the Harness checkout with `pnpm dsh web` (or `dsh web` for a global installation).
|
|
258
|
+
|
|
259
|
+
## Development
|
|
260
|
+
|
|
261
|
+
```bash
|
|
262
|
+
pnpm install
|
|
263
|
+
pnpm check # typecheck host and client
|
|
264
|
+
pnpm build # tsc -> lib/, tsdown -> lib/client.js
|
|
265
|
+
node dev/standalone.mjs # standalone smoke test without the DSH Host
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
`dev/standalone.mjs` needs `TELEGRAM_BOT_TOKEN` in the environment and connects to Telegram directly. It is useful for testing the bot loop without a Harness profile.
|
|
269
|
+
|
|
270
|
+
After `pnpm build`, restart `pnpm dsh web`: HMR reloads the plugin configuration, but linked host code and the client entry need a fresh Host boot. The settings page appears after that restart.
|
|
271
|
+
|
|
272
|
+
To rebuild the install archive:
|
|
273
|
+
|
|
274
|
+
```bash
|
|
275
|
+
pnpm build
|
|
276
|
+
pnpm pack --pack-destination dist
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
### Project layout
|
|
280
|
+
|
|
281
|
+
```text
|
|
282
|
+
src/index.ts Host plugin: config, bot runtime, menus, commands
|
|
283
|
+
src/client/index.tsx Web settings page (token + admin ID)
|
|
284
|
+
src/client/locales.ts Russian and English UI strings
|
|
285
|
+
src/state/index.ts Chat bindings in the storageDomain
|
|
286
|
+
src/logging/index.ts JSONL file log with rotation
|
|
287
|
+
src/*/SPEC.md Module contracts and data formats
|
|
288
|
+
docs/telegram-ux/ Telegram UX contract
|
|
289
|
+
dev/standalone.mjs Smoke test without the Host
|
|
290
|
+
lib/ Built host and client code (committed for the archive)
|
|
291
|
+
dist/ Prebuilt install archive
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
## Current limitations
|
|
295
|
+
|
|
296
|
+
- No `/history` command and no reply-to-message routing.
|
|
297
|
+
- No completion notifications for turns in other sessions or workspaces.
|
|
298
|
+
- Web settings expose only the token and the admin ID; `lowBalanceUsd`, `rich` and `apiRoot` are configured through `cordis.patch.yml`.
|
|
299
|
+
- No voice or file handling: Telegram transcribes voice messages itself.
|
|
300
|
+
- No proxy configuration.
|
|
301
|
+
- Approvals and questions are tied to the bound session; multi-select and free-text questions continue in the Web UI.
|
|
302
|
+
- Progress tracking is in memory, so a Host restart in the middle of a turn can leave a stale progress message.
|
|
303
|
+
|
|
304
|
+
## Roadmap
|
|
305
|
+
|
|
306
|
+
- Phase 2.2: `/history`, reply routing, completion notifications for other sessions.
|
|
307
|
+
- Phase 3.2: npm package and listing in the plugin catalog.
|
|
308
|
+
|
|
309
|
+
## License
|
|
310
|
+
|
|
311
|
+
MIT. See [LICENSE](LICENSE).
|
package/README.ru.md
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
# dsh-telegram-bot
|
|
2
|
+
|
|
3
|
+
[English](README.md) | **Русский**
|
|
4
|
+
|
|
5
|
+
Пакет: [`@shliamb/dsh-telegram-bot`](https://www.npmjs.com/package/@shliamb/dsh-telegram-bot)
|
|
6
|
+
|
|
7
|
+
Telegram-мост для **DeepSeek Harness**. Плагин устанавливается в профиль `web` как внешний бандл и работает внутри Host-процесса: вы общаетесь с агентом из приватного чата Telegram, выбираете пространство и сессию, следите за длинными ходами через одно progress-сообщение и управляете Host удалённо.
|
|
8
|
+
|
|
9
|
+
> **Статус:** Phase 2.2, ранняя альфа. Бандл рассчитан на DeepSeek Harness `0.2.2-alpha.3` и профиль `web`.
|
|
10
|
+
|
|
11
|
+
## Возможности
|
|
12
|
+
|
|
13
|
+
- Текстовая переписка с агентом из Telegram.
|
|
14
|
+
- Выбор пространства и сессии (ветки). Если в пространстве нет сессий, она создаётся при первом сообщении.
|
|
15
|
+
- Rich-ответы: Markdown с таблицами, заголовками, списками и кодом; при ошибке — rich HTML, затем обычный текст.
|
|
16
|
+
- Одно редактируемое progress-сообщение на ход (`💭 думает`, `🔧 инструмент`, `✍️ пишет`, `✅ готово`) вместо потока bash-вывода.
|
|
17
|
+
- Параллельные ходы: можно переключиться в другое пространство, а старое progress-сообщение продолжит обновляться. Финальный ответ всё равно придёт в тот же чат.
|
|
18
|
+
- Подтверждения инструментов и вопросы агента кнопками.
|
|
19
|
+
- Главное меню с балансом, пространством, сессией, процентом контекста и цветными кнопками.
|
|
20
|
+
- Звук on/off для чата, сжатие истории через `/compact`, остановка с подтверждением.
|
|
21
|
+
- Админ-экран с логами документом и удалённым перезапуском Harness.
|
|
22
|
+
- Русский или английский интерфейс по языку Telegram (`ru*` → русский, иначе английский).
|
|
23
|
+
|
|
24
|
+
## Требования
|
|
25
|
+
|
|
26
|
+
- DeepSeek Harness с профилем `web`. Бандл объявляет `engines.dsh >=0.2.2-alpha.3 <0.3.0`, поэтому на несовместимом Host установка будет отклонена.
|
|
27
|
+
- Node.js `>= 24.9` и pnpm.
|
|
28
|
+
- Токен бота из [@BotFather](https://t.me/BotFather).
|
|
29
|
+
- Числовой Telegram ID, например из [@userinfobot](https://t.me/userinfobot).
|
|
30
|
+
- Запущенный Host. Один токен может опрашивать только один Host-процесс (иначе Telegram вернёт `409 Conflict`).
|
|
31
|
+
|
|
32
|
+
## Установка
|
|
33
|
+
|
|
34
|
+
Пакет опубликован в npm как **`@shliamb/dsh-telegram-bot`**. Короткое имя `dsh-telegram-bot` уже занято другим проектом, поэтому используйте имя со scope.
|
|
35
|
+
|
|
36
|
+
### Вариант 1 — из npm (рекомендуется)
|
|
37
|
+
|
|
38
|
+
Если команда `dsh` доступна в `PATH`:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
dsh plugin --profile web add @shliamb/dsh-telegram-bot
|
|
42
|
+
dsh web
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Если Harness запускается из исходников:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
cd /path/to/deepseek-harness
|
|
49
|
+
pnpm dsh plugin --profile web add @shliamb/dsh-telegram-bot
|
|
50
|
+
pnpm dsh web
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
То же самое можно сделать в интерфейсе: **Плагины → Add plugin**, ввести `@shliamb/dsh-telegram-bot` и подтвердить установку.
|
|
54
|
+
|
|
55
|
+
После добавления нового бандла нужен перезапуск Host. Сессии и привязки переживают перезапуск; новая строка плагина и страница настроек загружаются при старте.
|
|
56
|
+
|
|
57
|
+
### Вариант 2 — готовый архив
|
|
58
|
+
|
|
59
|
+
В репозитории также лежит готовый к установке архив:
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
dist/shliamb-dsh-telegram-bot-0.2.0.tgz
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Если команда `dsh` доступна в `PATH`, выполните из корня репозитория:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.0.tgz
|
|
69
|
+
dsh web
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Если Harness запускается из исходников, используйте `pnpm dsh` из его checkout и передайте абсолютный путь к архиву:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
cd /path/to/deepseek-harness
|
|
76
|
+
pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.0.tgz
|
|
77
|
+
pnpm dsh web
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`dsh plugin` передаёт аргументы в pnpm внутри каталога профиля. Относительные пути считаются от каталога, где вы запустили команду, поэтому при сомнениях надёжнее абсолютный путь.
|
|
81
|
+
|
|
82
|
+
### Вариант 3 — из исходников
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
cd /path/to/HarnessBot
|
|
86
|
+
pnpm install
|
|
87
|
+
pnpm build
|
|
88
|
+
|
|
89
|
+
cd /path/to/deepseek-harness
|
|
90
|
+
pnpm dsh plugin --profile web add /path/to/HarnessBot
|
|
91
|
+
pnpm dsh web
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
У связанного checkout свой `node_modules`. После изменения исходников снова выполните `pnpm build` и перезапустите Host. HMR обновляет конфиг плагина, но не перезагружает host-код связанного бандла и не регистрирует новый клиентский entry.
|
|
95
|
+
|
|
96
|
+
### Первый запуск
|
|
97
|
+
|
|
98
|
+
Пока токен не настроен, бот не начинает long polling. Откройте Web-интерфейс, перейдите в **Плагины → @shliamb/dsh-telegram-bot** и укажите токен и Telegram ID, как описано ниже.
|
|
99
|
+
|
|
100
|
+
Официального маркетплейса у DeepSeek Harness нет. Community-каталоги вроде FindHarness индексируют пакеты из npm, поэтому опубликованный scoped-пакет появляется там без отдельной отправки в магазин.
|
|
101
|
+
|
|
102
|
+
## Настройка
|
|
103
|
+
|
|
104
|
+
### Web-интерфейс
|
|
105
|
+
|
|
106
|
+
1. Откройте Web-интерфейс Harness.
|
|
107
|
+
2. Перейдите в **Плагины → @shliamb/dsh-telegram-bot**.
|
|
108
|
+
3. Нажмите **«Настроить»** в правом верхнем углу карточки бандла или выберите строку `telegram-bot` в списке строк.
|
|
109
|
+
4. Вставьте токен бота и введите числовой Telegram ID.
|
|
110
|
+
5. Нажмите **«Сохранить»**.
|
|
111
|
+
|
|
112
|
+
Поле токена write-only:
|
|
113
|
+
|
|
114
|
+
- сохранённый токен никогда не возвращается в браузер;
|
|
115
|
+
- страница показывает только статус **«настроен»** или **«не настроен»**;
|
|
116
|
+
- пустое поле сохраняет текущий токен, поэтому можно поменять только ID админа;
|
|
117
|
+
- чтобы заменить токен, вставьте новый и сохраните.
|
|
118
|
+
|
|
119
|
+
ID админа хранится в конфиге плагина. Если `allowedUserIds` пуст, админ становится единственным пользователем, которому разрешено общаться с ботом. Админ всегда добавляется в allowlist.
|
|
120
|
+
|
|
121
|
+
Сохранение формы автоматически перезапускает polling, поэтому после настройки перезапускать Host не нужно.
|
|
122
|
+
|
|
123
|
+
### Конфиг-файл (для продвинутых)
|
|
124
|
+
|
|
125
|
+
Те же настройки можно задать через `cordis.patch.yml` профиля:
|
|
126
|
+
|
|
127
|
+
```yaml
|
|
128
|
+
- id: telegram-bot
|
|
129
|
+
config:
|
|
130
|
+
adminUserId: 123456789
|
|
131
|
+
allowedUserIds: [123456789]
|
|
132
|
+
botTokenRef: DSH_TELEGRAM_BOT_TOKEN
|
|
133
|
+
lowBalanceUsd: 1 # предупреждать, когда USD-баланс <= 1
|
|
134
|
+
rich: true # false отключает rich-сообщения
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`adminUserId` — администратор, он всегда добавляется в allowlist. `allowedUserIds` необязателен: если список пуст, разрешён только админ. Принимаются только приватные чаты.
|
|
138
|
+
|
|
139
|
+
Сам токен по-прежнему хранится в `credentials` под ref `DSH_TELEGRAM_BOT_TOKEN`. Проще всего сохранить его через страницу настроек в Web. `apiRoot` может указывать на собственный сервер Telegram Bot API.
|
|
140
|
+
|
|
141
|
+
### Где взять токен и Telegram ID
|
|
142
|
+
|
|
143
|
+
1. Откройте [@BotFather](https://t.me/BotFather), отправьте `/newbot` и следуйте подсказкам. Скопируйте выданный токен.
|
|
144
|
+
2. Откройте [@userinfobot](https://t.me/userinfobot), отправьте любое сообщение и скопируйте числовой ID.
|
|
145
|
+
3. Вставьте оба значения в настройки плагина.
|
|
146
|
+
|
|
147
|
+
## Использование
|
|
148
|
+
|
|
149
|
+
### Главное меню
|
|
150
|
+
|
|
151
|
+
`/start` и `/menu` открывают главное меню. В нём:
|
|
152
|
+
|
|
153
|
+
- баланс аккаунта заголовком H1 с двумя знаками после запятой;
|
|
154
|
+
- активное пространство, сессия и процент контекста;
|
|
155
|
+
- кнопки: пространства, сессии, новая сессия, сжать, звук, стоп.
|
|
156
|
+
|
|
157
|
+
Кнопки используют стили Telegram `success`, `primary`, `danger` и `link`, если клиент их поддерживает. Если пространство не выбрано, **«Новая сессия»** сначала открывает выбор пространства.
|
|
158
|
+
|
|
159
|
+
При свежем старте Host бот один раз присылает админу сообщение **«Harness на связи»** с кнопкой **«Меню»**. При HMR-перезагрузке плагина приветствие не дублируется.
|
|
160
|
+
|
|
161
|
+
### Команды
|
|
162
|
+
|
|
163
|
+
В меню команд Telegram видна только `/start`. Остальные команды скрыты, но работают при вводе вручную.
|
|
164
|
+
|
|
165
|
+
| Команда | Описание |
|
|
166
|
+
| --- | --- |
|
|
167
|
+
| `/start`, `/menu` | Главное меню с балансом и кнопками. |
|
|
168
|
+
| `/admin` | Только админ: лог документом и перезапуск Harness с подтверждением. |
|
|
169
|
+
| `/new` | Новая сессия в активном пространстве. |
|
|
170
|
+
| `/compact` | Сжать историю текущей сессии. |
|
|
171
|
+
| `/stop` | Остановить текущий ход (в меню — с подтверждением). |
|
|
172
|
+
| `/status` | Показать баланс, активное пространство/сессию, состояние агента, контекст и звук. |
|
|
173
|
+
| `/logs` | Отправить хвост лога документом (только админ). |
|
|
174
|
+
|
|
175
|
+
Финальные ответы приходят отдельными rich-сообщениями. Длинный текст делится на части по лимиту Telegram. Если rich-форматирование не удалось, плагин повторяет попытку с rich HTML, затем с обычным текстом, поэтому ответ не теряется.
|
|
176
|
+
|
|
177
|
+
### Пространства и сессии
|
|
178
|
+
|
|
179
|
+
После выбора пространства:
|
|
180
|
+
|
|
181
|
+
- если сессия одна — она выбирается автоматически;
|
|
182
|
+
- если сессий несколько — появляется inline-список `🟢`/`⚪` с названиями;
|
|
183
|
+
- если сессий нет — новая создаётся при первом сообщении.
|
|
184
|
+
|
|
185
|
+
Текст, отправленный до выбора сессии, не теряется: он ждёт в `pendingPrompt` и уходит после выбора.
|
|
186
|
+
|
|
187
|
+
### Прогресс и параллельные ходы
|
|
188
|
+
|
|
189
|
+
У каждого хода своё progress-сообщение, привязанное к `sessionId`. Сообщение редактируется на месте и показывает текущую стадию:
|
|
190
|
+
|
|
191
|
+
```text
|
|
192
|
+
💭 думает
|
|
193
|
+
🔧 bash: <короткая команда>
|
|
194
|
+
✍️ пишет
|
|
195
|
+
✅ готово
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Можно запустить задачу в одном пространстве, переключиться в другое и запустить вторую. Оба progress-сообщения продолжают обновляться, и оба финальных ответа приходят в тот же чат, даже если активное пространство уже сменилось. Последняя стадия progress не теряется из-за троттлинга: она откладывается и применяется через 1.5 секунды.
|
|
199
|
+
|
|
200
|
+
Отслеживание ходов живёт в памяти Host. Если перезапустить Host посреди хода, старое progress-сообщение может остаться на последней стадии.
|
|
201
|
+
|
|
202
|
+
### Подтверждения и вопросы
|
|
203
|
+
|
|
204
|
+
Когда агент просит подтвердить инструмент, бот присылает inline-кнопки **«Разрешить»** / **«Запретить»**. Когда агент задаёт вопрос с готовыми вариантами, ответы тоже приходят кнопками. Таймаут запроса — 10 минут.
|
|
205
|
+
|
|
206
|
+
Подтверждения и вопросы отвечаются для привязанной сессии. Вопросы, которым нужен multi-select или свободный текст, остаются в Web-интерфейсе.
|
|
207
|
+
|
|
208
|
+
### Сжатие, звук и остановка
|
|
209
|
+
|
|
210
|
+
- **«Сжать»** показывает текущий процент контекста и просит подтверждение. Плагин вызывает preset-команду `/compact` через сервис `commands`, затем показывает локализованный результат и новый процент. Если агент занят, сжатие отклоняется.
|
|
211
|
+
- **«Звук»** хранится для каждого чата. Когда он выключен, ответы, правки progress и приветствие при старте идут с `disable_notification`.
|
|
212
|
+
- **«Стоп»** просит подтверждение, затем отменяет текущий ход через `agent.cancel({ kind: 'user' })`.
|
|
213
|
+
|
|
214
|
+
### Админ и удалённый перезапуск
|
|
215
|
+
|
|
216
|
+
`/admin` доступен только настроенному админу. Оттуда можно:
|
|
217
|
+
|
|
218
|
+
- получить лог бота документом;
|
|
219
|
+
- перезапустить Harness Host после подтверждения.
|
|
220
|
+
|
|
221
|
+
Перезапуск выполняется в фоне через `pnpm dsh web --no-open`, вывод пишется в `$DSH_HOME/logs/harness-restart.log`. Бот возвращается через несколько секунд. Перезапуск создаёт новый launch URL Web-интерфейса, поэтому обновите страницу или откройте URL, который напечатает новый процесс. Cookie браузера обычно переживает перезапуск.
|
|
222
|
+
|
|
223
|
+
## Данные и приватность
|
|
224
|
+
|
|
225
|
+
- Токен бота хранится в `credentials` DeepSeek Harness под `DSH_TELEGRAM_BOT_TOKEN`. Со страницы настроек он write-only и никогда не возвращается в браузер.
|
|
226
|
+
- Логи пишутся в `$DSH_HOME/logs/telegram-bot.log` в JSONL с правами `0600` и ротацией 2 МБ × 3. Токен заменяется на `<redacted-token>`; текст сообщений не логируется.
|
|
227
|
+
- Привязки чатов хранятся в домене `telegram_bridge` (JSON backend, `$DSH_HOME/storages/telegram_bridge.json`). Если storage недоступен, плагин держит привязки в памяти и пишет предупреждение в лог.
|
|
228
|
+
- Принимаются только приватные чаты. Админ разрешён всегда; `allowedUserIds` сужает доступ до перечисленных аккаунтов.
|
|
229
|
+
- В репозитории нет настоящего токена бота или Telegram ID. Установочный архив собирается без локальных credentials.
|
|
230
|
+
|
|
231
|
+
## Решение проблем
|
|
232
|
+
|
|
233
|
+
### Бот не отвечает
|
|
234
|
+
|
|
235
|
+
1. Откройте **Плагины → @shliamb/dsh-telegram-bot → Настроить** и проверьте, что статус токена — **«настроен»**, а ID админа верный.
|
|
236
|
+
2. Убедитесь, что пишете боту в приватном чате с админского аккаунта (или с аккаунта из `allowedUserIds`).
|
|
237
|
+
3. Проверьте `$DSH_HOME/logs/telegram-bot.log` на `token-missing`, `polling-unauthorized`, `409` или `state-open-failed`.
|
|
238
|
+
4. Если тот же токен опрашивает другой Host-процесс, остановите его: Telegram разрешает только одного потребителя long polling.
|
|
239
|
+
|
|
240
|
+
### Нет кнопки «Настроить»
|
|
241
|
+
|
|
242
|
+
- Жёстко обновите Web-интерфейс (`Ctrl+Shift+R`).
|
|
243
|
+
- Убедитесь, что в установленном пакете есть `lib/client.js`.
|
|
244
|
+
- Перезапустите Host после установки нового бандла. Новый клиентский entry регистрируется при старте.
|
|
245
|
+
- Если ставили из исходников, выполните `pnpm check` и `pnpm build` в checkout плагина.
|
|
246
|
+
|
|
247
|
+
### Web-страница не открывается после перезапуска
|
|
248
|
+
|
|
249
|
+
Перезапущенный Host печатает новый launch URL со свежим токеном. Откройте его или обновите текущую страницу, если Host уже поднялся. Старый URL не переиспользуется.
|
|
250
|
+
|
|
251
|
+
### Пропало rich-форматирование
|
|
252
|
+
|
|
253
|
+
Плагин автоматически откатывается на rich HTML, затем на обычный текст. Если конкретная таблица или заголовок не поддерживается клиентом Telegram, plain-text версия всё равно будет доставлена.
|
|
254
|
+
|
|
255
|
+
### Перезапуск не удался
|
|
256
|
+
|
|
257
|
+
Посмотрите `$DSH_HOME/logs/harness-restart.log`. Если Host не поднялся, запустите его вручную из checkout Harness командой `pnpm dsh web` (или `dsh web` для глобальной установки).
|
|
258
|
+
|
|
259
|
+
## Разработка
|
|
260
|
+
|
|
261
|
+
```bash
|
|
262
|
+
pnpm install
|
|
263
|
+
pnpm check # проверка типов host и client
|
|
264
|
+
pnpm build # tsc -> lib/, tsdown -> lib/client.js
|
|
265
|
+
node dev/standalone.mjs # smoke-тест без DSH Host
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
Для `dev/standalone.mjs` нужен `TELEGRAM_BOT_TOKEN` в окружении; скрипт подключается к Telegram напрямую. Это удобно для проверки цикла бота без профиля Harness.
|
|
269
|
+
|
|
270
|
+
После `pnpm build` перезапустите `pnpm dsh web`: HMR перезагружает конфиг плагина, но связанному host-коду и клиентскому entry нужен свежий старт Host. Страница настроек появляется после этого перезапуска.
|
|
271
|
+
|
|
272
|
+
Пересобрать установочный архив:
|
|
273
|
+
|
|
274
|
+
```bash
|
|
275
|
+
pnpm build
|
|
276
|
+
pnpm pack --pack-destination dist
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
### Структура проекта
|
|
280
|
+
|
|
281
|
+
```text
|
|
282
|
+
src/index.ts Host-плагин: конфиг, runtime бота, меню, команды
|
|
283
|
+
src/client/index.tsx Web-страница настроек (токен + ID админа)
|
|
284
|
+
src/client/locales.ts Русские и английские строки интерфейса
|
|
285
|
+
src/state/index.ts Привязки чатов в storageDomain
|
|
286
|
+
src/logging/index.ts JSONL-лог с ротацией
|
|
287
|
+
src/*/SPEC.md Контракты модулей и форматы данных
|
|
288
|
+
docs/telegram-ux/ UX-контракт Telegram
|
|
289
|
+
dev/standalone.mjs Smoke-тест без Host
|
|
290
|
+
lib/ Собранный host- и client-код (закоммичен для архива)
|
|
291
|
+
dist/ Готовый установочный архив
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
## Текущие ограничения
|
|
295
|
+
|
|
296
|
+
- Нет команды `/history` и маршрутизации ответов на сообщения.
|
|
297
|
+
- Нет уведомлений о завершении ходов в других сессиях или пространствах.
|
|
298
|
+
- В Web-настройках только токен и ID админа; `lowBalanceUsd`, `rich` и `apiRoot` задаются через `cordis.patch.yml`.
|
|
299
|
+
- Нет голосовых и файлов: Telegram сам транскрибирует голос.
|
|
300
|
+
- Нет настройки прокси.
|
|
301
|
+
- Подтверждения и вопросы привязаны к выбранной сессии; multi-select и свободный текст продолжаются в Web.
|
|
302
|
+
- Отслеживание progress живёт в памяти, поэтому перезапуск Host посреди хода может оставить устаревшее progress-сообщение.
|
|
303
|
+
|
|
304
|
+
## Roadmap
|
|
305
|
+
|
|
306
|
+
- Phase 2.2: `/history`, маршрутизация ответов, уведомления о завершении в других сессиях.
|
|
307
|
+
- Phase 3.2: npm-пакет и публикация в каталоге плагинов.
|
|
308
|
+
|
|
309
|
+
## Лицензия
|
|
310
|
+
|
|
311
|
+
MIT. См. [LICENSE](LICENSE).
|