dsh-quay-bot 1.0.2 → 1.0.4

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.
Files changed (59) hide show
  1. package/README.md +28 -105
  2. package/botscreen/requirements.txt +1 -1
  3. package/client.js +3 -2
  4. package/cordis.patch.yml +1 -1
  5. package/host/api.js +4 -0
  6. package/host/remote.js +285 -8
  7. package/host/screen.js +22 -86
  8. package/package.json +35 -32
  9. package/remote/bin/dsh-remote.mjs +435 -0
  10. package/remote/package.json +27 -0
  11. package/remote/src/config.mjs +183 -0
  12. package/remote/src/crypto.mjs +220 -0
  13. package/remote/src/keys.mjs +226 -0
  14. package/remote/src/proxy.mjs +1028 -0
  15. package/remote/src/sessions.mjs +163 -0
  16. package/remote/src/shim.js +838 -0
  17. package/remote/src/supervisor.mjs +207 -0
  18. package/remote/src/tunnel.mjs +533 -0
  19. package/remote/src/upstream.mjs +403 -0
  20. package/remote/src/util.mjs +149 -0
  21. package/remote/src/ws.mjs +313 -0
  22. package/LICENSE +0 -21
  23. package/avatar/build.mjs +0 -81
  24. package/avatar/gallery/droid.json +0 -14
  25. package/avatar/gallery/ghost.json +0 -14
  26. package/avatar/gallery/grok-pod.json +0 -14
  27. package/avatar/gallery/guardian.json +0 -14
  28. package/avatar/gallery/mecha.json +0 -14
  29. package/avatar/gallery/mochi.json +0 -14
  30. package/avatar/gallery/neko.json +0 -14
  31. package/avatar/gallery/orbiter.json +0 -14
  32. package/avatar/gallery/relay.json +0 -14
  33. package/avatar/gallery/spark.json +0 -14
  34. package/avatar/src/bot/clay.ts +0 -135
  35. package/avatar/src/bot/effects.ts +0 -100
  36. package/avatar/src/bot/grok-bot.ts +0 -626
  37. package/avatar/src/bot/index.ts +0 -15
  38. package/avatar/src/bot/palettes.ts +0 -62
  39. package/avatar/src/bot/ring.ts +0 -219
  40. package/avatar/src/bot/scheduler.ts +0 -239
  41. package/avatar/src/bot/shapes.ts +0 -277
  42. package/avatar/src/bot/spring.ts +0 -196
  43. package/avatar/src/core/color.ts +0 -92
  44. package/avatar/src/core/eyes.ts +0 -297
  45. package/avatar/src/core/field.ts +0 -482
  46. package/avatar/src/core/frame.ts +0 -655
  47. package/avatar/src/core/fx.ts +0 -375
  48. package/avatar/src/core/index.ts +0 -49
  49. package/avatar/src/core/paint.ts +0 -331
  50. package/avatar/src/core/path.ts +0 -495
  51. package/avatar/src/core/pose.ts +0 -581
  52. package/avatar/src/core/svg.ts +0 -98
  53. package/avatar/src/core/types.ts +0 -153
  54. package/avatar/src/core/validate.ts +0 -296
  55. package/avatar/src/core/volume.ts +0 -681
  56. package/avatar/src/entry.ts +0 -260
  57. package/bin/doctor.mjs +0 -148
  58. package/botscreen/requirements-offline.txt +0 -11
  59. package/market/index.json +0 -41
package/README.md CHANGED
@@ -1,114 +1,37 @@
1
- # dsh-quay-bot
2
-
3
- DeepSeek Harness 的 **Bot 团队模式**插件(Host + Web Client 双半区),并内置一套自举的 **BotScreen 虚拟桌面**(X + 窗口管理器 + 把画面流进 Web UI)。装完即用:Python 依赖走包内 wheel,系统组件在首次启动时自动补装,不需要手工 `pip install` / `apt install`。
4
-
5
- ```bash
6
- dsh plugin install dsh-quay-bot # 在目标 profile 里
7
- # 或在 DSH 桌面端 Plugin Manager → Install → 输入 dsh-quay-bot
8
- # 或在 Discover 页把下面「Market index」里的 URL 加成索引源后直接搜索安装
9
- ```
10
-
11
- ---
12
-
13
- ## 1. 这个包做了什么
14
-
15
- - 每个 Bot 独立目录、`SOUL.md` / `MEMORY.md`、永久私聊会话,以及**按房间隔离的隐藏 Group Session**(支持房间共享工程目录 `workDir`)
16
- - 每个 Bot 可单独绑定模型:DSH 默认(空绑定,每轮重读)、provider/model、思考档位;模型目录标注是否支持图片输入
17
- - Bot 聊天可发图片(PNG/JPEG/WebP/GIF,≤6 张 × 12 MB),纯文本模型在 Host 入队前拒绝
18
- - `message_agent` 异步队友消息(会话级 FIFO、跳数护栏 `MAX_AGENT_HOPS=4`、同链去重、回信降级、>16k 落盘、群聊隐藏会话禁止)
19
- - **Group Room(2–6 人)**:`auto`(并发协作 + `@` 接力)/ `everyone`(全员并发审阅)/ `lead`(Lead 派工与验收);全异步 `BotActor` 总线 + `snapshotSeq` 水位线防漏看;3 种显式终态(`completed` / `settled` / `waiting_user`);3 个病态探针(`idle_spin` / `paused_error` / `token_budget`);共享任务板 `claim_subtask(taskId, paths)` + 文件软锁;前端按 `botId` 分轨流式渲染;人类中途发言走 Soft Steer 软插话
20
- - **Memory Hub**:`memory_tencentdb`(v3 HTTP Gateway `127.0.0.1:8420`,熔断后自动降级 Node 原生 SQLite FTS5)、`local_sqlite`、`builtin`,支持页面/命令一键下载安装第三方记忆库
21
- - Host 持久 Routines(cron + 冷会话唤醒)、审批与提问桥(`approval/request`、`user-questions/request`)
22
- - **BotScreen 屏幕工具**:`screen_screenshot` / `screen_click` / `screen_type` / `screen_key` / `screen_scroll` / `screen_drag` / `screen_open_app` / `screen_windows` / `screen_request_help`,网关 `127.0.0.1:6200`
23
-
24
- ---
25
-
26
- ## 2. 依赖:一个都不用手动装
27
-
28
- | 层 | 内容 | 包内自带? |
29
- |---|---|---|
30
- | Node | ≥ 22.13(`node:sqlite` 需无 flag 版本);DSH 本体要求 ≥ 24.9 | DSH 侧负责 |
31
- | DSH | `>= 0.2.2-rc.3`(写进 `engines.dsh`,不满足会被安装器拦下) | — |
32
- | JS 依赖 | **零**(无 `dependencies`;只动态 `import` 可选的 `@deepseek-ai/dsh-mcp-client`,缺失自动降级) | ✅ |
33
- | Web Client | `dsh-client-locale` / `ui-layout` / `ui-sidebar` / `ui-workspace` / `dsh-api-session-controller` | 由 DSH 提供 |
34
- | Python | `fastapi uvicorn python-multipart Pillow python-xlib websockets httpx mss` | ✅ `vendor/wheels/` 离线 wheel(linux **x86_64 + aarch64**,CPython **3.12**) |
35
- | pip 自身 | `vendor/pip/` 内置 `pip` + `setuptools` wheel(宿主机没有 ensurepip 也能建 venv) | ✅ |
36
- | 系统组件 | `xvfb x11vnc websockify novnc xauth xfwm4 xfdesktop4 xfconf dbus-x11 tint2 picom pcmanfm xterm xdotool xclip glib-networking gvfs gvfs-daemons feh adwaita-icon-theme fonts-noto-color-emoji fonts-noto-cjk` | 首次启动自动 `apt-get install`(需 root 或无密码 sudo) |
37
- | 运行时底座 | cgroup v2 unified(屏幕冻结)、`Xvfb`(或 KasmVNC 提供的 `Xvnc`) | 检测/自动装 Xvfb;KasmVNC 可选 |
38
-
39
- 首次启动的顺序(`host/screen.js` → `bootstrapVenv` / `ensureSystemDependencies`):
40
-
41
- 1. 探活 `127.0.0.1:6200/healthz`,已就绪直接复用;
42
- 2. 找 Python:`BOTSCREEN_PYTHON` → `$DSH_HOME/botmode/screen-venv` → 插件内 `.venv` → 仓库 `.venv` → `python3`(只要它的 import 探针通过就原地用);
43
- 3. 否则建 venv,用包内 pip wheel 播种,再 **离线** `pip install --no-index --find-links vendor/wheels/{any,linux-<arch>}`;wheel 不匹配解释器(如 3.10/3.11/3.13)时回退 PyPI,仍是全自动;
44
- 4. 逐项探测 14 个系统 bin,缺哪个就 `apt-get install` 全套一次(无 root/免密 sudo 时打印可复制的一行命令,不阻断其它功能);
45
- 5. 拉起 `python -m botscreen`,写日志 `$DSH_HOME/botmode/botscreen-gateway.log`。
46
-
47
- 关掉自动安装:`BOTSCREEN_AUTO_INSTALL_DEPS=0`。
48
-
49
- ---
50
-
51
- ## 3. 自检
1
+ # @local/dsh-botmode
2
+
3
+ DeepSeek Harness 的 Bot 团队模式插件(Host + Web Client 双半区,v0.6.0)。
4
+
5
+ - 每个 Bot 独立目录、SOUL/MEMORY、永久私聊会话,以及**按房间隔离的隐藏 Group Session**(支持配置房间共享工程目录 `workDir`)
6
+ - 每个 Bot 可单独绑定模型:DSH 默认(空绑定,下一轮重新读取)、provider/model、思考档位;模型目录标出是否支持图片输入
7
+ - Bot 聊天可发图片(PNG/JPEG/WebP/GIF),纯文本模型由 Host 在入队前拒绝
8
+ - `message_agent` 异步队友消息(会话级 FIFO、跳数护栏 `MAX_AGENT_HOPS=4`、同链去重、回信降级、>16k 落盘、群聊隐藏会话严格禁止)
9
+ - **Hermes 底座 + 终态驱动全异步 Actor 并发群聊(Group Room)**:
10
+ - 2–6 人,支持 `auto`(并发协作 / `@` 接力)/ `everyone`(全员并发审阅)/ `lead`(Lead 统筹派工与验收)
11
+ - **全异步 `BotActor` 总线 + 快照水位线防漏看**:空闲 Bot 并发响应消除慢 Bot 木桶效应;提交前锁定 `snapshotSeq` + `selfSentSeqs` 跳过集,杜绝并发漏看;精准 `@` 他人消息零 Token 推进水位线
12
+ - **3 种显式业务终态(默认无回合数硬切)**:`completed`(仅显式调用 `room_finish_task` 触发,绝不靠正文正则误判)、`settled`(全员 `(pass)` 且无在途任务/待审批)、`waiting_user`(`@user` 询问,或局部挂起等待工具审批 / `ask_user_question`,不阻塞其他并行成员)
13
+ - **3 个病态异常探针兜底**:连续 5 轮纯文本零工具/零改文件/零认领空转软暂停(`idle_spin`)、单 Bot 连续 3 次重复报错指纹局部暂停并广播排障求助(`paused_error`)、软 Token 预算检查点(`token_budget`,点继续无损续跑)
14
+ - **共享任务板与文件软锁 + 分轨流式渲染**:`claim_subtask(taskId, paths)` 配合 DSH 工具拦截层软锁防并发覆写文件;前端底部按 `botId` 分轨实时流式展示思考与工具状态,完成后按 `seq` 到达顺序固化入主聊天流;人类中途发言采用 **Soft Steer 软插话**(不强杀在途脚本,仅 `Stop` / `/stop` 全局强停)
15
+ - **全局可插拔团队记忆库(Memory Hub)**:
16
+ - 所有 Bot 共用一套全局激活的记忆库插件,按 `team_id` + `agent_id (= bot.id)` + `user_id` 严格隔离各 Bot 记忆
17
+ - 默认内置 `memory_tencentdb`(对接 v3 HTTP Gateway `127.0.0.1:8420`,支持 L0–L3 并行预取与异步写入、熔断保护,网关未启动时自动回退至 Node 22 原生 SQLite FTS5)
18
+ - 同时内置 `local_sqlite`(纯本地零依赖 SQLite FTS5)与 `builtin`(仅 `MEMORY.md`)
19
+ - 支持在页面或 `/botmode memory install` 一键下载、安装、配置、热切换与卸载其他记忆库插件
20
+ - Host 持久 Routines:cron 解析 + 冷会话唤醒,定时器在 `ctx.effect()` 内
21
+ - Bot 审批与提问桥:`approval/request`(once / session / always / deny)与 `user-questions/request`(`ask_user_question`)同时覆盖私聊与隐藏群聊会话
22
+
23
+ 安装(桌面端):
52
24
 
53
25
  ```bash
54
- npx dsh-quay-bot # 人类可读报告(node / python / 系统 bin / 内置 wheel / 网关)
55
- npx dsh-quay-bot --json # 给脚本用
56
- npx dsh-quay-bot --fix-hint # 只输出需要执行的命令
26
+ dsh plugin --profile desktop install /path/to/dsh-bot/packages/dsh-botmode
57
27
  ```
58
28
 
59
- 常见环境变量:`DSH_HOME`、`BOTSCREEN_DATA_ROOT`(默认 `/data/botscreen`)、`BOTSCREEN_PORT`(6200)、`BOTSCREEN_PYTHON`、`BOTSCREEN_X_BACKEND`(`xvfb`/`x11vnc`)、`BOTSCREEN_WM`(`openbox`/`xfwm4`)、`BOTSCREEN_WIDTH` / `BOTSCREEN_HEIGHT`、`BOTSCREEN_IDLE_MODE`。
29
+ 状态根:`$DSH_HOME/botmode`。HTTP:`/botmode/api/state`、`/botmode/api/models`、`/botmode/api/memory`、`/botmode/api/image`、`/botmode/api/command`。
60
30
 
61
- ---
62
-
63
- ## 4. Market index(Discover 页搜索)
64
-
65
- 包内提供一份符合 DSH plugin market format 1 的索引:`market/index.json`。把它放到任意 https 可访问地址(或本机 http),在 DSH 的 Discover / 插件市场设置里添加为索引源,即可在页面里搜到 `dsh-quay-bot` 并一键安装:
66
-
67
- ```json
68
- {
69
- "format": 1,
70
- "title": { "en": "Quay Bot", "zh": "Quay Bot 团队模式" },
71
- "metadata": { "updated": 1764276000 },
72
- "plugins": [
73
- {
74
- "name": "dsh-quay-bot",
75
- "versions": [
76
- { "version": "1.0.0", "publishTimestamp": 1764276000, "source": { "type": "npm" }, "engines": { "dsh": ">=0.2.2-rc.3" } }
77
- ]
78
- }
79
- ]
80
- }
81
- ```
82
-
83
- 索引 URL 必须能被 DSH 以 `https:`(或同源的 http)读取;`source.type: "npm"` 会解析成 `dsh-quay-bot@1.0.0` 交给 profile 的包管理器。
84
-
85
- ---
86
-
87
- ## 5. 安装后去哪里找
88
-
89
- - Host 行:`include:botmode`,模块 `dsh-quay-bot`
90
- - Client 模块:`dsh-quay-bot/client`(侧边栏底部「Bot 模式」+ 机器人图标 → `main` 面板 `botmode`)
91
- - 状态根:`$DSH_HOME/botmode`(`state.json` v4、`rooms/`、`bots/`、`memory-data/`、`memory-plugins/`、网关日志)
92
- - HTTP:`/botmode/api/state`、`/models`、`/memory`、`/image`、`/command`、`/screen/*`、`/avatar/*`、`/artifacts/*`
93
-
94
- 改代码后:Plugin Manager 里关再开 `include:botmode` 重载 Host;Client 改动刷新页面即可(跑着 `pnpm run dev:web` 会热更新)。
95
-
96
- ---
97
-
98
- ## 6. 测试
31
+ 测试:
99
32
 
100
33
  ```bash
101
- node test/host.test.mjs && node test/screen.test.mjs && node test/avatar.test.mjs \
102
- && node test/artifacts.test.mjs && node test/routines.test.mjs && node test/qr.test.mjs \
103
- && node test/remote.test.mjs && node test/isolation.test.mjs && node test/governance-channels.test.mjs
34
+ node packages/dsh-botmode/test/host.test.mjs
104
35
  ```
105
36
 
106
- 覆盖 cron 解析、store/身份文件、会话隔离与 FIFO、模型与图片能力、Group Room 协议纯函数与多轮状态机、`message_agent` 护栏、Memory Hub(含降级路径)、审批策略、全部 HTTP 端点、venv 自举与系统依赖探测。
107
-
108
- ---
109
-
110
- ## 7. 与 `@local/dsh-botmode` 的关系
111
-
112
- 本包是同一套源码的**公开发布版**:包名、`dsh.bundle.patch` 的插件名、`client` 模块 id 改为 `dsh-quay-bot`;补上 `builtin-skills/**` 与 `vendor/wheels/**`;`bootstrapVenv` 改为离线优先;`ensureSystemDependencies` 从「5 个 bin」扩到「14 个 bin」。状态根、数据格式、`teamId=dsh-botmode` 保持不变,已有 Bot / 房间 / 记忆库可原样沿用。
113
-
114
- 同一 profile 里不要与 `@local/dsh-botmode` 同时启用(两者都插入 `include:botmode`)。
37
+ 完整架构、命令表与限制见 [docs/BOTMODE.md](../../docs/BOTMODE.md);项目总览见仓库根 [README.md](../../README.md)。
@@ -1,8 +1,8 @@
1
1
  fastapi>=0.110
2
2
  uvicorn[standard]>=0.27
3
3
  python-multipart>=0.0.9
4
+ pydantic>=2.0
4
5
  Pillow>=10.0
5
6
  python-xlib>=0.33
6
7
  websockets>=12.0
7
8
  httpx>=0.27
8
- mss>=9.0
package/client.js CHANGED
@@ -1,5 +1,5 @@
1
1
  window.__ModuleLoader__.load({
2
- id: 'dsh-quay-bot',
2
+ id: '@local/dsh-botmode',
3
3
  factory(require) {
4
4
  const React = require('react')
5
5
  const ReactDOM = require('react-dom')
@@ -8369,7 +8369,8 @@ window.__ModuleLoader__.load({
8369
8369
  h('div', { className: 'bm-remote-hint' }, t('remote.appLabel')),
8370
8370
  h('div', { className: 'bm-remote-link' }, data.appLink),
8371
8371
  h('div', { className: 'bm-remote-hint' }, t('remote.appHint')))
8372
- : h('div', { className: 'bm-remote-empty' }, busy || t('remote.appDisabled'))
8372
+ : h('div', { className: 'bm-remote-empty' },
8373
+ busy || (error ? t('remote.failed') : (data ? t('remote.appDisabled') : t('remote.starting'))))
8373
8374
 
8374
8375
  const dialog = h('div', {
8375
8376
  className: 'bm-modal-backdrop bm-remote-backdrop',
package/cordis.patch.yml CHANGED
@@ -1,3 +1,3 @@
1
1
  - insert:
2
2
  - id: botmode
3
- name: 'dsh-quay-bot'
3
+ name: '@local/dsh-botmode'
package/host/api.js CHANGED
@@ -283,6 +283,7 @@ export class BotApi {
283
283
  }
284
284
  if (route === 'remote' && req.method === 'GET') {
285
285
  try {
286
+ await this.remote?.recordUpstreamHintFromRequest?.(req)
286
287
  sendJson(res, 200, await this.remote.status({ qr: url.searchParams.get('qr') !== '0' }))
287
288
  } catch (error) {
288
289
  sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })
@@ -892,6 +893,9 @@ export class BotApi {
892
893
  sendJson(res, 400, { ok: false, error: 'invalid JSON' })
893
894
  return
894
895
  }
896
+ if (String(payload?.type ?? '').startsWith('remote.')) {
897
+ await this.remote?.recordUpstreamHintFromRequest?.(req)
898
+ }
895
899
  const result = await this.command(payload)
896
900
  sendJson(res, 200, { ok: true, state: this.publicState(), result })
897
901
  return
package/host/remote.js CHANGED
@@ -11,22 +11,157 @@
11
11
  */
12
12
  import { execFile } from 'node:child_process'
13
13
  import { existsSync } from 'node:fs'
14
- import { readFile, stat } from 'node:fs/promises'
14
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
15
15
  import { homedir } from 'node:os'
16
16
  import { dirname, join } from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
17
18
  import { promisify } from 'node:util'
18
19
  import { qrDataUrl, qrSvg } from './qr.js'
19
20
 
20
21
  const execFileAsync = promisify(execFile)
22
+ const HERE = dirname(fileURLToPath(import.meta.url))
23
+ const BUNDLED_BIN = join(HERE, '..', 'remote', 'bin', 'dsh-remote.mjs')
21
24
 
22
25
  const DEFAULT_HOME = process.env.DSH_REMOTE_HOME || join(homedir(), '.dsh-remote')
23
26
  const BIN_CANDIDATES = [
24
27
  process.env.DSH_REMOTE_BIN,
28
+ BUNDLED_BIN,
25
29
  join(process.cwd(), 'bin', 'dsh-remote.mjs'),
26
30
  join(homedir(), 'Desktop', 'dsh-remote', 'bin', 'dsh-remote.mjs'),
27
31
  join(homedir(), 'dsh-remote', 'bin', 'dsh-remote.mjs'),
28
32
  ].filter(Boolean)
29
33
 
34
+ function systemNodeCandidates(platform = process.platform, env = process.env) {
35
+ const list = []
36
+ if (env.DSH_NODE_BIN) list.push(env.DSH_NODE_BIN)
37
+ if (platform === 'win32') {
38
+ list.push('node.exe', 'node')
39
+ const pf = env.ProgramFiles || 'C:\\Program Files'
40
+ const pf86 = env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)'
41
+ const localAppData = env.LOCALAPPDATA
42
+ list.push(join(pf, 'nodejs', 'node.exe'))
43
+ list.push(join(pf86, 'nodejs', 'node.exe'))
44
+ if (localAppData) list.push(join(localAppData, 'Programs', 'nodejs', 'node.exe'))
45
+ if (env.NVM_SYMLINK) list.push(join(env.NVM_SYMLINK, 'node.exe'))
46
+ if (env.VOLTA_HOME) list.push(join(env.VOLTA_HOME, 'bin', 'node.exe'))
47
+ } else if (platform === 'darwin') {
48
+ list.push(
49
+ 'node',
50
+ '/opt/homebrew/bin/node',
51
+ '/usr/local/bin/node',
52
+ '/opt/local/bin/node',
53
+ join(homedir(), '.volta', 'bin', 'node'),
54
+ join(homedir(), '.asdf', 'shims', 'node'),
55
+ )
56
+ } else {
57
+ list.push(
58
+ 'node',
59
+ '/usr/local/bin/node',
60
+ '/usr/bin/node',
61
+ join(homedir(), '.volta', 'bin', 'node'),
62
+ join(homedir(), '.asdf', 'shims', 'node'),
63
+ )
64
+ }
65
+ return [...new Set(list.filter(Boolean))]
66
+ }
67
+
68
+ async function probeNodeMajor(command, extraEnv = {}) {
69
+ try {
70
+ const { stdout } = await execFileAsync(command, ['-p', 'process.versions.node'], {
71
+ timeout: 5_000,
72
+ windowsHide: true,
73
+ env: { ...process.env, ...extraEnv },
74
+ })
75
+ const match = /^(\d+)\./.exec(String(stdout ?? '').trim())
76
+ return match ? Number(match[1]) : 0
77
+ } catch {
78
+ return 0
79
+ }
80
+ }
81
+
82
+ let cachedNodeRuntime = null
83
+
84
+ /**
85
+ * 解析可执行 dsh-remote.mjs 的 Node 运行时(兼容 Linux / macOS / Windows 及 Electron 桌面端):
86
+ * - 非 Electron 环境:直接使用当前 `process.execPath`;
87
+ * - Electron 环境(macOS `.app` / Windows `.exe` / Linux 桌面端):
88
+ * 1) 优先选用宿主机已安装的独立 `node` (>= 20),避免 Electron 关闭 `RunAsNode` fuse 或拉起新 GUI 窗口;
89
+ * 2) 宿主机未安装 `node` 时,回退到 `process.execPath` 并注入 `ELECTRON_RUN_AS_NODE=1`。
90
+ */
91
+ export async function resolveNodeRuntime({
92
+ execPath = process.execPath,
93
+ isElectron = Boolean(process.versions?.electron),
94
+ platform = process.platform,
95
+ env = process.env,
96
+ probe = probeNodeMajor,
97
+ useCache = true,
98
+ } = {}) {
99
+ if (!isElectron) {
100
+ return { command: execPath, extraEnv: {} }
101
+ }
102
+ if (useCache && cachedNodeRuntime) return cachedNodeRuntime
103
+ for (const candidate of systemNodeCandidates(platform, env)) {
104
+ const major = await probe(candidate, {})
105
+ if (major >= 20) {
106
+ const resolved = { command: candidate, extraEnv: {} }
107
+ if (useCache) cachedNodeRuntime = resolved
108
+ return resolved
109
+ }
110
+ }
111
+ const electronFallback = { command: execPath, extraEnv: { ELECTRON_RUN_AS_NODE: '1' } }
112
+ if (useCache) cachedNodeRuntime = electronFallback
113
+ return electronFallback
114
+ }
115
+
116
+ async function atomicWriteFile(filePath, content, { mode = 0o600 } = {}) {
117
+ await mkdir(dirname(filePath), { recursive: true })
118
+ const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`
119
+ await writeFile(tmp, content, { encoding: 'utf8', mode })
120
+ if (process.platform !== 'win32') {
121
+ await chmod(tmp, mode).catch(() => {})
122
+ }
123
+ try {
124
+ await rename(tmp, filePath)
125
+ } catch (error) {
126
+ if (process.platform === 'win32' && (error?.code === 'EPERM' || error?.code === 'EEXIST')) {
127
+ await rm(filePath, { force: true }).catch(() => {})
128
+ await rename(tmp, filePath)
129
+ } else {
130
+ await rm(tmp, { force: true }).catch(() => {})
131
+ throw error
132
+ }
133
+ }
134
+ }
135
+
136
+ function hasRelayCookie(cookieHeader) {
137
+ if (typeof cookieHeader !== 'string' || !cookieHeader.trim()) return false
138
+ return cookieHeader
139
+ .split(';')
140
+ .some((part) => part.trim().startsWith('dsh-auth-relay='))
141
+ }
142
+
143
+ function normalizeSocketHost(raw) {
144
+ const s = String(raw ?? '').trim().replace(/^::ffff:/i, '')
145
+ if (!s || s === '::' || s === '::1' || s === '0.0.0.0') return '127.0.0.1'
146
+ return s
147
+ }
148
+
149
+ function extractDshAuthCookie(cookieHeader) {
150
+ if (typeof cookieHeader !== 'string' || !cookieHeader.trim()) return ''
151
+ const parts = cookieHeader.split(';')
152
+ for (const part of parts) {
153
+ const trimmed = part.trim()
154
+ const eq = trimmed.indexOf('=')
155
+ if (eq <= 0) continue
156
+ const name = trimmed.slice(0, eq).trim()
157
+ // 跳过 dsh-remote 自身的 relay cookie,避免自循环;只取宿主机真实 dsh-auth-* cookie
158
+ if (name.startsWith('dsh-auth-') && name !== 'dsh-auth-relay') {
159
+ return trimmed
160
+ }
161
+ }
162
+ return ''
163
+ }
164
+
30
165
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
31
166
 
32
167
  async function readJson(path) {
@@ -118,10 +253,80 @@ export class RemoteGateway {
118
253
  this.serviceName = serviceName
119
254
  this.useSystemd = useSystemd ?? (home === DEFAULT_HOME && !bin && process.platform === 'linux')
120
255
  this.runtimePath = join(home, 'state', 'runtime.json')
256
+ this.hintPath = join(home, 'state', 'upstream-hint.json')
257
+ this.configPath = join(home, 'config.json')
121
258
  this.linkPath = join(home, 'link.txt')
122
259
  this.lastAction = null
123
260
  }
124
261
 
262
+ /**
263
+ * 记录当前活跃 `dsh web` / Electron 内嵌网关的真实监听地址与鉴权信息到 `state/upstream-hint.json`。
264
+ * 即使用户在 Linux / macOS / Windows 裸跑 `dsh web` 或桌面端(无日志文件),dsh-remote 也能零配置自动对接。
265
+ */
266
+ async recordUpstreamHintFromRequest(req) {
267
+ try {
268
+ const port = Number(req?.socket?.localPort)
269
+ if (!Number.isInteger(port) || port <= 0) return false
270
+ const host = normalizeSocketHost(req?.socket?.localAddress)
271
+ const cookieHeader = req?.headers?.cookie
272
+ const cookie = extractDshAuthCookie(cookieHeader)
273
+ // 跳过仅来自 dsh-remote 自身的 relay 请求,避免自循环或覆盖真实 cookie
274
+ if (!cookie && hasRelayCookie(cookieHeader)) return false
275
+ if (!cookie) {
276
+ const existing = await readJson(this.hintPath)
277
+ if (existing && existing.port === port && existing.host === host && existing.cookie) {
278
+ return false
279
+ }
280
+ }
281
+ const payload = {
282
+ host,
283
+ port,
284
+ cookie: cookie || null,
285
+ authMode: cookie ? 'cookie' : 'none',
286
+ pid: process.pid,
287
+ updatedAt: Date.now(),
288
+ }
289
+ await atomicWriteFile(this.hintPath, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 })
290
+ return true
291
+ } catch {
292
+ return false
293
+ }
294
+ }
295
+
296
+ async #ensureDefaultConfig() {
297
+ if (existsSync(this.configPath)) return this.configPath
298
+ const homeDir = homedir()
299
+ const defaults = {
300
+ version: 1,
301
+ listen: { host: '127.0.0.1', port: 44691 },
302
+ public: { mode: 'quick' },
303
+ upstream: {
304
+ mode: 'auto',
305
+ log: null,
306
+ logs: [
307
+ join(homeDir, 'logs', 'dsh-web.log'),
308
+ join(homeDir, '.dsh', 'logs', 'dsh-web.log'),
309
+ join(homeDir, '.dsh-app-remote', 'web.log'),
310
+ ],
311
+ discoverIntervalMs: 3000,
312
+ },
313
+ proxy: { appBridge: true, hostRewrite: true },
314
+ tunnel: { persistAcrossRestart: true },
315
+ }
316
+ await atomicWriteFile(this.configPath, `${JSON.stringify(defaults, null, 2)}\n`, { mode: 0o600 })
317
+ return this.configPath
318
+ }
319
+
320
+ async #hasSystemdUserBus() {
321
+ if (!this.useSystemd || !this.serviceName) return false
322
+ try {
323
+ await execFileAsync('systemctl', ['--user', 'show-environment'], { timeout: 3000 })
324
+ return true
325
+ } catch {
326
+ return false
327
+ }
328
+ }
329
+
125
330
  async #hasSystemdService() {
126
331
  if (!this.useSystemd || !this.serviceName) return false
127
332
  try {
@@ -132,8 +337,70 @@ export class RemoteGateway {
132
337
  }
133
338
  }
134
339
 
340
+ /**
341
+ * Linux + systemd --user 环境下首次启动时自动安装独立的 `dsh-remote.service`,
342
+ * 让 dsh-remote / cloudflared 脱离 dsh-web.service 的 cgroup,避免 dsh 重启导致隧道断联。
343
+ */
344
+ async #ensureSystemdService() {
345
+ if (await this.#hasSystemdService()) return true
346
+ if (!(await this.#hasSystemdUserBus())) return false
347
+ if (!this.bin || !existsSync(this.bin)) return false
348
+ try {
349
+ const runtime = await resolveNodeRuntime()
350
+ const unitDir = join(homedir(), '.config', 'systemd', 'user')
351
+ const unitPath = join(unitDir, this.serviceName)
352
+ const logDir = join(this.home, 'logs')
353
+ await mkdir(unitDir, { recursive: true })
354
+ await mkdir(logDir, { recursive: true })
355
+ const workDir = dirname(dirname(this.bin))
356
+ const envLines = [
357
+ `Environment=HOME=${homedir()}`,
358
+ 'Environment=NODE_ENV=production',
359
+ `Environment=DSH_REMOTE_HOME=${this.home}`,
360
+ ]
361
+ if (runtime.extraEnv.ELECTRON_RUN_AS_NODE) {
362
+ envLines.push(`Environment=ELECTRON_RUN_AS_NODE=${runtime.extraEnv.ELECTRON_RUN_AS_NODE}`)
363
+ }
364
+ const unitBody = [
365
+ '[Unit]',
366
+ 'Description=dsh-remote — DSH Gateway Remote Tunnel (auto-managed by dsh-botmode)',
367
+ 'After=network-online.target',
368
+ 'Wants=network-online.target',
369
+ '',
370
+ '[Service]',
371
+ 'Type=simple',
372
+ ...envLines,
373
+ `WorkingDirectory=${workDir}`,
374
+ `ExecStart="${runtime.command}" "${this.bin}" up --foreground --config "${this.configPath}"`,
375
+ 'Restart=always',
376
+ 'RestartSec=3',
377
+ `StandardOutput=append:${join(logDir, 'relay.log')}`,
378
+ `StandardError=append:${join(logDir, 'relay.log')}`,
379
+ '',
380
+ '[Install]',
381
+ 'WantedBy=default.target',
382
+ '',
383
+ ].join('\n')
384
+ await writeFile(unitPath, unitBody, 'utf8')
385
+ await execFileAsync('systemctl', ['--user', 'daemon-reload'], { timeout: 10_000 })
386
+ await execFileAsync('systemctl', ['--user', 'enable', this.serviceName], { timeout: 10_000 }).catch(() => {})
387
+ return true
388
+ } catch (error) {
389
+ this.logger?.warn?.(`botmode: auto-install ${this.serviceName} failed, falling back: ${String(error?.message ?? error)}`)
390
+ return false
391
+ }
392
+ }
393
+
394
+ async #resolveWorkDir() {
395
+ const candidate = this.bin ? dirname(dirname(this.bin)) : null
396
+ if (candidate && existsSync(candidate)) return candidate
397
+ await mkdir(this.home, { recursive: true }).catch(() => {})
398
+ return existsSync(this.home) ? this.home : homedir()
399
+ }
400
+
135
401
  async #runDetachedUp({ timeoutMs = 120_000 } = {}) {
136
- if (await this.#hasSystemdService()) {
402
+ await this.#ensureDefaultConfig().catch(() => {})
403
+ if (await this.#ensureSystemdService()) {
137
404
  const startedAt = Date.now()
138
405
  await execFileAsync('systemctl', ['--user', 'start', this.serviceName], { timeout: 30_000 })
139
406
  this.lastAction = { args: ['systemctl', '--user', 'start', this.serviceName], ok: true, at: new Date().toISOString(), ms: Date.now() - startedAt }
@@ -141,13 +408,15 @@ export class RemoteGateway {
141
408
  }
142
409
  if (this.useSystemd) {
143
410
  try {
411
+ const runtime = await resolveNodeRuntime()
144
412
  const unit = `dsh-remote-detached-${Date.now()}`
145
- const env = { ...process.env, DSH_REMOTE_HOME: this.home }
413
+ const env = { ...process.env, ...runtime.extraEnv, DSH_REMOTE_HOME: this.home }
414
+ const cwd = await this.#resolveWorkDir()
146
415
  const startedAt = Date.now()
147
416
  await execFileAsync(
148
417
  'systemd-run',
149
- ['--user', '--scope', `--unit=${unit}`, '--', process.execPath, this.bin, 'up'],
150
- { timeout: timeoutMs, env, cwd: dirname(dirname(this.bin)), maxBuffer: 4 * 1024 * 1024 },
418
+ ['--user', '--scope', `--unit=${unit}`, '--', runtime.command, this.bin, 'up'],
419
+ { timeout: timeoutMs, env, cwd, windowsHide: true, maxBuffer: 4 * 1024 * 1024 },
151
420
  )
152
421
  this.lastAction = { args: ['systemd-run', 'up'], ok: true, at: new Date().toISOString(), ms: Date.now() - startedAt }
153
422
  return
@@ -159,13 +428,21 @@ export class RemoteGateway {
159
428
  }
160
429
 
161
430
  async #run(args, { timeoutMs = 90_000 } = {}) {
162
- const env = { ...process.env, DSH_REMOTE_HOME: this.home }
163
431
  const startedAt = Date.now()
432
+ if (!this.bin || !existsSync(this.bin)) {
433
+ const message = `未找到内置 dsh-remote 脚本(${this.bin ?? '未配置'})`
434
+ this.lastAction = { args, ok: false, at: new Date().toISOString(), ms: 0, error: message }
435
+ throw new Error(`dsh-remote ${args.join(' ')} 失败:${message}`)
436
+ }
437
+ const runtime = await resolveNodeRuntime()
438
+ const env = { ...process.env, ...runtime.extraEnv, DSH_REMOTE_HOME: this.home }
439
+ const cwd = await this.#resolveWorkDir()
164
440
  try {
165
- const { stdout, stderr } = await execFileAsync(process.execPath, [this.bin, ...args], {
441
+ const { stdout, stderr } = await execFileAsync(runtime.command, [this.bin, ...args], {
166
442
  timeout: timeoutMs,
167
443
  env,
168
- cwd: dirname(dirname(this.bin)),
444
+ cwd,
445
+ windowsHide: true,
169
446
  maxBuffer: 4 * 1024 * 1024,
170
447
  })
171
448
  this.lastAction = { args, ok: true, at: new Date().toISOString(), ms: Date.now() - startedAt }