dsh-plugin-dingtalk-bridge 0.3.7 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -26,7 +26,7 @@
26
26
  - **Star / Issue 入口**:面板右上角「使用说明」旁边有 **★ Star** 与 **提交 Issue**,说明卡底部也有同样的链接与 npm 入口,方便反馈问题。
27
27
  - **彩色插件图标**:侧边栏与面板标题使用 3D 机器人图标,宿主提供 `GET /icon` 路由,加载失败时回退单色 SVG。
28
28
  - **授权与去重**:默认 `loginMode=loopback`(浏览器授权,**不需要授权码**);`loginReset=true` 时重新授权会先 `dws auth logout --yes` 退出旧组织,只保留本次登录的组织;也支持手动「退出」。
29
- - **dws 自动检测 / 安装 / 更新**:插件启动时只做检测,不会偷偷装东西。如果这台机器没有 `dws`,面板顶部会出现一条提示,点 **安装 dws** 即自动执行 `npm install -g dingtalk-workspace-cli`(含 npm 12 会拦掉的 `install.js` 准备步骤),装完自动重新检测并开始接收;已装的话点 **检查更新** 能看到 npm 上的最新版本,再点 **更新到 vX** 升级。npm 源可用 `dwsRegistry` 换成国内镜像。
29
+ - **dws 自动检测 / 安装 / 更新**:插件启动时只做检测,不会偷偷装东西。如果这台机器没有 `dws`,面板顶部会出现一条提示,点 **安装 dws** 即自动安装:有 npm 时执行 `npm install -g dingtalk-workspace-cli`(含 npm 12 会拦掉的 `install.js` 准备步骤),**没有 npm 时直接下载 npm 包 tarball 解压到插件数据目录**(自带纯 Node 解压器,不依赖系统 tar),两条路径都会自动定位 `vendor/dws.exe`。已装的话点 **检查更新** 能看到最新版本,再点 **更新到 vX** 升级。收件箱提示卡与设置页按钮都能触发,npm 源可用 `dwsRegistry` 换成国内镜像。
30
30
  - **演练模式**:`dryRun=true` 时只预览将发送的内容(`dws --dry-run`),不真正发到钉钉,适合先试跑。
31
31
  - **持久化与自愈**:状态存在 `<DSH_HOME>/integrations/dingtalk-bridge/state.json`(tmp + rename 原子写,mode 0600),图片在 `.../media/`;早于 2020 年或超前一天的时间戳重置为当前时间,旧版 `confirmation_required` 失败记录自动清掉。
32
32
 
@@ -54,11 +54,37 @@
54
54
 
55
55
  ## 前置要求
56
56
 
57
- - DSH `>= 0.2.1-rc.3 < 0.3.0-0`,Node `>= 22.19.0`。
58
- - 本机已安装并登录钉钉工作台 CLI:`dws --version` 能输出版本号(当前验证版本 `1.0.68`)。
57
+ - DSH `>= 0.2.1-rc.3 < 0.3.0-0`,Node `>= 22.19.0`(DSH 自带的 Node 就够用)。
58
+ - **不需要预装 dws**:插件会检测环境,没有 `dws` 时点「安装 dws」即可自动安装(有 npm 走全局安装,**没有 npm 也能装**——直接下载 npm 包解压,并借用 DSH 自带的 Node)。
59
59
  - 首次使用需要一次钉钉授权(面板右上角 **钉钉授权**)。
60
60
 
61
- ## 安装(三步)
61
+ ## 安装(推荐:一句话 / 插件市场)
62
+
63
+ 插件已发布到 npm:`dsh-plugin-dingtalk-bridge`。装法从简到繁三种,任选一种:
64
+
65
+ **方式一 · 让 DSH 自己装(推荐)**
66
+
67
+ 在 DSH 对话框里直接说:
68
+
69
+ > 安装 npm 插件 `dsh-plugin-dingtalk-bridge`,装好后重启
70
+
71
+ 助手会调用 `plugin_manager` 以 npm 包名安装到当前 profile,完成后重启 DSH 即可。
72
+
73
+ **方式二 · 插件市场**
74
+
75
+ DSH → 插件市场(Open Plugin Market)→ 搜索 `dsh-plugin-dingtalk-bridge` 或「钉钉消息自动化」→ 安装 → 重启 DSH。
76
+ (收录申请审核中,暂时搜不到就用方式一。)
77
+
78
+ **方式三 · 手动装 npm 包**
79
+
80
+ ```bash
81
+ npm i -g dsh-plugin-dingtalk-bridge@0.3.9 # 或装到 profile 的 dependencies 里
82
+ ```
83
+
84
+ 然后在 DSH profile 的 `package.json` 的 `dsh.profile.bundles` 里加入 `"dsh-plugin-dingtalk-bridge"`,执行 `pnpm install`,重启 DSH。
85
+
86
+ <details>
87
+ <summary>开发者:从源码目录安装(改代码即时生效)</summary>
62
88
 
63
89
  1. 把插件目录放进本机任意位置,例如 `E:/project/deepseek-tool/dsh-plugin-dingtalk`。
64
90
  2. 在 DSH profile 的 `package.json` 里加 **link 依赖**(不要用 `file:`,`file:` 会复制一份,改源码不生效):
@@ -78,11 +104,16 @@
78
104
 
79
105
  3. 在该 profile 目录执行 `pnpm install --prefer-offline`,然后**重启 DSH**。
80
106
 
107
+ > 注意:npm 版与源码 `link:` 版共用同一个 loader id(`dingtalk-bridge`),**不要同时装**。从源码版切到 npm 版时,先删掉 `link:` 依赖再装。
108
+
109
+ </details>
110
+
81
111
  ## 验证是否装好
82
112
 
83
113
  - 侧边栏出现「钉钉消息」图标,点开后是「钉钉消息自动化」面板。
84
114
  - 设置 → 插件 → 钉钉消息自动化 能看到配置卡片;面板右上角点 **钉钉授权** 能弹出授权框。
85
- - 设置页 **宿主版本** 应与界面版本一致(当前 `0.3.2`);不一致说明宿主代码没重载,重启 DSH。
115
+ - 设置页 **宿主版本** 应与界面版本一致(当前 `0.3.9`);不一致说明宿主代码没重载,重启 DSH。
116
+ - 没装 dws 的机器会看到「未检测到 dws 命令」提示卡,点 **安装 dws** 即可。
86
117
 
87
118
  ## 配置项
88
119
 
@@ -149,7 +180,7 @@
149
180
 
150
181
  | 现象 | 处理 |
151
182
  | --- | --- |
152
- | 点授权报错 `'dws' 不是内部或外部命令` / `spawn dws ENOENT` | 这台机器没装 dws。面板顶部会自动出现提示卡,点 **安装 dws** 即执行 `npm install -g dingtalk-workspace-cli`(含被 npm 12 拦掉的 `install.js` 步骤),装完自动重新检测并开始接收;没有 npm 就先装 Node.js,或把 `dwsPath` 指到已有的 dws 可执行文件。 |
183
+ | 点授权报错 `'dws' 不是内部或外部命令` / `spawn dws ENOENT` | 这台机器没装 dws。点「钉钉授权」时插件会先拦住并提示去安装;在提示卡或设置页点 **安装 dws** 即可:有 npm 走全局安装,**没有 npm 也能装**(直接下载 npm 包解压,自带解压器,并借用 DSH 自带的 Node 跑 `install.js`)。装完自动重新检测并开始接收。 |
153
184
  | 想升级 dws | 点提示卡或设置页的 **检查更新**(只查 npm 上的版本),发现新版后点 **更新到 vX**;npm 源慢就改 `dwsRegistry`(如 `https://registry.npmmirror.com/`)。 |
154
185
  | 点「钉钉授权」后没有二维码 | **默认 loopback 模式本来就没有二维码**——弹框里是授权说明 + **打开钉钉授权页面** 按钮,浏览器会自动弹出授权页;没弹出就点 **复制链接**。只有 `loginMode=device` 才显示二维码。 |
155
186
  | 授权页要求输入授权码 | 说明 `loginMode` 是 `device`(设备流)。改回 `loopback` 并重启 DSH,即浏览器授权、无需授权码。 |
package/client.js CHANGED
@@ -24,7 +24,7 @@ window.__ModuleLoader__.load({
24
24
  const POLL_MS = 5000
25
25
  const SOFT_POLL_MS = 30000
26
26
  // 与 package.json 的 version 保持一致:宿主上报的 build 前缀对不上,说明 DSH 还在跑旧宿主代码。
27
- const CLIENT_BUILD = '0.3.7'
27
+ const CLIENT_BUILD = '0.3.9'
28
28
  // 源码仓库(GitHub):Star 与 Issue 入口都指向这里
29
29
  const REPO_URL = 'https://github.com/gcggcg/dsh-plugin-dingtalk-bridge'
30
30
  const ISSUES_URL = `${REPO_URL}/issues`
@@ -1345,7 +1345,7 @@ window.__ModuleLoader__.load({
1345
1345
  ? String(install.log || tool.error || '安装失败,请查看下面的日志。').slice(0, 600)
1346
1346
  : ready
1347
1347
  ? `更新后会重启监听,登录状态不受影响。安装来源:${source}`
1348
- : `这个插件通过 dws CLI 收发钉钉消息。点「安装 dws」会自动执行 npm install -g dingtalk-workspace-cli(来源:${source}),需要本机已安装 Node.js。`
1348
+ : `这个插件通过 dws CLI 收发钉钉消息。点「安装 dws」会自动安装 dingtalk-workspace-cli(来源:${source}):有 npm 时走全局安装,没有 npm 时直接下载安装包解压到插件数据目录,全程无需你手动配置。`
1349
1349
 
1350
1350
  return h(
1351
1351
  'div',
@@ -2388,6 +2388,11 @@ window.__ModuleLoader__.load({
2388
2388
 
2389
2389
  function SettingsCard() {
2390
2390
  const { state, error } = useBridge()
2391
+ const [installBusy, setInstallBusy] = useState('')
2392
+ const install = (state && state.install) || null
2393
+ const installStatus = (install && install.status) || 'unknown'
2394
+ const installUpdate = install && install.updateAvailable ? install.latestVersion : ''
2395
+ const dwsReady = Boolean(state && state.tool && state.tool.ok)
2391
2396
  const summary = listenerSummary(state)
2392
2397
  const model = (state && state.model) || null
2393
2398
  const modelText =
@@ -2471,12 +2476,20 @@ window.__ModuleLoader__.load({
2471
2476
  : state.install.status === 'installing'
2472
2477
  ? `安装中(${state.install.targetVersion ? `v${state.install.targetVersion},` : ''}${state.install.source || '...'})`
2473
2478
  : state.install.status === 'missing'
2474
- ? '未安装(可点上方「安装 dws」自动安装)'
2479
+ ? '未安装(可点上方「安装 dws」自动安装,没有 npm 也能装)'
2475
2480
  : state.install.status === 'error'
2476
2481
  ? '安装 / 更新失败(可查看日志后重试)'
2477
2482
  : '检测中'
2478
2483
  : '—',
2479
2484
  ],
2485
+ [
2486
+ '安装方式',
2487
+ state && state.install && state.install.mode
2488
+ ? state.install.mode === 'tarball'
2489
+ ? '免 npm(直接下载安装包解压)'
2490
+ : 'npm 全局安装'
2491
+ : '—',
2492
+ ],
2480
2493
  [
2481
2494
  'npm 安装源',
2482
2495
  state && state.install && state.install.source ? state.install.source : 'https://registry.npmjs.org/',
@@ -2537,6 +2550,51 @@ window.__ModuleLoader__.load({
2537
2550
  state && Array.isArray(state.profiles) && state.profiles.length > 0
2538
2551
  ? h(Button, { size: 'sm', onClick: () => postAction({ type: 'logout' }) }, '退出钉钉登录')
2539
2552
  : null,
2553
+ dwsReady
2554
+ ? null
2555
+ : h(
2556
+ Button,
2557
+ {
2558
+ size: 'sm',
2559
+ variant: 'primary',
2560
+ disabled: installBusy === 'install-dws' || installStatus === 'installing',
2561
+ onClick: () => {
2562
+ setInstallBusy('install-dws')
2563
+ Promise.resolve(postAction({ type: 'install-dws' })).finally(() => setInstallBusy(''))
2564
+ },
2565
+ title: '自动安装 dws(优先用 npm;没有 npm 时直接下载安装包解压)',
2566
+ },
2567
+ installStatus === 'installing' ? '安装中…' : '安装 dws',
2568
+ ),
2569
+ installUpdate
2570
+ ? h(
2571
+ Button,
2572
+ {
2573
+ size: 'sm',
2574
+ variant: 'primary',
2575
+ disabled: installBusy === 'update-dws' || installStatus === 'installing',
2576
+ onClick: () => {
2577
+ setInstallBusy('update-dws')
2578
+ Promise.resolve(postAction({ type: 'update-dws' })).finally(() => setInstallBusy(''))
2579
+ },
2580
+ title: `更新到 v${installUpdate}`,
2581
+ },
2582
+ installBusy === 'update-dws' ? '更新中…' : `更新到 v${installUpdate}`,
2583
+ )
2584
+ : null,
2585
+ h(
2586
+ Button,
2587
+ {
2588
+ size: 'sm',
2589
+ disabled: installBusy === 'check-dws-update' || installStatus === 'installing',
2590
+ onClick: () => {
2591
+ setInstallBusy('check-dws-update')
2592
+ Promise.resolve(postAction({ type: 'check-dws-update' })).finally(() => setInstallBusy(''))
2593
+ },
2594
+ title: '查询 npm 源上的最新 dws 版本',
2595
+ },
2596
+ installBusy === 'check-dws-update' ? '检查中…' : '检查 dws 更新',
2597
+ ),
2540
2598
  h(Button, { size: 'sm', onClick: () => postAction({ type: 'refresh' }) }, '刷新状态'),
2541
2599
  h(Button, { size: 'sm', onClick: () => postAction({ type: 'restart-listeners' }) }, '重启监听'),
2542
2600
  ),
Binary file
@@ -43,35 +43,69 @@
43
43
 
44
44
  ### 1.1 前置检查
45
45
 
46
- 在终端依次确认三件事,全部通过再安装插件。
46
+ 插件已发布到 npm(`dsh-plugin-dingtalk-bridge`),**普通使用只需要三件事**:
47
+
48
+ | 检查项 | 要求 | 不满足怎么办 |
49
+ | --- | --- | --- |
50
+ | DSH 版本 | `>= 0.2.1-rc.3 < 0.3.0-0` | 升级 DSH |
51
+ | Node | `>= 22.19.0`(DSH 自带的就够) | 一般无需单独安装 |
52
+ | dws | **可以不装** | 装好插件后在面板里点 **安装 dws**,插件会自动装(没有 npm 也能装) |
53
+
54
+ 也就是说,**不需要事先在终端里 `npm i -g dingtalk-workspace-cli`,也不需要自己配 `dwsPath`**。只有想手动排障时,才需要下面这些命令:
47
55
 
48
56
  ```bash
49
57
  # 1) Node 版本(要求 >= 22.19.0)
50
58
  node -v
51
59
 
52
- # 2) dws 是否可用(要求已 npm i -g dingtalk-workspace-cli)
60
+ # 2) dws 是否可用(插件会自动安装,这里只是自查)
53
61
  dws --version
54
62
 
55
- # 3) 是否已有可用登录态
63
+ # 3) 是否已有可用登录态(没有就在面板里点「钉钉授权」)
56
64
  dws profile list -f json
57
65
  ```
58
66
 
59
- `dws profile list -f json` 会输出 `currentProfile` 与 `profiles` 数组;每个 profile 形如 `corpId:userId`,并带 `corpName`、`userName`、`status` 字段。**至少要有一个 `status` 为 `active` 的组织**。
67
+ `dws profile list -f json` 会输出 `currentProfile` 与 `profiles` 数组;每个 profile 形如 `corpId:userId`,并带 `corpName`、`userName`、`status` 字段。
60
68
 
61
- 若没有任何 profile:
69
+ 若没有任何 profile,可以直接在面板里点 **钉钉授权**(推荐,默认 `loginMode=loopback`,弹框自动打开浏览器授权页,本机 `127.0.0.1:<port>/callback` 回调,**不需要授权码、不显示二维码**;远程环境把 `loginMode` 改成 `device` 才显示二维码 + 授权码)。详见 [第 8 节](#8-钉钉授权登录)。
70
+
71
+ 也可以在终端手动授权:
62
72
 
63
73
  ```bash
64
- # 本机浏览器授权(推荐,桌面环境):自动打开授权页,扫码或账号密码登录即可,不需要授权码
74
+ # 本机浏览器授权(推荐,桌面环境)
65
75
  dws auth login --no-browser --yes
66
76
 
67
77
  # 设备流授权:终端打印授权码 + 链接,适合没有图形界面的远程环境
68
78
  dws auth login --device --no-browser
69
79
  ```
70
80
 
71
- > 也可以先装好插件,再在收件箱面板右上角点 **钉钉授权** 完成同样的授权:默认 `loginMode=loopback`,弹框会自动打开浏览器授权页(本机 `127.0.0.1:<port>/callback` 回调),**全程不需要授权码、不显示二维码**;远程环境把 `loginMode` 改成 `device` 才会显示二维码 + 授权码。详见 [第 8 节](#8-钉钉授权登录)。
72
-
73
81
  ### 1.2 安装插件
74
82
 
83
+ 三种装法,从简到繁任选一种,**都不需要手工改配置文件**。
84
+
85
+ #### 方式一 · 让 DSH 自己装(推荐)
86
+
87
+ 在 DSH 对话框里直接说:
88
+
89
+ > 安装 npm 插件 `dsh-plugin-dingtalk-bridge`,装好后重启
90
+
91
+ 助手会用 `plugin_manager` 把 npm 包装进当前 profile,然后重启 DSH 即可。
92
+
93
+ #### 方式二 · 插件市场
94
+
95
+ DSH → **插件市场**(Open Plugin Market)→ 搜索 `dsh-plugin-dingtalk-bridge` 或「钉钉消息自动化」→ **安装** → 重启 DSH。
96
+ (收录申请审核中,暂时搜不到就用方式一。)
97
+
98
+ #### 方式三 · 手动装 npm 包
99
+
100
+ ```bash
101
+ npm i -g dsh-plugin-dingtalk-bridge@0.3.9
102
+ ```
103
+
104
+ 或者把 `"dsh-plugin-dingtalk-bridge": "^0.3.9"` 加进 DSH profile 的 `dependencies`、并把包名追加到 `dsh.profile.bundles`,然后 `pnpm install`,最后**完全退出 DSH 再启动**。
105
+
106
+ <details>
107
+ <summary><b>开发者:从源码目录安装(改代码即时生效)</b></summary>
108
+
75
109
  1. **放好目录**。把插件目录放到任意位置(示例:`E:/project/deepseek-tool/dsh-plugin-dingtalk`)。
76
110
  2. **登记到 DSH profile**。编辑 `<DSH_HOME>/profiles/<profile>/package.json`:
77
111
  - `dependencies` 里加 **`link:`** 依赖;
@@ -100,14 +134,12 @@ dws auth login --device --no-browser
100
134
  >
101
135
  > 两种协议都要**重启 DSH**(完全退出进程再启动),仅刷新页面不够。
102
136
 
103
- 3. **安装依赖**:在 profile 目录执行
137
+ 3. **安装依赖**:在 profile 目录执行 `pnpm install`。
138
+ 4. **重启 DSH**:完全退出 DSH 再启动,改动才会生效(仅刷新页面不够)。
104
139
 
105
- ```bash
106
- pnpm install
107
- ```
140
+ > npm 版与源码 `link:` 版共用同一个 loader id(`dingtalk-bridge`),**不要同时装**;从源码版切到 npm 版时先删掉 `link:` 依赖。
108
141
 
109
- 4. **重启 DSH**:完全退出 DSH 再启动,改动才会生效(仅刷新页面不够)。
110
- 5. **完成授权**:打开收件箱面板,点右上角 **钉钉授权**,弹框会自动打开浏览器授权页,扫码或账号密码登录即可完成(默认 loopback,不需要授权码,详见 [第 8 节](#8-钉钉授权登录))。已经有 `dws auth login` 登录态的可跳过这一步。
142
+ </details>
111
143
 
112
144
  ### 1.3 确认插件已加载
113
145
 
@@ -125,7 +157,7 @@ dws auth login --device --no-browser
125
157
  | 状态文案 | 含义 | 处理 |
126
158
  | --- | --- | --- |
127
159
  | **插件已禁用** | `enabled` 为 `false` | 到「设置 → 插件」启用后重启 DSH |
128
- | **dws 未就绪** | `dws --version` 失败,或没有登录态(详情为 dws 返回的错误与「尚未登录钉钉」提示) | 未登录先点 **钉钉授权**([第 8 节](#8-钉钉授权登录));其余见 [10.1](#101-顶部显示dws-未就绪) |
160
+ | **dws 未就绪** | `dws --version` 失败,或没有登录态(详情为 dws 返回的错误与「尚未登录钉钉」提示) | 没装 dws 时面板顶部会有「未检测到 dws 命令」提示卡,先点 **安装 dws**;已装则点 **钉钉授权**([第 8 节](#8-钉钉授权登录));其余见 [10.1](#101-顶部显示dws-未就绪) |
129
161
  | **正在连接钉钉…** | 监听进程已启动、还没就绪 | 等几秒;长期停留见 [10.2](#102-顶部显示监听异常或一直正在连接钉钉) |
130
162
  | **监听异常** | 监听进程报错或已退出 | 点右上角 **重启监听**;仍有问题见 [10.2](#102-顶部显示监听异常或一直正在连接钉钉) |
131
163
 
@@ -137,7 +169,7 @@ dws auth login --device --no-browser
137
169
  2. 首次打开时列表可能是三块灰色骨架屏,表示正在拉取状态;服务连不上会显示 **无法连接插件服务**。
138
170
  3. 如果顶部显示 **dws 未就绪**、右上角 **钉钉授权** 是蓝色主按钮,先点它完成授权([第 8 节](#8-钉钉授权登录)):弹框会说明「在浏览器里完成一次授权」并自动打开授权页,扫码或账号密码登录即可(默认 loopback,不用授权码);授权成功后弹框自动关闭,状态变成 **实时监听中 · N 个组织**。
139
171
  4. 空收件箱显示 **还没有收到消息**,说明为:*保持页面打开即可。当有人给你发钉钉私信或在群里 @ 你时,消息会实时出现在这里。*
140
- 5. 建议先点右上角 **使用说明** 看一遍内置的六条速查(接收 / 消息源 / 自动回复开关 / 阴影建议 / 快捷键 / 发送通道),再按第 2 节熟悉布局。
172
+ 5. 建议先点右上角 **使用说明** 看一遍内置速查(授权 / 接收 / 消息源 / 自动回复开关 / 阈值 / 匹配度 / 图片 / 上下文 / 阴影建议 / 快捷键 / 发送通道 / dws 环境等),再按第 2 节熟悉布局。
141
173
 
142
174
  ---
143
175
 
@@ -1289,7 +1321,7 @@ dws 版本 1.0.68
1289
1321
  | `dryRun` | boolean | `false` | — | 演练模式:只 `--dry-run` 预览发送内容,不真正发到钉钉 |
1290
1322
  | `loginMode` | string | `"loopback"` | `loopback` / `device` | 授权方式。`loopback` 用本机浏览器授权(`dws auth login --no-browser --yes`,不需要授权码、不显示二维码);`device` 用设备流(`dws auth login --device --no-browser`,显示二维码 + 授权码,适合无浏览器的远程环境)。见[第 8 章](#8-钉钉授权登录) |
1291
1323
  | `loginReset` | boolean | `true` | `true` / `false` | 重新授权前先退出已登录的组织(`dws auth logout --yes`),只保留本次新授权的组织。关闭后新组织会追加,组织数量只增不减。见 [8.2.3](#823-重新授权与退出登录) |
1292
- | `dwsRegistry` | string | `"https://registry.npmjs.org/"` | — | 自动安装 / 更新 dws 时使用的 npm 源,只在点「安装 dws」「更新 dws」时生效;国内可换 `https://registry.npmmirror.com/`。见 [10.0](#100-dws-没安装--想升级036) |
1324
+ | `dwsRegistry` | string | `"https://registry.npmjs.org/"` | — | 自动安装 / 更新 dws 时使用的 npm 源,只在点「安装 dws」「更新 dws」时生效;国内可换 `https://registry.npmmirror.com/`。见 [10.0](#100-dws-没安装--想升级036-起支持免-npm) |
1293
1325
 
1294
1326
  模型选择优先级:
1295
1327
 
@@ -1328,28 +1360,34 @@ dws 版本 1.0.68
1328
1360
 
1329
1361
  ## 10. FAQ / 排障
1330
1362
 
1331
- ### 10.0 dws 没安装 / 想升级(0.3.6)
1363
+ ### 10.0 dws 没安装 / 想升级(0.3.6 起支持免 npm)
1332
1364
 
1333
1365
  插件通过 `dws` CLI 收发钉钉消息。**换一台没装 dws 的机器时,面板顶部会出现一条提示卡**,不用去命令行折腾:
1334
1366
 
1335
1367
  | 情形 | 面板表现 | 点哪里 |
1336
1368
  | --- | --- | --- |
1337
- | 本机没有 `dws` 命令 | 提示卡「未检测到 dws 命令」,附当前 `dwsPath` 与 npm 源 | **安装 dws** → 自动执行 `npm install -g dingtalk-workspace-cli` |
1338
- | 正在安装 | 提示卡变蓝色「正在安装 dws vX…」 | 等 10~60 秒,装完自动重新检测并开始接收 |
1339
- | 装完仍不可用 | 提示卡变红色「dws 安装 / 更新失败」+ 折叠日志 | 展开 **查看完整日志**,多数是网络 / 权限 / 没有 npm |
1369
+ | 本机没有 `dws` 命令 | 提示卡「未检测到 dws 命令」,附当前 `dwsPath` 与 npm 源 | **安装 dws** → 有 npm 走全局安装,没有 npm 直接下载安装包解压 |
1370
+ | 正在安装 | 提示卡变蓝色「正在安装 dws vX…」 | 等 10~120 秒(免 npm 方式要下整包),装完自动重新检测并开始接收 |
1371
+ | 装完仍不可用 | 提示卡变红色「dws 安装 / 更新失败」+ 折叠日志 | 展开 **查看完整日志**,多数是网络 / 权限问题 |
1340
1372
  | 已安装,npm 上有新版 | 提示卡「发现新版本 dws vY(当前 vX)」 | **更新到 vY**(会先弹确认框,更新后重启监听,登录态不受影响) |
1341
- | 已是最新 | 提示卡不显示 | 想手动再查一次就去设置页点 **检查更新** |
1373
+ | 已是最新 | 提示卡不显示 | 想手动再查一次就去设置页点 **检查 dws 更新** |
1342
1374
 
1343
1375
  ![dws 未安装时的提示卡](images/dws-install.png)
1344
1376
 
1377
+ **两处都能装**:收件箱顶部的提示卡,以及 **设置 → 插件配置 → 底部按钮区**(「安装 dws」「检查 dws 更新」「更新到 vX」)。没装 dws 时点「钉钉授权」不会再去执行命令报错,而是直接提示「请先安装 dws」。
1378
+
1345
1379
  实现要点(便于排障时对照):
1346
1380
 
1347
1381
  - 插件**启动时只检测、不安装**;`dws --version` 能读出 `x.y.z` 才算就绪,报错文本命中「不是内部或外部命令 / ENOENT / command not found」才判定为「未安装」。
1348
- - 安装命令固定为 `npm install -g dingtalk-workspace-cli[@版本] --no-fund --no-audit --registry=<dwsRegistry>`;npm 依次尝试 `npm_execpath` → Node 同目录的 `npm.cmd` → PATH 里的 `npm`。
1349
- - npm 12 默认会拦掉依赖的 `postinstall`,插件会在装完后手动跑一次包内的 `install.js`(`DWS_NO_SKILLS=1`),再用 `npm root -g` 找到 `vendor/dws.exe` 并自动把 `dwsPath` 指过去。
1382
+ - **两条安装路径**:
1383
+ 1. **有 npm**:`npm install -g dingtalk-workspace-cli[@版本] --no-fund --no-audit --registry=<dwsRegistry>`;npm 依次尝试 `npm_execpath` → Node 同目录的 `npm.cmd` → `Program Files / Program Files (x86) / %APPDATA% / %LOCALAPPDATA%` 下的 `npm.cmd`(Linux/macOS 还有 `/usr/local/bin`、`/opt/homebrew/bin`、`/usr/bin`)→ PATH。
1384
+ 2. **没有 npm**(或 npm 安装失败):直接从 `dwsRegistry` 下载 npm 包 tarball,用插件内置的纯 Node 解压器(`src/host/dws-tar.js`,不依赖系统 tar / npm)解到 `<DSH_HOME>/integrations/dingtalk-bridge/dws-runtime/node_modules/dingtalk-workspace-cli`,再用 Node 跑包内 `install.js`。`dingtalk-workspace-cli` 自身**没有任何运行时依赖**,所以直装完全可行。
1385
+ - 找 node 的顺序:插件自己(Node 启动时)→ `<DSH_HOME>/dsh-runtimes/*/dependencies/node/bin/node`(DSH 自带的 Node)→ PATH 里的 `node`。因此**新机器上既没装 Node 也没装 npm,也能装上 dws**。
1386
+ - npm 12 默认会拦掉依赖的 `postinstall`,所以两条路径都会在装完后手动跑一次包内 `install.js`(`DWS_NO_SKILLS=1`),再定位 `vendor/dws.exe` 并自动把 `dwsPath` 指过去。
1350
1387
  - 「检查更新」只发一次 `GET <registry>/dingtalk-workspace-cli/latest`(10 秒超时),不下载任何东西。
1351
- - 想换国内镜像:配置项 `dwsRegistry` 改成 `https://registry.npmmirror.com/`。
1352
- - 安装成功后插件会把 `vendor/dws.exe` 的绝对路径写进 `state.json`,**重启后自动沿用**(前提是你没有在配置里显式指定 `dwsPath`),所以即使 npm 全局目录不在 PATH 里也能一直用。
1388
+ - 想换国内镜像:配置项 `dwsRegistry` 改成 `https://registry.npmmirror.com/`(两条安装路径都会用它)。
1389
+ - 安装成功后插件会把 `vendor/dws.exe` 的绝对路径写进 `state.json`,**重启后自动沿用**(前提是你没有在配置里显式指定 `dwsPath`),所以即使安装目录不在 PATH 里也能一直用。
1390
+ - 设置页「安装方式」一行会显示本次用的是 **npm 全局安装** 还是 **免 npm(直接下载安装包解压)**。
1353
1391
 
1354
1392
  ### 10.1 顶部显示「dws 未就绪」
1355
1393
 
@@ -1791,7 +1829,7 @@ dws chat +messages-send --as user --group cidAbCdEf123456= --text "收到,下
1791
1829
  | `remove` | `id` | 删除单条消息 |
1792
1830
  | `restart-listeners` | — | 重新检测 dws 并重建全部监听 |
1793
1831
  | `refresh` | — | 重新读取账号与 profile 列表 |
1794
- | `install-dws` | `version`(可选,空则装 latest) | 执行 `npm install -g dingtalk-workspace-cli[@版本]`,补跑包内 `install.js`,成功后自动重新检测、刷新组织并重启监听。见 [10.0](#100-dws-没安装--想升级036) |
1832
+ | `install-dws` | `version`(可选,空则装 latest) | 安装 `dingtalk-workspace-cli[@版本]`:有 npm 走全局安装,没有 npm(或 npm 失败)自动改为下载 tarball 解压到插件数据目录;两条路径都会补跑包内 `install.js`,成功后自动重新检测、刷新组织并重启监听。见 [10.0](#100-dws-没安装--想升级036-起支持免-npm-起支持免-npm) |
1795
1833
  | `check-dws-update` | — | 只查 npm 上的最新版本(`GET <dwsRegistry>/dingtalk-workspace-cli/latest`,10 秒超时),不下载任何东西 |
1796
1834
  | `update-dws` | — | 先查最新版本,再按该版本执行安装(等价 `install-dws` + 版本号) |
1797
1835
 
@@ -1828,7 +1866,7 @@ dws chat +messages-send --as user --group cidAbCdEf123456= --text "收到,下
1828
1866
  | `build` | string | 宿主代码编译标记(如 `0.2.9-20261117T0940`),设置页「宿主版本」显示它;与界面版本不一致时面板头部会多一个 **宿主待重启** 徽标 |
1829
1867
  | `requests` | `Array<{ at, method, path, status, detail }>` | 最近 8 条 API 请求,便于排查写操作被拦、阈值没保存之类的问题 |
1830
1868
  | `lastError` | string | 最近一次失败请求的摘要,如 `POST /api/dingtalk-bridge/action → 403` |
1831
- | `install` | `{ status, currentVersion, latestVersion, updateAvailable, targetVersion, source, log, latestError, checkedAt }` | dws 安装/更新状态:`status` 为 `unknown` / `ready` / `missing` / `installing` / `error`;`currentVersion` 当前版本、`latestVersion` npm 上最新版本、`updateAvailable` 是否可升级、`targetVersion` 本次安装目标、`source` 使用的 npm 源、`log` 安装日志(失败时界面可展开查看)、`latestError` 查询最新版本失败的原因。见 [10.0](#100-dws-没安装--想升级036) |
1869
+ | `install` | object | dws 安装 / 更新状态:`status`(`unknown`/`missing`/`installing`/`ready`/`error`)、`mode`(`npm` 或 `tarball`)、`currentVersion`、`latestVersion`、`updateAvailable`、`targetVersion`、`source`(npm 源)、`log`(失败日志尾部)、`latestError`、`checkedAt`。见 [10.0](#100-dws-没安装--想升级036-起支持免-npm) |
1832
1870
 
1833
1871
  ### 12.3 关键常量
1834
1872
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-dingtalk-bridge",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "钉钉私信 / 群 @ 消息实时接收、按发送人记录来源、AI 建议回复与自动回复插件",
@@ -0,0 +1,122 @@
1
+ import { gunzipSync } from 'node:zlib'
2
+ import { mkdir, writeFile } from 'node:fs/promises'
3
+ import { dirname, join, normalize, sep } from 'node:path'
4
+
5
+ const BLOCK = 512
6
+
7
+ function readString(buffer, offset, length) {
8
+ const slice = buffer.subarray(offset, offset + length)
9
+ const end = slice.indexOf(0)
10
+ return (end === -1 ? slice : slice.subarray(0, end)).toString('utf8')
11
+ }
12
+
13
+ function readOctal(buffer, offset, length) {
14
+ const text = readString(buffer, offset, length).trim()
15
+ if (text === '') return 0
16
+ const value = Number.parseInt(text, 8)
17
+ return Number.isFinite(value) ? value : 0
18
+ }
19
+
20
+ // pax 扩展头里每条记录是 "<长度> key=value\n",这里只关心 path / linkpath。
21
+ function parsePax(data) {
22
+ const out = {}
23
+ let index = 0
24
+ while (index < data.length) {
25
+ const space = data.indexOf(0x20, index)
26
+ if (space === -1) break
27
+ const length = Number.parseInt(data.subarray(index, space).toString('utf8'), 10)
28
+ if (!Number.isFinite(length) || length <= 0) break
29
+ const record = data.subarray(space + 1, index + length - 1).toString('utf8')
30
+ const equals = record.indexOf('=')
31
+ if (equals > 0) out[record.slice(0, equals)] = record.slice(equals + 1)
32
+ index += length
33
+ }
34
+ return out
35
+ }
36
+
37
+ // 统一用 POSIX 分隔符处理(Windows 的 normalize 会把 / 变成 \,那样就剥不掉 package/ 前缀了)。
38
+ // 含 `..` 的路径一律拒绝:正常的 npm tarball 不会有,出现就说明包被动过。
39
+ function safeRelativePath(raw) {
40
+ const cleaned = String(raw).replace(/\\/g, '/')
41
+ const parts = cleaned.split('/')
42
+ if (parts.includes('..')) throw new Error(`压缩包里有非法路径:${raw}`)
43
+ const trimmed = parts.filter((part) => part !== '' && part !== '.')
44
+ return trimmed.join('/')
45
+ }
46
+
47
+ /**
48
+ * 解压 npm 包 tarball(.tgz)到 destDir。纯 Node 实现,不依赖 npm / tar。
49
+ * npm 包里的顶层目录通常是 `package/`,这里会把 `package/` 前缀剥掉,
50
+ * 让调用方拿到 `<destDir>/package.json`、`<destDir>/install.js` 这样的结构。
51
+ */
52
+ export async function extractTarGz(buffer, destDir) {
53
+ const tar = gunzipSync(buffer)
54
+ let offset = 0
55
+ let pendingPath = ''
56
+ let pendingLink = ''
57
+ let longName = ''
58
+ const written = []
59
+
60
+ while (offset + BLOCK <= tar.length) {
61
+ const header = tar.subarray(offset, offset + BLOCK)
62
+ if (header.every((byte) => byte === 0)) break
63
+
64
+ const type = String.fromCharCode(header[156] || 0x30)
65
+ const size = readOctal(header, 124, 12)
66
+ const name = readString(header, 0, 100)
67
+ const prefix = readString(header, 345, 155)
68
+ const dataStart = offset + BLOCK
69
+ const data = tar.subarray(dataStart, dataStart + size)
70
+ const next = dataStart + Math.ceil(size / BLOCK) * BLOCK
71
+
72
+ if (type === 'x') {
73
+ const pax = parsePax(data)
74
+ if (pax.path) pendingPath = pax.path
75
+ if (pax.linkpath) pendingLink = pax.linkpath
76
+ offset = next
77
+ continue
78
+ }
79
+ if (type === 'g' || type === 'L') {
80
+ if (type === 'L') longName = readString(data, 0, data.length)
81
+ offset = next
82
+ continue
83
+ }
84
+
85
+ const rawName = longName || pendingPath || (prefix ? `${prefix}/${name}` : name)
86
+ longName = ''
87
+ pendingPath = ''
88
+ pendingLink = ''
89
+
90
+ const relative = safeRelativePath(rawName)
91
+ offset = next
92
+ if (relative === '') continue
93
+
94
+ const withoutPackage = relative.startsWith('package/') ? relative.slice('package/'.length) : relative
95
+ if (withoutPackage === '') continue
96
+ const target = join(destDir, ...withoutPackage.split('/'))
97
+
98
+ if (type === '5') {
99
+ await mkdir(target, { recursive: true })
100
+ continue
101
+ }
102
+ if (type !== '0' && type !== '\u0000' && type !== '7') continue
103
+
104
+ await mkdir(dirname(target), { recursive: true })
105
+ // 保持可执行位,install.js / bin 脚本才能直接跑。
106
+ const mode = readOctal(header, 100, 8)
107
+ await writeFile(target, data, { mode: mode > 0 ? mode : 0o644 })
108
+ written.push(withoutPackage)
109
+ }
110
+
111
+ return written
112
+ }
113
+
114
+ /** 从 npm registry 的元数据里挑出 tarball 地址。 */
115
+ export function tarballUrl(meta, fallbackName = 'dingtalk-workspace-cli') {
116
+ if (!meta || typeof meta !== 'object') return ''
117
+ const version = typeof meta.version === 'string' ? meta.version : ''
118
+ const dist = meta.dist && typeof meta.dist === 'object' ? meta.dist : null
119
+ if (dist && typeof dist.tarball === 'string' && dist.tarball !== '') return dist.tarball
120
+ if (version === '') return ''
121
+ return `https://registry.npmjs.org/${fallbackName}/-/${fallbackName}-${version}.tgz`
122
+ }
@@ -1,4 +1,4 @@
1
- import { readFile, writeFile, rename, mkdir, unlink, appendFile } from 'node:fs/promises'
1
+ import { readFile, writeFile, rename, mkdir, unlink, appendFile, readdir, rm } from 'node:fs/promises'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { homedir } from 'node:os'
4
4
  import { join, dirname } from 'node:path'
@@ -15,12 +15,13 @@ import {
15
15
  createLineReader,
16
16
  } from './dws.js'
17
17
  import QRCode from 'qrcode'
18
+ import { extractTarGz, tarballUrl } from './dws-tar.js'
18
19
 
19
20
  import { buildSuggestPrompt, generateSuggestion, formatClock } from './suggest.js'
20
21
 
21
22
  export const ROUTE_PREFIX = '/api/dingtalk-bridge'
22
23
  /** 每次改动宿主行为就换个标记:界面与 http-debug.log 都会带上,用来确认「跑的是新代码」。 */
23
- export const HOST_BUILD = '0.3.7-20261117T1445'
24
+ export const HOST_BUILD = '0.3.9-20261117T1615'
24
25
 
25
26
  /** 私信(单聊)全部消息。 */
26
27
  const O2O_KEY = 'user_im_message_receive_o2o_all'
@@ -357,12 +358,9 @@ export class DingTalkBridgeService {
357
358
  loginReset: asBool(config.loginReset, true),
358
359
  }
359
360
 
360
- this.statePath = join(
361
- process.env.DSH_HOME && process.env.DSH_HOME.trim() !== '' ? process.env.DSH_HOME : join(homedir(), '.dsh'),
362
- 'integrations',
363
- 'dingtalk-bridge',
364
- 'state.json',
365
- )
361
+ this.dshHomePath =
362
+ process.env.DSH_HOME && process.env.DSH_HOME.trim() !== '' ? process.env.DSH_HOME : join(homedir(), '.dsh')
363
+ this.statePath = join(this.dshHomePath, 'integrations', 'dingtalk-bridge', 'state.json')
366
364
 
367
365
  this.state = {
368
366
  autoReply: this.config.autoReply,
@@ -379,6 +377,7 @@ export class DingTalkBridgeService {
379
377
  // dws 的安装/更新状态:只有用户点「安装 dws」「更新 dws」才会真的执行 npm 命令。
380
378
  this.install = {
381
379
  status: 'unknown',
380
+ mode: '',
382
381
  currentVersion: '',
383
382
  latestVersion: '',
384
383
  updateAvailable: false,
@@ -554,7 +553,7 @@ export class DingTalkBridgeService {
554
553
  }
555
554
  }
556
555
 
557
- /** 依次尝试 npm_execpath、node 同目录的 npm、PATH 里的 npm。 */
556
+ /** 依次尝试 npm_execpath、node 同目录的 npm、PATH 里的 npm、常见安装目录。 */
558
557
  async findNpm() {
559
558
  const candidates = []
560
559
  const execPath = String(process.env.npm_execpath ?? '').trim()
@@ -562,8 +561,13 @@ export class DingTalkBridgeService {
562
561
  const nodeDir = dirname(process.execPath)
563
562
  if (process.platform === 'win32') {
564
563
  candidates.push(join(nodeDir, 'npm.cmd'))
564
+ candidates.push(join(process.env.ProgramFiles ?? 'C:\\Program Files', 'nodejs', 'npm.cmd'))
565
+ candidates.push(join(process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)', 'nodejs', 'npm.cmd'))
566
+ if (process.env.APPDATA) candidates.push(join(process.env.APPDATA, 'npm', 'npm.cmd'))
567
+ if (process.env.LOCALAPPDATA) candidates.push(join(process.env.LOCALAPPDATA, 'Programs', 'nodejs', 'npm.cmd'))
565
568
  } else {
566
569
  candidates.push(join(nodeDir, 'bin', 'npm'), join(nodeDir, 'npm'))
570
+ candidates.push('/usr/local/bin/npm', '/opt/homebrew/bin/npm', '/usr/bin/npm')
567
571
  }
568
572
  candidates.push('npm')
569
573
  for (const candidate of candidates) {
@@ -575,6 +579,37 @@ export class DingTalkBridgeService {
575
579
  return ''
576
580
  }
577
581
 
582
+ /** 找一个能跑 install.js 的 node:优先自己(node 启动时),其次 DSH 自带的 node,最后 PATH。 */
583
+ async findNode() {
584
+ const candidates = []
585
+ if (process.versions && process.versions.node && !process.versions.electron) candidates.push(process.execPath)
586
+ const runtimeRoot = join(this.dshHome(), 'dsh-runtimes')
587
+ try {
588
+ const entries = await readdir(runtimeRoot, { withFileTypes: true })
589
+ for (const entry of entries) {
590
+ if (!entry.isDirectory()) continue
591
+ const base = join(runtimeRoot, entry.name, 'dependencies', 'node')
592
+ candidates.push(join(base, 'bin', process.platform === 'win32' ? 'node.exe' : 'node'))
593
+ candidates.push(join(base, process.platform === 'win32' ? 'node.exe' : 'node'))
594
+ }
595
+ } catch {
596
+ // 没有 dsh-runtimes 目录就跳过。
597
+ }
598
+ if (process.versions && process.versions.node) candidates.push(process.execPath)
599
+ candidates.push('node')
600
+ for (const candidate of candidates) {
601
+ const probe = await runDws(candidate, ['--version'], { timeoutMs: 15_000 })
602
+ if (probe.code === 0 && /v?\d+\.\d+\.\d+/.test(`${probe.stdout}${probe.stderr}`)) return candidate
603
+ }
604
+ return ''
605
+ }
606
+
607
+ /** 不依赖 npm 的安装目录:<state 目录>/dws-runtime/node_modules/dingtalk-workspace-cli。 */
608
+ runtimePackageDir() {
609
+ return join(this.dataDir(), 'dws-runtime', 'node_modules', DWS_PACKAGE)
610
+ }
611
+
612
+
578
613
  /** `npm root -g`:全局 node_modules,用来找安装后的包目录。 */
579
614
  async npmGlobalRoot(npm) {
580
615
  const result = await runDws(npm, ['root', '-g'], { timeoutMs: 20_000 })
@@ -595,17 +630,20 @@ export class DingTalkBridgeService {
595
630
  const registry = this.registry()
596
631
  const npm = await this.findNpm()
597
632
  if (npm === '') {
633
+ // 没有 npm 也能装:直接下 tarball 解压,再用 node 跑包内 install.js。
598
634
  this.setInstall({
599
- status: 'error',
635
+ status: 'installing',
636
+ mode: 'tarball',
600
637
  source: registry,
601
638
  targetVersion: target,
602
- log: '没有找到 npm,无法自动安装 dws。请先安装 Node.js(自带 npm),或在配置项 dwsPath 里填一个已存在的 dws 路径。',
639
+ log: '没有找到 npm,改用免 npm 方式:直接从 npm 源下载安装包并解压。',
603
640
  })
604
- return { ok: false, error: 'npm not found' }
641
+ return this.installFromTarball(target)
605
642
  }
606
643
 
607
644
  this.setInstall({
608
645
  status: 'installing',
646
+ mode: 'npm',
609
647
  source: registry,
610
648
  targetVersion: target,
611
649
  log: `正在执行:${npm} ${buildInstallArgs({ target, registry }).join(' ')}`,
@@ -615,33 +653,18 @@ export class DingTalkBridgeService {
615
653
  const result = await runDws(npm, args, { timeoutMs: INSTALL_TIMEOUT })
616
654
  const output = `${result.stdout}\n${result.stderr}`.trim()
617
655
  if (result.code !== 0) {
656
+ // npm 装失败(权限、网络、被拦的 postinstall…)同样退到免 npm 方式,别让用户卡住。
618
657
  this.setInstall({
619
- status: 'error',
620
- log: output.slice(-INSTALL_LOG_LIMIT) || describeFailure(result),
658
+ status: 'installing',
659
+ mode: 'tarball',
660
+ log: `npm 安装失败,改用免 npm 方式重试。\n\n${output.slice(-1200)}`,
621
661
  })
622
- return { ok: false, error: describeFailure(result) }
662
+ return this.installFromTarball(target)
623
663
  }
624
664
 
625
665
  const root = await this.npmGlobalRoot(npm)
626
666
  const pkgDir = join(root || join(dirname(process.execPath), 'node_modules'), DWS_PACKAGE)
627
- // npm 12 默认会拦掉依赖的 postinstall(钉钉包靠 install.js 准备可执行文件),
628
- // 所以这里手动补跑一次 install.js,否则装完可能仍然找不到可用的 dws。
629
- let postinstallLog = ''
630
- const postinstall = join(pkgDir, 'install.js')
631
- try {
632
- await readFile(postinstall)
633
- const prepared = await runDws(process.execPath, [postinstall], {
634
- cwd: pkgDir,
635
- timeoutMs: 180_000,
636
- env: { ...process.env, DWS_NO_SKILLS: '1' },
637
- })
638
- postinstallLog = `${prepared.stdout}\n${prepared.stderr}`.trim().slice(-1200)
639
- if (prepared.code !== 0) postinstallLog = `install.js 退出码 ${prepared.code}\n${postinstallLog}`
640
- } catch {
641
- // 没有 install.js 说明这个版本不需要准备步骤。
642
- }
643
-
644
- // 有的版本把真正的可执行文件放在 vendor/ 下,优先用它(避免 cmd 垫片再绕一层)。
667
+ const postinstallLog = await this.preparePackage(pkgDir)
645
668
  const vendor = join(pkgDir, 'vendor', process.platform === 'win32' ? 'dws.exe' : 'dws')
646
669
  const installed = await runDws(vendor, ['--version'], { timeoutMs: 20_000 })
647
670
  if (installed.code === 0) this.config.dwsPath = vendor
@@ -657,6 +680,7 @@ export class DingTalkBridgeService {
657
680
 
658
681
  this.setInstall({
659
682
  status: 'ready',
683
+ mode: 'npm',
660
684
  currentVersion: this.tool.version,
661
685
  latestVersion: target.replace(/^v/, '') || this.install.latestVersion,
662
686
  updateAvailable: false,
@@ -664,7 +688,91 @@ export class DingTalkBridgeService {
664
688
  })
665
689
  await this.refreshProfiles()
666
690
  this.startAllListeners()
667
- return { ok: true, version: this.tool.version }
691
+ return { ok: true, version: this.tool.version, mode: 'npm' }
692
+ }
693
+
694
+ /**
695
+ * 跑包内 install.js:npm 12 会拦掉依赖的 postinstall,而 dws 靠这一步把
696
+ * 平台二进制解压到 vendor/。返回日志尾部,便于失败时展示。
697
+ */
698
+ async preparePackage(pkgDir) {
699
+ const postinstall = join(pkgDir, 'install.js')
700
+ try {
701
+ await readFile(postinstall)
702
+ } catch {
703
+ return ''
704
+ }
705
+ const node = await this.findNode()
706
+ if (node === '') return '没有找到可用的 node,无法执行 install.js'
707
+ const prepared = await runDws(node, [postinstall], {
708
+ cwd: pkgDir,
709
+ timeoutMs: 180_000,
710
+ env: { ...process.env, DWS_NO_SKILLS: '1' },
711
+ })
712
+ const log = `${prepared.stdout}\n${prepared.stderr}`.trim().slice(-1200)
713
+ return prepared.code === 0 ? log : `install.js 退出码 ${prepared.code}\n${log}`
714
+ }
715
+
716
+ /** 免 npm 安装:下载 npm 包 tarball → 解压到插件数据目录 → 跑 install.js → 定位 vendor 可执行文件。 */
717
+ async installFromTarball(target) {
718
+ const registry = this.registry().replace(/\/+$/, '')
719
+ const wanted = String(target ?? '').replace(/^v/, '').trim()
720
+ const metaUrl = wanted === '' ? `${registry}/${DWS_PACKAGE}/latest` : `${registry}/${DWS_PACKAGE}/${wanted}`
721
+ try {
722
+ const metaResponse = await fetch(metaUrl, {
723
+ headers: { accept: 'application/json' },
724
+ signal: AbortSignal.timeout(20_000),
725
+ })
726
+ if (!metaResponse.ok) throw new Error(`获取版本信息失败(HTTP ${metaResponse.status})`)
727
+ const meta = await metaResponse.json()
728
+ const url = tarballUrl(meta, DWS_PACKAGE)
729
+ const version = String(meta?.version ?? wanted ?? '')
730
+ if (url === '') throw new Error('版本信息里没有安装包地址')
731
+
732
+ const response = await fetch(url, { signal: AbortSignal.timeout(180_000) })
733
+ if (!response.ok) throw new Error(`下载安装包失败(HTTP ${response.status})`)
734
+ const buffer = Buffer.from(await response.arrayBuffer())
735
+
736
+ const pkgDir = this.runtimePackageDir()
737
+ await rm(pkgDir, { recursive: true, force: true })
738
+ await mkdir(pkgDir, { recursive: true })
739
+ const files = await extractTarGz(buffer, pkgDir)
740
+
741
+ const postinstallLog = await this.preparePackage(pkgDir)
742
+ const vendor = join(pkgDir, 'vendor', process.platform === 'win32' ? 'dws.exe' : 'dws')
743
+ const probe = await runDws(vendor, ['--version'], { timeoutMs: 20_000 })
744
+ if (probe.code === 0) this.config.dwsPath = vendor
745
+
746
+ await this.checkTool()
747
+ if (!this.tool.ok) {
748
+ this.setInstall({
749
+ status: 'error',
750
+ mode: 'tarball',
751
+ log: `已解压 ${files.length} 个文件到 ${pkgDir},但 dws 仍不可用:${this.tool.error}\n\n${postinstallLog}`.trim(),
752
+ })
753
+ return { ok: false, error: this.tool.error }
754
+ }
755
+
756
+ this.setInstall({
757
+ status: 'ready',
758
+ mode: 'tarball',
759
+ currentVersion: this.tool.version,
760
+ latestVersion: version || this.install.latestVersion,
761
+ updateAvailable: false,
762
+ log: `已安装 dws v${this.tool.version}(免 npm,来源:${registry})`,
763
+ })
764
+ await this.refreshProfiles()
765
+ this.startAllListeners()
766
+ return { ok: true, version: this.tool.version, mode: 'tarball' }
767
+ } catch (error) {
768
+ const message = String(error?.message || error)
769
+ this.setInstall({
770
+ status: 'error',
771
+ mode: 'tarball',
772
+ log: `免 npm 安装失败:${message}。请检查网络能否访问 ${registry},或手动安装 dws 后在配置项 dwsPath 里填绝对路径。`,
773
+ })
774
+ return { ok: false, error: message }
775
+ }
668
776
  }
669
777
 
670
778
  /** 「更新 dws」:先查最新版,再按版本号安装。 */
@@ -833,6 +941,23 @@ export class DingTalkBridgeService {
833
941
  async startLogin() {
834
942
  if (this.loginChild) return { ok: true, login: this.login }
835
943
 
944
+ // dws 不可用时直接授权只会拿到一句「'dws' 不是内部或外部命令」,
945
+ // 所以先拦一下,把用户引到「安装 dws」上。
946
+ if (!this.tool.ok) {
947
+ this.login = {
948
+ ...this.login,
949
+ status: 'failed',
950
+ code: '',
951
+ url: '',
952
+ qr: '',
953
+ qrUrl: '',
954
+ error: this.tool.error || `未检测到 dws 命令(当前配置:${this.config.dwsPath})`,
955
+ message: '还没有可用的 dws,所以无法发起钉钉授权。请先在上方「dws 未安装」提示卡里点「安装 dws」(没有 npm 也能装),装好后再点「钉钉授权」。',
956
+ }
957
+ this.broadcast()
958
+ return { ok: false, error: 'dws not ready' }
959
+ }
960
+
836
961
  // 默认先退出已登录的组织:否则每授权一次就多一个组织,监听列表越滚越长。
837
962
  if (this.config.loginReset && this.config.profiles.length === 0 && this.hasLogin()) {
838
963
  this.login = {
@@ -1381,6 +1506,11 @@ export class DingTalkBridgeService {
1381
1506
  return dirname(this.statePath)
1382
1507
  }
1383
1508
 
1509
+ /** DSH 的数据目录(dsh-runtimes 就在这里,用来找自带的 node)。 */
1510
+ dshHome() {
1511
+ return this.dshHomePath
1512
+ }
1513
+
1384
1514
  mediaDir() {
1385
1515
  return join(this.dataDir(), 'media')
1386
1516
  }