@michengai/dsh-skills-manager 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ <p align="center">
2
+ <img src="assets/icon.png" alt="DSH Skills Manager" width="96">
3
+ </p>
4
+
5
+ <h1 align="center">DSH Skills Manager</h1>
6
+
7
+ <p align="center">
8
+ <strong>Manage local DeepSeek Harness skills with a clear boundary for shared Agent skills.</strong>
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://github.com/MichengAI/dsh-skills-manager/issues">Report an issue</a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <strong>English</strong> · <a href="README.zh-CN.md">简体中文</a>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-blue.svg" alt="Apache License 2.0"></a>
21
+ <img src="https://img.shields.io/badge/DSH-Web%20Plugin-10b981" alt="DSH Web Plugin">
22
+ <img src="https://img.shields.io/badge/Node.js-%E2%89%A520-339933?logo=nodedotjs&logoColor=white" alt="Node.js 20 or later">
23
+ </p>
24
+
25
+ <p align="center">
26
+ <img src="assets/screenshots/skills-manager.png" alt="Native file picker opened from the Skills settings panel" width="960">
27
+ </p>
28
+
29
+ > The screenshot shows the Skills panel layout. In the current plugin, shared Agent skills are read-only and do not expose action buttons.
30
+
31
+ > DSH Skills Manager is a community-maintained plugin. It is not an official DeepSeek AI product.
32
+
33
+ ## What it provides
34
+
35
+ - **Two skill groups** — view local `$DSH_HOME\skills` and shared `$DSH_AGENTS_HOME\skills` in one Settings panel.
36
+ - **Local lifecycle controls** — enable, disable, upload, replace, and delete only DSH-local skills.
37
+ - **Safe shared-skill view** — public Agent skills are visible but strictly read-only; their global metadata is never changed.
38
+ - **Native file selection** — select a plugin `SKILL.md` from the operating system file picker, or explicitly choose its directory when the client cannot expose the selected file path.
39
+ - **Protected replacement** — a same-name import always requires confirmation, including a flat skill and a bundled skill with the same normalized name.
40
+ - **Predictable dialogs** — Escape closes only the active upload or confirmation dialog, leaving the Settings page open.
41
+
42
+ ## Directory permissions
43
+
44
+ | Directory | View | Enable/Disable | Upload/Replace | Delete |
45
+ | --- | --- | --- | --- | --- |
46
+ | `$DSH_HOME\skills` | Yes | Yes | Yes | Yes |
47
+ | `$DSH_AGENTS_HOME\skills` | Yes | No | No | No |
48
+
49
+ The shared Agent directory is intentionally read-only in both the interface and the server API.
50
+
51
+ ## Install
52
+
53
+ Requirements: a working DeepSeek Harness Web installation. The published package declares Node.js 20 or later for the DSH runtime.
54
+
55
+ Install the published package into the Web profile:
56
+
57
+ ```powershell
58
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
59
+ $OutputEncoding = [System.Text.Encoding]::UTF8
60
+ dsh plugin --profile web add @michengai/dsh-skills-manager
61
+ ```
62
+
63
+ No source checkout is required. Restart DSH, then open **Settings → Skills**. If a package mirror has not synchronized the latest version yet, append `--registry=https://registry.npmjs.org/` to the install command.
64
+
65
+ ## How to use it
66
+
67
+ 1. Open **Settings → Skills**. The panel separates **DSH Skills** from **Shared Agent Skills** and shows each skill's name, form, description, and current invocation status.
68
+ 2. In **DSH Skills**, choose **Enable** or **Disable** to control both model invocation and the `/` manual command. Other `SKILL.md` metadata remains untouched.
69
+ 3. Choose **Upload Plugin** in the upper-right corner. Select the plugin directory's `SKILL.md`; the complete plugin directory is copied to `$DSH_HOME\skills`.
70
+ 4. When the browser does not provide the selected file path, use **Choose Plugin Directory** in the dialog and select the directory that contains `SKILL.md`.
71
+ 5. Confirm any replacement of a same-name skill. Use **Delete** only for DSH-local skills you no longer need.
72
+ 6. Treat **Shared Agent Skills** as an inspection list: their controls are deliberately unavailable so the shared global skill metadata stays unchanged.
73
+
74
+ ## Development and verification
75
+
76
+ ```powershell
77
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
78
+ $OutputEncoding = [System.Text.Encoding]::UTF8
79
+ node test\core-test.mjs
80
+ ```
81
+
82
+ ## Project documentation
83
+
84
+ Project status, usage boundaries, architecture, and iteration records start at the [documentation entry point](https://github.com/MichengAI/dsh-skills-manager/blob/master/docs/00-%E4%BA%A4%E6%8E%A5%E5%85%A5%E5%8F%A3/00-%E9%98%85%E8%AF%BB%E5%AF%BC%E8%88%AA.md). The Chinese operational guide is available at `docs\02-产品与业务\01-使用说明.md` in the repository.
85
+
86
+ ## Publishing
87
+
88
+ The user-level npm registry may point to a download mirror such as `registry.npmmirror.com`; mirrors do not accept publication. This package therefore pins publication to the official npm registry. A maintainer with npm publishing access can release the current version with:
89
+
90
+ ```powershell
91
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
92
+ $OutputEncoding = [System.Text.Encoding]::UTF8
93
+ npm login --registry=https://registry.npmjs.org/
94
+ npm publish
95
+ ```
96
+
97
+ `prepublishOnly` runs the core test suite before publication, and `publishConfig.registry` prevents `npm publish` from going to a configured download mirror. Use `npm run pack:check` to inspect the exact tarball contents without publishing.
98
+
99
+ ## License
100
+
101
+ Licensed under the [Apache License 2.0](LICENSE).
@@ -0,0 +1,101 @@
1
+ <p align="center">
2
+ <img src="assets/icon.png" alt="DSH Skills Manager" width="96">
3
+ </p>
4
+
5
+ <h1 align="center">DSH Skills Manager</h1>
6
+
7
+ <p align="center">
8
+ <strong>管理本地 DeepSeek Harness 技能,并为公共 Agent 技能提供清晰、安全的查看边界。</strong>
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://github.com/MichengAI/dsh-skills-manager/issues">反馈问题</a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <a href="README.md">English</a> · <strong>简体中文</strong>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-blue.svg" alt="Apache License 2.0"></a>
21
+ <img src="https://img.shields.io/badge/DSH-Web%20Plugin-10b981" alt="DSH Web Plugin">
22
+ <img src="https://img.shields.io/badge/Node.js-%E2%89%A520-339933?logo=nodedotjs&logoColor=white" alt="Node.js 20 或更高版本">
23
+ </p>
24
+
25
+ <p align="center">
26
+ <img src="assets/screenshots/skills-manager.png" alt="从技能设置面板打开的系统原生文件选择器" width="960">
27
+ </p>
28
+
29
+ > 截图展示技能面板的整体布局。当前版本中的公共 Agent 技能为只读,不会显示操作按钮。
30
+
31
+ > DSH Skills Manager 是社区维护的插件,并非 DeepSeek AI 官方产品。
32
+
33
+ ## 核心能力
34
+
35
+ - **双目录分组**:在一个设置面板中查看本地 `$DSH_HOME\skills` 与公共 `$DSH_AGENTS_HOME\skills`。
36
+ - **本地技能管理**:仅对 DSH 本地技能提供启用、停用、上传、覆盖和删除。
37
+ - **公共技能安全查看**:公共 Agent 技能可见但严格只读,绝不会改写其全局元数据。
38
+ - **系统原生选择**:通过操作系统文件选择器选择插件的 `SKILL.md`;客户端无法提供所选文件路径时,可显式选择插件目录。
39
+ - **覆盖保护**:导入同名技能一定要求确认;flat 与 bundle 两种形态同名时同样如此。
40
+ - **弹窗行为可预期**:按 ESC 只关闭当前上传框或确认框,不会关闭设置页面。
41
+
42
+ ## 目录权限
43
+
44
+ | 目录 | 查看 | 启用/停用 | 上传/覆盖 | 删除 |
45
+ | --- | --- | --- | --- | --- |
46
+ | `$DSH_HOME\skills` | 支持 | 支持 | 支持 | 支持 |
47
+ | `$DSH_AGENTS_HOME\skills` | 支持 | 不支持 | 不支持 | 不支持 |
48
+
49
+ 公共 Agent 目录在界面和服务端均为只读,用于避免误改共享的全局技能元数据。
50
+
51
+ ## 安装
52
+
53
+ 环境要求:可正常运行的 DeepSeek Harness Web 环境。已发布的包会声明 DSH 运行时需要 Node.js 20 或更高版本。
54
+
55
+ 将已发布 npm 包安装到 Web profile:
56
+
57
+ ```powershell
58
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
59
+ $OutputEncoding = [System.Text.Encoding]::UTF8
60
+ dsh plugin --profile web add @michengai/dsh-skills-manager
61
+ ```
62
+
63
+ 无需下载源码。重启 DSH 后,打开「设置 → 技能」。若软件源镜像尚未同步最新版本,可在安装命令末尾添加 `--registry=https://registry.npmjs.org/`。
64
+
65
+ ## 使用说明
66
+
67
+ 1. 打开「设置 → 技能」。面板会区分「DSH 技能」和「公共 Agent 技能」,并展示每个技能的名称、形态、说明和调用状态。
68
+ 2. 仅在「DSH 技能」分组中使用「启用」或「停用」。它会同步控制模型调用和 `/` 手动命令,且不会改写 `SKILL.md` 的其他元数据。
69
+ 3. 点击右上角「上传插件」,选择插件目录中的 `SKILL.md`;整个插件目录会复制到 `$DSH_HOME\skills`。
70
+ 4. 若客户端无法提供所选文件路径,在弹窗中点击「选择插件文件夹」,并选择包含 `SKILL.md` 的目录。
71
+ 5. 遇到同名技能时,根据提示确认是否覆盖;仅在「DSH 技能」分组中使用「删除」移除不再需要的插件。
72
+ 6. 「公共 Agent 技能」仅供智能查看,不提供启停、上传、覆盖或删除,以保护共享的全局技能元数据。
73
+
74
+ ## 开发与验证
75
+
76
+ ```powershell
77
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
78
+ $OutputEncoding = [System.Text.Encoding]::UTF8
79
+ node test\core-test.mjs
80
+ ```
81
+
82
+ ## 项目文档
83
+
84
+ 项目状态、使用边界、技术架构和迭代记录从[文档交接入口](https://github.com/MichengAI/dsh-skills-manager/blob/master/docs/00-%E4%BA%A4%E6%8E%A5%E5%85%A5%E5%8F%A3/00-%E9%98%85%E8%AF%BB%E5%AF%BC%E8%88%AA.md)开始;详细操作说明见仓库中的 `docs\02-产品与业务\01-使用说明.md`。
85
+
86
+ ## 发布 npm 包
87
+
88
+ 用户级 npm registry 可能指向 `registry.npmmirror.com` 等下载镜像;镜像不接受发布。本包已固定发布目标为官方 npm registry,拥有 npm 发布权限的维护者可执行:
89
+
90
+ ```powershell
91
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
92
+ $OutputEncoding = [System.Text.Encoding]::UTF8
93
+ npm login --registry=https://registry.npmjs.org/
94
+ npm publish
95
+ ```
96
+
97
+ 发布前会由 `prepublishOnly` 自动运行核心测试,`publishConfig.registry` 会避免 `npm publish` 写入下载镜像。执行 `npm run pack:check` 可在不发布的情况下检查最终 tarball 内容。
98
+
99
+ ## 许可证
100
+
101
+ 本项目采用 [Apache License 2.0](LICENSE)。
Binary file
@@ -0,0 +1,7 @@
1
+ # dsh-skills-manager bundle patch
2
+ #
3
+ # 供 `dsh plugin --profile web add <路径>` 自动挂载(Loader bundle 层);
4
+ # 手动挂载的用户也可在 profiles/web/cordis.patch.yml 自行添加 insert 条目。
5
+ - insert:
6
+ - id: skills-manager
7
+ name: '@michengai/dsh-skills-manager'
package/lib/client.js ADDED
@@ -0,0 +1,237 @@
1
+ // dsh-skills-manager client half:DSH 设置中的单目录技能管理面板。
2
+ window.__ModuleLoader__.load({
3
+ id: "dsh-skills-manager",
4
+ factory: (require) => {
5
+ var module = { exports: {} };
6
+ Object.defineProperty(module.exports, Symbol.toStringTag, { value: "Module" });
7
+ var react = require("react");
8
+ var h = react.createElement;
9
+ var pickDirectory = null;
10
+
11
+ var CSS = `
12
+ .dssm-section{display:flex;min-width:0;flex-direction:column;gap:20px;color:var(--dsw-alias-label-primary)}
13
+ .dssm-toolbar{display:flex;align-items:flex-start;gap:16px;padding-bottom:16px;border-bottom:1px solid var(--dsw-alias-border-l2)}
14
+ .dssm-title{margin:0;font-size:20px;line-height:28px;font-weight:650;letter-spacing:-.2px}.dssm-desc{margin:4px 0 0;color:var(--dsw-alias-label-secondary);font-size:13px;line-height:20px}
15
+ .dssm-actions{display:flex;align-items:center;gap:8px;margin-left:auto}.dssm-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:0 13px;border:1px solid transparent;border-radius:8px;background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-foreground);font:inherit;font-size:13px;font-weight:550;cursor:pointer;transition:opacity 180ms ease,background 180ms ease,border-color 180ms ease}
16
+ .dssm-btn:hover:not(:disabled){opacity:.9}.dssm-btn:disabled{opacity:.5;cursor:default}.dssm-btn-secondary{background:transparent;border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-primary)}.dssm-btn-danger{background:transparent;border-color:var(--dsw-alias-state-error-primary);color:var(--dsw-alias-state-error-primary)}
17
+ .dssm-btn:focus-visible,.dssm-dropzone:focus-visible,.dssm-icon-btn:focus-visible{outline:2px solid var(--dsw-alias-state-success-primary);outline-offset:2px}.dssm-summary{display:flex;align-items:center;gap:12px;padding:12px 14px;border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-layer-2)}
18
+ .dssm-summary-count{font-size:18px;font-weight:650}.dssm-summary-label{color:var(--dsw-alias-label-secondary);font-size:12px}.dssm-summary-separator{width:1px;height:24px;background:var(--dsw-alias-border-l2)}
19
+ .dssm-group{display:flex;flex-direction:column;overflow:hidden;border:1px solid var(--dsw-alias-border-l2);border-radius:12px;background:var(--dsw-alias-bg-layer-2)}.dssm-group-head{display:flex;align-items:center;gap:10px;padding:14px 16px;border-bottom:1px solid var(--dsw-alias-border-l1)}.dssm-group-title{margin:0;font-size:14px;font-weight:600}.dssm-count{color:var(--dsw-alias-label-tertiary);font-size:12px}.dssm-path{margin-left:auto;max-width:48%;overflow:hidden;color:var(--dsw-alias-label-tertiary);font-size:12px;text-overflow:ellipsis;white-space:nowrap}
20
+ .dssm-row{display:flex;align-items:center;gap:12px;padding:13px 16px;border-bottom:1px solid var(--dsw-alias-border-l1)}.dssm-row:last-child{border-bottom:0}.dssm-row-main{display:flex;min-width:0;flex:1;flex-direction:column;gap:3px}.dssm-row-id{display:flex;align-items:center;gap:7px;min-width:0}.dssm-row-name{overflow:hidden;font-size:14px;font-weight:560;line-height:20px;text-overflow:ellipsis;white-space:nowrap}.dssm-tag{flex:none;padding:1px 6px;border:1px solid var(--dsw-alias-border-l3);border-radius:4px;color:var(--dsw-alias-label-secondary);font-size:11px;line-height:16px}.dssm-tag-on{border-color:var(--dsw-alias-state-success-primary);color:var(--dsw-alias-state-success-primary)}.dssm-tag-off{border-color:var(--dsw-alias-state-error-primary);color:var(--dsw-alias-state-error-primary)}.dssm-note{overflow:hidden;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px;text-overflow:ellipsis;white-space:nowrap}.dssm-empty{padding:28px 16px;color:var(--dsw-alias-label-tertiary);font-size:13px;text-align:center}.dssm-error{color:var(--dsw-alias-state-error-primary);font-size:13px;line-height:20px}
21
+ .dssm-mask{position:fixed;z-index:1100;inset:0;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.58)}.dssm-modal{box-sizing:border-box;display:flex;width:min(480px,100%);flex-direction:column;gap:18px;padding:24px;border:1px solid var(--dsw-alias-border-l2);border-radius:16px;background:var(--dsw-alias-bg-layer-2);box-shadow:var(--dsw-shadow-lv3)}.dssm-modal-head{display:flex;align-items:center;gap:12px}.dssm-modal-title{margin:0;flex:1;font-size:17px;line-height:24px;font-weight:650}.dssm-icon-btn{display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:20px;line-height:1;cursor:pointer}.dssm-icon-btn:hover{background:var(--dsw-alias-interactive-bg-hover)}
22
+ .dssm-dropzone{display:flex;min-height:144px;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:18px;border:1px dashed var(--dsw-alias-border-l3);border-radius:12px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary);cursor:pointer;transition:border-color 180ms ease,background 180ms ease}.dssm-dropzone:hover,.dssm-dropzone-active{border-color:var(--dsw-alias-state-success-primary);background:var(--dsw-alias-interactive-bg-hover)}.dssm-dropzone-title{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:560}.dssm-dropzone-copy{font-size:12px;line-height:18px;text-align:center}.dssm-file{display:flex;align-items:center;gap:8px;padding:9px 10px;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;color:var(--dsw-alias-label-primary);font-size:13px}.dssm-file-name{overflow:hidden;flex:1;text-overflow:ellipsis;white-space:nowrap}.dssm-modal-actions{display:flex;justify-content:flex-end;gap:8px}.dssm-hidden-input{display:none}
23
+ @media (max-width:560px){.dssm-toolbar{flex-wrap:wrap}.dssm-actions{margin-left:0}.dssm-path{display:none}.dssm-row{align-items:flex-start;flex-wrap:wrap}.dssm-row>.dssm-btn{margin-left:auto}}@media (prefers-reduced-motion:reduce){.dssm-btn,.dssm-dropzone{transition:none}}
24
+ `;
25
+
26
+ function callApi(path, options) {
27
+ return fetch("/api/dsh-skills-manager" + path, options).then(function (response) {
28
+ return response.json().then(function (payload) {
29
+ if (!payload.ok) throw new Error(payload.error || ("HTTP " + response.status));
30
+ return payload.data;
31
+ });
32
+ });
33
+ }
34
+
35
+ function SkillManagerSection() {
36
+ var snapshotState = react.useState({ loading: true, error: null, data: null });
37
+ var snapshot = snapshotState[0];
38
+ var setSnapshot = snapshotState[1];
39
+ var busyState = react.useState(null);
40
+ var busy = busyState[0];
41
+ var setBusy = busyState[1];
42
+ var uploadState = react.useState(false);
43
+ var uploadOpen = uploadState[0];
44
+ var setUploadOpen = uploadState[1];
45
+ var selectedState = react.useState(null);
46
+ var selected = selectedState[0];
47
+ var setSelected = selectedState[1];
48
+ var resultState = react.useState(null);
49
+ var importResult = resultState[0];
50
+ var setImportResult = resultState[1];
51
+ var confirmState = react.useState(null);
52
+ var confirmImport = confirmState[0];
53
+ var setConfirmImport = confirmState[1];
54
+ var deleteState = react.useState(null);
55
+ var confirmDelete = deleteState[0];
56
+ var setConfirmDelete = deleteState[1];
57
+ var inputRef = react.useRef(null);
58
+
59
+ function refresh() {
60
+ setSnapshot({ loading: true, error: null, data: snapshot.data });
61
+ callApi("/state").then(function (data) {
62
+ setSnapshot({ loading: false, error: null, data: data });
63
+ }).catch(function (error) {
64
+ setSnapshot({ loading: false, error: String(error && error.message || error), data: snapshot.data });
65
+ });
66
+ }
67
+
68
+ react.useEffect(function () { refresh(); }, []);
69
+
70
+ react.useEffect(function () {
71
+ if (!uploadOpen && !confirmImport && !confirmDelete) return undefined;
72
+ function closeTopModal(event) {
73
+ if (event.key !== "Escape") return;
74
+ event.preventDefault();
75
+ event.stopPropagation();
76
+ if (event.stopImmediatePropagation) event.stopImmediatePropagation();
77
+ if (confirmDelete) setConfirmDelete(null);
78
+ else if (confirmImport) setConfirmImport(null);
79
+ else setUploadOpen(false);
80
+ }
81
+ window.addEventListener("keydown", closeTopModal, true);
82
+ return function () { window.removeEventListener("keydown", closeTopModal, true); };
83
+ }, [uploadOpen, confirmImport, confirmDelete]);
84
+
85
+ function action(path, body) {
86
+ if (busy) return;
87
+ setBusy(path);
88
+ callApi(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body || {}) }).then(function () {
89
+ setBusy(null);
90
+ refresh();
91
+ }).catch(function (error) {
92
+ setBusy(null);
93
+ setSnapshot({ loading: false, error: String(error && error.message || error), data: snapshot.data });
94
+ });
95
+ }
96
+
97
+ function selectFile(file) {
98
+ if (!file) return;
99
+ if (file.name.toLowerCase() !== "skill.md") {
100
+ setImportResult({ error: "请选择插件目录中的 SKILL.md 文件。" });
101
+ return;
102
+ }
103
+ if (!file.path) {
104
+ setSelected(null);
105
+ setImportResult({ error: "已选择 SKILL.md,但当前运行环境无法读取文件路径。请点击“选择插件文件夹”继续上传。" });
106
+ return;
107
+ }
108
+ setSelected({ name: file.name, source: file.path });
109
+ setImportResult(null);
110
+ }
111
+
112
+ function selectDirectory() {
113
+ if (!pickDirectory) {
114
+ setImportResult({ error: "当前运行环境无法读取本地文件路径,也未提供原生目录选择服务。" });
115
+ return;
116
+ }
117
+ setImportResult(null);
118
+ setBusy("pick-directory");
119
+ pickDirectory().then(function (path) {
120
+ setBusy(null);
121
+ if (path) {
122
+ setSelected({ name: "已选择插件目录", source: path });
123
+ setImportResult(null);
124
+ }
125
+ }).catch(function (error) {
126
+ setBusy(null);
127
+ setImportResult({ error: "选择插件目录失败:" + String(error && error.message || error) });
128
+ });
129
+ }
130
+
131
+ function openNativePicker() {
132
+ if (!busy && inputRef.current) inputRef.current.click();
133
+ }
134
+
135
+ function executeImport(source, conflict) {
136
+ setBusy("import");
137
+ setConfirmImport(null);
138
+ callApi("/import", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ source: source, conflict: conflict }) }).then(function (data) {
139
+ setBusy(null);
140
+ setImportResult(data);
141
+ setSelected(null);
142
+ setUploadOpen(false);
143
+ refresh();
144
+ }).catch(function (error) {
145
+ setBusy(null);
146
+ setImportResult({ error: String(error && error.message || error) });
147
+ });
148
+ }
149
+
150
+ function installSelected() {
151
+ if (!selected || busy) return;
152
+ setBusy("import-check");
153
+ callApi("/import", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ source: selected.source, dryRun: true }) }).then(function (data) {
154
+ if (data.conflicts && data.conflicts.length) {
155
+ setBusy(null);
156
+ setConfirmImport({ source: selected.source, conflicts: data.conflicts });
157
+ return;
158
+ }
159
+ executeImport(selected.source, "skip");
160
+ }).catch(function (error) {
161
+ setBusy(null);
162
+ setImportResult({ error: String(error && error.message || error) });
163
+ });
164
+ }
165
+
166
+ function skillRow(skill, root) {
167
+ var enabled = skill.modelInvocable && skill.userInvocable;
168
+ return h("div", { key: skill.name, className: "dssm-row" },
169
+ h("div", { className: "dssm-row-main" },
170
+ h("div", { className: "dssm-row-id" },
171
+ h("span", { className: "dssm-row-name" }, skill.name),
172
+ h("span", { className: "dssm-tag" }, skill.kind === "bundle" ? "目录插件" : "单文件"),
173
+ h("span", { className: "dssm-tag " + (enabled ? "dssm-tag-on" : "dssm-tag-off") }, enabled ? "已启用" : "已停用")),
174
+ h("div", { className: "dssm-note", title: skill.description || "" }, skill.description || "未提供简介")),
175
+ root.mutable ? h("button", { className: "dssm-btn dssm-btn-secondary", disabled: !!busy, onClick: function () { action(enabled ? "/disable" : "/enable", { name: skill.name, root: root.key }); } }, enabled ? "停用" : "启用") : null,
176
+ root.mutable ? h("button", { className: "dssm-btn dssm-btn-danger", disabled: !!busy, onClick: function () { setConfirmDelete(skill); } }, "删除") : null);
177
+ }
178
+
179
+ var nodes = [h("style", { key: "css" }, CSS)];
180
+ if (snapshot.error) nodes.push(h("div", { key: "error", className: "dssm-error", role: "alert" }, "操作失败:" + snapshot.error));
181
+ if (snapshot.data) {
182
+ var roots = snapshot.data.roots || [];
183
+ var skills = roots.reduce(function (all, root) { return all.concat(root.skills || []); }, []);
184
+ var enabled = skills.filter(function (skill) { return skill.modelInvocable; }).length;
185
+ nodes.push(h("div", { key: "toolbar", className: "dssm-toolbar" },
186
+ h("div", null, h("h2", { className: "dssm-title" }, "技能"), h("p", { className: "dssm-desc" }, "DSH 技能可上传、启停和删除;公共 Agent 技能仅供查看。")),
187
+ h("div", { className: "dssm-actions" },
188
+ h("button", { className: "dssm-btn dssm-btn-secondary", disabled: !!busy, onClick: refresh }, "刷新"),
189
+ h("button", { className: "dssm-btn", disabled: !!busy, onClick: function () { setImportResult(null); setUploadOpen(true); } }, "上传插件"))));
190
+ nodes.push(h("div", { key: "summary", className: "dssm-summary" },
191
+ h("span", { className: "dssm-summary-count" }, skills.length), h("span", { className: "dssm-summary-label" }, "个插件"), h("span", { className: "dssm-summary-separator" }), h("span", { className: "dssm-summary-count" }, enabled), h("span", { className: "dssm-summary-label" }, "个已启用")));
192
+ roots.forEach(function (root) {
193
+ var groupSkills = root.skills || [];
194
+ nodes.push(h("div", { key: root.key, className: "dssm-group" },
195
+ h("div", { className: "dssm-group-head" }, h("h3", { className: "dssm-group-title" }, root.label), h("span", { className: "dssm-count" }, groupSkills.length + " 个"), h("span", { className: "dssm-path", title: root.path }, root.path)),
196
+ root.exists === false ? h("div", { className: "dssm-empty" }, root.mutable ? "目录尚未创建,上传第一个插件后会自动创建。" : "公共目录不存在。") : (groupSkills.length ? groupSkills.map(function (skill) { return skillRow(skill, root); }) : h("div", { className: "dssm-empty" }, "暂未安装插件。"))));
197
+ });
198
+ } else if (snapshot.loading) {
199
+ nodes.push(h("div", { key: "loading", className: "dssm-note" }, "加载中…"));
200
+ }
201
+ if (importResult) {
202
+ var importedNames = (importResult.imported || []).map(function (item) { return item.name; });
203
+ var failedItems = importResult.failed || [];
204
+ var failedText = failedItems.map(function (item) { return item.error; }).join(";");
205
+ var resultText = importResult.error ? "上传失败:" + importResult.error : failedItems.length ? (importedNames.length ? "部分上传成功:" + importedNames.join("、") + ";失败:" + failedText : "上传失败:" + failedText) : "上传完成:" + importedNames.join("、");
206
+ nodes.push(h("div", { key: "import-result", className: importResult.error || failedItems.length ? "dssm-error" : "dssm-note", role: "status" }, resultText));
207
+ }
208
+ if (uploadOpen) {
209
+ nodes.push(h("div", { key: "upload", className: "dssm-mask" }, h("div", { className: "dssm-modal", role: "dialog", "aria-modal": "true", "aria-labelledby": "dssm-upload-title" },
210
+ h("div", { className: "dssm-modal-head" }, h("h3", { id: "dssm-upload-title", className: "dssm-modal-title" }, "上传插件"), h("button", { className: "dssm-icon-btn", "aria-label": "关闭上传弹窗", onClick: function () { setUploadOpen(false); } }, "×")),
211
+ h("input", { ref: inputRef, className: "dssm-hidden-input", type: "file", accept: ".md", onChange: function (event) { selectFile(event.target.files && event.target.files[0]); event.target.value = ""; } }),
212
+ h("div", { className: "dssm-dropzone", tabIndex: 0, onClick: openNativePicker, onKeyDown: function (event) { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); openNativePicker(); } }, onDragOver: function (event) { event.preventDefault(); }, onDrop: function (event) { event.preventDefault(); selectFile(event.dataTransfer.files && event.dataTransfer.files[0]); } }, h("span", { className: "dssm-dropzone-title" }, "拖放 SKILL.md 文件到这里"), h("span", { className: "dssm-dropzone-copy" }, "或点击打开系统原生文件选择窗口")),
213
+ selected ? h("div", { className: "dssm-file", title: selected.source }, h("span", { className: "dssm-file-name" }, selected.name), h("span", { className: "dssm-tag dssm-tag-on" }, "已选择")) : h("p", { className: "dssm-desc" }, "请选择插件目录中的 SKILL.md;目录内其他文件会一并上传。"),
214
+ busy === "pick-directory" ? h("div", { className: "dssm-note", role: "status" }, "正在打开系统原生目录选择窗口…") : null,
215
+ importResult && importResult.error ? h("div", { className: "dssm-error", role: "alert" }, "选择失败:" + importResult.error) : null,
216
+ h("div", { className: "dssm-modal-actions" }, h("button", { className: "dssm-btn dssm-btn-secondary", disabled: !!busy, onClick: openNativePicker }, "选择本地文件"), pickDirectory ? h("button", { className: "dssm-btn dssm-btn-secondary", disabled: !!busy, onClick: selectDirectory }, "选择插件文件夹") : null, h("button", { className: "dssm-btn", disabled: !selected || !!busy, onClick: installSelected }, busy === "import" || busy === "import-check" ? "上传中…" : "上传到 DSH")))));
217
+ }
218
+ if (confirmImport) {
219
+ nodes.push(h("div", { key: "import-confirm", className: "dssm-mask" }, h("div", { className: "dssm-modal", role: "dialog", "aria-modal": "true" }, h("div", { className: "dssm-modal-head" }, h("h3", { className: "dssm-modal-title" }, "发现同名插件")), h("p", { className: "dssm-desc" }, "将覆盖现有插件:" + confirmImport.conflicts.map(function (item) { return item.name; }).join("、")), h("div", { className: "dssm-modal-actions" }, h("button", { className: "dssm-btn dssm-btn-secondary", onClick: function () { setConfirmImport(null); } }, "取消"), h("button", { className: "dssm-btn", disabled: !!busy, onClick: function () { executeImport(confirmImport.source, "overwrite"); } }, "覆盖上传")))));
220
+ }
221
+ if (confirmDelete) {
222
+ nodes.push(h("div", { key: "delete-confirm", className: "dssm-mask" }, h("div", { className: "dssm-modal", role: "dialog", "aria-modal": "true" }, h("div", { className: "dssm-modal-head" }, h("h3", { className: "dssm-modal-title" }, "删除插件?")), h("p", { className: "dssm-desc" }, "“" + confirmDelete.name + "”将从 DSH 技能目录中永久删除,无法恢复。"), h("div", { className: "dssm-modal-actions" }, h("button", { className: "dssm-btn dssm-btn-secondary", disabled: !!busy, onClick: function () { setConfirmDelete(null); } }, "取消"), h("button", { className: "dssm-btn dssm-btn-danger", disabled: !!busy, onClick: function () { setConfirmDelete(null); action("/delete", { name: confirmDelete.name }); } }, "确认删除")))));
223
+ }
224
+ return h("section", { className: "dssm-section" }, nodes);
225
+ }
226
+
227
+ function apply(ctx) {
228
+ pickDirectory = function () { return ctx.workspaces.pickDirectory(); };
229
+ ctx.slots.inject("settings.section", function () {
230
+ return ctx.slots.register({ name: "settings.section", id: "skills-manager", order: 17, label: "技能" }, SkillManagerSection);
231
+ });
232
+ }
233
+ module.exports.apply = apply;
234
+ module.exports.inject = ["slots", "workspaces"];
235
+ return module.exports;
236
+ }
237
+ });
package/lib/core.js ADDED
@@ -0,0 +1,423 @@
1
+ // dsh-skills-manager core —— 纯 Node 技能文件管理核心(零第三方依赖,可独立单测)
2
+ //
3
+ // 覆盖 DSH 用户级技能根:
4
+ // - 根目录:~/.dsh/skills
5
+ // - 条目形态:<root>/<name>/SKILL.md(bundle)或 <root>/<name>.md(flat),只扫一层
6
+ // - 前端展示 name、description 与启停状态,不做格式检查或自动修复
7
+ //
8
+ // 所有函数返回普通结果对象,失败时返回 { ok: false, error };写文件/日志失败静默降级。
9
+
10
+ import { homedir } from "node:os";
11
+ import { join, basename, dirname } from "node:path";
12
+ import { promises as fs } from "node:fs";
13
+
14
+ const KEBAB_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
15
+
16
+ // ── 路径解析 ────────────────────────────────────────────────────────────────
17
+
18
+ export function resolveDshHome() {
19
+ return process.env.DSH_HOME || join(homedir(), ".dsh");
20
+ }
21
+
22
+ export function resolveAgentsHome() {
23
+ return process.env.DSH_AGENTS_HOME || join(homedir(), ".agents");
24
+ }
25
+
26
+ /** DSH 可管理目录与只读的公共 Agent 目录。 */
27
+ export function userRoots() {
28
+ return [
29
+ { key: "dsh", path: join(resolveDshHome(), "skills"), label: "DSH 技能", mutable: true },
30
+ { key: "agents", path: join(resolveAgentsHome(), "skills"), label: "公共 Agent 技能", mutable: false },
31
+ ];
32
+ }
33
+
34
+ export function logPath() {
35
+ return join(resolveDshHome(), "dsh-skills-manager.log");
36
+ }
37
+
38
+ // ── 命名规整 ────────────────────────────────────────────────────────────────
39
+
40
+ /** 尽量把任意名称规整为 kebab-case;无法生成合法名称时返回空串。 */
41
+ export function toKebab(s) {
42
+ let t = String(s).trim();
43
+ if (t === "") return "";
44
+ t = t.replace(/([a-z0-9])([A-Z])/g, "$1-$2"); // camelCase 边界
45
+ t = t.toLowerCase();
46
+ t = t.replace(/[\s_.]+/g, "-");
47
+ t = t.replace(/[^a-z0-9-]/g, "-");
48
+ t = t.replace(/-+/g, "-").replace(/^-+|-+$/g, "");
49
+ return t;
50
+ }
51
+
52
+ // ── frontmatter 解析 / 序列化(宽松 YAML 对象,保留键序)────────────────────
53
+
54
+ /** 剥离 UTF-8 BOM(Windows 工具常写入,不剥离会导致开头 --- 失配)。 */
55
+ function stripBom(text) {
56
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
57
+ }
58
+
59
+ /** 解析 SKILL.md 的 frontmatter。返回 { fields, map, body },map 保留键序。 */
60
+ export function parseSkillDoc(text) {
61
+ const src = stripBom(String(text));
62
+ const lines = src.split(/\r?\n/);
63
+ const map = {};
64
+ const fields = [];
65
+ let body = src;
66
+ if (lines.length > 0 && lines[0].trim() === "---") {
67
+ let end = -1;
68
+ for (let i = 1; i < lines.length; i++) {
69
+ if (lines[i].trim() === "---") {
70
+ end = i;
71
+ break;
72
+ }
73
+ }
74
+ if (end >= 0) {
75
+ for (let i = 1; i < end; i++) {
76
+ const m = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(lines[i]);
77
+ if (m) {
78
+ fields.push({ key: m[1], raw: m[2] });
79
+ const block = /^([>|])[-+]?\s*$/.exec(m[2]);
80
+ if (block) {
81
+ const content = [];
82
+ while (i + 1 < end && (/^\s/.test(lines[i + 1]) || lines[i + 1] === "")) {
83
+ i++;
84
+ content.push(lines[i].replace(/^\s{1,2}/, ""));
85
+ }
86
+ map[m[1]] = block[1] === ">" ? content.join(" ").replace(/\s+/g, " ").trim() : content.join("\n").trim();
87
+ } else {
88
+ map[m[1]] = decodeYamlScalar(m[2]);
89
+ }
90
+ }
91
+ }
92
+ body = lines.slice(end + 1).join("\n");
93
+ }
94
+ }
95
+ return { fields, map, body };
96
+ }
97
+
98
+ /** 读取 YAML 标量的显示值;不依赖第三方 YAML 解析器。 */
99
+ function decodeYamlScalar(v) {
100
+ const s = String(v == null ? "" : v).trim();
101
+ if (s.length >= 2 && s[0] === '"' && s[s.length - 1] === '"') {
102
+ try {
103
+ const value = JSON.parse(s);
104
+ if (typeof value === "string") return value;
105
+ } catch {
106
+ /* 保留无法解析的原始内容 */
107
+ }
108
+ }
109
+ if (s.length >= 2 && s[0] === "'" && s[s.length - 1] === "'") return s.slice(1, -1).replace(/''/g, "'");
110
+ return s;
111
+ }
112
+
113
+ export function unquote(v) {
114
+ const s = String(v == null ? "" : v).trim();
115
+ if (s.length >= 2 && ((s[0] === '"' && s[s.length - 1] === '"') || (s[0] === "'" && s[s.length - 1] === "'"))) {
116
+ return s.slice(1, -1);
117
+ }
118
+ return s;
119
+ }
120
+
121
+ /** 把 JS 值序列化为 YAML 标量;需要转义的字符串用 JSON 引号形式。 */
122
+ export function yamlScalar(v) {
123
+ if (v === true) return "true";
124
+ if (v === false) return "false";
125
+ if (v === null || v === undefined) return "null";
126
+ if (typeof v === "number") return String(v);
127
+ const s = String(v);
128
+ if (s === "") return '""';
129
+ if (/^(true|false|null|yes|no|on|off|~)$/i.test(s) || /^[-+]?\d+(\.\d+)?$/.test(s)) return JSON.stringify(s);
130
+ if (/[:#{}[\]&*,?|>%@`"'\s]/.test(s) || s !== s.trim()) return JSON.stringify(s);
131
+ return s;
132
+ }
133
+
134
+ export function serializeSkillDoc(map, body) {
135
+ let out = "---\n";
136
+ for (const key of Object.keys(map)) {
137
+ out += `${key}: ${yamlScalar(map[key])}\n`;
138
+ }
139
+ out += "---\n";
140
+ out += body;
141
+ return out;
142
+ }
143
+
144
+ /** 仅更新调用策略行,避免重写并破坏其他 YAML frontmatter。 */
145
+ function updateInvocationPolicy(text, enabled) {
146
+ const source = String(text);
147
+ const newline = source.includes("\r\n") ? "\r\n" : "\n";
148
+ const lines = source.split(/\r?\n/);
149
+ if (lines[0]?.trim() !== "---") return source;
150
+ const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
151
+ if (end < 0) return source;
152
+ const fields = lines.slice(1, end).filter((line) => !/^(disable-model-invocation|user-invocable)\s*:/.test(line));
153
+ if (!enabled) fields.push("disable-model-invocation: true", "user-invocable: false");
154
+ return ["---", ...fields, "---", ...lines.slice(end + 1)].join(newline);
155
+ }
156
+
157
+ /** 解析布尔字段值;合法布尔返回 true/false,非法返回 undefined。 */
158
+ export function parseBoolValue(raw) {
159
+ const v = unquote(raw).trim().toLowerCase();
160
+ if (v === "true" || v === "yes" || v === "on" || v === "1") return true;
161
+ if (v === "false" || v === "no" || v === "off" || v === "0") return false;
162
+ return undefined;
163
+ }
164
+
165
+ // ── 条目定位 / 扫描 ─────────────────────────────────────────────────────────
166
+
167
+ /** 按名称解析条目(bundle 优先,其次 flat)。找不到返回 null。 */
168
+ export async function resolveEntry(root, name) {
169
+ if (typeof name !== "string" || name === "" || basename(name) !== name) return null;
170
+ const bundleDoc = join(root, name, "SKILL.md");
171
+ try {
172
+ const st = await fs.stat(bundleDoc);
173
+ if (st.isFile()) return { kind: "bundle", docPath: bundleDoc };
174
+ } catch {}
175
+ const flatDoc = join(root, `${name}.md`);
176
+ try {
177
+ const st = await fs.stat(flatDoc);
178
+ if (st.isFile()) return { kind: "flat", docPath: flatDoc };
179
+ } catch {}
180
+ return null;
181
+ }
182
+
183
+ function entryOf(name, kind, docPath, doc) {
184
+ const description = doc.map.description !== undefined ? unquote(doc.map.description) : "";
185
+ const modelDisabled = parseBoolValue(doc.map["disable-model-invocation"]) === true;
186
+ const userDisabled = parseBoolValue(doc.map["user-invocable"]) === false;
187
+ return {
188
+ name,
189
+ kind,
190
+ docPath,
191
+ description,
192
+ modelInvocable: !modelDisabled,
193
+ userInvocable: !userDisabled,
194
+ };
195
+ }
196
+
197
+ /** 扫描一个技能根(只扫一层)。返回 { exists, entries }。 */
198
+ export async function scanEntries(root) {
199
+ let items;
200
+ try {
201
+ items = await fs.readdir(root, { withFileTypes: true });
202
+ } catch {
203
+ return { exists: false, entries: [] };
204
+ }
205
+ const entries = [];
206
+ for (const it of items) {
207
+ try {
208
+ if (it.isDirectory()) {
209
+ const docPath = join(root, it.name, "SKILL.md");
210
+ const st = await fs.stat(docPath);
211
+ if (!st.isFile()) continue;
212
+ const doc = parseSkillDoc(await fs.readFile(docPath, "utf8"));
213
+ entries.push(entryOf(it.name, "bundle", docPath, doc));
214
+ } else if (it.isFile() && it.name.endsWith(".md") && it.name !== "SKILL.md") {
215
+ const docPath = join(root, it.name);
216
+ const doc = parseSkillDoc(await fs.readFile(docPath, "utf8"));
217
+ entries.push(entryOf(it.name.slice(0, -3), "flat", docPath, doc));
218
+ }
219
+ } catch {
220
+ /* 跳过不可读条目 */
221
+ }
222
+ }
223
+ entries.sort((a, b) => a.name.localeCompare(b.name));
224
+ return { exists: true, entries };
225
+ }
226
+
227
+ // ── 启用 / 停用(同时控制模型与 / 手动调用,非破坏)──────────────────────────
228
+
229
+ /** enabled=true 恢复模型与 / 手动调用;false 同时停用两种调用入口。 */
230
+ export async function setSkillEnabled(root, name, enabled) {
231
+ if (root !== userRoots()[0].path) return { ok: false, error: "公共 Agent 技能目录不允许启用或停用" };
232
+ const resolved = await resolveEntry(root, name);
233
+ if (resolved === null) return { ok: false, error: `技能不存在: ${name}` };
234
+ const source = await fs.readFile(resolved.docPath, "utf8");
235
+ await fs.writeFile(resolved.docPath, updateInvocationPolicy(source, enabled), "utf8");
236
+ return { name, enabled };
237
+ }
238
+
239
+ /** 删除 DSH 根目录中的单个技能。调用方必须先向用户确认。 */
240
+ export async function deleteSkill(root, name, log) {
241
+ if (root !== userRoots()[0].path) return { ok: false, error: "公共 Agent 技能目录不允许删除" };
242
+ const resolved = await resolveEntry(root, name);
243
+ if (resolved === null) return { ok: false, error: `技能不存在: ${name}` };
244
+ const entryPath = resolved.kind === "bundle" ? join(root, name) : resolved.docPath;
245
+ await fs.rm(entryPath, { recursive: resolved.kind === "bundle", force: true });
246
+ if (log) log("delete", `删除 ${entryPath}`);
247
+ return { name };
248
+ }
249
+
250
+ // ── 导入 ────────────────────────────────────────────────────────────────────
251
+
252
+ /** 分析来源:单 skill 目录 / 单 .md 文件 / 批量目录。 */
253
+ async function analyzeSource(source) {
254
+ let st;
255
+ try {
256
+ st = await fs.stat(source);
257
+ } catch {
258
+ return { kind: "none", error: `路径不存在: ${source}` };
259
+ }
260
+ if (st.isDirectory()) {
261
+ try {
262
+ const sk = join(source, "SKILL.md");
263
+ const skSt = await fs.stat(sk);
264
+ if (skSt.isFile()) {
265
+ return { kind: "single", rawName: basename(source), kebab: toKebab(basename(source)), source, isDir: true, skillFile: sk };
266
+ }
267
+ } catch {}
268
+ return { kind: "batch", rawName: basename(source), source, isDir: true };
269
+ }
270
+ if (st.isFile() && source.toLowerCase().endsWith(".md")) {
271
+ if (basename(source).toLowerCase() === "skill.md") {
272
+ const parent = dirname(source);
273
+ return { kind: "single", rawName: basename(parent), kebab: toKebab(basename(parent)), source: parent, isDir: true, skillFile: source };
274
+ }
275
+ const rawName = basename(source).slice(0, -3);
276
+ return { kind: "single", rawName, kebab: toKebab(rawName), source, isDir: false, skillFile: source };
277
+ }
278
+ return { kind: "none", error: `无法识别的 skill 来源: ${source}` };
279
+ }
280
+
281
+ async function collectCandidates(dir) {
282
+ const items = await fs.readdir(dir, { withFileTypes: true });
283
+ const out = [];
284
+ for (const it of items) {
285
+ try {
286
+ if (it.isDirectory()) {
287
+ const sk = join(dir, it.name, "SKILL.md");
288
+ const st = await fs.stat(sk);
289
+ if (st.isFile()) {
290
+ out.push({ source: join(dir, it.name), kebab: toKebab(it.name), rawName: it.name, isDir: true });
291
+ }
292
+ } else if (it.isFile() && it.name.endsWith(".md") && it.name !== "SKILL.md") {
293
+ out.push({ source: join(dir, it.name), kebab: toKebab(it.name.slice(0, -3)), rawName: it.name.slice(0, -3), isDir: false });
294
+ }
295
+ } catch {
296
+ /* 跳过 */
297
+ }
298
+ }
299
+ return out;
300
+ }
301
+
302
+ /**
303
+ * 导入技能到目标根。
304
+ * options: { conflict: 'skip'|'overwrite', dryRun: boolean }
305
+ * 成功返回 { kind, imported, skipped, failed };失败返回 { ok:false, error }。
306
+ */
307
+ export async function importSkill(source, log, options = {}) {
308
+ const targetRoot = userRoots()[0].path;
309
+ const conflict = options.conflict === "overwrite" ? "overwrite" : "skip";
310
+ const dryRun = options.dryRun === true;
311
+
312
+ const analysis = await analyzeSource(source);
313
+ if (analysis.kind === "none") return { ok: false, error: analysis.error || "无法识别的 skill 来源" };
314
+
315
+ let candidates = [];
316
+ if (analysis.kind === "single") {
317
+ candidates = [{ source: analysis.source, kebab: analysis.kebab, rawName: analysis.rawName, isDir: analysis.isDir }];
318
+ } else {
319
+ candidates = await collectCandidates(source);
320
+ if (candidates.length === 0) return { ok: false, error: `目录下未找到任何 skill 条目(需含 SKILL.md 的子目录或 .md 文件): ${source}` };
321
+ }
322
+
323
+ const pending = [];
324
+ const conflicts = [];
325
+ const failed = [];
326
+ const imported = [];
327
+ const skipped = [];
328
+
329
+ function failureResult() {
330
+ return {
331
+ ok: false,
332
+ error: failed.map((item) => item.error).join(";"),
333
+ kind: analysis.kind,
334
+ imported,
335
+ skipped,
336
+ failed,
337
+ };
338
+ }
339
+
340
+ for (const c of candidates) {
341
+ if (!c.kebab || !KEBAB_RE.test(c.kebab)) {
342
+ failed.push({ source: c.source, error: `无法生成合法 kebab-case 名称(原始名: ${c.rawName || basename(c.source)})` });
343
+ continue;
344
+ }
345
+ const dest = c.isDir ? join(targetRoot, c.kebab) : join(targetRoot, `${c.kebab}.md`);
346
+ const paths = [join(targetRoot, c.kebab), join(targetRoot, `${c.kebab}.md`)];
347
+ const existing = [];
348
+ for (const path of paths) {
349
+ try {
350
+ await fs.stat(path);
351
+ existing.push(path);
352
+ } catch {}
353
+ }
354
+ if (existing.length) {
355
+ conflicts.push({ name: c.kebab, source: c.source, isDir: c.isDir, paths: existing });
356
+ continue;
357
+ }
358
+ pending.push({ name: c.kebab, source: c.source, isDir: c.isDir, dest });
359
+ }
360
+
361
+ if (dryRun) {
362
+ if (failed.length && pending.length === 0 && conflicts.length === 0) return failureResult();
363
+ return { kind: analysis.kind, pending, conflicts, failed };
364
+ }
365
+
366
+ await fs.mkdir(targetRoot, { recursive: true });
367
+
368
+ for (const p of pending) {
369
+ try {
370
+ if (p.isDir) await fs.cp(p.source, p.dest, { recursive: true });
371
+ else await fs.copyFile(p.source, p.dest);
372
+ imported.push({ name: p.name, overwritten: false, warnings: [] });
373
+ if (log) log("import", `导入 ${p.source} -> ${p.dest}`);
374
+ } catch (e) {
375
+ failed.push({ source: p.source, error: String(e && e.message ? e.message : e) });
376
+ }
377
+ }
378
+
379
+ if (conflict === "overwrite") {
380
+ for (const c of conflicts) {
381
+ try {
382
+ const dest = c.isDir ? join(targetRoot, c.name) : join(targetRoot, `${c.name}.md`);
383
+ for (const path of c.paths) await fs.rm(path, { recursive: true, force: true });
384
+ if (c.isDir) await fs.cp(c.source, dest, { recursive: true });
385
+ else await fs.copyFile(c.source, dest);
386
+ imported.push({ name: c.name, overwritten: true, warnings: [] });
387
+ if (log) log("import-overwrite", `覆盖导入 ${c.source} -> ${dest}`);
388
+ } catch (e) {
389
+ failed.push({ source: c.source, error: String(e && e.message ? e.message : e) });
390
+ }
391
+ }
392
+ } else {
393
+ for (const c of conflicts) skipped.push({ name: c.name, source: c.source });
394
+ }
395
+
396
+ if (failed.length && imported.length === 0) return failureResult();
397
+ return { kind: analysis.kind, imported, skipped, failed };
398
+ }
399
+
400
+ // ── 状态快照 ────────────────────────────────────────────────────────────────
401
+
402
+ /** DSH 与公共 Agent 根目录技能快照。 */
403
+ export async function state() {
404
+ const roots = userRoots();
405
+ const result = { roots: [] };
406
+ for (const root of roots) {
407
+ const { exists, entries } = await scanEntries(root.path);
408
+ const skills = [];
409
+ for (const e of entries) {
410
+ skills.push({
411
+ name: e.name,
412
+ kind: e.kind,
413
+ description: e.description,
414
+ modelInvocable: e.modelInvocable,
415
+ userInvocable: e.userInvocable,
416
+ });
417
+ }
418
+ result.roots.push({ key: root.key, path: root.path, label: root.label, mutable: root.mutable, exists, skills });
419
+ }
420
+ return result;
421
+ }
422
+
423
+ export { KEBAB_RE };
package/lib/index.js ADDED
@@ -0,0 +1,138 @@
1
+ // dsh-skills-manager host half:设置面板的 HTTP 后端(webServer prefix 路由)
2
+ // - 零第三方 import(仅 node: 内置 + 本地 core.js)
3
+ // - 路由:/api/dsh-skills-manager/state | enable | disable | delete | import
4
+ // - $DSH_HOME\skills 可上传、删除、启停;$DSH_AGENTS_HOME\skills 仅允许查看
5
+
6
+ import { appendFile } from "node:fs/promises";
7
+ import { state, setSkillEnabled, deleteSkill, importSkill, userRoots, logPath } from "./core.js";
8
+
9
+ const name = "skills-manager";
10
+ const inject = ["webServer", "skills"];
11
+
12
+ function makeLog() {
13
+ const file = logPath();
14
+ return async (event, detail) => {
15
+ try {
16
+ await appendFile(file, `${JSON.stringify({ ts: new Date().toISOString(), event, detail })}\n`, "utf8");
17
+ } catch {
18
+ /* 日志失败不阻塞主流程 */
19
+ }
20
+ };
21
+ }
22
+
23
+ function readBody(req, limit = 1 << 20) {
24
+ return new Promise((resolve, reject) => {
25
+ let size = 0;
26
+ const chunks = [];
27
+ req.on("data", (c) => {
28
+ size += c.length;
29
+ if (size > limit) {
30
+ reject(new Error("body too large"));
31
+ req.destroy();
32
+ return;
33
+ }
34
+ chunks.push(c);
35
+ });
36
+ req.on("end", () => {
37
+ try {
38
+ const raw = Buffer.concat(chunks).toString("utf8");
39
+ resolve(raw ? JSON.parse(raw) : {});
40
+ } catch (e) {
41
+ reject(new Error(`invalid JSON body: ${e.message}`));
42
+ }
43
+ });
44
+ req.on("error", reject);
45
+ });
46
+ }
47
+
48
+ function json(res, code, payload) {
49
+ const body = JSON.stringify(payload);
50
+ res.writeHead(code, {
51
+ "content-type": "application/json; charset=utf-8",
52
+ "content-length": Buffer.byteLength(body),
53
+ });
54
+ res.end(body);
55
+ }
56
+
57
+ /** 成功统一包成 { ok: true, data };核心返回 { ok:false, error } 时透传为 400。 */
58
+ function run(res, p, afterSuccess) {
59
+ p.then((r) => {
60
+ if (r && r.ok === false) json(res, 400, r);
61
+ else {
62
+ try {
63
+ if (afterSuccess) afterSuccess();
64
+ } catch {
65
+ /* 目录刷新失败不影响已完成的文件操作 */
66
+ }
67
+ json(res, 200, { ok: true, data: r });
68
+ }
69
+ }).catch((e) => {
70
+ try {
71
+ json(res, 500, { ok: false, error: String(e && e.message ? e.message : e) });
72
+ } catch {
73
+ /* response already closed */
74
+ }
75
+ });
76
+ }
77
+
78
+ function apply(ctx) {
79
+ const log = makeLog();
80
+ const roots = userRoots();
81
+ const rootByKey = Object.fromEntries(roots.map((r) => [r.key, r.path]));
82
+ let invalidateSkills = () => {};
83
+ ctx.effect(() => ctx.skills.registerProvider((control) => {
84
+ invalidateSkills = control.invalidate;
85
+ return {
86
+ name: "dsh-skills-manager-refresh",
87
+ list: async () => [],
88
+ get: async () => undefined,
89
+ };
90
+ }), "skills-manager catalog invalidator");
91
+
92
+ const route = ctx.webServer.register({
93
+ kind: "prefix",
94
+ path: "/api/dsh-skills-manager",
95
+ handler: async (req, res) => {
96
+ const u = new URL(req.url, "http://localhost");
97
+ const path = u.pathname.replace(/\/+$/, "");
98
+ try {
99
+ if (req.method === "GET" && path === "/api/dsh-skills-manager/state") {
100
+ run(res, state());
101
+ return;
102
+ }
103
+ if (req.method !== "POST") {
104
+ json(res, 405, { ok: false, error: `method not allowed: ${req.method}` });
105
+ return;
106
+ }
107
+ const body = await readBody(req);
108
+ switch (path) {
109
+ case "/api/dsh-skills-manager/enable": {
110
+ run(res, String(body.root || "dsh") === "dsh" ? setSkillEnabled(rootByKey.dsh, String(body.name || ""), true) : Promise.resolve({ ok: false, error: "公共 Agent 技能目录不允许启用或停用" }), invalidateSkills);
111
+ return;
112
+ }
113
+ case "/api/dsh-skills-manager/disable": {
114
+ run(res, String(body.root || "dsh") === "dsh" ? setSkillEnabled(rootByKey.dsh, String(body.name || ""), false) : Promise.resolve({ ok: false, error: "公共 Agent 技能目录不允许启用或停用" }), invalidateSkills);
115
+ return;
116
+ }
117
+ case "/api/dsh-skills-manager/delete": {
118
+ run(res, deleteSkill(rootByKey.dsh, String(body.name || ""), log), invalidateSkills);
119
+ return;
120
+ }
121
+ case "/api/dsh-skills-manager/import":
122
+ run(res, importSkill(String(body.source || ""), log, {
123
+ conflict: body.conflict === "overwrite" ? "overwrite" : "skip",
124
+ dryRun: body.dryRun === true,
125
+ }), body.dryRun === true ? undefined : invalidateSkills);
126
+ return;
127
+ default:
128
+ json(res, 404, { ok: false, error: `unknown action: ${path}` });
129
+ }
130
+ } catch (e) {
131
+ json(res, 500, { ok: false, error: String(e && e.message ? e.message : e) });
132
+ }
133
+ },
134
+ });
135
+ return route;
136
+ }
137
+
138
+ export { apply, inject, name };
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@michengai/dsh-skills-manager",
3
+ "version": "0.1.0",
4
+ "description": "DSH Web plugin: manage local DSH skills and safely view shared Agent skills.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/MichengAI/dsh-skills-manager.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/MichengAI/dsh-skills-manager/issues"
12
+ },
13
+ "homepage": "https://github.com/MichengAI/dsh-skills-manager#readme",
14
+ "type": "module",
15
+ "main": "lib/index.js",
16
+ "exports": {
17
+ ".": "./lib/index.js",
18
+ "./client": "./lib/client.js",
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "lib",
23
+ "assets",
24
+ "cordis.patch.yml"
25
+ ],
26
+ "dsh": {
27
+ "bundle": {
28
+ "patch": "./cordis.patch.yml"
29
+ },
30
+ "client": {
31
+ "inject": [
32
+ "@deepseek-ai/dsh-client-runtime",
33
+ "@deepseek-ai/dsh-client-ui-slots",
34
+ "@deepseek-ai/dsh-client-ui-workspace"
35
+ ],
36
+ "platform": "web"
37
+ }
38
+ },
39
+ "scripts": {
40
+ "test": "node test/core-test.mjs",
41
+ "pack:check": "npm pack --dry-run --json",
42
+ "prepublishOnly": "npm test"
43
+ },
44
+ "publishConfig": {
45
+ "registry": "https://registry.npmjs.org/",
46
+ "access": "public"
47
+ },
48
+ "peerDependencies": {
49
+ "@deepseek-ai/cordis": ">=4.0.1 <5.0.0",
50
+ "@deepseek-ai/dsh-host-webserver": ">=0.1.0-rc.5",
51
+ "@deepseek-ai/dsh-skill": ">=0.1.0-rc.5",
52
+ "@deepseek-ai/dsh-client-ui-workspace": ">=0.1.0-rc.5"
53
+ },
54
+ "engines": {
55
+ "node": ">=20"
56
+ },
57
+ "keywords": [
58
+ "deepseek-harness",
59
+ "dsh",
60
+ "dsh-plugin",
61
+ "skill",
62
+ "skills",
63
+ "cordis"
64
+ ]
65
+ }