dsh-tg-bridge 1.11.0 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,87 @@
1
+ # Injecting into a running turn and composing replies in Telegram
2
+
3
+ Date: 24.10.2026. Source: DSH code in `app.asar`, bridge code in `~/.dsh/tg-bridge`, Hermes behaviour.
4
+
5
+ ## Part 1. What "injecting into an already running prompt" means
6
+
7
+ The agent runs a turn: model -> tool -> model -> … While the turn is running, the user may
8
+ want to (a) add a clarification the agent sees **in the same turn**, or (b) put a message
9
+ **in the queue** for the next turn, or (c) **interrupt** the turn and replace the task.
10
+
11
+ These are three different modes and must not be confused: "add to queue" and "intervene" give different UX.
12
+
13
+ ### How DSH does it (fact from the code)
14
+
15
+ `@deepseek-ai/dsh-api-session-controller`, `lib/client.js`:
16
+
17
+ ```js
18
+ const placement = this.running
19
+ ? input.mode === "steer" ? "steering" : "queued"
20
+ : "transcript";
21
+ // mode: queue — appends after the current turn; steer — interrupts it.
22
+ ```
23
+
24
+ So DSH **already has** the mechanism:
25
+ - `prompt(input, { mode: "queue" })` — the message joins the session queue, the turn is left alone;
26
+ - `prompt(input, { mode: "steer" })` — the message is delivered into the **running** turn (steering),
27
+ the model sees it at the next step boundary;
28
+ - `cancel()` — cancels the turn; `interruptByParent()` — interrupts a child session.
29
+ - The queue lives in session state and survives client reconnects (queue mutation,
30
+ receipts, dedup by `requestId`).
31
+
32
+ Limitations (from the same code):
33
+ - queue and steer are accepted only for a **live** session; for a "cold" one, prompt creates/
34
+ resumes a session and that is ordinary input, not an injection;
35
+ - steer does not "append" to history, it cuts into the current turn — aborting it too
36
+ roughly loses tool work, so cancel and steer are distinct operations.
37
+
38
+ ### Why the current bridge has neither
39
+
40
+ The bridge drives `dsh --profile headless --json "text"`: one CLI process per turn, no live
41
+ session between turns, and the CLI has no channel to "append to the active turn" (`--help` shows only task /
42
+ `--json` / `--session-id`). A message that arrives mid-turn simply joins the bridge queue
43
+ (`enqueue`) and starts **after** the previous one finishes.
44
+
45
+ ### How to add injection to the bridge
46
+
47
+ 1. Move to the API transport: `@deepseek-ai/dsh-api-client` / `dsh-api-gateway`
48
+ (`/api/remote.mux`), methods `session.prompt({ mode })`, `session.cancel()`.
49
+ The bridge then keeps one live session per topic and can:
50
+ - `mode: "queue"` — the usual queue (current behaviour, but without restarting the CLI);
51
+ - `mode: "steer"` — deliver a clarification into the running turn.
52
+ 2. In Telegram this shows up as buttons under the status: "⏹ Stop" (cancel), "➕ Into turn" (steer),
53
+ "🕘 To queue" (queue). Default is queue, as now.
54
+ 3. Until the API transport exists, a cheap compromise: mark such messages in the chat as
55
+ "accepted, will add to the current turn" and still run them afterwards (do not pretend to steer).
56
+
57
+ ## Part 2. How Hermes composes a reply in Telegram
58
+
59
+ The scheme for one turn:
60
+
61
+ 1. **Status message** is created once: `⏳ Working… 42 s`, with the latest steps below
62
+ (`• terminal: npm test`, `• read: src/app.ts`). Updates go through `editMessageText`, no more often than every 1.5–2 s
63
+ (Telegram limit ~20 edits/min per chat).
64
+ 2. **Heartbeat**: if no events arrive for 2 minutes, the status is still redrawn — the time
65
+ counter changes. That is the "I can see it is alive" signal, not "hung".
66
+ 3. **Intermediate model text** (if the model said something before the final answer) goes on a
67
+ line `• text: first 120 characters` — you see the reasoning, without a wall of text.
68
+ 4. **The final answer replaces the status**: `✅ Done · 1:12 · 6 steps`, below it the answer itself in HTML
69
+ (code in `<pre><code>` with a "copy" button), then the line `🧠 cache: 97%`.
70
+ 5. **Error** — the same status turns into `⚠️ Turn failed · 9 s` + code and hint
71
+ (`TG_CONFLICT`, `SANDBOX_DENY`, `INSUFFICIENT_QUOTA`), rather than a separate message.
72
+ 6. **Queue**: if a second message arrives during a turn, a short `⏳ queued (2)`,
73
+ and the first message is not lost when the turn completes.
74
+ 7. **Buttons** (where enabled): "Stop" under the status, "Retry" under an error, "Send file"
75
+ after a turn, "Allow/Deny" for approvals.
76
+ 8. **Limits handled**: 4096 characters per message (a long answer is split at code block
77
+ boundaries), `message is not modified` is ignored, `retry_after` from 429 is respected.
78
+
79
+ What the DSH bridge already has of this: status with steps and heartbeat, HTML blocks, queue,
80
+ fail-fast on quota. What it lacks: buttons, streaming of the final text, error codes in the message.
81
+
82
+ ## Practical takeaway
83
+
84
+ - Injection in DSH is implementable **without modifying DSH itself** — it already knows `queue` and `steer`;
85
+ it only needs a transport (API instead of CLI) and two buttons in Telegram.
86
+ - Estimate: API transport + steer — 2–3 days, and the same transport gives approvals and files without workarounds.
87
+ - Until the transport is done, it is more honest to keep the queue and not promise "I'll cut into the current turn".
package/README.md CHANGED
@@ -123,7 +123,7 @@ You do not need to set up the command menu by hand: `init` and `setup` install i
123
123
  in Russian, English and Chinese at once. The menu is not refreshed by a plain
124
124
  bridge restart, so after adding commands run `dsh-tg menu`. The full settings
125
125
  table, permissions, checks and common errors are in
126
- [docs/TELEGRAM-SETUP.md](docs/TELEGRAM-SETUP.md).
126
+ [docs/TELEGRAM-SETUP.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/TELEGRAM-SETUP.md).
127
127
 
128
128
  **Autostart** is installed by the setup: `launchd` on macOS, `systemd --user` on
129
129
  Linux. On Windows `setup` registers the `DSH-TG-Bridge` task, which runs the
@@ -367,12 +367,12 @@ no lock race and no lost update.
367
367
 
368
368
  ## Documentation
369
369
 
370
- - [docs/TELEGRAM-SETUP.md](docs/TELEGRAM-SETUP.md): BotFather settings, group and bot permissions
371
- - [docs/ROADMAP.md](docs/ROADMAP.md): what comes next
372
- - [docs/UX-ANALYSIS.md](docs/UX-ANALYSIS.md): interactive UX review
373
- - [docs/COST.md](docs/COST.md): what one turn costs and how to reduce it
374
- - [docs/CHANGELOG.md](docs/CHANGELOG.md): change history
375
- - [docs/RELEASE-CRITERIA.md](docs/RELEASE-CRITERIA.md): release readiness criteria
370
+ - [docs/TELEGRAM-SETUP.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/TELEGRAM-SETUP.md): BotFather settings, group and bot permissions
371
+ - [docs/ROADMAP.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/ROADMAP.md): what comes next
372
+ - [docs/UX-ANALYSIS.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/UX-ANALYSIS.md): interactive UX review
373
+ - [docs/COST.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/COST.md): what one turn costs and how to reduce it
374
+ - [docs/CHANGELOG.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/CHANGELOG.md): change history
375
+ - [docs/RELEASE-CRITERIA.md](https://github.com/aleksvega/dsh-tg-bridge/blob/master/docs/RELEASE-CRITERIA.md): release readiness criteria
376
376
 
377
377
  ## License
378
378
 
package/SECURITY.md ADDED
@@ -0,0 +1,33 @@
1
+ # Security
2
+
3
+ ## Reporting
4
+
5
+ Open a private security advisory on GitHub
6
+ (`Security` → `Advisories` → `Report a vulnerability`) or email the maintainer
7
+ listed on the npm package page. Do not open a public issue for a working
8
+ exploit.
9
+
10
+ Include the version, the platform, and the smallest reproduction you can. A
11
+ Telegram bot token or a session archive in the report is a credential leak:
12
+ rotate the token with [@BotFather](https://t.me/BotFather) before sending it.
13
+
14
+ ## What the bridge can do
15
+
16
+ The bridge runs the harness with the permissions of the profile it starts
17
+ (`headless` by default), from the directory bound to the topic. Anyone who can
18
+ message the bot and passes `allowedUserIds` can run tools on that machine.
19
+ Treat the bot token and the allowlist as root access:
20
+
21
+ - keep `allowedUserIds` non-empty and limited to your own numeric id;
22
+ - keep the token in `~/.dsh/.credentials.yaml`, never in `config.json`, a
23
+ commit, or a screenshot;
24
+ - run the bridge under a dedicated OS user if other people share the machine;
25
+ - revoke the token in BotFather if it ever appears in a log or a chat.
26
+
27
+ The bridge does not ship a sandbox. Isolation comes from the DSH profile's
28
+ permission mode and the OS account, not from this project.
29
+
30
+ ## Supported versions
31
+
32
+ The latest `1.x` release receives fixes. A report against an older version is
33
+ still welcome, but the fix may land only in the current line.
package/bridge.mjs CHANGED
@@ -329,7 +329,15 @@ function providerKeys(cfg) {
329
329
  function findToken() {
330
330
  const env = (process.env.DSH_TELEGRAM_BOT_TOKEN || '').trim();
331
331
  if (env) return env;
332
- for (const name of ['DSH_TELEGRAM_BOT_TOKEN', 'DSH_TELEGRAM_BOT_TOKEN_3278A97027814C501779F5E2']) {
332
+ // The suffixed name carries a random id of the machine that created the
333
+ // secret (DSH_TELEGRAM_BOT_TOKEN_<hex>), so it must not be spelled out here:
334
+ // any install is free to carry its own suffix. Try the plain name first, then
335
+ // whatever suffixed variants the credentials file actually holds.
336
+ const suffixes = [];
337
+ try {
338
+ for (const m of readFileSync(CRED, 'utf8').matchAll(/^\s*(DSH_TELEGRAM_BOT_TOKEN_[A-Z0-9_]+):/gm)) suffixes.push(m[1]);
339
+ } catch {}
340
+ for (const name of ['DSH_TELEGRAM_BOT_TOKEN', ...suffixes]) {
333
341
  try {
334
342
  const value = readSecret(name);
335
343
  if (value) return value;
@@ -574,6 +582,20 @@ function immediateCommandOf(text) {
574
582
  return immediateKind(collapsed, rest);
575
583
  }
576
584
 
585
+ /**
586
+ * Language for a chat and topic.
587
+ *
588
+ * Extracting the formatting helpers into `format.mjs` took this function with
589
+ * them, and the two `langFor` call sites stayed behind — so `send()` threw
590
+ * `langFor is not defined` on its first line and the restart notice never
591
+ * reached the chat. Nothing caught it: the error was logged and swallowed by
592
+ * the outer `try`, and the process kept running. It is a one-line wrapper, and
593
+ * the tests below pin the call sites so a missing name fails there instead.
594
+ */
595
+ function langFor(chatId, threadId = 0) {
596
+ return resolveLang(state, sessionKey(chatId, threadId), null, config);
597
+ }
598
+
577
599
  async function send(chatId, text, threadId = 0, replyTo = 0) {
578
600
  // Who is reading: the topic's language decides even the fallback line, so an
579
601
  // English or Chinese topic never sees a Russian placeholder.
package/install.ps1 ADDED
@@ -0,0 +1,61 @@
1
+ # Install or update dsh-tg-bridge from the npm registry (Windows).
2
+ #
3
+ # $env:DSH_TG_TOKEN='123456789:AA...'; $env:DSH_TG_USER='123456789'
4
+ # .\install.ps1
5
+ #
6
+ # Optional: DSH_TG_VOICE=1 (voice), DSH_TG_HOME (install dir),
7
+ # DSH_TG_NOSETUP=1 (install and check only, do not restart the bridge),
8
+ # DSH_TG_PACKAGE (npm package, default dsh-tg-bridge).
9
+ $ErrorActionPreference = 'Stop'
10
+
11
+ $Pkg = if ($env:DSH_TG_PACKAGE) { $env:DSH_TG_PACKAGE } else { 'dsh-tg-bridge' }
12
+ $Dest = if ($env:DSH_TG_HOME) { $env:DSH_TG_HOME } else { Join-Path $env:USERPROFILE '.dsh\tg-bridge' }
13
+ $Token = $env:DSH_TG_TOKEN
14
+ $User = $env:DSH_TG_USER
15
+
16
+ foreach ($tool in 'node', 'npm') {
17
+ if (-not (Get-Command $tool -ErrorAction SilentlyContinue)) { throw "$tool is required" }
18
+ }
19
+ $major = [int]((node -v).TrimStart('v').Split('.')[0])
20
+ if ($major -lt 20) { throw "node >= 20 is required (found $(node -v))" }
21
+
22
+ $Tmp = Join-Path $env:TEMP ("dsh-tg-" + [guid]::NewGuid().ToString('n'))
23
+ New-Item -ItemType Directory -Force -Path $Tmp | Out-Null
24
+ try {
25
+ Write-Host "downloading $Pkg@latest"
26
+ npm pack "$Pkg@latest" --pack-destination $Tmp | Out-Null
27
+ $tgz = Get-ChildItem $Tmp -Filter *.tgz | Select-Object -First 1
28
+ if (-not $tgz) { throw 'npm pack produced no tarball' }
29
+ tar -xzf $tgz.FullName -C $Tmp
30
+
31
+ Write-Host "installing into $Dest"
32
+ New-Item -ItemType Directory -Force -Path $Dest | Out-Null
33
+ # config.json, state.json and pending\ are not part of the package, so an
34
+ # update keeps them while every code file is replaced.
35
+ Copy-Item (Join-Path $Tmp 'package\*') $Dest -Recurse -Force
36
+ } finally {
37
+ Remove-Item $Tmp -Recurse -Force -ErrorAction SilentlyContinue
38
+ }
39
+
40
+ Push-Location $Dest
41
+ try {
42
+ if ($Token -and $User) {
43
+ $initArgs = @('cli.mjs', 'init', '--token', $Token, '--user', $User)
44
+ if ($env:DSH_TG_VOICE -eq '1') { $initArgs += '--voice' }
45
+ node @initArgs
46
+ } elseif (-not (Test-Path 'config.json')) {
47
+ Copy-Item 'config.example.json' 'config.json'
48
+ Write-Host 'created config.json - set allowedUserIds and cwd, or rerun with DSH_TG_TOKEN and DSH_TG_USER'
49
+ }
50
+
51
+ if ($Token -and $User -and -not $env:DSH_TG_NOSETUP) {
52
+ node cli.mjs setup
53
+ } else {
54
+ node cli.mjs check
55
+ }
56
+ } finally { Pop-Location }
57
+
58
+ Write-Host ''
59
+ Write-Host 'Next:'
60
+ Write-Host ' in Telegram: /doctor, /help, /plugins, /cd <project>'
61
+ Write-Host " logs: $Dest\bridge.log"
package/install.sh ADDED
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env bash
2
+ # Install or update dsh-tg-bridge from the npm registry (macOS / Linux).
3
+ #
4
+ # DSH_TG_TOKEN=123456:AA... DSH_TG_USER=123456789 bash install.sh
5
+ #
6
+ # Optional: --voice, --no-autostart. Environment: DSH_TG_HOME (install dir),
7
+ # DSH_TG_PACKAGE (npm package, default dsh-tg-bridge).
8
+ set -euo pipefail
9
+
10
+ PKG="${DSH_TG_PACKAGE:-dsh-tg-bridge}"
11
+ DEST="${DSH_TG_HOME:-$HOME/.dsh/tg-bridge}"
12
+ SERVICE="dsh-tg-bridge"
13
+ VOICE=""
14
+
15
+ for arg in "$@"; do
16
+ case "$arg" in
17
+ --voice) VOICE="--voice" ;;
18
+ --no-autostart) NO_AUTOSTART=1 ;;
19
+ *) ;;
20
+ esac
21
+ done
22
+
23
+ command -v node >/dev/null || { echo "node >= 20 is required"; exit 1; }
24
+ command -v npm >/dev/null || { echo "npm is required"; exit 1; }
25
+ node -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 20 ? 0 : 1)' \
26
+ || { echo "node >= 20 is required (found $(node -v))"; exit 1; }
27
+
28
+ TMP="$(mktemp -d)"
29
+ trap 'rm -rf "$TMP"' EXIT
30
+ echo "downloading $PKG@latest"
31
+ npm pack "$PKG@latest" --pack-destination "$TMP" >/dev/null
32
+ TARBALL="$(find "$TMP" -maxdepth 1 -name '*.tgz' | head -n 1)"
33
+ [ -n "$TARBALL" ] || { echo "npm pack produced no tarball"; exit 1; }
34
+ tar -xzf "$TARBALL" -C "$TMP"
35
+
36
+ echo "installing into $DEST"
37
+ mkdir -p "$DEST"
38
+ # config.json, state.json and pending/ are not part of the package, so an
39
+ # update keeps them while every code file is replaced.
40
+ cp -R "$TMP/package/." "$DEST/"
41
+
42
+ cd "$DEST"
43
+
44
+ # Credentials first: config.json and the token together are the whole setup.
45
+ if [ -n "${DSH_TG_TOKEN:-}" ] && [ -n "${DSH_TG_USER:-}" ]; then
46
+ node cli.mjs init --token "$DSH_TG_TOKEN" --user "$DSH_TG_USER" ${VOICE:+"$VOICE"}
47
+ elif [ ! -f config.json ]; then
48
+ cp config.example.json config.json
49
+ echo "created config.json - set allowedUserIds and cwd, or rerun with DSH_TG_TOKEN/DSH_TG_USER"
50
+ fi
51
+
52
+ # Autostart keeps the bot alive across reboots and crashes. It is skipped when the
53
+ # person only wants to look around (--no-autostart).
54
+ if [ -z "${NO_AUTOSTART:-}" ]; then
55
+ NODE_BIN="$(command -v node)"
56
+ case "$(uname -s)" in
57
+ Darwin)
58
+ PLIST="$HOME/Library/LaunchAgents/com.dsh.tg-bridge.plist"
59
+ mkdir -p "$(dirname "$PLIST")"
60
+ cat > "$PLIST" <<PLIST_EOF
61
+ <?xml version="1.0" encoding="UTF-8"?>
62
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
63
+ <plist version="1.0">
64
+ <dict>
65
+ <key>Label</key><string>com.dsh.tg-bridge</string>
66
+ <key>ProgramArguments</key>
67
+ <array>
68
+ <string>$NODE_BIN</string>
69
+ <string>--dns-result-order=ipv4first</string>
70
+ <string>$DEST/bridge.mjs</string>
71
+ </array>
72
+ <key>WorkingDirectory</key><string>$DEST</string>
73
+ <key>RunAtLoad</key><true/>
74
+ <key>KeepAlive</key><true/>
75
+ <key>StandardOutPath</key><string>$DEST/bridge.out.log</string>
76
+ <key>StandardErrorPath</key><string>$DEST/bridge.err.log</string>
77
+ </dict>
78
+ </plist>
79
+ PLIST_EOF
80
+ launchctl unload "$PLIST" 2>/dev/null || true
81
+ launchctl load "$PLIST"
82
+ echo "autostart: launchd $PLIST"
83
+ ;;
84
+ Linux)
85
+ UNIT_DIR="$HOME/.config/systemd/user"
86
+ mkdir -p "$UNIT_DIR"
87
+ cat > "$UNIT_DIR/$SERVICE.service" <<UNIT_EOF
88
+ [Unit]
89
+ Description=DSH Telegram bridge
90
+ After=network-online.target
91
+
92
+ [Service]
93
+ Type=simple
94
+ WorkingDirectory=$DEST
95
+ ExecStart=$NODE_BIN --dns-result-order=ipv4first $DEST/bridge.mjs
96
+ Restart=always
97
+ RestartSec=5
98
+ Environment=NODE_ENV=production
99
+
100
+ [Install]
101
+ WantedBy=default.target
102
+ UNIT_EOF
103
+ systemctl --user daemon-reload || true
104
+ systemctl --user enable --now "$SERVICE" || echo "systemd --user unavailable - start manually: node $DEST/bridge.mjs"
105
+ echo "autostart: systemd --user $SERVICE"
106
+ ;;
107
+ *)
108
+ echo "autostart: $(uname -s) is not supported - start manually: node $DEST/bridge.mjs"
109
+ ;;
110
+ esac
111
+ fi
112
+
113
+ echo
114
+ node cli.mjs check || true
115
+ echo
116
+ echo "Next:"
117
+ echo " in Telegram: /doctor, /help, /plugins, /cd <project>"
118
+ echo " logs: tail -f $DEST/bridge.out.log"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.11.0",
3
+ "version": "1.12.1",
4
4
  "description": "Telegram bridge for DeepSeek Harness: text, voice, photos and project-per-topic sessions without opening the desktop app",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
@@ -72,6 +72,10 @@
72
72
  "profiles.mjs",
73
73
  "cli-args.mjs",
74
74
  "thoughts.mjs",
75
- "sync-runtime.mjs"
75
+ "sync-runtime.mjs",
76
+ "install.ps1",
77
+ "install.sh",
78
+ "INJECTION-AND-REPLIES.md",
79
+ "SECURITY.md"
76
80
  ]
77
81
  }