dsh-remote-plugin 0.7.4 → 0.7.6

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.en.md CHANGED
@@ -1,72 +1,53 @@
1
1
  # dsh-remote-plugin
2
2
 
3
- The official DSH bundle plugin for DSH Remote. It adds a DSH sidebar entry, a compact status panel, a full admin console, and a gateway managed alongside DSH.
3
+ The DSH bundle plugin for DSH Remote adds a sidebar entry, status panel, admin console, and a bundled gateway that respects the user's start/stop intent.
4
4
 
5
5
  [English](README.en.md) · [中文](README.md)
6
6
 
7
- ## Install
7
+ ## Install and connect
8
8
 
9
9
  ```sh
10
- dsh plugin --profile web add dsh-remote-plugin
10
+ dsh plugin --profile web add dsh-remote-plugin@latest
11
11
  dsh plugin --profile web list --depth 0
12
-
13
- # Optional version pin
14
- dsh plugin --profile web add dsh-remote-plugin@0.6.8
15
12
  ```
16
13
 
17
- The second command verifies installation in the `web` profile. Completely restart DSH Web and hard-refresh with Ctrl+F5. For a user service, a typical restart is `systemctl --user restart dsh-web`; for a manual setup, stop the old `dsh web` process and launch it again.
18
-
19
- Open `http://127.0.0.1:8787/health` on the DSH host before pairing a phone. Once it returns JSON, connect the phone to `http://PC-LAN-IP:8787` or the host's Tailscale IP. Do not use `127.0.0.1` or `localhost` on the phone; those point to the phone itself.
20
-
21
- ## What the plugin provides
14
+ Use the actual profile for custom setups. DSH Desktop uses its own plugin manager and needs a complete exit/reopen. For Web, fully restart DSH Web, hard-refresh with Ctrl+F5 and open Remote in the sidebar.
22
15
 
23
- - Compact panel: gateway state, connected devices, token usage, and quick actions.
24
- - Admin console: port, upstream, devices, requests, token statistics, QR pairing, and token rotation.
25
- - Bundled `gateway.cjs`: Bearer-token gateway listening on `0.0.0.0:8787` by default.
26
- - Self-healing lifecycle: relaunches the gateway after a DSH restart or unexpected exit; start and stop it from the panel.
27
- - `/fs/*` file endpoints: list, download, chunked upload, resume, pause/continue/cancel, and SHA-256 verification.
28
- - Mobile, desktop, and admin WebUI assets, plus the Android APK distributed with the plugin.
16
+ On the host, open `http://127.0.0.1:8787/health`, then pair through the admin QR code. A phone connects to `http://PC-LAN-IP:8787` with its token, not its own localhost. RCs use `@next`; pin an existing version with `@<version>`.
29
17
 
30
- ## Mobile capabilities
18
+ ## Capabilities and limits
31
19
 
32
- The Android app / mobile WebUI has five main destinations: Sessions, Files, Home, Stats, and Settings. Session detail supports goals, subagent interruption, model selection, fullscreen input, slash commands, and image attachments. Images can come from the camera or gallery and are sent as image content in `session.prompt`.
20
+ - Status panel, admin console, Doctor, automatic management and explicit stop intent.
21
+ - Bearer authentication, optional per-device keys and short-lived WS tickets.
22
+ - mux/host downlinks, independent long polling, weak-network settings and local history.
23
+ - Allowed file roots, resumable chunks, hashes, previews/downloads and image attachments.
24
+ - Current-host plugin management and optional context/cost insights.
25
+ - Mobile navigation: Sessions, Files, Home, Plugins, Settings; five Web themes.
26
+ - Existing Android APKs are bundled when available; notifications/background require device permissions.
27
+ - Windows Desktop lifecycle control is experimental, needs verified instance evidence and does not configure login startup.
28
+ - HarmonyOS is a separate source project; release CI does not build HAPs. Insights and Web GenUI are not ported.
29
+ - Android ASR was removed; the feature-test page retains navigation only.
33
30
 
34
- Notification settings include approval / question notifications, background polling, peak reminders, task completion notices, and announcement history. Announcements update from a central HTTPS source every 30 seconds while the app is in the foreground, with gateway-cache and bundled-file fallback. Four themes are retained: Default Deep Space, Sunset, Elbphilharmonie, and Prairie Tower.
31
+ ## Configuration and troubleshooting
35
32
 
36
- ## Gateway configuration
33
+ Plugin port priority: `DSH_REMOTE_GATEWAY_PORT` → `~/.dsh-remote/gateway-port` → 8787. Bind address priority: `DSH_REMOTE_GATEWAY_HOST` → `HOST` → gateway-host file → `0.0.0.0`. The plugin passes the actual DSH upstream.
37
34
 
38
- - Port priority: `DSH_REMOTE_GATEWAY_PORT` → `~/.dsh-remote/gateway-port` → `8787`.
39
- - Token: `~/.dsh-remote/token`, generated on first run.
40
- - Self-healing: `~/.dsh-remote/gateway.enabled`; use `DSH_REMOTE_AUTOSTART=0` to disable automatic management.
41
- - File roots: registered DSH workspaces are allowed automatically; configure other directories with `DSH_REMOTE_FS_ROOT`, separated by `:` on Linux/macOS and `;` on Windows.
42
- - Upload limit: `DSH_REMOTE_FS_MAX_UPLOAD`, 2 GB by default.
43
- - Central announcements: override the default HTTPS endpoint with `DSH_REMOTE_ANNOUNCEMENTS_URL`, or set it to an empty string to disable the central source.
44
- - DSH upstream: `http://127.0.0.1:3080` by default.
35
+ The token defaults to `~/.dsh-remote/token`; `DSH_REMOTE_AUTOSTART=0` disables automatic management. File roots, DSH workspaces and Windows defaults have specific authorization boundaries; see configuration.
45
36
 
46
- The token grants remote control of DSH. Keep it private. For cross-network access, prefer Tailscale or another authenticated secure tunnel.
47
-
48
- ## Gateway cannot be opened
49
-
50
- ```bash
51
- curl -i http://127.0.0.1:8787/health
52
- ss -ltnp | grep ':8787'
53
- curl -i http://127.0.0.1:3080/
54
- ```
37
+ For local refusal, check the actual profile, full restart and port ownership. Degraded upstream means troubleshoot DSH. For phone access, check network/firewall; for 401, pair again; for stale assets, hard-refresh. Embedded admin uses the DSH login boundary; standalone admin uses the Remote master token. A transient gateway is not necessarily a persistent systemd service.
55
38
 
56
- - If port 8787 refuses locally, verify the `web` profile installation, gateway state in the plugin panel, a real DSH Web restart, and port ownership.
57
- - If `/health` works but `upstreamOk` is false, the gateway is running; troubleshoot DSH Web on port 3080.
58
- - If local access works but the phone fails, use the host LAN/Tailscale IP and permit inbound TCP 8787. Do not expose port 3080 publicly.
59
- - A 401 response means the token is wrong; pair again or copy the current `~/.dsh-remote/token`.
60
- - For a blank/stale page after an upgrade, hard-refresh or fully close and reopen the app.
39
+ Keep QR codes and credentials private. Prefer Tailscale across networks. Remote device/master tokens and the DSH upstream Cookie have separate roles.
61
40
 
62
- The managed gateway may be a transient process. Do not rely on `systemctl --user restart dsh-remote-gateway.service`; use Start Gateway in the plugin panel or restart DSH Web to trigger self-healing.
41
+ ## Documentation
63
42
 
64
- ## Links
43
+ - [Documentation index](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/README.md)
44
+ - [Installation](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/getting-started.md)
45
+ - [Configuration](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/configuration.md)
46
+ - [Troubleshooting](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/troubleshooting.md)
47
+ - [Main project](https://github.com/Blank-not-black/dsh-Remote)
48
+ - [Releases](https://github.com/Blank-not-black/dsh-Remote/releases)
65
49
 
66
- - Admin page: `http://<gateway-ip>:8787/admin`
67
- - Desktop WebUI: `http://<gateway-ip>:8787`
68
- - Main project: [dsh-Remote](https://github.com/Blank-not-black/dsh-Remote)
69
- - Stable releases: [GitHub Releases](https://github.com/Blank-not-black/dsh-Remote/releases/latest)
50
+ Checked against repository 0.7.4 on 2026-10-12. This does not verify current npm tags, installed devices or all platform behavior. Detailed guides are currently in Chinese.
70
51
 
71
52
  ## License
72
53
 
package/README.md CHANGED
@@ -1,72 +1,53 @@
1
1
  # dsh-remote-plugin
2
2
 
3
- DSH Remote 的官方 bundle 插件:在 DSH 侧边栏提供入口,打开快速状态面板和完整管理控制台,并内置随 DSH 自动启停的远程网关。
3
+ DSH Remote 的 DSH bundle 插件:提供侧栏入口、快速面板、管理控制台及受用户启停意图约束的内置网关。
4
4
 
5
5
  **中文** · [English](README.en.md)
6
6
 
7
- ## 安装
7
+ ## 安装与连接
8
8
 
9
9
  ```sh
10
- dsh plugin --profile web add dsh-remote-plugin
10
+ dsh plugin --profile web add dsh-remote-plugin@latest
11
11
  dsh plugin --profile web list --depth 0
12
-
13
- # 也可以安装指定版本
14
- dsh plugin --profile web add dsh-remote-plugin@0.6.8
15
12
  ```
16
13
 
17
- 第二条命令用于确认插件安装在正确的 `web` profile。然后完整重启 DSH Web 进程并 Ctrl+F5 强刷浏览器,左侧边栏会出现 DSH Remote 入口。如果 DSH Web 由 systemd 用户服务管理,可执行 `systemctl --user restart dsh-web`;手动运行时则需停止旧的 `dsh web` 进程后重新启动。
18
-
19
- 安装后先在 DSH 主机访问 `http://127.0.0.1:8787/health`。看到 JSON 后再用手机连接 `http://电脑局域网IP:8787`;手机上的 `127.0.0.1` 和 `localhost` 指向手机自己,不是 DSH 主机。
20
-
21
- ## 插件提供什么
14
+ 示例针对 Web profile;自定义 profile 使用实际名称。DSH Desktop 从自身插件管理入口安装,完整退出并重开。Web 安装完成后完整重启 DSH Web,Ctrl+F5,从侧栏打开 Remote。
22
15
 
23
- - 快速面板:网关状态、在线设备、Token 用量和快捷操作;
24
- - 管理控制台:端口、上游、设备、请求、Token 统计、二维码和令牌轮换;
25
- - 内置 `gateway.cjs`:默认监听 `0.0.0.0:8787`,带 Bearer token 鉴权;
26
- - 网关自愈:DSH 重启或网关意外退出后自动拉起,可在面板中停止或启动;
27
- - `/fs/*` 文件端点:列表、下载、分块上传、断点续传、暂停/继续/取消和 SHA-256 校验;
28
- - 手机端、桌面端和管理页 WebUI,以及随插件分发的 Android APK。
16
+ 在主机访问 `http://127.0.0.1:8787/health`,然后从管理控制台扫码。手机手动连接填 `http://电脑局域网IP:8787` 与令牌,不能填手机 localhost。RC 使用 `@next`,固定版本使用 `@<已发布版本>`。
29
17
 
30
- ## 手机端能力
18
+ ## 当前能力与限制
31
19
 
32
- Android 应用 / 手机 WebUI 采用五个主要页面:会话、文件、主页、统计、设置。会话详情支持目标控制、子代理中断、模型切换、全屏输入、斜杠命令和图片附件。图片附件可从相机或相册选择,并以 `session.prompt` 图片内容发送到当前会话。
20
+ - 快速状态、完整管理控制台、Doctor、自启/自愈与明确停止意图。
21
+ - Bearer token、可选独立设备密钥、短时 WS ticket。
22
+ - mux/host 下行、独立长轮询、弱网设置与历史缓存。
23
+ - 文件多根、分块续传、校验、预览/下载与图片附件。
24
+ - 当前主机插件管理与可选上下文/费用洞察。
25
+ - 手机导航:会话、文件、主页、插件、设置;五套 Web 主题。
26
+ - Android APK 在已有构建产物时随包分发,通知与后台需设备权限。
27
+ - Windows Desktop 控制是实验能力,需可信实例证据,不提供登录自启。
28
+ - HarmonyOS 为独立源码工程,当前 release CI 不构建 HAP;会话洞察和 Web GenUI 未移植。
29
+ - Android ASR 桥已移除,功能测试页保留导航;不要沿用旧说明。
33
30
 
34
- 通知设置支持审批 / 提问通知、后台轮询、峰谷提醒、任务完成提醒和历史公告。公告通过中央 HTTPS 源更新,App 前台每 30 秒检查,中央源不可达时回退网关缓存或安装包内公告。当前保留四套主题:默认深空、落日、易北爱乐厅、草原孤塔。
31
+ ## 配置与排查
35
32
 
36
- ## 网关配置
33
+ 插件端口优先级:`DSH_REMOTE_GATEWAY_PORT` → `~/.dsh-remote/gateway-port` → 8787。监听地址优先级:`DSH_REMOTE_GATEWAY_HOST` → `HOST` → gateway-host 文件 → `0.0.0.0`。插件从当前 DSH 实例传入上游。
37
34
 
38
- - 网关端口优先级:`DSH_REMOTE_GATEWAY_PORT` 环境变量 → `~/.dsh-remote/gateway-port` → `8787`;
39
- - 令牌:`~/.dsh-remote/token`,首次运行自动生成;
40
- - 自愈开关:`~/.dsh-remote/gateway.enabled`,或使用 `DSH_REMOTE_AUTOSTART=0` 禁用自动管理;
41
- - 文件根目录:DSH 已登记工作区会自动放行;其他目录用 `DSH_REMOTE_FS_ROOT` 配置,Linux/macOS 使用 `:`,Windows 使用 `;`;
42
- - 文件上限:`DSH_REMOTE_FS_MAX_UPLOAD`,默认 2GB;
43
- - 中央公告:`DSH_REMOTE_ANNOUNCEMENTS_URL` 可覆盖默认 HTTPS 地址,设为空字符串可禁用中央源;
44
- - DSH 上游:默认 `http://127.0.0.1:3080`。
35
+ 令牌默认 `~/.dsh-remote/token`;`DSH_REMOTE_AUTOSTART=0` 禁用自动管理。文件授权、工作区及 Windows 默认根存在边界,详见完整配置参考。
45
36
 
46
- 令牌等同于 DSH 远程操作凭证,请不要公开或提交到仓库。局域网访问建议配合防火墙;跨网络访问建议使用 Tailscale 或其他带认证的安全隧道。
47
-
48
- ## 网关打不开
49
-
50
- ```bash
51
- curl -i http://127.0.0.1:8787/health
52
- ss -ltnp | grep ':8787'
53
- curl -i http://127.0.0.1:3080/
54
- ```
37
+ 本机拒绝连接先检查实际 profile、完整重启与端口;上游 degraded 检查 DSH;手机不可达检查网络和防火墙;401 重新配对;升级界面旧先强刷。插件内嵌管理页使用 DSH 登录边界,独立管理页使用 Remote 主令牌。不要把 transient 网关当成固定可 restart 的 systemd 服务。
55
38
 
56
- - 8787 本机也拒绝连接:检查插件是否装在 `web` profile、插件面板的网关开关、DSH Web 是否真正重启,以及 8787 是否被占用。
57
- - `/health` 能打开但 `upstreamOk: false`:网关已运行,应检查 DSH Web 的 3080 端口。
58
- - 本机能打开但手机不能:使用电脑局域网/Tailscale IP,并允许防火墙 TCP 8787 入站;不需要对公网放行 3080。
59
- - 出现 401:重新扫码或复制 `~/.dsh-remote/token`。
60
- - 页面黑屏/功能未更新:Ctrl+F5 强刷,手机端完全退出后重开。
39
+ 配对二维码包含凭证,不公开;跨网络优先 Tailscale。主令牌、设备令牌与 DSH 上游 Cookie 不混用。
61
40
 
62
- 插件网关可能以 transient 进程运行,不要依赖 `systemctl --user restart dsh-remote-gateway.service`。优先在插件面板启动网关,或重启 DSH Web 触发自愈。
41
+ ## 文档
63
42
 
64
- ## 相关地址
43
+ - [完整文档](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/README.md)
44
+ - [安装与连接](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/getting-started.md)
45
+ - [配置](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/configuration.md)
46
+ - [故障排查](https://github.com/Blank-not-black/dsh-Remote/blob/main/docs/troubleshooting.md)
47
+ - [主项目与下载](https://github.com/Blank-not-black/dsh-Remote)
48
+ - [GitHub Releases](https://github.com/Blank-not-black/dsh-Remote/releases)
65
49
 
66
- - 管理页:`http://<网关IP>:8787/admin`
67
- - 桌面 WebUI:`http://<网关IP>:8787`
68
- - 主项目:[dsh-Remote](https://github.com/Blank-not-black/dsh-Remote)
69
- - 正式版本:[GitHub Releases](https://github.com/Blank-not-black/dsh-Remote/releases/latest)
50
+ 说明按仓库 0.7.4(2026-10-12)核对,不代表当前 npm 标签、设备实装或所有平台验收结果。
70
51
 
71
52
  ## License
72
53
 
Binary file
package/gateway.cjs CHANGED
@@ -2582,7 +2582,7 @@ function applyModernSessionFrame(sessionId, value) {
2582
2582
  modernState.sessionCursors.set(sessionId, value.cursor)
2583
2583
  legacyPush('mux', { type: 'session/subscribed', sessionId, lastSeq: value.cursor })
2584
2584
  for (const record of value.records || []) {
2585
- if (record?.event) legacyPush('mux', { type: 'session/event', sessionId, event: record.event })
2585
+ if (record?.event) legacyPush('mux', { type: 'session/event', sessionId, event: record.event, replay: true })
2586
2586
  }
2587
2587
  for (const [key, projection] of Object.entries(value.projections?.values || {})) {
2588
2588
  applyModernProjection(sessionId, key, projection, value.projections?.asOfSeq ?? value.cursor)
@@ -4962,7 +4962,9 @@ function proxyApi(req, res, url) {
4962
4962
  // Credential exchange is restricted to named client endpoints. Administrative
4963
4963
  // plugin routes must authenticate the master token before reaching DSH.
4964
4964
  const remoteClientPath = ['/remote/api/command', '/remote/api/command-status', '/remote/admin/api/dsh'].includes(url.pathname)
4965
+ || (url.pathname === '/remote/api/session-file' && ['GET','HEAD'].includes(req.method))
4965
4966
  || (url.pathname === '/remote/api/insights/cost' && req.method === 'GET')
4967
+ || /^\/remote\/api\/skills\/(list|read)$/.test(url.pathname)
4966
4968
  || /^\/remote\/api\/plugins\/(state|details|market|operations|recover)$/.test(url.pathname)
4967
4969
  const remoteAdminPath = url.pathname.startsWith('/remote/') && !remoteClientPath
4968
4970
  const ok = remoteAdminPath ? adminAuthorized(req, url) : remoteClientPath ? controlAuthorized(req, url) : authorized(req, url)
package/index.mjs CHANGED
@@ -14,6 +14,8 @@ import { dirname, extname, normalize, resolve } from 'node:path'
14
14
  import { fileURLToPath } from 'node:url'
15
15
  import { createPluginCenter, detectProfile } from './plugin-center.mjs'
16
16
  import { readCostInsights } from './insights.mjs'
17
+ import { serveSessionFile } from './session-file.mjs'
18
+ import { createSkillsAdapter } from './skills.mjs'
17
19
 
18
20
  export const name = 'dsh-remote'
19
21
  export const inject = ['webServer', 'commands', 'agents', 'connection']
@@ -652,6 +654,28 @@ async function resolveFile(pathname) {
652
654
 
653
655
  async function serveStatic(req, res, ctx) {
654
656
  const pathname = new URL(req.url ?? '/', 'http://x').pathname
657
+ if (pathname.startsWith(`${MOUNT}/api/skills/`)) {
658
+ res.setHeader('cache-control', 'no-store')
659
+ if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
660
+ const adapter = createSkillsAdapter(async path => {
661
+ // Use this host's listener, never a URL, origin or cookie supplied by the caller.
662
+ const base = upstreamUrlForListener({ host: ctx.webServer.host, port: ctx.webServer.port })
663
+ let cookie = ''
664
+ try { cookie = readFileSync(dshUpstreamCookieFile(), 'utf8').trim() } catch {}
665
+ const response = await fetch(base + path, { headers: cookie ? { cookie } : {}, redirect: 'error', signal: AbortSignal.timeout(10000) })
666
+ if (!response.ok) { await response.body?.cancel(); throw Object.assign(new Error('native-read-failed'), { status: response.status }) }
667
+ const chunks = []; let bytes = 0
668
+ for await (const chunk of response.body) {
669
+ bytes += chunk.length
670
+ if (bytes > 2 * 1024 * 1024) throw new Error('response-too-large')
671
+ chunks.push(chunk)
672
+ }
673
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { throw new Error('unsupported') }
674
+ })
675
+ const url = new URL(req.url, 'http://x')
676
+ const result = await adapter.handle(req.method, pathname.slice(`${MOUNT}/api/skills`.length), url.searchParams)
677
+ return sendJson(res, result.status, result.body)
678
+ }
655
679
  if (pathname === `${MOUNT}/api/insights/cost`) {
656
680
  if (!remoteCommandAuthorized(req)) return sendJson(res, 401, { ok: false, code: 'unauthorized' })
657
681
  if (req.method !== 'GET') return sendJson(res, 405, { ok: false, code: 'read-only' })
@@ -878,6 +902,10 @@ async function serveStatic(req, res, ctx) {
878
902
  return
879
903
  }
880
904
 
905
+ if (pathname === `${MOUNT}/api/session-file`) {
906
+ if (!remoteCommandAuthorized(req)) { sendJson(res,401,{ok:false,message:'unauthorized'});return }
907
+ return serveSessionFile(ctx, req, res, new URL(req.url, 'http://host'))
908
+ }
881
909
  // 命令状态:由插件进程跟踪长期操作,客户端重连后可恢复可见状态。
882
910
  if (pathname === `${MOUNT}/api/command-status`) {
883
911
  if (req.method !== 'GET') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.7.4",
3
+ "version": "0.7.6",
4
4
  "description": "DSH Remote 官方 bundle 插件:DSH 左侧原生边栏入口 + 右侧抽屉内嵌管理控制台;内置网关随 DSH 自动启停(systemd 独立单元),抽屉直显令牌与设备监控;网关提供 /fs/* 文件传输端点(列表/断点下载/上传),配合 Android App 远程操控会话/审批/提问/goal 与文件互传(多服务器测速切换、聊天记录离线缓存)。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -20,7 +20,9 @@
20
20
  "cordis.patch.yml",
21
21
  "*.md",
22
22
  "plugin-center.mjs",
23
- "insights.mjs"
23
+ "insights.mjs",
24
+ "skills.mjs",
25
+ "session-file.mjs"
24
26
  ],
25
27
  "keywords": [
26
28
  "dsh-plugin",
package/plugin-center.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  /* Profile-scoped plugin management. No shell input, dependencies or client-selected paths. */
2
- import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, readdirSync, copyFileSync, unlinkSync, realpathSync, openSync, closeSync } from 'node:fs'
2
+ import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, readdirSync, copyFileSync, cpSync, unlinkSync, realpathSync, openSync, closeSync } from 'node:fs'
3
3
  import { dirname, basename, join, resolve } from 'node:path'
4
4
  import { fileURLToPath } from 'node:url'
5
5
  import { createHash } from 'node:crypto'
6
- import { spawn } from 'node:child_process'
6
+ import { spawn, execFile } from 'node:child_process'
7
7
 
8
8
  const REGISTRY = 'https://registry.npmjs.org'
9
9
  const SELF = fileURLToPath(import.meta.url)
@@ -19,22 +19,78 @@ function atomic(path, value) {
19
19
  const fail = (message, status = 400) => Object.assign(new Error(message), { status })
20
20
  const protectedPackage = name => name === 'dsh-remote-plugin' || name.startsWith('@deepseek-ai/')
21
21
  const revision = path => createHash('sha256').update(readFileSync(path)).digest('hex')
22
+ // A detached worker can replace/delete its ledger between two manager reads.
23
+ // Windows sharing violations are uncertain ownership, never proof of death.
24
+ function ownershipText(path) {
25
+ try { return readFileSync(path, 'utf8') } catch (error) {
26
+ if (error.code === 'ENOENT') return null
27
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error.code)) return undefined
28
+ throw error
29
+ }
30
+ }
31
+ const ownershipPending = '任务锁正在更新或暂时无法读取,已保留锁;请稍后刷新。'
22
32
 
23
- function alive(pid) {
24
- if (!Number.isInteger(pid) || pid <= 0) return false
25
- try { process.kill(pid, 0); return true } catch (error) { return error.code !== 'ESRCH' }
33
+ let windowsProbe
34
+ function windowsProcessIds() {
35
+ // Windows can return EPERM for an exited PID. Enumerate OS processes instead;
36
+ // failure or malformed output must never be interpreted as an empty list.
37
+ if (!windowsProbe) windowsProbe = new Promise((resolveIds, reject) => {
38
+ execFile(join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
39
+ ['-NoProfile', '-NonInteractive', '-Command', '$ErrorActionPreference="Stop"; ConvertTo-Json -Compress -InputObject @(Get-Process -ErrorAction Stop | Select-Object -ExpandProperty Id)'],
40
+ { windowsHide: true, timeout: 5000, maxBuffer: 1024 * 1024 }, (error, stdout) => {
41
+ if (error) return reject(error)
42
+ try {
43
+ const ids = JSON.parse(stdout.replace(/^\uFEFF/, ''))
44
+ if (!Array.isArray(ids) || !ids.length || !ids.every(Number.isInteger)) throw new Error('Invalid process list')
45
+ resolveIds(new Set(ids))
46
+ } catch (error) { reject(error) }
47
+ })
48
+ }).finally(() => { windowsProbe = null })
49
+ return windowsProbe
50
+ }
51
+
52
+ export async function probeProcesses(pids, runtime = process, enumerate = windowsProcessIds) {
53
+ const states = new Map(), uncertain = []
54
+ for (const pid of new Set(pids.filter(pid => Number.isInteger(pid) && pid > 0))) {
55
+ try { runtime.kill(pid, 0); states.set(pid, 'alive') }
56
+ catch (error) {
57
+ states.set(pid, error.code === 'ESRCH' ? 'dead' : 'unknown')
58
+ if (error.code === 'EPERM' && runtime.platform === 'win32') uncertain.push(pid)
59
+ }
60
+ }
61
+ if (uncertain.length) {
62
+ try {
63
+ const ids = await enumerate()
64
+ for (const pid of uncertain) states.set(pid, ids.has(pid) ? 'alive' : 'dead')
65
+ } catch { /* Keep unknown on timeout, denied access or unavailable OS query. */ }
66
+ }
67
+ return states
26
68
  }
27
69
 
28
70
  // Never clear a live worker or its package-manager child. PID reuse fails closed.
29
- function recoverDeadLock(storage) {
71
+ async function recoverDeadLock(storage, probe = probeProcesses) {
30
72
  const path = join(storage, 'lock.json')
31
- if (!existsSync(path)) return
32
- const owner = read(path)
73
+ const original = ownershipText(path)
74
+ if (original === null) return
75
+ if (original === undefined) return ownershipPending
76
+ const owner = JSON.parse(original)
33
77
  if (!idPattern.test(owner.id || '')) throw fail('插件任务锁损坏,请在主机检查', 409)
34
78
  const launchPath = join(storage, 'launch-' + owner.id + '.json')
35
- const workerPid = owner.workerPid || (existsSync(launchPath) ? read(launchPath).pid : null)
36
- if (alive(workerPid) || alive(owner.cliPid)) return
37
- if (!workerPid && (!owner.launcherPid || alive(owner.launcherPid) || Date.now() - owner.createdAt < 30000)) return
79
+ const launchRecord = ownershipText(launchPath)
80
+ if (launchRecord === undefined) return ownershipPending
81
+ const workerPid = owner.workerPid || (launchRecord ? JSON.parse(launchRecord).pid : null)
82
+ const pids = workerPid ? [workerPid, owner.cliPid] : [owner.launcherPid, owner.cliPid]
83
+ if (pids.some(pid => pid != null && (!Number.isSafeInteger(pid) || pid <= 0))) return '任务锁进程信息损坏,已保留锁;请在主机检查。'
84
+ const states = await probe(pids)
85
+ const currentOwner = ownershipText(path), currentLaunch = ownershipText(launchPath)
86
+ if (currentOwner === undefined || currentLaunch === undefined) return ownershipPending
87
+ if (currentOwner !== original || currentLaunch !== launchRecord) return
88
+ if ([...states.values()].some(state => state !== 'dead')) {
89
+ return [...states.values()].includes('unknown')
90
+ ? '无法确认任务进程是否已退出,已保留锁;请在主机检查进程权限与操作记录。'
91
+ : '主机任务进程仍在运行,其他修改暂不可用;可展开操作记录查看日志。'
92
+ }
93
+ if (!workerPid && (!owner.launcherPid || !Number.isFinite(owner.createdAt) || Date.now() - owner.createdAt < 30000)) return
38
94
  const jobPath = join(storage, 'job-' + owner.id + '.json')
39
95
  if (existsSync(jobPath)) {
40
96
  const job = read(jobPath)
@@ -45,7 +101,25 @@ function recoverDeadLock(storage) {
45
101
  }
46
102
  }
47
103
  // All reads/writes here are synchronous; recheck ownership before unlinking.
48
- if (read(path).id === owner.id) unlinkSync(path)
104
+ if (ownershipText(path) === original) {
105
+ copyFileSync(path, join(storage, 'recovered-lock-' + owner.id + '.json'))
106
+ unlinkSync(path)
107
+ }
108
+ }
109
+
110
+ async function profileLock(dir, probe = probeProcesses) {
111
+ const path = join(dir, 'package.json.lock')
112
+ if (!existsSync(path)) return null
113
+ const raw = readFileSync(path, 'utf8'), text = raw.trim()
114
+ const pid = /^\d+$/.test(text) ? Number(text) : null
115
+ if (!Number.isSafeInteger(pid) || pid <= 0) return { path, raw, state: 'unknown', message: 'DSH 配置锁格式无法识别,请在主机检查 package.json.lock。' }
116
+ const state = (await probe([pid])).get(pid) || 'unknown'
117
+ if (!existsSync(path)) return null
118
+ if (readFileSync(path, 'utf8') !== raw) return { state: 'unknown', message: 'DSH 配置锁已变化,请刷新后重试。' }
119
+ return { path, raw, pid, state, message: state === 'dead'
120
+ ? '检测到已退出进程遗留的 DSH 配置锁;下一次操作会备份并回收。'
121
+ : state === 'alive' ? 'DSH 配置被进程 ' + pid + ' 占用,请等待主机操作结束后重试。'
122
+ : '无法确认 DSH 配置锁进程 ' + pid + ' 是否已退出,请在主机检查;锁已保留。' }
49
123
  }
50
124
 
51
125
  export function detectProfile(ctx, cli = process.argv[1], runtime = process) {
@@ -114,6 +188,7 @@ export async function pluginDetails(name, version = 'latest') {
114
188
  export function createPluginCenter(ctx, options = {}) {
115
189
  const profile = options.profile === undefined ? detectProfile(ctx) : options.profile
116
190
  const details = options.details || pluginDetails
191
+ const probe = options.probeProcesses || probeProcesses
117
192
  const launch = options.launch || (args => {
118
193
  const desktop = profile?.cliMode === 'desktop'
119
194
  const errorLog = openSync(join(profile.dir, '.remote-plugin-center', 'worker-' + args[2] + '.log'), 'a', 0o600)
@@ -134,7 +209,7 @@ export function createPluginCenter(ctx, options = {}) {
134
209
  const storage = profile && join(profile.dir, '.remote-plugin-center')
135
210
  let submitting = false
136
211
  async function inventory() {
137
- if (storage) recoverDeadLock(storage)
212
+ const busyReason = storage ? await recoverDeadLock(storage, probe) : ''
138
213
  let runtime = [], runtimeAvailable = false
139
214
  const loader = ctx.get?.('loader') || ctx.loader
140
215
  if (loader?.entries) {
@@ -157,6 +232,7 @@ export function createPluginCenter(ctx, options = {}) {
157
232
  return { name, displayName, version: pkg?.version || '', requested: manifest.dependencies?.[name] || '',
158
233
  enabled: bundles.includes(name), bundle: !!pkg?.dsh?.bundle?.patch || bundles.includes(name),
159
234
  managed: !!manifest.dependencies?.[name] && !protectedPackage(name),
235
+ selfUpdate: name === 'dsh-remote-plugin' && !!profile.cli,
160
236
  description: pkg?.description || '', runtime: runtime.filter(entry => entry.name === name) }
161
237
  })
162
238
  let operations = []
@@ -164,14 +240,17 @@ export function createPluginCenter(ctx, options = {}) {
164
240
  try { return read(join(storage, name)) } catch { return null }
165
241
  }).filter(Boolean).sort((a, b) => b.startedAt - a.startedAt).slice(0, 20).map(publicJob)
166
242
  const lockPath = join(storage, 'lock.json')
167
- const owner = existsSync(lockPath) ? read(lockPath) : null
243
+ const ownerText = ownershipText(lockPath)
244
+ const owner = ownerText === null ? null : ownerText === undefined ? {} : JSON.parse(ownerText)
168
245
  const legacyLock = owner && idPattern.test(owner.id || '') && !owner.launcherPid && !owner.workerPid && !owner.cliPid && !existsSync(join(storage, 'launch-' + owner.id + '.json'))
169
246
  return { ok: true, profile: profile.name, revision: revision(manifestPath), writable: !!profile.cli,
170
247
  reason: profile.cli ? '' : profile.name === 'desktop'
171
248
  ? '未能验证当前桌面安装的插件管理入口;仅显示状态,请检查 DSH Desktop 版本与安装完整性。'
172
249
  : '当前启动方式没有可验证的 DSH CLI,管理操作不可用。',
173
250
  pendingRestart: revision(manifestPath) !== initialRevision || operations.some(job => job.phase === 'interrupted' && job.restartRequired),
174
- busy: submitting || !!owner, recovery: legacyLock ? { id: owner.id, reason: '旧任务锁没有进程信息,需在主机核对后手动解除。' } : null,
251
+ busy: submitting || !!owner, busyReason: owner ? busyReason || '主机任务正在启动;可查看操作记录。' : '',
252
+ profileLock: await profileLock(profile.dir, probe).then(lock => lock && ({ state: lock.state, message: lock.message })),
253
+ recovery: legacyLock ? { id: owner.id, reason: '旧任务锁没有进程信息,需在主机核对后手动解除。' } : null,
175
254
  items, runtime, runtimeAvailable, operations }
176
255
  }
177
256
  function recoverLegacy(body) {
@@ -199,9 +278,11 @@ export function createPluginCenter(ctx, options = {}) {
199
278
  if (!body || typeof body !== 'object' || Array.isArray(body)) throw fail('Invalid operation')
200
279
  const { id, action, name, version } = body
201
280
  if (!idPattern.test(id || '') || !packagePattern.test(name || '') || !['install', 'update', 'remove', 'enable', 'disable'].includes(action)) throw fail('Invalid operation')
202
- if (protectedPackage(name)) throw fail('核心插件与 Remote 自身请通过主机维护流程管理', 409)
281
+ const selfUpdate = name === 'dsh-remote-plugin' && action === 'update'
282
+ if (protectedPackage(name) && !selfUpdate) throw fail('核心插件与 Remote 的卸载、启停请通过主机维护流程管理', 409)
283
+ if (selfUpdate && body.confirmSelfUpdate !== true) throw fail('请确认 Remote 本体更新及重启后生效', 409)
203
284
  mkdirSync(storage, { recursive: true, mode: 0o700 })
204
- recoverDeadLock(storage)
285
+ await recoverDeadLock(storage, probe)
205
286
  const jobPath = join(storage, 'job-' + id + '.json')
206
287
  if (existsSync(jobPath)) {
207
288
  const previous = read(jobPath)
@@ -228,7 +309,7 @@ export function createPluginCenter(ctx, options = {}) {
228
309
  const lock = join(storage, 'lock.json')
229
310
  try { writeFileSync(lock, JSON.stringify({ id, launcherPid: process.pid, createdAt: Date.now() }), { flag: 'wx', mode: 0o600 }) }
230
311
  catch (error) { if (error.code === 'EEXIST') throw fail('已有插件任务运行中;请查看操作记录', 409); throw error }
231
- const job = { id, action, name, version: version || '', revision: body.revision, profile: profile.name, phase: 'queued', startedAt: Date.now(), log: '', restartRequired: false }
312
+ const job = { id, action, name, version: version || '', revision: body.revision, profile: profile.name, phase: 'queued', stage: 'queued', startedAt: Date.now(), updatedAt: Date.now(), log: '', restartRequired: false }
232
313
  try {
233
314
  atomic(jobPath, job)
234
315
  const pid = await launch([profile.dir, profile.cli, id, profile.cliMode || 'node'])
@@ -260,11 +341,11 @@ export function createPluginCenter(ctx, options = {}) {
260
341
  }
261
342
 
262
343
  function publicJob(job) {
263
- const { id, action, name, version, profile, phase, startedAt, endedAt, log, message, restartRequired } = job
264
- return { id, action, name, version, profile, phase, startedAt, endedAt, log, message, restartRequired }
344
+ const { id, action, name, version, profile, phase, stage, startedAt, endedAt, updatedAt, lastOutputAt, log, message, restartRequired } = job
345
+ return { id, action, name, version, profile, phase, stage, startedAt, endedAt, updatedAt, lastOutputAt, log, message, restartRequired }
265
346
  }
266
347
 
267
- export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node') {
348
+ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node', probe = probeProcesses) {
268
349
  if (!idPattern.test(id || '')) throw fail('Invalid worker id')
269
350
  const storage = join(dir, '.remote-plugin-center')
270
351
  const lock = join(storage, 'lock.json')
@@ -276,24 +357,42 @@ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node'
276
357
  const manifestPath = join(dir, 'package.json')
277
358
  const disabledPath = join(storage, 'disabled.json')
278
359
  let disabled
279
- const save = () => atomic(jobPath, job)
360
+ const save = () => { job.updatedAt = Date.now(); atomic(jobPath, job) }
361
+ const progress = (stage, message) => { job.stage = stage; job.message = message; save() }
362
+ let heartbeat
280
363
  try {
281
- job.phase = 'running'; save()
364
+ job.phase = 'running'; progress('backup', '正在备份配置文件。')
365
+ heartbeat = setInterval(save, 4000); heartbeat.unref()
282
366
  if (job.revision !== revision(manifestPath)) throw fail('任务开始前 profile 已变化,请刷新后重试')
283
367
  disabled = new Set(existsSync(disabledPath) ? read(disabledPath) : [])
284
368
  const backup = join(storage, 'backup-' + id)
285
369
  mkdirSync(backup, { mode: 0o700 })
286
- for (const name of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.patch.yml']) {
370
+ for (const name of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.patch.yml', 'cordis.yml']) {
287
371
  if (existsSync(join(dir, name))) copyFileSync(join(dir, name), join(backup, name))
288
372
  }
289
373
  if (existsSync(disabledPath)) copyFileSync(disabledPath, join(backup, 'disabled.json'))
374
+ if (job.name === 'dsh-remote-plugin') cpSync(join(dir, 'node_modules', 'dsh-remote-plugin'), join(backup, 'remote-plugin'), { recursive: true, dereference: true })
375
+ progress('profile-lock', '正在检查 DSH 配置锁。')
376
+ const existingLock = await profileLock(dir, probe)
377
+ if (existingLock) {
378
+ if (existingLock.state !== 'dead') throw fail(existingLock.message, 409)
379
+ // No await between final ownership comparison, backup and removal.
380
+ if (!existsSync(existingLock.path) || readFileSync(existingLock.path, 'utf8') !== existingLock.raw) throw fail('DSH 配置锁已变化,请刷新后重试', 409)
381
+ copyFileSync(existingLock.path, join(backup, 'package.json.lock'))
382
+ unlinkSync(existingLock.path)
383
+ job.log += '已备份并回收确认退出的进程遗留的 DSH 配置锁。\n'
384
+ }
385
+ if (job.revision !== revision(manifestPath)) throw fail('检查配置锁期间 profile 已变化,请刷新后重试')
290
386
  if (['install', 'update', 'remove'].includes(job.action)) {
387
+ progress('cli', '正在运行 DSH 插件命令,等待主机输出。')
291
388
  const args = job.action === 'remove' ? ['remove', job.name, '--config.ignore-scripts=true'] : ['add', job.name + '@' + job.version, '--save-exact', '--ignore-scripts', '--registry=' + REGISTRY]
292
389
  await execute(cli, ['plugin', '--profile', basename(dir), ...args], dir, chunk => {
390
+ job.lastOutputAt = Date.now()
293
391
  job.log = (job.log + chunk.replace(/\x1b\[[0-9;]*m/g, '').replace(/(token|password|authorization)\s*[=:]\s*\S+/gi, '$1=[redacted]')).slice(-12000)
294
392
  save()
295
393
  }, pid => atomic(lock, { ...read(lock), cliPid: pid }), cliMode)
296
394
  }
395
+ progress('verify', '正在保存配置并核验插件状态。')
297
396
  if (job.action === 'disable') disabled.add(job.name)
298
397
  if (job.action === 'enable' || job.action === 'remove') disabled.delete(job.name)
299
398
  const manifest = read(manifestPath)
@@ -307,15 +406,16 @@ export async function runWorker(dir, cli, id, execute = runCli, cliMode = 'node'
307
406
  const pkg = read(join(dir, 'node_modules', ...job.name.split('/'), 'package.json'))
308
407
  if (pkg.version !== job.version || !pkg.dsh?.bundle?.patch) throw fail('安装后的包版本或 bundle 校验失败')
309
408
  }
310
- job.phase = 'complete'; job.restartRequired = true
409
+ job.phase = 'complete'; job.stage = 'complete'; job.restartRequired = true
311
410
  job.message = '配置已保存;重启 DSH 后生效。安装脚本未执行。'
312
411
  } catch (error) {
313
412
  job.phase = 'failed'; job.message = String(error.message || error)
314
413
  // A failed package manager may have changed files. Never claim rollback.
315
414
  job.restartRequired = true
316
415
  } finally {
416
+ clearInterval(heartbeat)
317
417
  job.endedAt = Date.now(); save()
318
- if (read(lock).id === id) unlinkSync(lock)
418
+ if (existsSync(lock) && read(lock).id === id) unlinkSync(lock)
319
419
  }
320
420
  }
321
421