dsh-capability-switch 1.4.9 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # 更新记录
2
2
 
3
+ ## 1.5.1
4
+
5
+ 完善更新检查反馈与布局。
6
+
7
+ - 有可用更新时显示最新版本号、当前版本号和“更新到该版本”按钮。
8
+ - 没有可用更新时,点击“检查更新”显示“当前已是最新版本”和当前版本号。
9
+ - 更新结果统一显示在标题区下方的状态条,不再与普通操作通知重复。
10
+ - 检查过程中显示“正在检查”,失败时可重试。
11
+ - 更新状态使用 DSH 主题令牌、状态图标和响应式布局。
12
+
13
+ ## 1.5.0
14
+
15
+ 新增 npm 自动更新机制。
16
+
17
+ - 启动后延迟检查,并每 6 小时检查一次 npm registry。
18
+ - 仅对 npm registry 安装启用自动更新。
19
+ - 本地目录链接和 Git 固定提交安装不会自我替换。
20
+ - 只选择兼容当前 DSH 的稳定版本,跳过预发布、弃用和不包含 bundle 的版本。
21
+ - 通过 DSH `pluginManager.updateBundle` 安装,支持 HMR 热更新;无 HMR 时提示重启。
22
+ - 顶部增加当前版本、自动更新开关、检查更新和更新状态。
23
+ - 自动更新偏好保存在 `~/.dsh/capability-switch/update-preferences.json`。
24
+ - 新增 `/update/check`、`/update/apply` 和 `/update/config` Host 路由。
25
+ - 补充自动更新测试与 README 说明。
26
+
3
27
  ## 1.4.9
4
28
 
5
29
  收尾修复审查问题。
package/README.md CHANGED
@@ -108,7 +108,13 @@ $WORKSPACE/.agents/skills
108
108
 
109
109
  当前版本针对 DSH `0.2.2-rc.5` 开发和验证。DSH 的其他版本可能调整服务接口。
110
110
 
111
- 从源码安装:
111
+ 从 npm 安装,支持自动更新:
112
+
113
+ ```bash
114
+ dsh plugin --profile desktop add dsh-capability-switch
115
+ ```
116
+
117
+ 从源码安装(本地目录安装不会自动更新):
112
118
 
113
119
  ```bash
114
120
  git clone https://github.com/lock-down/dsh-capability-switch.git
@@ -118,14 +124,32 @@ npm install --ignore-scripts
118
124
 
119
125
  在 DSH 中打开“插件”,选择“添加插件”,然后选择这个目录。安装完成后,左侧边栏会出现 `技能与MCP`。
120
126
 
121
- 也可以下载 GitHub Release 中的 `dsh-capability-switch-1.4.9.tgz`,解压后按上面的目录方式安装。
127
+ 也可以下载 GitHub Release 中的 `dsh-capability-switch-1.5.1.tgz`,解压后按上面的目录方式安装。
122
128
 
123
- 从 GitHub 固定版本安装:
129
+ 从 GitHub 固定版本安装(Git 安装不会自动更新):
124
130
 
125
131
  ```bash
126
- dsh plugin --profile desktop add "git+https://github.com/lock-down/dsh-capability-switch.git#v1.4.9"
132
+ dsh plugin --profile desktop add "git+https://github.com/lock-down/dsh-capability-switch.git#v1.5.1"
127
133
  ```
128
134
 
135
+ ## 自动更新
136
+
137
+ 通过 npm 安装的插件会自动检查并更新到兼容的稳定版本:
138
+
139
+ - 启动约 45 秒后检查一次,之后每 6 小时检查一次。
140
+ - 只更新 npm registry 安装的 `dsh-capability-switch`。
141
+ - 本地目录链接和 Git 固定提交安装不会自我替换。
142
+ - 只选择 `bundle: true`、未弃用、非预发布且兼容当前 DSH 的版本。
143
+ - 更新通过 DSH 的 `pluginManager.updateBundle` 完成。
144
+ - 有 HMR 时安装后自动加载;没有 HMR 时提示重启 DSH。
145
+ - 自动更新不会修改 Skills、MCP、工作区或同步状态。
146
+
147
+ 顶部显示当前版本、自动更新开关和“检查更新”。发现新版本时,状态条会同时显示最新版本号和当前版本号,并提供“更新到该版本”按钮;没有可用更新时,手动检查会明确显示“当前已是最新版本”和当前版本号。关闭自动更新后仍可手动检查和安装。设置保存在 `~/.dsh/capability-switch/update-preferences.json`。
148
+
149
+ `1.5.0` 是首个带自动更新机制的版本;`1.4.9` 及更早版本需要手动安装一次 `1.5.0`,之后的新版本才会自动更新。
150
+
151
+ 更新检查会访问 npm registry 读取版本列表;不会上传本机 Skills 或 MCP 配置。
152
+
129
153
  ## 使用
130
154
 
131
155
  ### 同步 Skills
@@ -171,11 +195,13 @@ dsh plugin --profile desktop add "git+https://github.com/lock-down/dsh-capabilit
171
195
  - `~/.dsh/capability-switch/backups`
172
196
  - `~/.dsh/capability-switch/trash`
173
197
  - `~/.dsh/capability-switch/skill-sync-backups`
198
+ - `~/.dsh/capability-switch/skill-sync-state.json`
199
+ - `~/.dsh/capability-switch/update-preferences.json`
174
200
  - 当前 DSH profile 的 `cordis.patch.yml`
175
201
 
176
202
  删除独立 MCP 前,原 profile 补丁会备份到 `~/.dsh/capability-switch/backups`。
177
203
 
178
- 插件不上传技能、MCP 配置或凭据。MCP 连接由 DSH 的 MCP Manager 和对应 MCP 服务处理。
204
+ 插件不上传技能、MCP 配置或凭据。自动更新只访问 npm registry 读取版本列表并安装插件包;MCP 连接由 DSH 的 MCP Manager 和对应 MCP 服务处理。
179
205
 
180
206
  ## 开发
181
207
 
@@ -198,6 +224,7 @@ npm pack
198
224
  - 独立 MCP 编辑、只读权限、启停、补丁删除和备份
199
225
  - SSE 映射、表单与 JSON 编辑
200
226
  - Host 路由、代理工具和无损 JSON 输出
227
+ - npm registry 更新检查、稳定版本筛选、无更新状态和本地安装拒绝自动更新
201
228
 
202
229
  主要文件:
203
230
 
@@ -205,6 +232,7 @@ npm pack
205
232
  - `lib/client.js`:侧边栏界面
206
233
  - `lib/skills.js`:Skills 管理和同步
207
234
  - `lib/mcp.js`:MCP 管理和独立实例操作
235
+ - `lib/update.js`:npm 自动更新检查、下载和 DSH 插件管理器更新
208
236
  - `lib/imports.js`:其他应用的 MCP 配置读取
209
237
 
210
238
  ## 许可证
package/lib/client.js CHANGED
@@ -43,6 +43,8 @@ window.__ModuleLoader__.load({
43
43
  prefsTitle: '自定义显示', sidebarVisible: '在左侧边栏显示入口', sidebarLabel: '入口名称', defaultTab: '默认打开',
44
44
  showDescriptions: '显示描述与配置摘要', compactRows: '使用紧凑行距', prefsSaved: '显示偏好已保存到 DSH 配置',
45
45
  preferencesHint: '这些偏好保存在当前 DSH profile 中,重启后仍会保留。设置页始终保留,便于恢复侧边栏入口。',
46
+ autoUpdate: '自动更新', autoUpdateHint: '仅 npm 安装支持自动更新;会检查兼容的稳定版本并通过 DSH 插件管理器安装。', checkUpdate: '检查更新', checkingUpdate: '正在检查…',
47
+ updateAvailable: '发现新版本', updateAvailableDetail: '最新版本 v{latest} · 当前版本 v{current}', updateNow: '更新到 v{version}', updatingVersion: '正在更新到 v{version}…', updateCurrent: '当前已是最新版本', updateCurrentDetail: '当前版本 v{version}', updateUnsupported: '当前安装方式不自动更新', updateFailed: '更新失败:', updateRestart: '已安装 v{version},重启 DSH 后生效', updateDone: '已更新到 v{version}', updateAutoSaved: '自动更新设置已保存',
46
48
  userSkillsDir: '用户级技能目录', readonlyHint: '用户级和所有已注册工作区的 .agents 项目技能支持编辑、启停和删除;跨工作区修改会提示影响范围。',
47
49
  connected: '已连接', connecting: '连接中', reconnecting: '等待重连', failed: '连接失败', waiting: '等待凭据', closed: '已关闭',
48
50
  unknownStatus: '未知状态', toolCount: '{count} 个工具', invalidJson: 'JSON 格式不正确', empty: '暂无描述',
@@ -88,6 +90,8 @@ window.__ModuleLoader__.load({
88
90
  prefsTitle: 'Customize display', sidebarVisible: 'Show an entry in the left sidebar', sidebarLabel: 'Entry label', defaultTab: 'Open by default',
89
91
  showDescriptions: 'Show descriptions and configuration summaries', compactRows: 'Use compact rows', prefsSaved: 'Display preferences saved to the DSH configuration',
90
92
  preferencesHint: 'Preferences persist in the active DSH profile. The Settings page always remains available so you can restore the sidebar entry.',
93
+ autoUpdate: 'Auto update', autoUpdateHint: 'Only npm installs auto-update; compatible stable releases are installed through the DSH plugin manager.', checkUpdate: 'Check for updates', checkingUpdate: 'Checking…',
94
+ updateAvailable: 'New version available', updateAvailableDetail: 'Latest v{latest} · Current v{current}', updateNow: 'Update to v{version}', updatingVersion: 'Updating to v{version}…', updateCurrent: 'You are on the latest version', updateCurrentDetail: 'Current version v{version}', updateUnsupported: 'This install cannot auto-update', updateFailed: 'Update failed: ', updateRestart: 'Version v{version} is installed; restart DSH to apply', updateDone: 'Updated to v{version}', updateAutoSaved: 'Auto-update setting saved',
91
95
  userSkillsDir: 'User skill directory', readonlyHint: 'User and .agents project skills in every registered workspace support editing, toggling, and deletion; cross-workspace edits show their impact.',
92
96
  connected: 'Connected', connecting: 'Connecting', reconnecting: 'Reconnecting', failed: 'Failed', waiting: 'Waiting for credentials', closed: 'Closed',
93
97
  unknownStatus: 'Unknown status', toolCount: '{count} tools', invalidJson: 'Invalid JSON', empty: 'No description',
@@ -128,6 +132,16 @@ window.__ModuleLoader__.load({
128
132
  '.dsh-caps-title{font-size:24px;line-height:1.25;font-weight:650;letter-spacing:-.02em;margin:0 0 7px;}',
129
133
  '.dsh-caps-subtitle{color:var(--dsw-alias-label-secondary);margin:0;max-width:620px;}',
130
134
  '.dsh-caps-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}',
135
+ '.dsh-caps-update-actions{justify-content:flex-end;row-gap:10px;}',
136
+ '.dsh-caps-version{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;font-size:12px;}',
137
+ '.dsh-caps-update{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:16px;border:.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);}',
138
+ '.dsh-caps-update-icon{display:grid;place-items:center;flex:0 0 20px;color:var(--dsw-alias-label-secondary);}',
139
+ '.dsh-caps-update-copy{display:flex;flex:1;min-width:180px;flex-direction:column;gap:2px;}',
140
+ '.dsh-caps-update-title{color:var(--dsw-alias-label-primary);font-weight:600;}',
141
+ '.dsh-caps-update-detail{color:var(--dsw-alias-label-secondary);font-size:12px;font-variant-numeric:tabular-nums;}',
142
+ '.dsh-caps-update[data-state=available] .dsh-caps-update-icon{color:var(--dsw-alias-brand-primary);}',
143
+ '.dsh-caps-update[data-state=current] .dsh-caps-update-icon,.dsh-caps-update[data-state=updated] .dsh-caps-update-icon{color:var(--dsw-alias-state-success-primary);}',
144
+ '.dsh-caps-update[data-state=failed]{color:var(--dsw-alias-state-error-primary);background:color-mix(in srgb,var(--dsw-alias-state-error-primary) 7%,transparent);border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary) 24%,transparent);}',
131
145
  '.dsh-caps-btn{border:.5px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary);border-radius:7px;min-height:32px;padding:5px 11px;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:6px;white-space:nowrap;}',
132
146
  '.dsh-caps-btn:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);}',
133
147
  '.dsh-caps-btn:focus-visible,.dsh-caps-tab:focus-visible,.dsh-caps-switch:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px;}',
@@ -187,7 +201,7 @@ window.__ModuleLoader__.load({
187
201
  '.dsh-caps-sync-mode-icon{display:grid;place-items:center;color:var(--dsw-alias-label-secondary);padding-top:1px;}.dsh-caps-sync-mode.is-selected .dsh-caps-sync-mode-icon{color:var(--dsw-alias-brand-primary);}',
188
202
  '.dsh-caps-sync-mode-copy{display:flex;flex-direction:column;gap:2px;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.4;}.dsh-caps-sync-mode-copy strong{color:var(--dsw-alias-label-primary);font-weight:600;}',
189
203
  '.dsh-caps-modal-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:22px;}.dsh-caps-spinner{color:var(--dsw-alias-label-secondary);padding:30px 0;text-align:center;}',
190
- '@media(max-width:700px){.dsh-caps{--caps-pad:16px}.dsh-caps-shell{padding-top:20px}.dsh-caps-header{flex-direction:column}.dsh-caps-row{grid-template-columns:1fr}.dsh-caps-row-actions{justify-content:flex-start}.dsh-caps-toolbar{flex-wrap:wrap}.dsh-caps-search{flex-basis:100%}.dsh-caps-modal{padding:18px}.dsh-caps-workspace-fields,.dsh-caps-mcp-grid,.dsh-caps-sync-mode-list{grid-template-columns:1fr}}',
204
+ '@media(max-width:700px){.dsh-caps{--caps-pad:16px}.dsh-caps-shell{padding-top:20px}.dsh-caps-header{flex-direction:column}.dsh-caps-update-actions{justify-content:flex-start}.dsh-caps-row{grid-template-columns:1fr}.dsh-caps-row-actions{justify-content:flex-start}.dsh-caps-toolbar{flex-wrap:wrap}.dsh-caps-search{flex-basis:100%}.dsh-caps-modal{padding:18px}.dsh-caps-workspace-fields,.dsh-caps-mcp-grid,.dsh-caps-sync-mode-list{grid-template-columns:1fr}}',
191
205
  ].join('\n')
192
206
 
193
207
  function Icon({ name, size = 16 }) {
@@ -203,6 +217,9 @@ window.__ModuleLoader__.load({
203
217
  link: h('path', { d: 'M6.2 9.8 4.8 11.2a2.3 2.3 0 0 1-3.3-3.3l2.2-2.2a2.3 2.3 0 0 1 3.3 0M9.8 6.2l1.4-1.4a2.3 2.3 0 0 1 3.3 3.3l-2.2 2.2a2.3 2.3 0 0 1-3.3 0M5.5 10.5l5-5' }),
204
218
  copy: h('path', { d: 'M5.5 2.5h6a2 2 0 0 1 2 2v6M3 5.5h7.5v8H3z' }),
205
219
  close: h('path', { d: 'm4 4 8 8m0-8-8 8' }),
220
+ check: h('path', { d: 'm3 8.2 3.1 3.1L13 4.8' }),
221
+ download: h('path', { d: 'M8 2v8m-3-3 3 3 3-3M3 12.5h10' }),
222
+ info: h('path', { d: 'M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11ZM8 7v4M8 4.7v.2' }),
206
223
  }
207
224
  return h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, paths[name] || paths.settings)
208
225
  }
@@ -601,7 +618,7 @@ window.__ModuleLoader__.load({
601
618
  function CapabilityPanel({ cwd, preferenceStore }) {
602
619
  const prefs = React.useSyncExternalStore(preferenceStore.subscribe, preferenceStore.getSnapshot)
603
620
  const [tab, setTab] = useState(prefs.defaultTab)
604
- const [data, setData] = useState({ skills: [], mcp: [], workspaces: [], skillWarnings: [] })
621
+ const [data, setData] = useState({ skills: [], mcp: [], workspaces: [], skillWarnings: [], update: null })
605
622
  const [query, setQuery] = useState('')
606
623
  const [loading, setLoading] = useState(true)
607
624
  const [error, setError] = useState('')
@@ -639,6 +656,27 @@ window.__ModuleLoader__.load({
639
656
  return result || true
640
657
  }
641
658
 
659
+ const update = data.update || {}
660
+ const updateNotice = result => {
661
+ if (!result) return ''
662
+ if (result.state === 'available') return t('updateAvailable')
663
+ if (result.state === 'current') return t('updateCurrent')
664
+ if (result.state === 'updated') return t('updateDone', { version: result.latest })
665
+ if (result.state === 'restart-required') return t('updateRestart', { version: result.latest })
666
+ if (result.state === 'updating') return t('updatingVersion', { version: result.latest })
667
+ if (result.state === 'unsupported') return result.error || t('updateUnsupported')
668
+ if (result.state === 'failed') return t('updateFailed') + (result.error || '')
669
+ return ''
670
+ }
671
+ const updateDetail = update.state === 'available'
672
+ ? t('updateAvailableDetail', { latest: update.latest, current: update.current })
673
+ : update.state === 'current' ? t('updateCurrentDetail', { version: update.current }) : ''
674
+ const updateIcon = update.state === 'available' || update.state === 'updating' ? 'download'
675
+ : update.state === 'current' || update.state === 'updated' ? 'check' : 'info'
676
+ const checkForUpdates = () => perform('update-check', () => api('/update/check', { body: {} }), '')
677
+ const applyUpdate = version => perform('update-apply', () => api('/update/apply', { body: { version } }), '')
678
+ const setAutoUpdate = enabled => perform('update-config', () => api('/update/config', { body: { autoUpdate: enabled } }), t('updateAutoSaved'))
679
+
642
680
  const filtered = useMemo(() => {
643
681
  const needle = query.trim().toLowerCase()
644
682
  if (!needle) return data[tab] || []
@@ -742,7 +780,20 @@ window.__ModuleLoader__.load({
742
780
  h('style', null, CSS),
743
781
  h('div', { className: 'dsh-caps-shell', inert: (modal || confirm) ? '' : undefined, 'aria-hidden': (modal || confirm) ? true : undefined },
744
782
  h('header', { className: 'dsh-caps-header' },
745
- h('div', null, h('h1', { className: 'dsh-caps-title' }, t('title')), h('p', { className: 'dsh-caps-subtitle' }, t('subtitle')))),
783
+ h('div', null, h('h1', { className: 'dsh-caps-title' }, t('title')), h('p', { className: 'dsh-caps-subtitle' }, t('subtitle'))),
784
+ h('div', { className: 'dsh-caps-actions dsh-caps-update-actions' },
785
+ update.current ? h('span', { className: 'dsh-caps-version', title: t('autoUpdateHint') }, 'v' + update.current) : null,
786
+ h('label', { className: 'dsh-caps-check', title: t('autoUpdateHint') },
787
+ h('input', { type: 'checkbox', checked: update.autoUpdate !== false, disabled: Boolean(busy) || update.state === 'updating' || update.supported === false, onChange: event => setAutoUpdate(event.target.checked) }),
788
+ t('autoUpdate')),
789
+ h('button', { className: 'dsh-caps-btn', disabled: Boolean(busy) || update.state === 'updating', 'aria-busy': busy === 'update-check', onClick: checkForUpdates }, h(Icon, { name: 'refresh' }), t(busy === 'update-check' ? 'checkingUpdate' : 'checkUpdate')))),
790
+ ['available', 'current', 'updating', 'failed', 'restart-required', 'updated', 'unsupported'].includes(update.state) ? h('div', { className: 'dsh-caps-notice dsh-caps-update', 'data-state': update.state, role: update.state === 'failed' ? 'alert' : 'status', 'aria-live': 'polite' },
791
+ h('span', { className: 'dsh-caps-update-icon' }, h(Icon, { name: updateIcon, size: 18 })),
792
+ h('div', { className: 'dsh-caps-update-copy' },
793
+ h('div', { className: 'dsh-caps-update-title' }, updateNotice(update)),
794
+ updateDetail ? h('div', { className: 'dsh-caps-update-detail' }, updateDetail) : null),
795
+ update.state === 'available' ? h('button', { className: 'dsh-caps-btn dsh-caps-primary', disabled: Boolean(busy), onClick: () => applyUpdate(update.latest) }, t('updateNow', { version: update.latest }))
796
+ : update.state === 'failed' ? h('button', { className: 'dsh-caps-btn', disabled: Boolean(busy), onClick: checkForUpdates }, t('retry')) : null) : null,
746
797
  h('div', { className: 'dsh-caps-tabs' }, ['skills', 'mcp'].map(key => h('button', { key, 'aria-pressed': tab === key, className: 'dsh-caps-tab', onClick: () => setTab(key) }, t(key), h('span', { className: 'dsh-caps-count' }, (data[key] || []).length)))),
747
798
  h('div', { className: 'dsh-caps-toolbar' },
748
799
  h('div', { className: 'dsh-caps-search' }, h('span', { className: 'dsh-caps-search-icon' }, h(Icon, { name: 'search' })), h('input', { className: 'dsh-caps-input', type: 'search', value: query, onChange: e => setQuery(e.target.value), placeholder: t('search'), 'aria-label': t('search') })),
package/lib/index.js CHANGED
@@ -3,6 +3,7 @@ import { homedir } from 'node:os'
3
3
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
4
4
  import { listSkills, listProjectSkills, readSkill, createSkill, updateSkill, toggleSkill, deleteSkill, syncAgentSkills, previewAgentSkillSync, installSkillTakeover, invalidateSkillCatalog, dshHome } from './skills.js'
5
5
  import { listMcp, saveMcp, toggleMcp, deleteMcp, testMcp, restartMcp, listMcpImports, importMcp } from './mcp.js'
6
+ import { createUpdateManager } from './update.js'
6
7
 
7
8
  export const name = 'capability-switch'
8
9
  export const inject = ['tools', 'skills']
@@ -148,7 +149,7 @@ function requestedWorkspaceCwd(ctx, requestedCwd, sessionCwd) {
148
149
  return isRegisteredWorkspace(ctx, requestedCwd) ? resolve(requestedCwd) : sessionCwd
149
150
  }
150
151
 
151
- async function state(ctx, prefs, cwd, includeWorkspaces = true) {
152
+ async function state(ctx, prefs, cwd, includeWorkspaces = true, updates = null) {
152
153
  let mcp = []
153
154
  let mcpError
154
155
  try { mcp = await listMcp(ctx) } catch (error) { mcpError = error.message }
@@ -192,13 +193,14 @@ async function state(ctx, prefs, cwd, includeWorkspaces = true) {
192
193
  }
193
194
  return {
194
195
  ok: true, skills, mcp, skillWarnings, ...(mcpError === undefined ? {} : { mcpError }),
195
- prefs, dshHome: dshHome(), home: homedir(), userSkillsRoot: join(dshHome(), 'skills'), profile: currentProfile(ctx),
196
+ prefs, ...(updates ? { update: updates.status() } : {}),
197
+ dshHome: dshHome(), home: homedir(), userSkillsRoot: join(dshHome(), 'skills'), profile: currentProfile(ctx),
196
198
  workspace: currentWorkspacePath,
197
199
  workspaces,
198
200
  }
199
201
  }
200
202
 
201
- function tool(ctx, prefs) {
203
+ function tool(ctx, prefs, updates) {
202
204
  const mutateSkill = async operation => {
203
205
  const result = await operation()
204
206
  invalidateSkillCatalog(ctx)
@@ -236,7 +238,7 @@ function tool(ctx, prefs) {
236
238
  const trustedCwd = await currentAgentCwd(ctx)
237
239
  const requestedCwd = isRegisteredWorkspace(ctx, args.cwd) ? resolve(args.cwd) : trustedCwd
238
240
  switch (args.action) {
239
- case 'list': return await state(ctx, prefs, trustedCwd)
241
+ case 'list': return await state(ctx, prefs, trustedCwd, true, updates)
240
242
  case 'workspace_create': return await createWorkspace(ctx, { name: args.name, parent: args.parent })
241
243
  case 'skill_read': return await readSkill(args.path, requestedCwd)
242
244
  case 'skill_create': return await mutateSkill(() => createSkill({ ...args, cwd: projectCreateCwd(ctx, args, requestedCwd) }))
@@ -260,12 +262,14 @@ function tool(ctx, prefs) {
260
262
 
261
263
  export function apply(ctx, config = {}) {
262
264
  const prefs = normalizePreferences(config)
265
+ const updates = createUpdateManager(ctx)
263
266
  ctx.effect(() => installSkillTakeover(ctx), 'capability-switch: DSH skill takeover')
264
267
  invalidateSkillCatalog(ctx)
265
- ctx.effect(() => ctx.tools.register(tool(ctx, prefs)), 'capability-switch: agent tool')
268
+ ctx.effect(() => ctx.tools.register(tool(ctx, prefs, updates)), 'capability-switch: agent tool')
269
+ ctx.effect(() => updates.start(), 'capability-switch: auto update')
266
270
 
267
271
  const routes = [
268
- ['GET', '/state', async (_req, url, sessionCwd) => await state(ctx, prefs, sessionCwd || url.searchParams.get('cwd'), url.searchParams.get('workspaces') !== '0')],
272
+ ['GET', '/state', async (_req, url, sessionCwd) => await state(ctx, prefs, sessionCwd || url.searchParams.get('cwd'), url.searchParams.get('workspaces') !== '0', updates)],
269
273
  ['GET', '/skill', async (_req, url, sessionCwd) => await readSkill(url.searchParams.get('path'), requestedWorkspaceCwd(ctx, url.searchParams.get('cwd'), sessionCwd))],
270
274
  ['POST', '/skill/create', async (body, _url, sessionCwd) => await createSkill({ ...body, cwd: projectCreateCwd(ctx, body, sessionCwd) })],
271
275
  ['POST', '/workspace/create', async body => await createWorkspace(ctx, body)],
@@ -281,6 +285,9 @@ export function apply(ctx, config = {}) {
281
285
  ['POST', '/mcp/delete', async body => await deleteMcp(ctx, body.name, body.confirm)],
282
286
  ['POST', '/mcp/test', async body => await testMcp(ctx, body.name)],
283
287
  ['POST', '/mcp/restart', async body => await restartMcp(ctx, body.name)],
288
+ ['POST', '/update/config', async body => await updates.setAutoUpdate(body.autoUpdate === true)],
289
+ ['POST', '/update/check', async () => await updates.check()],
290
+ ['POST', '/update/apply', async body => await updates.apply(body.version)],
284
291
  ]
285
292
 
286
293
  const skillMutationPaths = new Set(['/skill/create', '/skill/update', '/skill/toggle', '/skill/delete', '/skill/sync'])
package/lib/update.js ADDED
@@ -0,0 +1,193 @@
1
+ import { promises as fs } from 'node:fs'
2
+ import { basename, dirname, join } from 'node:path'
3
+ import { createRequire } from 'node:module'
4
+ import { dshHome } from './skills.js'
5
+
6
+ export const UPDATE_BUNDLE = 'dsh-capability-switch'
7
+ const UPDATE_REGISTRY_PACKAGE = UPDATE_BUNDLE + '@'
8
+ const INITIAL_DELAY = 45_000
9
+ const CHECK_INTERVAL = 6 * 60 * 60 * 1000
10
+
11
+ function installedVersion() {
12
+ try { return createRequire(import.meta.url)('../package.json').version } catch { return null }
13
+ }
14
+
15
+ function preferencesPath() {
16
+ return join(dshHome(), 'capability-switch', 'update-preferences.json')
17
+ }
18
+
19
+ async function readPreferences() {
20
+ try {
21
+ const parsed = JSON.parse(await fs.readFile(preferencesPath(), 'utf8'))
22
+ return { autoUpdate: parsed?.autoUpdate !== false }
23
+ } catch {
24
+ return { autoUpdate: true }
25
+ }
26
+ }
27
+
28
+ async function writePreferences(value) {
29
+ const file = preferencesPath()
30
+ await fs.mkdir(dirname(file), { recursive: true })
31
+ const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.tmp`)
32
+ await fs.writeFile(temporary, JSON.stringify({ autoUpdate: value.autoUpdate !== false }, null, 2) + '\n')
33
+ await fs.rename(temporary, file)
34
+ }
35
+
36
+ function statusMessage(error) {
37
+ return error?.message || String(error)
38
+ }
39
+
40
+ /**
41
+ * Keep the npm-installed copy current through DSH's plugin manager.
42
+ * Local links, Git installs, and incompatible releases are deliberately left alone.
43
+ */
44
+ export function createUpdateManager(ctx) {
45
+ let current = installedVersion()
46
+ let latest = null
47
+ let phase = 'idle'
48
+ let error = null
49
+ let checkedAt = null
50
+ let autoUpdate = true
51
+ let supported = null
52
+ let running = null
53
+ let timer = null
54
+ let interval = null
55
+
56
+ const manager = () => {
57
+ const value = ctx.get('pluginManager')
58
+ return value && typeof value.listBundles === 'function' && typeof value.listVersions === 'function' && typeof value.updateBundle === 'function'
59
+ ? value
60
+ : null
61
+ }
62
+
63
+ const status = () => ({
64
+ name: UPDATE_BUNDLE,
65
+ current,
66
+ latest,
67
+ state: phase,
68
+ error,
69
+ checkedAt,
70
+ autoUpdate,
71
+ supported,
72
+ })
73
+
74
+ async function loadPreferences() {
75
+ const preferences = await readPreferences()
76
+ autoUpdate = preferences.autoUpdate
77
+ return status()
78
+ }
79
+
80
+ async function setAutoUpdate(enabled) {
81
+ autoUpdate = enabled !== false
82
+ await writePreferences({ autoUpdate })
83
+ return status()
84
+ }
85
+
86
+ async function check({ auto = false } = {}) {
87
+ if (running) return running
88
+ running = (async () => {
89
+ const pluginManager = manager()
90
+ if (!pluginManager) {
91
+ phase = 'unsupported'
92
+ supported = false
93
+ error = '当前 DSH 未提供插件管理器'
94
+ checkedAt = new Date().toISOString()
95
+ return status()
96
+ }
97
+ try {
98
+ const bundles = await pluginManager.listBundles()
99
+ const bundle = Array.isArray(bundles) ? bundles.find(item => item?.name === UPDATE_BUNDLE) : null
100
+ if (bundle?.version) current = bundle.version
101
+ supported = bundle?.update === 'registry'
102
+ && typeof bundle.source === 'string'
103
+ && bundle.source.startsWith(UPDATE_REGISTRY_PACKAGE)
104
+ if (!supported) {
105
+ phase = 'unsupported'
106
+ error = bundle?.source?.startsWith('link:')
107
+ ? '本地目录安装不支持自动更新,请改用 npm 安装'
108
+ : '当前安装来源不支持自动更新,请改用 npm 安装'
109
+ checkedAt = new Date().toISOString()
110
+ return status()
111
+ }
112
+ const listed = await pluginManager.listVersions(UPDATE_BUNDLE)
113
+ if (listed?.status !== 'listed') {
114
+ phase = 'failed'
115
+ error = listed?.reason || '无法读取 npm 版本列表'
116
+ checkedAt = new Date().toISOString()
117
+ return status()
118
+ }
119
+ const candidate = listed.versions.find(item => item?.bundle === true
120
+ && item.incompatible === undefined
121
+ && item.deprecated === undefined
122
+ && item.prerelease !== true
123
+ && item.version !== current)
124
+ checkedAt = new Date().toISOString()
125
+ latest = candidate?.version || null
126
+ if (!candidate) {
127
+ phase = 'current'
128
+ error = null
129
+ return status()
130
+ }
131
+ phase = 'available'
132
+ error = null
133
+ if (auto && autoUpdate) return await apply(candidate.version, pluginManager)
134
+ return status()
135
+ } catch (problem) {
136
+ phase = 'failed'
137
+ error = statusMessage(problem)
138
+ checkedAt = new Date().toISOString()
139
+ return status()
140
+ }
141
+ })().finally(() => { running = null })
142
+ return running
143
+ }
144
+
145
+ async function apply(version, knownManager) {
146
+ const pluginManager = knownManager || manager()
147
+ if (!pluginManager || !version) return status()
148
+ if (phase === 'updating') return status()
149
+ phase = 'updating'
150
+ latest = version
151
+ error = null
152
+ try {
153
+ const result = await pluginManager.updateBundle(UPDATE_BUNDLE, version)
154
+ const application = result?.result?.application
155
+ if (application === 'applied' || application === 'restart-required') {
156
+ current = version
157
+ phase = application === 'applied' ? 'updated' : 'restart-required'
158
+ } else {
159
+ phase = 'failed'
160
+ error = result?.result?.error?.diagnostic || result?.result?.error?.code || '插件管理器未完成更新'
161
+ }
162
+ } catch (problem) {
163
+ phase = 'failed'
164
+ error = statusMessage(problem)
165
+ }
166
+ checkedAt = new Date().toISOString()
167
+ return status()
168
+ }
169
+
170
+ function start() {
171
+ void loadPreferences()
172
+ const run = () => {
173
+ if (!autoUpdate) return
174
+ void check({ auto: true }).catch(problem => {
175
+ phase = 'failed'
176
+ error = statusMessage(problem)
177
+ checkedAt = new Date().toISOString()
178
+ })
179
+ }
180
+ timer = setTimeout(run, INITIAL_DELAY)
181
+ timer.unref?.()
182
+ interval = setInterval(run, CHECK_INTERVAL)
183
+ interval.unref?.()
184
+ return () => {
185
+ if (timer) clearTimeout(timer)
186
+ if (interval) clearInterval(interval)
187
+ timer = null
188
+ interval = null
189
+ }
190
+ }
191
+
192
+ return { status, check, apply, setAutoUpdate, loadPreferences, start }
193
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-capability-switch",
3
- "version": "1.4.9",
3
+ "version": "1.5.1",
4
4
  "description": "A DSH sidebar plugin for managing Skills and MCP servers.",
5
5
  "license": "MIT",
6
6
  "author": "lock-down",