dsh-plugin-tool-management 0.21.7 → 0.21.8

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/CHANGELOG.md CHANGED
@@ -10,6 +10,19 @@
10
10
 
11
11
  ---
12
12
 
13
+ ## [0.21.8] - 2026-10-28
14
+
15
+ ### 新增
16
+
17
+ - **检查更新给出可复制的升级命令**:有兼容更新时点击更新键弹出升级卡,展示固定到该版本的 `dsh plugin ... add ...` 命令;复制到终端执行并重启 DSH。命令不使用 `@latest`,也不在界面内自动安装。
18
+ - **更新检查跟随宿主的下载源**:按宿主登记的源(配置的第一源 + fallback,含镜像)依次请求,并用宿主的双源测速决定先问哪个;不再写死 npm 官方源。
19
+ - **更新检查不再丢弃显式配置的私有源**:冷启动时不再因为等待宿主解析源超时而退回 npm 官方源。
20
+ - **更新检查加固**:跳过 registry 上被标记为 deprecated 的版本;registry 响应加 8 MiB 流式上限;`host-unknown` 按失败缓存 1 小时;缓存读数按当前 profile 重建命令。
21
+ - **档案同步不再复制演示视频**:`docs/videos`(约 97MB)不进入 profile,已有副本会在下一次构建时清掉。
22
+ - **web / desktop 同时运行时不再互相覆盖侧车**:hub 写入加跨进程文件锁(`.write.lock`),停用表 / 作用域覆盖 / 工具表不会被后写的进程整份盖掉;进程崩溃留下的锁最多挡一分钟。
23
+ - **作用域侧车损坏可修复**:作用域条出现写入错误时可点「修复作用域文件」,确认后把损坏文件改名留存、按空表继续,不再只能手删。
24
+ - **技能 / 来源意图随资源删除清理**:对账时清掉已不存在的技能与技能来源的全局意图,同名资源重建不再继承旧的 off / blocked。
25
+
13
26
  ## [0.21.7] - 2026-10-27
14
27
 
15
28
  ### 修复
package/docs/UPDATE.md CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  | 版本 | 发布 | 主题 |
6
6
  | ------------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
7
+ | [0.21.8](../CHANGELOG.md#0218---2026-10-28) | 2026-10-28 | 「检查更新」在发现兼容版本时给出可复制的固定版本升级命令(不使用 `@latest`,不在界面内安装);检查跟随宿主登记的下载源(含镜像回退),不再写死 npm 官方源;更新检查跳过 deprecated、限制响应体大小,档案同步不再复制演示视频;作用域侧车损坏可在作用域条一键隔离修复,技能 / 来源意图随资源删除清理;web / desktop 同时运行时 hub 写入加跨进程锁,不再互相覆盖 |
7
8
  | [0.21.7](../CHANGELOG.md#0217---2026-10-27) | 2026-10-27 | 修好面板在对话进行中持续闪烁:会话清单变动不再触发顶栏 loading 与提示词 / 记忆页整份重取;MCP 注入域开启且无服务器时,状态段改为 60 秒确认一次,降低后台开销 |
8
9
  | [0.21.6](../CHANGELOG.md#0216---2026-10-24) | 2026-10-24 | 修好「应用提示词预设」恒定失败(并发指纹校验误拿正文当指纹,#22);记忆附件补根内断言、保留期清理先送系统回收站、场景冻结口径统一(回收站永久删除与被锁场景编辑纳入)且即时生效、人设名单逐条转义、预设 / 快捷词 / 人设改名可重试;适配宿主 0.2.1-rc.3 |
9
10
  | [0.21.5](../CHANGELOG.md#0215---2026-10-23) | 2026-10-23 | 十处写操作补上确认卡(MCP 停机、提示词正向应用、五域删除、开关落到机器级),恢复路径不拦;错误消息附现成候选(记忆 id、技能名、场景名、预设 id、MCP 服务器名) |
package/lib/client.js CHANGED
@@ -2520,6 +2520,8 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
2520
2520
  currentSessionId: function () { return '' },
2521
2521
  /** 订阅宿主会话列表 / 工作区记账(归档 / 恢复 / 起标题后下拉要跟着变);返回取消函数。 */
2522
2522
  subscribeSessionList: function (fn) { return null },
2523
+ /** 提示条(修复结果用);缺省不弹。参数须与 `showPluginToast` 同形,供 checkJs 推断。 */
2524
+ toast: function (text, kind) {},
2523
2525
  }
2524
2526
  function configureScopeDeps(next) {
2525
2527
  scopeDeps = Object.assign({}, scopeDeps, next || {})
@@ -2942,6 +2944,32 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
2942
2944
  function scopeClearWriteError() {
2943
2945
  if (scopeState.writeError !== null) setScopeState({ writeError: null })
2944
2946
  }
2947
+ /**
2948
+ * 隔离损坏的作用域侧车(`scope-repair`)。
2949
+ *
2950
+ * 只改名、不覆盖:损坏文件留在 hub 里供事后查看,覆盖表/意图表按空表继续。
2951
+ * 调用方(ScopeBar)负责二次确认 —— 这是把用户设置退回默认的动作。
2952
+ */
2953
+ function scopeRepair() {
2954
+ return apiCall('scope-repair', {}).then(function (res) {
2955
+ if (!res || res.ok !== true) {
2956
+ scopeDeps.toast(scopeT('scope.repair.failed', { error: scopeErrorText(res) || '?' }), 'err')
2957
+ return res
2958
+ }
2959
+ var files = []
2960
+ if (res.scopeQuarantined) files.push('scope-overrides.json')
2961
+ if (res.intentQuarantined) files.push('scope-intent.json')
2962
+ scopeDeps.toast(files.length
2963
+ ? scopeT('scope.repair.done', { files: files.join(' / ') })
2964
+ : scopeT('scope.repair.none'), files.length ? 'ok' : 'warn')
2965
+ scopeClearWriteError()
2966
+ refreshScope({ silent: true })
2967
+ return res
2968
+ }).catch(function (e) {
2969
+ scopeDeps.toast(scopeT('scope.repair.failed', { error: errMsg(e) }), 'err')
2970
+ return { ok: false, error: errMsg(e) }
2971
+ })
2972
+ }
2945
2973
  /**
2946
2974
  * 锁 / 解锁**本会话**(0.21.2,决策 12)。只在会话层成立:
2947
2975
  * 锁冻结的是这个会话自己的覆盖写入,与场景锁(全局写)互不干扰。
@@ -2973,6 +3001,13 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
2973
3001
  function ScopeBar(props) {
2974
3002
  var t = props.t
2975
3003
  var snap = React.useSyncExternalStore(subscribeScope, scopeSnapshot, scopeSnapshot)
3004
+ // 修复是破坏性动作:第一次点只切到「确认」,第二次才执行。
3005
+ var ra = React.useState(false)
3006
+ var repairArmed = ra[0], setRepairArmed = ra[1]
3007
+ // 错误消失(修复成功 / 用户点掉)后别让下一次错误直接落在「确认」态。
3008
+ React.useEffect(function () {
3009
+ if (!snap.writeError) setRepairArmed(false)
3010
+ }, [snap.writeError])
2976
3011
  // 首次挂载拉一次:面板一打开就要知道"我在哪一层"。失败不阻塞页面(下拉仍在,只是选项少)。
2977
3012
  // **每次挂载都拉**:设置页与侧栏入口是两个挂载点,切页签又会让页面重新挂载;
2978
3013
  // 只在模块作用域缓存一份的话,别处写进去的覆盖要等下一次下拉操作才看得见。
@@ -3028,6 +3063,18 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
3028
3063
  snap.writeError
3029
3064
  ? h('div', { key: 'writeerr', className: 'dsm-scope-bar-error', role: 'alert' }, [
3030
3065
  h('span', { key: 'text' }, String(snap.writeError)),
3066
+ // 损坏的侧车没有别的恢复入口:写入会一直失败。修复只隔离现场,不覆盖健康文件。
3067
+ h('button', {
3068
+ key: 'repair',
3069
+ type: 'button',
3070
+ className: 'dsm-btn dsm-btn-quiet',
3071
+ title: scopeT('scope.repair.hint'),
3072
+ onClick: function () {
3073
+ if (!repairArmed) { setRepairArmed(true); return }
3074
+ setRepairArmed(false)
3075
+ scopeRepair()
3076
+ },
3077
+ }, repairArmed ? scopeT('scope.repair.confirm') : scopeT('scope.repair.action')),
3031
3078
  h('button', { key: 'x', type: 'button', className: 'dsm-btn dsm-btn-quiet', onClick: function () { scopeClearWriteError() } }, scopeT('scope.warn.dismiss')),
3032
3079
  ])
3033
3080
  : null,
@@ -5987,6 +6034,14 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
5987
6034
  // 有兼容更新时那颗键**外观不变**(只多一个红点),但无障碍名换成「更新」——
5988
6035
  // 读屏该读到"有更新",而不是泛泛的"检查"。
5989
6036
  "update.action": "更新",
6037
+ // 升级入口只给命令,不在界面内安装:插件不能自我安装,宿主也没有更新已装插件的接口。
6038
+ // 命令里的版本由服务端固定,不出现 @latest。
6039
+ "update.install.open": "查看升级命令", "update.install.title": "升级到 {version}",
6040
+ "update.install.body": "插件不能自我安装,宿主也没有“更新已装插件”的接口。复制下面的命令到终端执行(当前 {current},命令固定到 {version},不会使用 @latest),完成后重启 DSH。",
6041
+ "update.install.after": "命令执行完再重启 DSH:运行中的仍是旧版本。",
6042
+ "update.install.copy": "复制命令", "update.install.copied": "已复制升级命令",
6043
+ "update.install.copyFailed": "复制失败,请手动选中命令复制",
6044
+ "update.install.noCommand": "这次检查没有给出可执行的命令,请重新点一次检查更新。",
5990
6045
  "compat.diag.copy": "复制诊断信息", "compat.diag.copied": "已复制诊断信息",
5991
6046
  "compat.host": "宿主版本", "compat.verified": "插件适配版本",
5992
6047
  "compat.caps": "可用能力", "compat.caps.degraded": "{count} 项不可用",
@@ -6583,6 +6638,11 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
6583
6638
  "scope.view.lease": "{count} 个对话单独设置",
6584
6639
  "scope.view.leaseHint": "全局是关的,但还有 {count} 个对话单独把它拨开了 —— 这只影响它们各自看到的内容,全局设置没变。",
6585
6640
  "scope.warn.dismiss": "知道了",
6641
+ "scope.repair.action": "修复作用域文件", "scope.repair.confirm": "确认隔离损坏文件(设置回到默认)",
6642
+ "scope.repair.hint": "仅在作用域侧车损坏时使用:损坏的文件会改名留存,覆盖表与全局意图回到默认,下一次对账会从运行态反推。",
6643
+ "scope.repair.done": "已隔离 {files},相关设置回到默认;损坏文件保留在 hub 里。",
6644
+ "scope.repair.none": "作用域侧车文件正常,无需修复。",
6645
+ "scope.repair.failed": "修复失败:{error}",
6586
6646
  "scope.intent.globalOnly": "全局意图只能在全局层修改",
6587
6647
  "scope.intent.blocked": "已统一关闭", "scope.intent.blockedHint": "全局已「统一关闭」:任何会话都不能再用它(包括在会话层打开)。要恢复,先在全局改回启用。",
6588
6648
  "scope.intent.lease": "临时运行 · {count} 个对话", "scope.intent.leaseHint": "全局是关的,但还有 {count} 个对话在用它 —— 它保持启用,只有这些对话看得到。",
@@ -6886,6 +6946,12 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
6886
6946
  "update.check": "Check for updates", "update.checking": "Checking for updates…", "update.recheck": "Click to check again",
6887
6947
  "update.failed": "Update check failed: {error}",
6888
6948
  "update.action": "Update",
6949
+ "update.install.open": "View upgrade command", "update.install.title": "Upgrade to {version}",
6950
+ "update.install.body": "The plugin cannot install itself, and the host exposes no 'update installed plugin' API. Copy the command below into a terminal (you are on {current}; it is pinned to {version}, never @latest), then restart DSH.",
6951
+ "update.install.after": "Restart DSH after running the command; the running copy is still the old version.",
6952
+ "update.install.copy": "Copy command", "update.install.copied": "Upgrade command copied",
6953
+ "update.install.copyFailed": "Copy failed; select the command and copy it manually",
6954
+ "update.install.noCommand": "This check produced no runnable command; check for updates again.",
6889
6955
  "compat.diag.copy": "Copy diagnostics", "compat.diag.copied": "Diagnostics copied",
6890
6956
  "compat.host": "Host version", "compat.verified": "Verified against",
6891
6957
  "compat.caps": "Usable capabilities", "compat.caps.degraded": "{count} unavailable",
@@ -7466,6 +7532,11 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
7466
7532
  "scope.view.lease": "set in {count} chats",
7467
7533
  "scope.view.leaseHint": "Off globally, but {count} conversation(s) switched it on for themselves — that only changes what they see; the global setting is unchanged.",
7468
7534
  "scope.warn.dismiss": "Dismiss",
7535
+ "scope.repair.action": "Repair scope files", "scope.repair.confirm": "Quarantine the corrupt file (settings reset to defaults)",
7536
+ "scope.repair.hint": "Only for corrupt scope sidecars: the corrupt file is renamed and kept, per-conversation overrides and global intent reset to defaults, and the next reconcile adopts the running state.",
7537
+ "scope.repair.done": "Quarantined {files}; related settings are back to defaults. The corrupt file is kept in the hub.",
7538
+ "scope.repair.none": "The scope sidecars are healthy; nothing to repair.",
7539
+ "scope.repair.failed": "Repair failed: {error}",
7469
7540
  "scope.intent.globalOnly": "Global intent can only be changed from the global layer",
7470
7541
  "scope.intent.blocked": "closed everywhere", "scope.intent.blockedHint": "Closed globally: no conversation can use it, even by switching it on locally. Set it back to on/off globally to allow it again.",
7471
7542
  "scope.intent.lease": "temporary · {count} conversation(s)", "scope.intent.leaseHint": "Off globally, but {count} conversation(s) still use it — it stays enabled and only they see it.",
@@ -7671,6 +7742,7 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
7671
7742
  t: t,
7672
7743
  currentSessionId: currentSessionId,
7673
7744
  subscribeSessionList: subscribeSessionList,
7745
+ toast: showPluginToast,
7674
7746
  })
7675
7747
  /**
7676
7748
  * 一次性「服务点名」:锁挂不上时把几个关键服务在**本插件上下文里**的可见性一起写出来。
@@ -8132,20 +8204,33 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
8132
8204
  // · GitHub 图标——原样保留,仓库入口一个都不能少。
8133
8205
  //
8134
8206
  // 交互约定:
8135
- // · 点击 = 查一次(只读 op `update-status` + `refresh:true`)—— 不安装、不改配置、
8136
- // 不碰 `@latest`,`update-check.ts` 那几条硬约束照旧。插件跑在宿主的
8137
- // node_modules 里,装不了自己 —— 这颗键**不许**承诺自动更新;
8138
- // · 答案用 toast 说,不弹窗:它是一句话结论,弹窗要压暗整页、还得再点一次才关。
8207
+ // · 没有更新时点击 = 查一次(只读 op `update-status` + `refresh:true`);
8208
+ // · 有更新时点击 = 打开升级卡,展示**固定版本**的 CLI 命令供复制。
8209
+ // 插件跑在宿主的 node_modules 里,不能自我安装;宿主也没有"更新已装插件"的接口
8210
+ // (`installBundle` 对已在 profile 依赖里的包在 HMR 下必拒),所以这里只给命令,
8211
+ // 不承诺在界面内完成安装,也不出现 `@latest`。
8212
+ // · 检查结论用 toast 说(一句话结论,不必弹窗);只有要给人抄命令时才弹卡。
8139
8213
  //
8140
- // 结果存**会话级**(`updateProbe`):设置面板每次打开都会重挂本组件,重挂不该把「更新」
8141
- // 抹掉,也不该每次都去读一遍盘。
8214
+ // 结果存**会话级**(`updateProbe`):设置面板每次打开都会重挂本组件,重挂不该把
8215
+ // 「更新」抹掉,也不该每次都去读一遍盘。
8142
8216
  var updateProbe = { info: null, asked: false }
8143
8217
 
8144
8218
  function FeedbackLinks() {
8145
8219
  var st = React.useState({ busy: false, info: updateProbe.info })
8146
8220
  var state = st[0], setState = st[1]
8221
+ var co = React.useState(false)
8222
+ var cardOpen = co[0], setCardOpen = co[1]
8223
+ var cp = React.useState(false)
8224
+ var copied = cp[0], setCopied = cp[1]
8147
8225
  var busy = state.busy === true
8148
8226
  var info = state.info
8227
+ var hasUpdate = !!info && String(info.status || '') === 'update-available'
8228
+ var targetVersion = String((info && info.bestCompatible) || '')
8229
+ // 服务端按当前 profile 拼好的命令;缓存读数读到 old cache 时也会重建(见 update-check.ts)。
8230
+ var command = String((info && info.command) || '')
8231
+
8232
+ // 只改给到的字段:补读数 / 检查两路异步回填不能互相覆盖。
8233
+ var patch = function (next) { setState(function (prev) { return Object.assign({}, prev, next) }) }
8149
8234
 
8150
8235
  // 挂载时补一次缓存读数(不带 refresh):服务端启动时预热过,这一次通常零网络,
8151
8236
  // 只是把盘上 `update-check.json` 的结论先摆上来。读不到 = 少一个「更新」标记,不报错。
@@ -8157,61 +8242,111 @@ button.dsm-rowselect-box:disabled{cursor:default;opacity:.45}
8157
8242
  if (!r || !r.ok) return
8158
8243
  updateProbe.info = r
8159
8244
  // 用户已经自己点过一次(拿到的是更新的结果)就不覆盖。
8160
- if (alive) setState(function (prev) { return prev.info ? prev : { busy: prev.busy, info: r } })
8245
+ if (alive) setState(function (prev) { return prev.info ? prev : Object.assign({}, prev, { info: r }) })
8161
8246
  }).catch(function () { /* 静默:这个标记只是便利,不是结论 */ })
8162
8247
  return function () { alive = false }
8163
8248
  }, [])
8164
8249
 
8165
- var hasUpdate = !!info && String(info.status || '') === 'update-available'
8166
-
8167
8250
  var check = function () {
8168
8251
  if (busy) return
8169
- setState({ busy: true, info: info })
8252
+ patch({ busy: true })
8170
8253
  // `refresh:true`:点这一下就是要一个**现在**的答案。读 12 小时前的缓存等于骗人
8171
8254
  // ——「已是最新」可能是在某个版本发布之前算出来的。
8172
8255
  apiCall('update-status', { refresh: true }).then(function (r) {
8173
8256
  if (!r || !r.ok) throw new Error(String((r && r.error) || t('compat.update.unknown')))
8174
8257
  updateProbe.info = r
8175
- setState({ busy: false, info: r })
8258
+ patch({ busy: false, info: r })
8176
8259
  var s = String(r.status || 'unknown')
8177
8260
  showPluginToast(updateStatusText(r, t), s === 'up-to-date' ? 'ok' : 'warn')
8178
8261
  }).catch(function (e) {
8179
- setState({ busy: false, info: info })
8262
+ patch({ busy: false })
8180
8263
  showPluginToast(t('update.failed', { error: errMsg(e) }), 'err')
8181
8264
  })
8182
8265
  }
8183
8266
 
8184
- // 标题就是"这一下会做什么":没有答案时是"查一次",有答案时是"再查一遍"。
8267
+ /**
8268
+ * 复制升级命令。命令由服务端按当前 profile 拼好(固定版本),这里只负责放进剪贴板。
8269
+ * 剪贴板不可用时命令仍显示在卡里,用户可以直接选中复制。
8270
+ */
8271
+ var copyCommand = function () {
8272
+ if (command === '') return
8273
+ var done = function () {
8274
+ setCopied(true)
8275
+ showPluginToast(t('update.install.copied'), 'ok')
8276
+ }
8277
+ var fail = function () { showPluginToast(t('update.install.copyFailed'), 'err') }
8278
+ try {
8279
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
8280
+ navigator.clipboard.writeText(command).then(done, fail)
8281
+ return
8282
+ }
8283
+ } catch (e) { /* 落到下面的失败提示 */ }
8284
+ fail()
8285
+ }
8286
+
8287
+ var onUpdateClick = function () {
8288
+ if (busy) return
8289
+ if (hasUpdate) { setCopied(false); setCardOpen(true); return }
8290
+ check()
8291
+ }
8292
+
8293
+ // 标题就是"这一下会做什么":没答案时"查一次",有答案时"再查一遍",
8294
+ // 有更新时"查看升级命令"。
8185
8295
  var tip = busy ? t('update.checking')
8186
- : info ? updateStatusText(info, t) + ' · ' + t('update.recheck')
8187
- : t('update.check')
8188
- return React.createElement('div', { className: 'dsm-feedback-links' },
8189
- // 版本号在最左:它回答的是"我现在装的是哪个版本",与右边两颗键各自回答的问题不同,
8190
- // 所以不并进按钮文字里(并进去就成了"要变成哪个版本",两件事会混)。
8191
- React.createElement(VersionBadgeComponent, null),
8192
- React.createElement('button', {
8193
- type: 'button',
8194
- // 永远是同一颗图标键(用户 2026-10-22:不必在有更新时多出「更新」二字)——
8195
- // 有更新只多一个红点,宽度不变,这一行也就不会因为状态变化而抖一下。
8196
- className: 'dsm-feedback-link dsm-feedback-check' + (busy ? ' dsm-feedback-link-busy' : ''),
8197
- 'aria-label': hasUpdate ? t('update.action') : t('update.check'),
8198
- 'aria-busy': busy ? 'true' : 'false',
8199
- title: tip,
8200
- onClick: check,
8201
- },
8202
- React.createElement(UpdateMark16, null),
8203
- // 有新版本时右上角挂一个小红点:这是这一簇里唯一"扫一眼就看见"的信号,
8204
- // 图标本身不随状态变(文字在窄面板下还会被挤掉)。
8205
- hasUpdate ? React.createElement('span', { className: 'dsm-feedback-dot', 'aria-hidden': 'true' }) : null),
8206
- React.createElement('a', {
8207
- className: 'dsm-feedback-link',
8208
- href: 'https://github.com/ouli-1242/dsh-plugin-tool-management',
8209
- target: '_blank',
8210
- rel: 'noreferrer',
8211
- 'aria-label': t('link.project'),
8212
- title: t('link.project'),
8296
+ : hasUpdate ? updateStatusText(info, t) + ' · ' + t('update.install.open')
8297
+ : info ? updateStatusText(info, t) + ' · ' + t('update.recheck')
8298
+ : t('update.check')
8299
+ var label = hasUpdate ? t('update.action') : t('update.check')
8300
+ return React.createElement(React.Fragment, null,
8301
+ React.createElement('div', { className: 'dsm-feedback-links' },
8302
+ // 版本号在最左:它回答的是"我现在装的是哪个版本",与右边两颗键各自回答的问题不同,
8303
+ // 所以不并进按钮文字里(并进去就成了"要变成哪个版本",两件事会混)。
8304
+ React.createElement(VersionBadgeComponent, null),
8305
+ React.createElement('button', {
8306
+ type: 'button',
8307
+ // 永远是同一颗图标键(用户 2026-10-22:不必在有更新时多出「更新」二字)——
8308
+ // 有更新只多一个红点,宽度不变,这一行也就不会因为状态变化而抖一下。
8309
+ className: 'dsm-feedback-link dsm-feedback-check' + (busy ? ' dsm-feedback-link-busy' : ''),
8310
+ 'aria-label': label,
8311
+ 'aria-busy': busy ? 'true' : 'false',
8312
+ title: tip,
8313
+ onClick: onUpdateClick,
8314
+ },
8315
+ React.createElement(UpdateMark16, null),
8316
+ hasUpdate ? React.createElement('span', { className: 'dsm-feedback-dot', 'aria-hidden': 'true' }) : null),
8317
+ React.createElement('a', {
8318
+ className: 'dsm-feedback-link',
8319
+ href: 'https://github.com/ouli-1242/dsh-plugin-tool-management',
8320
+ target: '_blank',
8321
+ rel: 'noreferrer',
8322
+ 'aria-label': t('link.project'),
8323
+ title: t('link.project'),
8324
+ },
8325
+ React.createElement(GithubMark16, null))),
8326
+ cardOpen ? React.createElement(Modal, {
8327
+ title: t('update.install.title', { version: targetVersion }),
8328
+ closeLabel: t('btn.close'),
8329
+ onClose: function () { setCardOpen(false) },
8330
+ className: 'dsm-modal-sm',
8213
8331
  },
8214
- React.createElement(GithubMark16, null)))
8332
+ React.createElement('p', { className: 'dsm-help' }, t('update.install.body', {
8333
+ current: String((info && info.current) || '?'),
8334
+ version: targetVersion,
8335
+ })),
8336
+ command !== ''
8337
+ ? React.createElement('pre', { className: 'dsm-code' }, command)
8338
+ : React.createElement('p', { className: 'dsm-help' }, t('update.install.noCommand')),
8339
+ React.createElement('div', { className: 'dsm-feedback dsm-warning' }, t('update.install.after')),
8340
+ React.createElement('div', { className: 'dsm-modal-actions' },
8341
+ React.createElement('button', {
8342
+ type: 'button', className: 'dsm-btn dsm-btn-secondary',
8343
+ onClick: function () { setCardOpen(false) },
8344
+ }, t('btn.close')),
8345
+ React.createElement('button', {
8346
+ type: 'button', className: 'dsm-btn', disabled: command === '',
8347
+ onClick: copyCommand,
8348
+ }, copied ? t('update.install.copied') : t('update.install.copy'))))
8349
+ : null)
8215
8350
  }
8216
8351
 
8217
8352
  // MCP 服务页:与 Skills 页共用 dsm-* 设计语言(统计卡 / 筛选 / 分组卡片 / 模态框)。
@@ -0,0 +1,121 @@
1
+ // hub 级跨进程写锁。
2
+ //
3
+ // 为什么需要:DSH 的 web 与 desktop 是两个宿主进程,却共用同一个 `$DSH_HOME`。apply 里那条
4
+ // `writeChain` 只能串行**同一进程**的写入;两个进程同时读-改-写同一份侧车时,后写的会覆盖
5
+ // 先写的(停用表、作用域覆盖、工具表都是整份写)。这里用 hub 根下的 `.write.lock` 做第二层。
6
+ //
7
+ // 锁文件不常开:写入 pid / 时间 / 随机 token 后立即关闭;临界区结束时按 token 删除。持锁期间
8
+ // 每 5 秒 touch 一次 mtime,心跳停了超过 `staleMs` 才允许别的进程抢占。这样进程崩溃留下的锁
9
+ // 最多挡一分钟,不会永久锁死 hub。
10
+ import { mkdir, open, readFile, stat, unlink, utimes } from 'node:fs/promises';
11
+ import { join } from 'node:path';
12
+ import { randomUUID } from 'node:crypto';
13
+ /** 锁文件名(hub 根;点开头,迁移与备份都不认识它)。 */
14
+ export const HUB_LOCK_FILE = '.write.lock';
15
+ /** 等锁的上限:超过就报错,不无限挂住一次面板写入。 */
16
+ const DEFAULT_TIMEOUT_MS = 30_000;
17
+ /** 没有心跳多久算死锁。必须明显大于心跳间隔,给一次长写入留余量。 */
18
+ const DEFAULT_STALE_MS = 60_000;
19
+ /** 心跳间隔:touch 锁文件 mtime。 */
20
+ const HEARTBEAT_MS = 5_000;
21
+ /** 等锁的重试间隔(带少量随机抖动,避免两个进程同步醒来反复撞)。 */
22
+ const RETRY_MS = 25;
23
+ /** 读锁文件的内容与 mtime;不存在 / 读不动返回 null。 */
24
+ async function readLock(path) {
25
+ try {
26
+ const [raw, info] = await Promise.all([readFile(path, 'utf8'), stat(path)]);
27
+ let parsed = null;
28
+ try {
29
+ const obj = JSON.parse(raw);
30
+ if (typeof obj.pid === 'number' && typeof obj.at === 'number' && typeof obj.token === 'string') {
31
+ parsed = { pid: obj.pid, at: obj.at, token: obj.token };
32
+ }
33
+ }
34
+ catch { /* 刚创建还没写完 / 坏内容:按"有锁但读不懂"处理 */ }
35
+ return { info: parsed, mtime: info.mtimeMs };
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ /** 进程还在吗:`EPERM` 表示存在但没权限发信号,按活着算。 */
42
+ function processAlive(pid) {
43
+ if (!Number.isInteger(pid) || pid <= 0)
44
+ return false;
45
+ try {
46
+ process.kill(pid, 0);
47
+ return true;
48
+ }
49
+ catch (e) {
50
+ return e?.code === 'EPERM';
51
+ }
52
+ }
53
+ /**
54
+ * 建一把 hub 文件锁。
55
+ *
56
+ * @param dir hub 根目录(`$DSH_HOME/tool-management`);不存在时首次等锁会创建
57
+ * @param options 超时与死锁阈值(测试可缩短)
58
+ */
59
+ export function createHubFileLock(dir, options = {}) {
60
+ const path = join(dir, HUB_LOCK_FILE);
61
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
62
+ const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
63
+ /** 尝试拿锁;拿不到返回 false,拿到后由调用方持有。 */
64
+ async function tryAcquire(token) {
65
+ try {
66
+ const handle = await open(path, 'wx');
67
+ try {
68
+ await handle.writeFile(JSON.stringify({ pid: process.pid, at: Date.now(), token }), 'utf8');
69
+ }
70
+ finally {
71
+ await handle.close();
72
+ }
73
+ return true;
74
+ }
75
+ catch (e) {
76
+ if (e?.code !== 'EEXIST')
77
+ throw e;
78
+ const seen = await readLock(path);
79
+ if (seen === null)
80
+ return false; // 刚被删;下一轮重试即可
81
+ const age = Date.now() - seen.mtime;
82
+ if (seen.info !== null && processAlive(seen.info.pid) && age < staleMs)
83
+ return false;
84
+ // 进程已死 / 心跳过期 / 内容读不懂:只删我们看到的那一份,避免误删别人刚建的新锁。
85
+ const again = await readLock(path);
86
+ if (again !== null && (seen.info === null || again.info?.token === seen.info.token)) {
87
+ await unlink(path).catch(() => undefined);
88
+ }
89
+ return false;
90
+ }
91
+ }
92
+ return {
93
+ async run(fn) {
94
+ await mkdir(dir, { recursive: true });
95
+ const token = randomUUID();
96
+ const started = Date.now();
97
+ for (;;) {
98
+ if (await tryAcquire(token))
99
+ break;
100
+ if (Date.now() - started > timeoutMs) {
101
+ throw new Error('另一个 DSH 进程正在写同一个数据目录,等待超时;请稍后重试,或只保留一个宿主进程。');
102
+ }
103
+ await new Promise((resolve) => setTimeout(resolve, RETRY_MS + Math.floor(Math.random() * RETRY_MS)));
104
+ }
105
+ const beat = setInterval(() => {
106
+ // 心跳失败(文件被删 / 被抢占)不打断临界区:释放时还会按 token 再确认一次。
107
+ void utimes(path, new Date(), new Date()).catch(() => undefined);
108
+ }, HEARTBEAT_MS);
109
+ beat.unref();
110
+ try {
111
+ return await fn();
112
+ }
113
+ finally {
114
+ clearInterval(beat);
115
+ const seen = await readLock(path);
116
+ if (seen?.info?.token === token)
117
+ await unlink(path).catch(() => undefined);
118
+ }
119
+ },
120
+ };
121
+ }
package/lib/index.js CHANGED
@@ -51,6 +51,7 @@ import { createCandidates } from './scenes/candidates.js';
51
51
  // 「已知工具」归一化与「当前可用工具数」原本定义在本文件(导出仅为测试接缝),
52
52
  export { normalizeKnownTools, countEnabledTools } from './mcp/manager.js';
53
53
  import { hubBackupDir, hubPath, hubRoot, migrateHubLayoutSync, relocateEntries } from './hub.js';
54
+ import { createHubFileLock } from './hub-lock.js';
54
55
  // 分域的 HTTP ops(从本文件 handlers 表抽出,依赖显式传参)。
55
56
  import { buildCompatOps } from './ops/compat.js';
56
57
  import { createUpdateChecker } from './update-check.js';
@@ -60,12 +61,12 @@ import { buildQuickPromptOps } from './ops/quick-prompts.js';
60
61
  import { buildScopeOps } from './ops/scope.js';
61
62
  import { buildSessionOps } from './ops/sessions.js';
62
63
  import { buildTrashRetentionOps } from './ops/trash-retention.js';
63
- // 会话作用域:侧车 scope-overrides.json + 五条 op + 启动对账。
64
+ // 会话作用域:侧车 scope-overrides.json / scope-intent.json + 作用域 op + 启动对账。
64
65
  import { rememberSessionCwd, scopeKeyOfAgent, scopeKeyOfIdSync, sessionIdentityOf, sessionIdOf, sessionScopeIdOf } from './scope/resolve.js';
65
66
  import { createScopeStore } from './scope/store.js';
66
67
  import { isWorkspaceScopeKey, scopeKeyLabel } from './scope/workspace-key.js';
67
68
  import { createIntentStore } from './scope/intent-store.js';
68
- import { effectiveLayerOf, intentOf, isIntentDomain, planReconcile, resolveResource, scanSessionClaims, withIntent, } from './scope/intent.js';
69
+ import { effectiveLayerOf, intentOf, isIntentDomain, planReconcile, pruneIntentKeys, resolveResource, scanSessionClaims, withIntent, } from './scope/intent.js';
69
70
  import { SCOPE_FLAG_DOMAINS, clampPromptBaseline, hasPromptOverride, mcpToolServerSegments, promptBaselineOf, promptOverrideOf, removeSceneInScope, renameSceneInScope, sessionScenePinOf, sessionToolTableHidden, setSceneToolTableInScope, withBaseline, } from './scope/scope-overrides.js';
70
71
  import { promptBaselineDiffers } from './memories/prompt-layer.js';
71
72
  // 回收站保留期:侧车 `hub/trash-retention.json` + 六类回收站的到期清扫。
@@ -226,9 +227,13 @@ export default {
226
227
  const { CONFIG_TOKEN, CONFIG_TOKEN_FROM_FILE, TOKEN_DISABLED, TOKEN, tokenMatches, BOOT_ID, acceptedThisBoot, markAccepted, unmarkAccepted } = createAccessToken({ config });
227
228
  const wait = (ms) => ctx.timeout(ms);
228
229
  const message = (e) => String((e && e.message) || e);
230
+ // 两层串行:`writeChain` 管同一进程内的排队;`hubLock` 管 web / desktop 两个进程
231
+ // 共用同一个 `$DSH_HOME` 时的整份读-改-写。只保留前者会让后写的整份覆盖先写的
232
+ // (停用表丢掉一条 = 已停用的 MCP 工具重新可调用)。
233
+ const hubLock = createHubFileLock(hubPath());
229
234
  let writeChain = Promise.resolve();
230
235
  function withWriteLock(fn) {
231
- const run = writeChain.then(() => fn(), () => fn());
236
+ const run = writeChain.then(() => hubLock.run(fn), () => hubLock.run(fn));
232
237
  writeChain = run.then(() => undefined, () => undefined);
233
238
  return run;
234
239
  }
@@ -3193,6 +3198,7 @@ export default {
3193
3198
  let intent;
3194
3199
  let patchRows;
3195
3200
  let roots;
3201
+ let skillStateOk = false;
3196
3202
  try {
3197
3203
  intent = await intentStore.read(true);
3198
3204
  const [rowsResult, skillResult] = await Promise.all([
@@ -3201,7 +3207,8 @@ export default {
3201
3207
  ]);
3202
3208
  patchRows = rowsResult;
3203
3209
  const st = skillResult;
3204
- roots = st && st.ok !== false ? ((st.data && st.data.roots) || []) : [];
3210
+ skillStateOk = !!st && st.ok !== false;
3211
+ roots = skillStateOk ? ((st.data && st.data.roots) || []) : [];
3205
3212
  }
3206
3213
  catch {
3207
3214
  return report;
@@ -3230,17 +3237,24 @@ export default {
3230
3237
  // 把声明名传给 core 会得到「技能不存在: pdf-reader」(真机:重启后
3231
3238
  // 租约里的技能拉不起来)。界面的启停 op 收的是 `sk.name`,与这里同一个口径。
3232
3239
  const skillRows = [];
3240
+ // 影子副本不参与对账,但**算"这个键还在"**:它只是暂时被同名条目压住,
3241
+ // 压住它的那份删掉后还会回来,不能把它的意图当成"资源已删除"清掉。
3242
+ const knownSkillKeys = new Set();
3233
3243
  for (const root of roots) {
3234
3244
  const rootKey = String((root && root.key) || '');
3235
3245
  if (rootKey === '')
3236
3246
  continue;
3237
3247
  for (const sk of ((root && root.skills) || [])) {
3238
- if (!sk || sk.shadowedBy)
3248
+ if (!sk)
3239
3249
  continue;
3240
3250
  const name = String(sk.declaredName || sk.name || '');
3241
3251
  if (name === '')
3242
3252
  continue;
3243
- skillRows.push({ key: rootKey + '/' + name, root: rootKey, name: String(sk.name || name), running: sk.enabled === true });
3253
+ const key = rootKey + '/' + name;
3254
+ knownSkillKeys.add(key);
3255
+ if (sk.shadowedBy)
3256
+ continue;
3257
+ skillRows.push({ key, root: rootKey, name: String(sk.name || name), running: sk.enabled === true });
3244
3258
  }
3245
3259
  }
3246
3260
  const claims = await leaseClaimsOf(servers, sources, skillRows.map((row) => row.key)).catch(() => ({
@@ -3284,7 +3298,8 @@ export default {
3284
3298
  explicitClaims: (claims.skillExplicit.get(row.key) || []).length,
3285
3299
  traced: tracedOf('skills', row.key),
3286
3300
  })), { adoptExternal: opts.adoptExternal === true });
3287
- // ① 意图采纳(升级推断 / 外部改动)一次落盘。写失败不拦运行态 —— 下一轮会再试。
3301
+ // ① 意图采纳(升级推断 / 外部改动)与清理(资源已不存在)一次落盘。
3302
+ // 写失败不拦运行态 —— 下一轮会再试。
3288
3303
  const intentWrites = [];
3289
3304
  for (const d of mcpDecisions)
3290
3305
  if (d.intentNext !== undefined)
@@ -3295,12 +3310,26 @@ export default {
3295
3310
  for (const d of skillDecisions)
3296
3311
  if (d.intentNext !== undefined)
3297
3312
  intentWrites.push({ domain: 'skills', key: d.key, state: d.intentNext });
3313
+ // 清单完整才清理:技能状态读失败时 `roots` 是空数组,拿它当"全部删除"会把用户
3314
+ // 所有技能意图一次清掉(与 `liveSessionIds` 读不到不剪枝同一条纪律)。
3315
+ //
3316
+ // MCP 这一轮**不剪**:`patchServerRows` 只覆盖两份 patch,loader 里临时挂载 / 手写
3317
+ // 配置的服务器不在其中;而 loader 清单读取失败时 `configuredServerStates` 会静默退回
3318
+ // patch-only。拿一份可能缺项的名册剪意图,会把仍在运行的服务器决定删掉。
3319
+ const pruneSources = skillStateOk ? new Set(sources) : null;
3320
+ const pruneSkills = skillStateOk ? knownSkillKeys : null;
3321
+ const pruneNeeded = (pruneSources !== null && Object.keys(intent.skillSources).some((key) => !pruneSources.has(key)))
3322
+ || (pruneSkills !== null && Object.keys(intent.skills).some((key) => !pruneSkills.has(key)));
3298
3323
  let finalIntent = intent;
3299
- if (intentWrites.length > 0) {
3324
+ if (intentWrites.length > 0 || pruneNeeded) {
3300
3325
  const res = await intentStore.mutate((current) => {
3301
3326
  let next = current;
3302
3327
  for (const write of intentWrites)
3303
3328
  next = withIntent(next, write.domain, [write.key], write.state);
3329
+ if (pruneSources !== null)
3330
+ next = pruneIntentKeys(next, 'skillSources', pruneSources);
3331
+ if (pruneSkills !== null)
3332
+ next = pruneIntentKeys(next, 'skills', pruneSkills);
3304
3333
  return next;
3305
3334
  });
3306
3335
  if (res.ok)
@@ -3818,6 +3847,59 @@ export default {
3818
3847
  stateDir: hubPath(),
3819
3848
  current: PKG_VERSION,
3820
3849
  currentEngines: PKG_DSH_RANGE,
3850
+ // 下载源跟宿主走:`configuredRegistries` 是宿主安装器自己的配置源(第一源 + fallback),
3851
+ // `fastest()` 是宿主插件页用的双源测速。两个都软取 —— 服务没挂载或字段不在
3852
+ // 就返回 null,更新检查退回 npm 官方单源,不因为取不到宿主服务而失败。
3853
+ //
3854
+ // **先读 `configuredRegistries` 属性,不先调 `registries()`**:后者每次都会 spawn
3855
+ // `pnpm config get registry`(宿主默认 20 秒超时),而更新检查只等 2.5 秒 —— 冷启动时
3856
+ // 会把用户显式配置的私有源丢掉。属性里已经有显式源时不需要 pnpm 的 `resolved`;
3857
+ // 只有「没配置第一源、也没有 fallback」的 `.npmrc`-only 机器才回退去问宿主。
3858
+ registries: async () => {
3859
+ try {
3860
+ const manager = ctx.get('pluginManager');
3861
+ if (!manager)
3862
+ return null;
3863
+ const direct = manager.configuredRegistries;
3864
+ if (direct && typeof direct === 'object') {
3865
+ const fallback = Array.isArray(direct.fallbackRegistries)
3866
+ ? direct.fallbackRegistries.filter((value) => typeof value === 'string' && value.trim() !== '')
3867
+ : [];
3868
+ const registry = typeof direct.registry === 'string' && direct.registry.trim() !== '' ? direct.registry : null;
3869
+ if (registry !== null || fallback.length > 0) {
3870
+ return { registry, fallbackRegistries: fallback, resolved: null };
3871
+ }
3872
+ }
3873
+ if (typeof manager.registries !== 'function')
3874
+ return null;
3875
+ const raw = await manager.registries();
3876
+ if (!raw || typeof raw !== 'object')
3877
+ return null;
3878
+ const fallback = Array.isArray(raw.fallbackRegistries)
3879
+ ? raw.fallbackRegistries.filter((value) => typeof value === 'string' && value.trim() !== '')
3880
+ : [];
3881
+ return {
3882
+ registry: typeof raw.registry === 'string' && raw.registry.trim() !== '' ? raw.registry : null,
3883
+ fallbackRegistries: fallback,
3884
+ resolved: typeof raw.resolved === 'string' && raw.resolved.trim() !== '' ? raw.resolved : null,
3885
+ };
3886
+ }
3887
+ catch {
3888
+ return null;
3889
+ }
3890
+ },
3891
+ fastest: async () => {
3892
+ try {
3893
+ const probe = ctx.get('pluginRegistryProbe');
3894
+ if (!probe || typeof probe.fastest !== 'function')
3895
+ return null;
3896
+ const answer = await probe.fastest();
3897
+ return typeof answer === 'string' && answer.trim() !== '' ? answer : null;
3898
+ }
3899
+ catch {
3900
+ return null;
3901
+ }
3902
+ },
3821
3903
  hostVersion: () => {
3822
3904
  try {
3823
3905
  const registry = history.getSessionsRegistry();
@@ -4041,6 +4123,9 @@ export default {
4041
4123
  const res = await intentStore.mutate((current) => withIntent(current, domain, keys, state));
4042
4124
  return res.ok ? null : res.error;
4043
4125
  },
4126
+ // 作用域侧车损坏时的显式修复通道(scope-repair):隔离现场后按空表继续。
4127
+ repairScope: () => scopeStore.repair(),
4128
+ repairIntent: () => intentStore.repair(),
4044
4129
  // 基线:会话**创建时**的冻结快照 —— 启动期与 agent/created 各调一次(`ensureBaselineFor`)。
4045
4130
  captureBaseline: () => captureBaselineSnapshot(),
4046
4131
  // 会话提示词:应用前读一次正文(校验存在性 + 拒绝空预设)
@@ -276,6 +276,8 @@ export const OP_REGISTRY = Object.freeze({
276
276
  'scope-clear': { write: true },
277
277
  // 锁开关自己不能被自己挡住,否则锁上了解不开(与 `rules-scene-lock` 同一条)。
278
278
  'scope-lock': { write: true },
279
+ // 作用域侧车损坏后的显式修复:隔离现场、按空表继续。**不冻结** —— 场景锁着时也可能需要修。
280
+ 'scope-repair': { write: true },
279
281
  // 全局意图(`hub/scope-intent.json`):MCP 服务器 / 技能 / 技能来源三格的**全局开关**。
280
282
  // 与 `mcpm-set-enabled` / `skill-source-enable` 同档:写全局定义、场景锁要冻结它。
281
283
  // 会话层的 scope-set 仍不冻结(它只写租约,不改全局)。
package/lib/ops/compat.js CHANGED
@@ -443,14 +443,14 @@ export function buildCompatOps(deps) {
443
443
  'update-status': async (args) => {
444
444
  const checker = deps.updateChecker;
445
445
  if (!checker) {
446
- return { ok: true, status: 'unknown', current: null, host: null, newest: null, bestCompatible: null, command: null, checkedAt: null, fromCache: false, error: '更新检查未接线' };
446
+ return { ok: true, status: 'unknown', current: null, host: null, newest: null, bestCompatible: null, source: null, command: null, checkedAt: null, fromCache: false, error: '更新检查未接线' };
447
447
  }
448
448
  try {
449
449
  // `ok` 刻意放在最后覆盖:op 本身成功,答案由 `status` 表达(含 `unknown`)。
450
450
  return { ...(await checker.check(Boolean(args && args.refresh))), ok: true };
451
451
  }
452
452
  catch (e) {
453
- return { ok: true, status: 'unknown', current: null, host: null, newest: null, bestCompatible: null, command: null, checkedAt: null, fromCache: false, error: deps.message(e) };
453
+ return { ok: true, status: 'unknown', current: null, host: null, newest: null, bestCompatible: null, source: null, command: null, checkedAt: null, fromCache: false, error: deps.message(e) };
454
454
  }
455
455
  },
456
456
  };
package/lib/ops/scope.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // scope-sessions-list 只读:当前会话区里的未归档会话(下拉框的数据源,按工作区分组)
7
7
  // scope-lock 写:锁 / 解锁某个会话的覆盖
8
8
  // scope-intent-set 写:MCP 服务器 / 技能来源的全局意图(on / off / blocked)
9
+ // scope-repair 写:隔离损坏的 scope-overrides.json / scope-intent.json(显式修复)
9
10
  //
10
11
  // ## 为什么这几条都不标 frozen
11
12
  //
@@ -1193,5 +1194,33 @@ export function buildScopeOps(deps) {
1193
1194
  return { ok: false, error: '保存失败: ' + res.error };
1194
1195
  return { ok: true, sessionId, locked };
1195
1196
  },
1197
+ /**
1198
+ * 修复损坏的作用域侧车:只把解析不了的文件改名留存,不覆盖任何健康文件。
1199
+ *
1200
+ * 这是**显式**的破坏性动作:隔离后覆盖表/意图表按空表继续,下一次对账会把意图从
1201
+ * 运行态反推。界面必须先确认再调用;健康的文件返回 `null`,不做任何事。
1202
+ */
1203
+ 'scope-repair': async () => {
1204
+ const errors = [];
1205
+ let scopeQuarantined = null;
1206
+ let intentQuarantined = null;
1207
+ if (deps.repairScope) {
1208
+ const res = await deps.repairScope();
1209
+ if (res.ok)
1210
+ scopeQuarantined = res.quarantined;
1211
+ else
1212
+ errors.push('scope-overrides.json: ' + res.error);
1213
+ }
1214
+ if (deps.repairIntent) {
1215
+ const res = await deps.repairIntent();
1216
+ if (res.ok)
1217
+ intentQuarantined = res.quarantined;
1218
+ else
1219
+ errors.push('scope-intent.json: ' + res.error);
1220
+ }
1221
+ if (errors.length)
1222
+ return { ok: false, error: errors.join(';') };
1223
+ return { ok: true, scopeQuarantined, intentQuarantined };
1224
+ },
1196
1225
  };
1197
1226
  }
@@ -98,9 +98,38 @@ export function createIntentStore(deps) {
98
98
  }
99
99
  });
100
100
  }
101
+ async function repair() {
102
+ return deps.withWriteLock(async () => {
103
+ let raw;
104
+ try {
105
+ raw = await readFile(file(), 'utf8');
106
+ }
107
+ catch (e) {
108
+ if (e?.code === 'ENOENT')
109
+ return { ok: true, quarantined: null };
110
+ return { ok: false, error: deps.message(e) };
111
+ }
112
+ try {
113
+ normalizeScopeIntent(JSON.parse(raw));
114
+ return { ok: true, quarantined: null };
115
+ }
116
+ catch {
117
+ const target = file() + '.corrupt-' + Date.now();
118
+ try {
119
+ await renameWithRetry(file(), target);
120
+ }
121
+ catch (e) {
122
+ return { ok: false, error: deps.message(e) };
123
+ }
124
+ cache = null;
125
+ rev += 1;
126
+ return { ok: true, quarantined: target };
127
+ }
128
+ });
129
+ }
101
130
  function invalidate() {
102
131
  cache = null;
103
132
  rev += 1;
104
133
  }
105
- return { read, snapshot, revision: () => rev, mutate, invalidate };
134
+ return { read, snapshot, revision: () => rev, mutate, repair, invalidate };
106
135
  }
@@ -92,6 +92,24 @@ export function withIntent(intent, domain, keys, state) {
92
92
  }
93
93
  return { ...intent, [domain]: map };
94
94
  }
95
+ /**
96
+ * 只保留 `keep` 里的键(返回新对象,不改入参)。
97
+ *
98
+ * 资源被删除后它的意图要跟着消失:否则重新创建同名资源会继承旧的 off / blocked,
99
+ * 用户以为新资源默认能用,实际被一条已经无主的决定压着。调用方必须**先确认清单完整**:
100
+ * 清单读失败时传空集合会把所有意图清掉,那比不清理危险得多。
101
+ */
102
+ export function pruneIntentKeys(intent, domain, keep) {
103
+ let changed = false;
104
+ const next = Object.create(null);
105
+ for (const [key, state] of Object.entries(intent[domain])) {
106
+ if (keep.has(key))
107
+ next[key] = state;
108
+ else
109
+ changed = true;
110
+ }
111
+ return changed ? { ...intent, [domain]: next } : intent;
112
+ }
95
113
  /**
96
114
  * 一台服务器 / 一个来源在某个会话里的可见性。`lower` 是会话的那三层
97
115
  * (覆盖 → 场景层 → 基线)的并值,`undefined` = 三层都没话说。
@@ -235,10 +235,38 @@ export function createScopeStore(deps) {
235
235
  }
236
236
  });
237
237
  }
238
+ async function repair() {
239
+ return deps.withWriteLock(async () => {
240
+ let raw;
241
+ try {
242
+ raw = await readFile(file(), 'utf8');
243
+ }
244
+ catch (e) {
245
+ if (e?.code === 'ENOENT')
246
+ return { ok: true, quarantined: null };
247
+ return { ok: false, error: deps.message(e) };
248
+ }
249
+ try {
250
+ normalizeScopeOverrides(JSON.parse(raw));
251
+ return { ok: true, quarantined: null };
252
+ }
253
+ catch {
254
+ const target = file() + '.corrupt-' + Date.now();
255
+ try {
256
+ await renameWithRetry(file(), target);
257
+ }
258
+ catch (e) {
259
+ return { ok: false, error: deps.message(e) };
260
+ }
261
+ cache = null;
262
+ return { ok: true, quarantined: target };
263
+ }
264
+ });
265
+ }
238
266
  function invalidate() {
239
267
  cache = null;
240
268
  }
241
- return { read, readStrict, snapshot, mode, modeSync, scopeOf, scopeOfSync, switchMode, mutate, mutateAll, clearSession, pruneDeletedSessions, invalidate };
269
+ return { read, readStrict, snapshot, mode, modeSync, scopeOf, scopeOfSync, switchMode, mutate, mutateAll, clearSession, pruneDeletedSessions, repair, invalidate };
242
270
  }
243
271
  /**
244
272
  * 剪枝的**纯函数**部分(导出给契约测试):留下 `live` 里有的会话。
@@ -7,7 +7,12 @@
7
7
  // · 挑不出来就说 `no-compatible-version`,不给"最新版"这种没有意义的答案;
8
8
  // · 命令固定 `dsh plugin --profile <p> add <pkg>@<version>`,**绝不出现 `@latest`**。
9
9
  //
10
- // 网络策略:只请求 npm registry;3 秒硬超时;检测到代理环境变量直接返回 `proxy-unsupported`,
10
+ // 下载源跟宿主走,不自己再定一套:`pluginManager.registries()` 给出配置的第一源与 fallback,
11
+ // `pluginRegistryProbe.fastest()` 是宿主自己的双源测速;两个都取不到时退回 npm 官方单源。
12
+ // 这里只把宿主的顺序落成请求顺序 —— 私有源优先是用户明确配置的意图,测速结果不许把它挤后。
13
+ //
14
+ // 网络策略:只请求 npm registry(不穿透代理);首源 3 秒、回退源 4 秒——镜像的元数据可能比
15
+ // `/ping` 慢得多,3 秒会把能通的路判死;检测到代理环境变量直接返回 `proxy-unsupported`,
11
16
  // 不尝试穿透(穿透失败会挂住启动流程,而这件事本来就不该阻塞任何东西)。
12
17
  import { mkdir, readFile } from 'node:fs/promises';
13
18
  import { join } from 'node:path';
@@ -17,17 +22,161 @@ import { writeFileAtomically } from './memories/index-io.js';
17
22
  export const UPDATE_CHECK_FILE = 'update-check.json';
18
23
  /** 本插件在 npm 上的包名 —— 查更新与拼安装命令都用它。 */
19
24
  export const PACKAGE_NAME = 'dsh-plugin-tool-management';
20
- /** npm registry 的元数据地址(只读一次、3 秒超时、走系统代理设置)。 */
21
- export const REGISTRY_URL = 'https://registry.npmjs.org/' + PACKAGE_NAME;
25
+ /** npm 官方 registry:没有宿主登记时的唯一来源,也是单源回退的默认值。 */
26
+ const DEFAULT_REGISTRY = 'https://registry.npmjs.org/';
27
+ /** npm registry 的元数据地址(单源回退时使用)。 */
28
+ export const REGISTRY_URL = DEFAULT_REGISTRY + PACKAGE_NAME;
29
+ /** 公网源集合:宿主测速只覆盖这两个,只有它们能被测速结果提到最前。 */
30
+ const PUBLIC_REGISTRIES = new Set([DEFAULT_REGISTRY, 'https://registry.npmmirror.com/']);
31
+ /**
32
+ * registry 元数据的响应体上限(8 MiB)。
33
+ *
34
+ * 本包的 install-v1 元数据只有几十 KiB;上限只用来挡住恶意或误配的源在超时前推来
35
+ * 数百 MB —— `res.json()` 本身不设限,宿主与插件同进程,内存峰值会直接拖垮宿主。
36
+ */
37
+ const MAX_REGISTRY_BYTES = 8 * 1024 * 1024;
22
38
  /** 代理环境变量:命中任意一个就当作"网络路径不确定",不尝试请求。 */
23
39
  export function proxyDetected(env) {
24
40
  return ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy']
25
41
  .some((key) => String(env[key] || '').trim() !== '');
26
42
  }
43
+ /**
44
+ * 规范成与 pnpm 比较时同样的形状:http(s)、主机小写、路径以 `/` 结尾。
45
+ *
46
+ * 保留路径与端口 —— 私有源常挂在反向代理的子路径下(`/artifactory/api/npm/`),
47
+ * 砍掉就指到别处去了。
48
+ *
49
+ * @param raw 配置里的原始地址
50
+ * @returns 规范化后的地址;不是合法 http(s) URL 时 null
51
+ */
52
+ function normalizeRegistry(raw) {
53
+ const text = String(raw ?? '').trim();
54
+ if (text === '')
55
+ return null;
56
+ try {
57
+ const url = new URL(text);
58
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
59
+ return null;
60
+ if (!url.pathname.endsWith('/'))
61
+ url.pathname += '/';
62
+ url.search = '';
63
+ url.hash = '';
64
+ // 凭据走 ~/.npmrc(宿主安装器的口径),不跟着地址进缓存与界面。
65
+ url.username = '';
66
+ url.password = '';
67
+ return url.toString();
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ /**
74
+ * 把宿主的下载源登记整理成按序尝试的列表。
75
+ *
76
+ * 顺序就是宿主安装器自己的顺序:配置的第一源 → fallback 列表 →(配置为空时)pnpm 解析到的源。
77
+ * 测速结果只在**首项本来就是公网源**时提前:首项是私有源时保持用户配置的顺序,
78
+ * 一次公网测速不许把私有源挤到后面。
79
+ *
80
+ * @param configured 宿主登记;null(取不到)→ 返回空数组,由调用方走 npm 官方单源
81
+ * @param fastest 测速命中的源;null = 没测或都不可达
82
+ * @returns 规范化、去重后的源列表;可能为空
83
+ */
84
+ export function sourcePlan(configured, fastest) {
85
+ if (!configured)
86
+ return [];
87
+ const first = normalizeRegistry(configured.registry) ?? normalizeRegistry(configured.resolved);
88
+ const plan = [];
89
+ for (const raw of [first, ...configured.fallbackRegistries.map(normalizeRegistry)]) {
90
+ if (raw !== null && !plan.includes(raw))
91
+ plan.push(raw);
92
+ }
93
+ const probed = normalizeRegistry(fastest);
94
+ const head = plan[0];
95
+ if (probed !== null && plan.includes(probed) && (head === undefined || PUBLIC_REGISTRIES.has(head))) {
96
+ return [probed, ...plan.filter((registry) => registry !== probed)];
97
+ }
98
+ return plan;
99
+ }
100
+ /**
101
+ * 限时等待外部答案;超时或抛错都得到 null。
102
+ *
103
+ * 超时的那次调用没法取消(宿主的 pnpm 子进程照跑),但这里不等它 ——
104
+ * 更新检查不该被一次 pnpm 慢启动拖住。
105
+ */
106
+ async function settleWithin(run, ms) {
107
+ if (!run)
108
+ return null;
109
+ let timer;
110
+ try {
111
+ return await Promise.race([
112
+ run().catch(() => null),
113
+ new Promise((resolvePromise) => { timer = setTimeout(() => resolvePromise(null), ms); }),
114
+ ]);
115
+ }
116
+ finally {
117
+ if (timer !== undefined)
118
+ clearTimeout(timer);
119
+ }
120
+ }
121
+ /**
122
+ * 读一份 registry 元数据,流式累计并限制响应体大小。
123
+ *
124
+ * @param fetchImpl 注入的 fetch(便于测试)
125
+ * @param url 完整元数据地址
126
+ * @param timeoutMs 本次请求的超时(与调用方的首源 / 回退源预算一致)
127
+ * @returns 解析后的元数据
128
+ * @throws 非 2xx、响应体超过 `MAX_REGISTRY_BYTES`、超时或 JSON 不合法
129
+ */
130
+ async function readRegistryMeta(fetchImpl, url, timeoutMs) {
131
+ const res = await fetchImpl(url, {
132
+ headers: { accept: 'application/vnd.npm.install-v1+json' },
133
+ signal: AbortSignal.timeout(timeoutMs),
134
+ });
135
+ if (!res.ok)
136
+ throw new Error('registry HTTP ' + res.status);
137
+ const declared = Number(res.headers.get('content-length'));
138
+ if (Number.isFinite(declared) && declared > MAX_REGISTRY_BYTES)
139
+ throw new Error('registry response too large');
140
+ const body = res.body;
141
+ let text;
142
+ if (body && typeof body.getReader === 'function') {
143
+ const reader = body.getReader();
144
+ const chunks = [];
145
+ let total = 0;
146
+ try {
147
+ for (;;) {
148
+ const { done, value } = await reader.read();
149
+ if (done)
150
+ break;
151
+ if (!value)
152
+ continue;
153
+ total += value.byteLength;
154
+ if (total > MAX_REGISTRY_BYTES)
155
+ throw new Error('registry response too large');
156
+ chunks.push(value);
157
+ }
158
+ }
159
+ finally {
160
+ try {
161
+ await reader.cancel?.();
162
+ }
163
+ catch { /* 已经读完或已中止 */ }
164
+ }
165
+ text = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)), total).toString('utf8');
166
+ }
167
+ else {
168
+ // 没有流实现的 fetch(测试替身 / 老运行时):只能读完再校验,至少不把超大文本交给 JSON.parse。
169
+ text = await res.text();
170
+ if (Buffer.byteLength(text, 'utf8') > MAX_REGISTRY_BYTES)
171
+ throw new Error('registry response too large');
172
+ }
173
+ return JSON.parse(text);
174
+ }
27
175
  /**
28
176
  * 从 registry 的 `versions` 里挑与 `host` 兼容的最高版本。
29
177
  *
30
178
  * 兼容判据是**每个版本自己的** `engines.dsh`:没有该字段、不是合法 range、或不满足 → 跳过。
179
+ * 被维护者标记 `deprecated` 的版本也跳过 —— 它可能仍满足 range,但正是维护者明确不建议装的。
31
180
  * `host` 为空 / 非法 → `null`(调用方报 `host-unknown`)。
32
181
  */
33
182
  export function pickBestCompatible(versions, host) {
@@ -40,6 +189,9 @@ export function pickBestCompatible(versions, host) {
40
189
  for (const { version, meta } of list) {
41
190
  if (!semver.valid(version))
42
191
  continue;
192
+ const deprecated = meta && meta.deprecated;
193
+ if (deprecated !== undefined && deprecated !== null && deprecated !== false && deprecated !== '')
194
+ continue;
43
195
  const range = meta && meta.engines && typeof meta.engines.dsh === 'string' ? meta.engines.dsh.trim() : '';
44
196
  if (range === '')
45
197
  continue;
@@ -86,11 +238,14 @@ export function installCommand(profile, version) {
86
238
  return 'dsh plugin --profile ' + (profile && profile.trim() !== '' ? profile.trim() : '<profile>') +
87
239
  ' add ' + PACKAGE_NAME + '@' + version;
88
240
  }
89
- /** 更新检查器:按 TTL 缓存结果,3 秒超时,检测到代理直接跳过,绝不自动更新。 */
241
+ /** 更新检查器:按 TTL 缓存结果,源跟随宿主登记,检测到代理直接跳过,绝不自动更新。 */
90
242
  export function createUpdateChecker(options) {
91
243
  const ttlMs = options.ttlMs ?? 12 * 60 * 60 * 1000;
92
244
  const failureTtlMs = options.failureTtlMs ?? 60 * 60 * 1000;
93
245
  const timeoutMs = options.timeoutMs ?? 3000;
246
+ const fallbackTimeoutMs = options.fallbackTimeoutMs ?? 4000;
247
+ const planTimeoutMs = options.planTimeoutMs ?? 2500;
248
+ const probeTimeoutMs = options.probeTimeoutMs ?? 2000;
94
249
  const env = options.env ?? process.env;
95
250
  const now = options.now ?? Date.now;
96
251
  const cacheFile = join(options.stateDir, UPDATE_CHECK_FILE);
@@ -110,12 +265,14 @@ export function createUpdateChecker(options) {
110
265
  host,
111
266
  newest: null,
112
267
  bestCompatible: null,
268
+ source: null,
113
269
  command: null,
114
270
  };
115
271
  };
116
272
  const finish = (status, extra = {}) => {
117
273
  const result = {
118
- ok: status !== 'unknown',
274
+ // `host-unknown` 是"这一拍读不到宿主版本",不是结论:按失败 TTL 缓存,等宿主就绪后重试。
275
+ ok: status !== 'unknown' && status !== 'host-unknown',
119
276
  ...base(),
120
277
  status,
121
278
  checkedAt: new Date(now()).toISOString(),
@@ -145,7 +302,13 @@ export function createUpdateChecker(options) {
145
302
  const ttl = raw.ok === false ? failureTtlMs : ttlMs;
146
303
  if (age > ttl)
147
304
  return null;
148
- const result = { ...raw, fromCache: true };
305
+ // 旧缓存没有 `source`:按 null 处理,装的时候不指定源即可,不算无效缓存。
306
+ const result = { ...raw, fromCache: true, source: typeof raw.source === 'string' ? raw.source : null };
307
+ // 命令按当前 profile 重建:启动早期的检查可能还没有 profile 名,缓存里的 `<profile>` 不能一直留着。
308
+ if (result.bestCompatible) {
309
+ const profile = typeof options.profile === 'function' ? options.profile() : options.profile;
310
+ result.command = installCommand(profile, result.bestCompatible);
311
+ }
149
312
  last = result;
150
313
  return result;
151
314
  }
@@ -162,6 +325,18 @@ export function createUpdateChecker(options) {
162
325
  // 缓存写不进去不影响结论:下一次重新请求即可。
163
326
  }
164
327
  };
328
+ /** 宿主登记 + 测速 → 本次按序尝试的源;登记取不到时返回空数组,调用方走默认单源。 */
329
+ const resolveSources = async () => {
330
+ const configured = await settleWithin(options.registries, planTimeoutMs);
331
+ if (!configured)
332
+ return [];
333
+ const head = sourcePlan(configured, null)[0];
334
+ // 首项已是私有源时不测速:测速只覆盖两个公网源,把结果提到私有源前面是错的。
335
+ const probed = head === undefined || PUBLIC_REGISTRIES.has(head)
336
+ ? await settleWithin(options.fastest, probeTimeoutMs)
337
+ : null;
338
+ return sourcePlan(configured, probed);
339
+ };
165
340
  const run = async () => {
166
341
  const b = base();
167
342
  if (proxyDetected(env))
@@ -171,20 +346,24 @@ export function createUpdateChecker(options) {
171
346
  const fetchImpl = options.fetchImpl ?? globalThis.fetch;
172
347
  if (typeof fetchImpl !== 'function')
173
348
  return finish('unknown', { ok: false, error: 'fetch unavailable' });
174
- let meta;
175
- try {
176
- const res = await fetchImpl(REGISTRY_URL, {
177
- headers: { accept: 'application/vnd.npm.install-v1+json' },
178
- signal: AbortSignal.timeout(timeoutMs),
179
- });
180
- if (!res.ok)
181
- return finish('unknown', { ok: false, error: 'registry HTTP ' + res.status });
182
- meta = await res.json();
183
- }
184
- catch (e) {
185
- const message = e instanceof Error ? e.message : String(e);
186
- return finish('unknown', { ok: false, error: message });
349
+ const plan = await resolveSources();
350
+ // 最多试两个:首项(通常已经过测速)失败时用回退源兜一次,再多只是把等待拖长。
351
+ const sources = plan.length ? plan.slice(0, 2) : [DEFAULT_REGISTRY];
352
+ let meta = null;
353
+ let source = null;
354
+ let lastError = '';
355
+ for (const [index, registry] of sources.entries()) {
356
+ try {
357
+ meta = await readRegistryMeta(fetchImpl, registry + PACKAGE_NAME, index === 0 ? timeoutMs : fallbackTimeoutMs);
358
+ source = registry;
359
+ break;
360
+ }
361
+ catch (e) {
362
+ lastError = e instanceof Error ? e.message : String(e);
363
+ }
187
364
  }
365
+ if (!meta)
366
+ return finish('unknown', { ok: false, error: lastError || 'registry unreachable' });
188
367
  const versions = meta && meta.versions && typeof meta.versions === 'object' ? meta.versions : {};
189
368
  const all = Object.keys(versions).filter((v) => semver.valid(v));
190
369
  const newest = all.length ? semver.rsort(all)[0] : (meta && meta['dist-tags'] && meta['dist-tags'].latest) || null;
@@ -195,7 +374,7 @@ export function createUpdateChecker(options) {
195
374
  bestCompatible,
196
375
  currentEngines: options.currentEngines ?? null,
197
376
  });
198
- return finish(status, { newest, bestCompatible });
377
+ return finish(status, { newest, bestCompatible, source });
199
378
  };
200
379
  const check = async (force) => {
201
380
  if (!force) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-tool-management",
3
- "version": "0.21.7",
3
+ "version": "0.21.8",
4
4
  "description": "一个设置面板,统一管理 MCP、技能、记忆、子智能体、提示词和归档会话;可自定义搭配场景,一个场景即可切换整个环境;Agent也能帮你操作这个插件。",
5
5
  "repository": {
6
6
  "type": "git",
@@ -96,17 +96,17 @@
96
96
  },
97
97
  "devDependencies": {
98
98
  "@deepseek-ai/cordis": "^4.0.5",
99
- "@deepseek-ai/dsh-agent-preset-registry": "^0.2.1-rc.2",
100
- "@deepseek-ai/dsh-llm": "^0.2.1-rc.2",
101
- "@deepseek-ai/dsh-session": "^0.2.1-rc.2",
102
- "@deepseek-ai/dsh-session-projection-cache": "^0.2.1-rc.2",
103
- "@deepseek-ai/dsh-settings": "^0.2.1-rc.2",
104
- "@deepseek-ai/dsh-spill-local": "^0.2.1-rc.2",
105
- "@deepseek-ai/dsh-storage-domain": "^0.2.1-rc.2",
106
- "@deepseek-ai/dsh-subagent-fork-in-process": "^0.2.1-rc.2",
107
- "@deepseek-ai/dsh-subagent-spawn-in-process": "^0.2.1-rc.2",
108
- "@deepseek-ai/dsh-tools": "^0.2.1-rc.2",
109
- "@deepseek-ai/dsh-workspace": "^0.2.1-rc.2",
99
+ "@deepseek-ai/dsh-agent-preset-registry": "^0.2.1-rc.3",
100
+ "@deepseek-ai/dsh-llm": "^0.2.1-rc.3",
101
+ "@deepseek-ai/dsh-session": "^0.2.1-rc.3",
102
+ "@deepseek-ai/dsh-session-projection-cache": "^0.2.1-rc.3",
103
+ "@deepseek-ai/dsh-settings": "^0.2.1-rc.3",
104
+ "@deepseek-ai/dsh-spill-local": "^0.2.1-rc.3",
105
+ "@deepseek-ai/dsh-storage-domain": "^0.2.1-rc.3",
106
+ "@deepseek-ai/dsh-subagent-fork-in-process": "^0.2.1-rc.3",
107
+ "@deepseek-ai/dsh-subagent-spawn-in-process": "^0.2.1-rc.3",
108
+ "@deepseek-ai/dsh-tools": "^0.2.1-rc.3",
109
+ "@deepseek-ai/dsh-workspace": "^0.2.1-rc.3",
110
110
  "@types/js-yaml": "^4.0.9",
111
111
  "@types/node": "^24.0.0",
112
112
  "@types/semver": "^7.7.0",