dxkj 0.0.0-stage → 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 CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # dxkj
2
+
3
+ dxkj 目录 CLI(prompt / skill / agent / plugin / tool)+ opencode 插件壳。
4
+
5
+ 以 `收录.md`(Skill & Agent Tool 分类与命名规范 v1.0)为元数据基线:
6
+ 按编号浏览、检索、查看条目(含多图画廊与简介),并单装/批量安装到三种目标。
7
+
8
+ ## 安装
9
+
10
+ ```bash
11
+ npm i -g dxkj
12
+ # 或
13
+ npx -y dxkj list
14
+ ```
15
+
16
+ ## 命令
17
+
18
+ ```bash
19
+ dxkj list [--kind skill] [--category CG] [--tag x] [--json]
20
+ dxkj search <关键词>
21
+ dxkj show <编号|id>
22
+ dxkj install <编号...> [--target ai-editor|navlink|generic] [--editor opencode|claude] [--dir 路径]
23
+ dxkj install --all [--kind skill]
24
+ dxkj uninstall <编号...>
25
+ dxkj validate <条目.json>
26
+ dxkj config get [键] | config set <键> <值> | config path
27
+ ```
28
+
29
+ 站点尚未集成时,可用内置示例数据本地验证:
30
+
31
+ ```bash
32
+ dxkj list --source ./node_modules/dxkj/fixtures/sample-registry.json
33
+ ```
34
+
35
+ ## 三种安装目标
36
+
37
+ | target | 说明 | 目录来源 |
38
+ | :--- | :--- | :--- |
39
+ | `ai-editor` | 按 kind 分派到 opencode / Claude 的 skills / agent / command 等目录 | `config.targets.aiEditor.<editor>`(默认 opencode) |
40
+ | `navlink` | 装入目标 NavLink 实例的 `plugins/` 目录 | `--dir` 或 `config.targets.navlink.pluginsDir` |
41
+ | `generic` | 解压到任意目录 | `--dir` 或 `config.targets.generic.dir` |
42
+
43
+ ## 配置
44
+
45
+ 配置文件:`~/.dxkj/config.json`
46
+
47
+ ```bash
48
+ dxkj config set serverUrl https://tools.dxkj.online
49
+ dxkj config set target ai-editor
50
+ dxkj config set editor opencode
51
+ dxkj config get
52
+ ```
53
+
54
+ 优先级:命令行 `--server` > 环境变量 `DXKJ_SERVER_URL` > 配置文件 > 默认 `https://tools.dxkj.online`。
55
+
56
+ ## opencode 插件
57
+
58
+ `opencode.json`:
59
+
60
+ ```json
61
+ {
62
+ "$schema": "https://opencode.ai/config.json",
63
+ "plugin": ["dxkj"]
64
+ }
65
+ ```
66
+
67
+ 注册后提供 `dxkj_catalog` 与 `dxkj_install` 两个工具。
68
+
69
+ ## 收录规范校验
70
+
71
+ `dxkj validate item.json` 校验命名格式、必填字段、status 生命周期、deprecated 原因、tags 类型等(依据 `收录.md` 第 2/3 章)。
72
+
73
+ ## License
74
+
75
+ Apache-2.0
package/bin/dxk.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../src/cli.js';
3
+
4
+ run(process.argv.slice(2))
5
+ .then((code) => {
6
+ if (typeof code === 'number') process.exit(code);
7
+ })
8
+ .catch((err) => {
9
+ console.error(`dxkj: ${err && err.message ? err.message : err}`);
10
+ process.exit(1);
11
+ });
@@ -0,0 +1,12 @@
1
+ ---
2
+ name: english_sentence_correct
3
+ description: 英文句子语法纠错示例技能(dxkj CLI 安装测试用)。Use when the user asks to correct an English sentence.
4
+ ---
5
+
6
+ # English Sentence Correct (Demo)
7
+
8
+ 这是一个用于验证 dxkj CLI 安装流程的最小 SKILL 示例。
9
+
10
+ ## 用法
11
+
12
+ 给定一句英文,返回纠错后的句子与中文解析。
@@ -0,0 +1,5 @@
1
+ // 示例原子工具(dxkj CLI 安装测试用)
2
+ export function math_calculator(expr) {
3
+ // 仅演示:请勿用于不可信输入
4
+ return Function(`"use strict";return (${expr})`)();
5
+ }
@@ -0,0 +1,44 @@
1
+ {
2
+ "schemaVersion": "1.0",
3
+ "generatedAt": "2026-10-02T00:00:00.000Z",
4
+ "items": [
5
+ {
6
+ "number": 1,
7
+ "id": "skill.CG.demo.english_sentence_correct@v1.1",
8
+ "kind": "skill",
9
+ "name": "english_sentence_correct",
10
+ "category": "ContentGeneration.TextGen",
11
+ "description": "英文句子语法纠错,并给出中文解析(示例条目)",
12
+ "intro": "面向英语学习者的语法纠错技能。\n输入一句英文,返回修正后的句子与中文讲解。",
13
+ "version": "1.1",
14
+ "status": "active",
15
+ "author": "dxkj-demo",
16
+ "tags": ["english", "grammar", "education"],
17
+ "images": ["https://tools.dxkj.online/uploads/ai-catalog/images/demo-1.png"],
18
+ "install": {
19
+ "format": "zip",
20
+ "url": "./fixtures/packages/hello-skill.zip",
21
+ "entry": "SKILL.md"
22
+ }
23
+ },
24
+ {
25
+ "number": 2,
26
+ "id": "tool.CL.demo.math_calculator@v1.2",
27
+ "kind": "tool",
28
+ "name": "math_calculator",
29
+ "category": "Calculation&Logic.MathCompute",
30
+ "description": "自然语言数学表达式计算,支持四则运算、开方(示例条目)",
31
+ "intro": "原子计算工具示例,CLI 安装后可作为本地工具使用。",
32
+ "version": "1.2",
33
+ "status": "experimental",
34
+ "author": "dxkj-demo",
35
+ "tags": ["math", "arithmetic"],
36
+ "images": [],
37
+ "install": {
38
+ "format": "zip",
39
+ "url": "./fixtures/packages/hello-skill.zip",
40
+ "entry": "tool.js"
41
+ }
42
+ }
43
+ ]
44
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
- {
2
- "name": "dxkj",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dxkj",
3
+ "version": "0.1.0",
4
+ "description": "dxkj CLI — browse and install prompts/skills/agents/plugins/tools from the dxkj catalog, plus an opencode plugin shell.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "bin": {
8
+ "dxkj": "bin/dxk.js"
9
+ },
10
+ "main": "./src/opencode.js",
11
+ "exports": {
12
+ ".": "./src/opencode.js",
13
+ "./cli": "./src/cli.js",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "bin",
18
+ "src",
19
+ "fixtures",
20
+ "README.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=18.17"
24
+ },
25
+ "dependencies": {
26
+ "adm-zip": "^0.5.16"
27
+ },
28
+ "publishConfig": {
29
+ "registry": "https://registry.npmjs.org",
30
+ "access": "public"
31
+ },
32
+ "keywords": [
33
+ "dxkj",
34
+ "cli",
35
+ "opencode",
36
+ "skill",
37
+ "agent",
38
+ "prompt",
39
+ "catalog"
40
+ ],
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://gitee.com/amdyhaha/navlink_release_amdy.git"
44
+ }
45
+ }
package/src/cli.js ADDED
@@ -0,0 +1,321 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { loadConfig, saveConfig, resolveServerUrl, CONFIG_PATH, getByPath, setByPath } from './lib/config.js';
5
+ import { loadRegistry, filterItems, findByRef, resolveSource } from './lib/registry.js';
6
+ import { validateItem, formatReport } from './lib/validator.js';
7
+ import { renderList, renderDetail } from './lib/format.js';
8
+ import { resolveTargetDir } from './lib/targets.js';
9
+ import { downloadToTemp, extractZip, writeManifest, cleanup } from './lib/installer.js';
10
+
11
+ const VERSION = '0.1.0';
12
+
13
+ const OPTIONS = {
14
+ source: { type: 'string' },
15
+ server: { type: 'string' },
16
+ kind: { type: 'string' },
17
+ category: { type: 'string' },
18
+ tag: { type: 'string' },
19
+ status: { type: 'string' },
20
+ target: { type: 'string' },
21
+ editor: { type: 'string' },
22
+ dir: { type: 'string' },
23
+ json: { type: 'boolean' },
24
+ all: { type: 'boolean' },
25
+ force: { type: 'boolean' },
26
+ help: { type: 'boolean', short: 'h' },
27
+ version: { type: 'boolean', short: 'v' },
28
+ yes: { type: 'boolean', short: 'y' }
29
+ };
30
+
31
+ function parse(argv) {
32
+ return parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: false });
33
+ }
34
+
35
+ function help() {
36
+ return `dxkj v${VERSION} — dxkj 目录 CLI(prompt / skill / agent / plugin / tool)
37
+
38
+ 用法:
39
+ dxkj list [--kind skill] [--category CG] [--tag x] [--source <url|file>] [--json]
40
+ dxkj search <关键词>
41
+ dxkj show <编号|id>
42
+ dxkj install <编号...> [--target ai-editor|navlink|generic] [--editor opencode|claude] [--dir 路径]
43
+ dxkj install --all [--kind skill]
44
+ dxkj uninstall <编号...>
45
+ dxkj validate <条目.json>
46
+ dxkj config get [键] | config set <键> <值> | config path
47
+ dxkj --help | --version
48
+
49
+ 默认服务地址:${resolveServerUrl()}
50
+ 配置文件:${CONFIG_PATH}
51
+ 站点未集成时可用 --source ./fixtures/sample-registry.json 本地验证。`;
52
+ }
53
+
54
+ async function cmdList(argv) {
55
+ const { values } = parse(argv);
56
+ const cfg = loadConfig();
57
+ const { items, source } = await loadRegistry(values, cfg);
58
+ const list = filterItems(items, values);
59
+ if (values.json) {
60
+ console.log(JSON.stringify({ source, count: list.length, items: list }, null, 2));
61
+ return 0;
62
+ }
63
+ console.log(`数据源: ${source}`);
64
+ console.log(renderList(list));
65
+ console.log(`\n共 ${list.length} 条`);
66
+ return 0;
67
+ }
68
+
69
+ async function cmdSearch(argv) {
70
+ const { values, positionals } = parse(argv);
71
+ const kw = positionals.slice(1).join(' ').toLowerCase();
72
+ if (!kw) {
73
+ console.error('用法:dxkj search <关键词>');
74
+ return 1;
75
+ }
76
+ const cfg = loadConfig();
77
+ const { items } = await loadRegistry(values, cfg);
78
+ const list = filterItems(items, values).filter((it) =>
79
+ [it.id, it.name, it.description, it.intro, it.category, ...it.tags].join(' ').toLowerCase().includes(kw)
80
+ );
81
+ console.log(renderList(list));
82
+ console.log(`\n命中 ${list.length} 条`);
83
+ return 0;
84
+ }
85
+
86
+ async function cmdShow(argv) {
87
+ const { values, positionals } = parse(argv);
88
+ const ref = positionals[1];
89
+ if (!ref) {
90
+ console.error('用法:dxkj show <编号|id>');
91
+ return 1;
92
+ }
93
+ const cfg = loadConfig();
94
+ const { items } = await loadRegistry(values, cfg);
95
+ const item = findByRef(items, ref);
96
+ if (!item) {
97
+ console.error(`未找到条目:${ref}`);
98
+ return 1;
99
+ }
100
+ if (values.json) {
101
+ console.log(JSON.stringify(item, null, 2));
102
+ return 0;
103
+ }
104
+ console.log(renderDetail(item, resolveServerUrl(values, cfg)));
105
+ return 0;
106
+ }
107
+
108
+ async function cmdInstall(argv) {
109
+ const { values, positionals } = parse(argv);
110
+ const cfg = loadConfig();
111
+ const { items } = await loadRegistry(values, cfg);
112
+
113
+ let targets = positionals.slice(1);
114
+ if (values.all) {
115
+ targets = filterItems(items, values).map((it) => String(it.number));
116
+ } else if (values.kind && targets.length === 0) {
117
+ targets = filterItems(items, values).map((it) => String(it.number));
118
+ }
119
+ if (targets.length === 0) {
120
+ console.error('用法:dxkj install <编号...> | dxkj install --all [--kind skill]');
121
+ return 1;
122
+ }
123
+
124
+ // navlink 目标可直接复用插件安装包(先支持 zip 解压方式)
125
+ let ok = 0;
126
+ let failed = 0;
127
+ for (const ref of targets) {
128
+ const item = findByRef(items, ref);
129
+ if (!item) {
130
+ console.error(`✗ 未找到条目:${ref}`);
131
+ failed++;
132
+ continue;
133
+ }
134
+ if (!item.install.url) {
135
+ console.error(`✗ #${item.number} ${item.name} 缺少安装包地址,跳过`);
136
+ failed++;
137
+ continue;
138
+ }
139
+ let dest;
140
+ try {
141
+ dest = resolveTargetDir(item, values, cfg);
142
+ } catch (err) {
143
+ console.error(`✗ #${item.number} ${item.name}: ${err.message}`);
144
+ failed++;
145
+ continue;
146
+ }
147
+ let temp = null;
148
+ try {
149
+ temp = await downloadToTemp(item.install.url);
150
+ extractZip(temp, dest.dir);
151
+ writeManifest(dest.dir, {
152
+ id: item.id,
153
+ number: item.number,
154
+ name: item.name,
155
+ kind: item.kind,
156
+ version: item.version,
157
+ source: item.install.url,
158
+ target: dest.target,
159
+ installedAt: new Date().toISOString()
160
+ });
161
+ console.log(`✓ 已安装 #${item.number} ${item.name} → ${dest.dir} (${dest.hint})`);
162
+ ok++;
163
+ } catch (err) {
164
+ console.error(`✗ #${item.number} ${item.name}: ${err.message}`);
165
+ failed++;
166
+ } finally {
167
+ if (temp) cleanup(temp);
168
+ }
169
+ }
170
+ console.log(`\n完成:成功 ${ok},失败 ${failed}`);
171
+ return failed === 0 ? 0 : 1;
172
+ }
173
+
174
+ async function cmdUninstall(argv) {
175
+ const { values, positionals } = parse(argv);
176
+ const cfg = loadConfig();
177
+ const { items } = await loadRegistry(values, cfg);
178
+ const { removeDirSafe, readManifest } = await import('./lib/installer.js');
179
+
180
+ const refs = positionals.slice(1);
181
+ if (refs.length === 0) {
182
+ console.error('用法:dxkj uninstall <编号...>');
183
+ return 1;
184
+ }
185
+ let ok = 0;
186
+ let failed = 0;
187
+ for (const ref of refs) {
188
+ const item = findByRef(items, ref);
189
+ if (!item) {
190
+ console.error(`✗ 未找到条目:${ref}`);
191
+ failed++;
192
+ continue;
193
+ }
194
+ let dest;
195
+ try {
196
+ dest = resolveTargetDir(item, values, cfg);
197
+ } catch (err) {
198
+ console.error(`✗ ${item.name}: ${err.message}`);
199
+ failed++;
200
+ continue;
201
+ }
202
+ if (!fs.existsSync(dest.dir)) {
203
+ console.error(`✗ ${item.name}: 未安装(${dest.dir} 不存在)`);
204
+ failed++;
205
+ continue;
206
+ }
207
+ const meta = readManifest(dest.dir);
208
+ removeDirSafe(dest.dir);
209
+ console.log(`✓ 已卸载 ${meta ? meta.name : item.name}(${dest.dir})`);
210
+ ok++;
211
+ }
212
+ console.log(`\n完成:成功 ${ok},失败 ${failed}`);
213
+ return failed === 0 ? 0 : 1;
214
+ }
215
+
216
+ async function cmdValidate(argv) {
217
+ const { positionals } = parse(argv);
218
+ const file = positionals[1];
219
+ if (!file) {
220
+ console.error('用法:dxkj validate <条目.json>');
221
+ return 1;
222
+ }
223
+ const abs = path.resolve(process.cwd(), file);
224
+ if (!fs.existsSync(abs)) {
225
+ console.error(`文件不存在:${abs}`);
226
+ return 1;
227
+ }
228
+ let data;
229
+ try {
230
+ data = JSON.parse(fs.readFileSync(abs, 'utf-8').replace(/^\uFEFF/, ''));
231
+ } catch (err) {
232
+ console.error(`JSON 解析失败:${err.message}`);
233
+ return 1;
234
+ }
235
+ const list = Array.isArray(data) ? data : [data];
236
+ let hasError = false;
237
+ for (const it of list) {
238
+ const report = formatReport(it.id || it.name || '(未命名)', validateItem(it));
239
+ console.log(report.text);
240
+ if (!report.ok) hasError = true;
241
+ }
242
+ return hasError ? 1 : 0;
243
+ }
244
+
245
+ async function cmdConfig(argv) {
246
+ const { values, positionals } = parse(argv);
247
+ const action = positionals[1] || 'get';
248
+ const cfg = loadConfig();
249
+
250
+ if (action === 'path') {
251
+ console.log(CONFIG_PATH);
252
+ return 0;
253
+ }
254
+ if (action === 'get') {
255
+ const key = positionals[2];
256
+ if (!key) {
257
+ console.log(JSON.stringify(cfg, null, 2));
258
+ return 0;
259
+ }
260
+ const val = getByPath(cfg, key);
261
+ console.log(typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val));
262
+ return 0;
263
+ }
264
+ if (action === 'set') {
265
+ const key = positionals[2];
266
+ let val = positionals.slice(3).join(' ');
267
+ if (!key || val === '') {
268
+ console.error('用法:dxkj config set <键> <值>');
269
+ return 1;
270
+ }
271
+ // 数字/布尔简单转换
272
+ if (val === 'true') val = true;
273
+ else if (val === 'false') val = false;
274
+ const base = loadConfig();
275
+ setByPath(base, key, val);
276
+ saveConfig(base);
277
+ console.log(`✓ 已写入 ${key} = ${val}`);
278
+ return 0;
279
+ }
280
+ console.error(`未知 config 操作:${action}`);
281
+ return 1;
282
+ }
283
+
284
+ export async function run(argv) {
285
+ const command = argv[0];
286
+
287
+ if (!command || command === 'help' || argv.includes('--help') || argv.includes('-h')) {
288
+ console.log(help());
289
+ return 0;
290
+ }
291
+ if (command === 'version' || argv.includes('--version') || argv.includes('-v')) {
292
+ console.log(VERSION);
293
+ return 0;
294
+ }
295
+
296
+ switch (command) {
297
+ case 'list':
298
+ return cmdList(argv);
299
+ case 'search':
300
+ return cmdSearch(argv);
301
+ case 'show':
302
+ case 'info':
303
+ return cmdShow(argv);
304
+ case 'install':
305
+ case 'i':
306
+ return cmdInstall(argv);
307
+ case 'uninstall':
308
+ case 'remove':
309
+ case 'rm':
310
+ return cmdUninstall(argv);
311
+ case 'validate':
312
+ case 'lint':
313
+ return cmdValidate(argv);
314
+ case 'config':
315
+ return cmdConfig(argv);
316
+ default:
317
+ console.error(`未知命令:${command}\n`);
318
+ console.log(help());
319
+ return 1;
320
+ }
321
+ }
@@ -0,0 +1,93 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+
5
+ /** 默认服务地址:dxkj 工具站在服务器上的子域名 */
6
+ export const DEFAULT_SERVER_URL = 'https://tools.dxkj.online';
7
+
8
+ /** 目录 API 路径(由 NavLink 的 ai-catalog 插件提供) */
9
+ export const REGISTRY_PATH = '/api/plugins/ai-catalog/api/registry';
10
+
11
+ export const CONFIG_DIR = path.join(os.homedir(), '.dxkj');
12
+ export const CONFIG_PATH = path.join(CONFIG_DIR, 'config.json');
13
+
14
+ export function defaultConfig() {
15
+ return {
16
+ serverUrl: DEFAULT_SERVER_URL,
17
+ target: 'generic',
18
+ editor: 'opencode',
19
+ targets: {
20
+ aiEditor: {
21
+ opencode: {
22
+ base: path.join(os.homedir(), '.config', 'opencode'),
23
+ map: { skill: 'skills', agent: 'agent', prompt: 'command', plugin: 'plugin', tool: 'tool' }
24
+ },
25
+ claude: {
26
+ base: path.join(os.homedir(), '.claude'),
27
+ map: { skill: 'skills', agent: 'agents', prompt: 'commands', plugin: 'plugins', tool: 'tools' }
28
+ }
29
+ },
30
+ navlink: { pluginsDir: '' },
31
+ generic: { dir: '' }
32
+ }
33
+ };
34
+ }
35
+
36
+ function isObject(v) {
37
+ return v && typeof v === 'object' && !Array.isArray(v);
38
+ }
39
+
40
+ export function deepMerge(base, over) {
41
+ if (!isObject(over)) return base;
42
+ const out = Array.isArray(base) ? [...base] : { ...base };
43
+ for (const [k, v] of Object.entries(over)) {
44
+ out[k] = isObject(v) && isObject(out[k]) ? deepMerge(out[k], v) : v;
45
+ }
46
+ return out;
47
+ }
48
+
49
+ export function readConfigFile() {
50
+ try {
51
+ return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8').replace(/^\uFEFF/, ''));
52
+ } catch {
53
+ return {};
54
+ }
55
+ }
56
+
57
+ export function loadConfig() {
58
+ return deepMerge(defaultConfig(), readConfigFile());
59
+ }
60
+
61
+ export function saveConfig(cfg) {
62
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
63
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 4) + '\n', 'utf-8');
64
+ }
65
+
66
+ export function getByPath(obj, dotted) {
67
+ return dotted.split('.').reduce((acc, k) => (acc == null ? acc : acc[k]), obj);
68
+ }
69
+
70
+ /** 把 "a.b.c" 写成嵌套对象 */
71
+ export function setByPath(obj, dotted, value) {
72
+ const keys = dotted.split('.');
73
+ let cur = obj;
74
+ for (let i = 0; i < keys.length - 1; i++) {
75
+ if (!isObject(cur[keys[i]])) cur[keys[i]] = {};
76
+ cur = cur[keys[i]];
77
+ }
78
+ cur[keys[keys.length - 1]] = value;
79
+ return obj;
80
+ }
81
+
82
+ /** serverUrl 解析优先级:--server > DXKJ_SERVER_URL > 配置文件 > 默认 */
83
+ export function resolveServerUrl(opts = {}, cfg = loadConfig()) {
84
+ const raw = opts.server || process.env.DXKJ_SERVER_URL || cfg.serverUrl || DEFAULT_SERVER_URL;
85
+ return String(raw).replace(/\/+$/, '');
86
+ }
87
+
88
+ export function expandHome(p) {
89
+ if (!p) return p;
90
+ if (p === '~') return os.homedir();
91
+ if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2));
92
+ return p;
93
+ }
@@ -0,0 +1,49 @@
1
+ export function truncate(str, len) {
2
+ const s = String(str ?? '');
3
+ return s.length > len ? s.slice(0, Math.max(0, len - 1)) + '…' : s;
4
+ }
5
+
6
+ export function renderList(items, { showIntro = false } = {}) {
7
+ if (!items.length) return '(空)';
8
+ const rows = items.map((it) => ({
9
+ no: String(it.number).padStart(4, ' '),
10
+ kind: truncate(it.kind, 7).padEnd(7, ' '),
11
+ id: it.id,
12
+ status: it.status,
13
+ desc: truncate(it.description, showIntro ? 60 : 40)
14
+ }));
15
+ const idw = Math.min(52, Math.max(4, ...rows.map((r) => r.id.length)));
16
+ return rows
17
+ .map((r) => `${r.no} ${r.kind} ${r.id.padEnd(idw, ' ')} ${r.desc}`)
18
+ .join('\n');
19
+ }
20
+
21
+ export function renderDetail(it, serverUrl) {
22
+ const lines = [];
23
+ lines.push(`#${it.number} ${it.name} [${it.kind}]`);
24
+ lines.push(` id ${it.id}`);
25
+ lines.push(` 分类 ${it.category}`);
26
+ lines.push(` 状态 ${it.status}`);
27
+ if (it.version) lines.push(` 版本 ${it.version}`);
28
+ if (it.author) lines.push(` 作者 ${it.author}`);
29
+ if (it.tags.length) lines.push(` 标签 ${it.tags.join(', ')}`);
30
+ lines.push(` 简介 ${it.description}`);
31
+ if (it.intro) {
32
+ lines.push(' ———— 简介区 ————');
33
+ for (const l of String(it.intro).split(/\r?\n/)) lines.push(` ${l}`);
34
+ }
35
+ if (it.images.length) {
36
+ lines.push(' ———— 图片展示区 ————');
37
+ for (const img of it.images) lines.push(` ${img}`);
38
+ }
39
+ lines.push(` 安装 dxkj install ${it.number}`);
40
+ return lines.join('\n');
41
+ }
42
+
43
+ export function pluck(value, keys) {
44
+ for (const k of keys) {
45
+ if (value == null) return value;
46
+ value = value[k];
47
+ }
48
+ return value;
49
+ }
@@ -0,0 +1,68 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import AdmZip from 'adm-zip';
6
+
7
+ export const MANIFEST = '.dxkj.json';
8
+
9
+ export async function downloadToTemp(url) {
10
+ const tmp = path.join(os.tmpdir(), `dxkj-${Date.now()}-${Math.random().toString(36).slice(2)}`);
11
+ fs.mkdirSync(tmp, { recursive: true });
12
+ const target = path.join(tmp, 'package.zip');
13
+
14
+ if (/^https?:\/\//i.test(url)) {
15
+ const res = await fetch(url, { headers: { 'User-Agent': 'dxkj-cli/0.1.0' } });
16
+ if (!res.ok) throw new Error(`下载失败 HTTP ${res.status}:${url}`);
17
+ await pipeline(res.body, fs.createWriteStream(target));
18
+ } else {
19
+ const local = path.resolve(process.cwd(), url);
20
+ if (!fs.existsSync(local)) throw new Error(`安装包文件不存在:${local}`);
21
+ fs.copyFileSync(local, target);
22
+ }
23
+ return target;
24
+ }
25
+
26
+ /** 解压 zip 到 destDir(含 Zip Slip 防护) */
27
+ export function extractZip(zipPath, destDir) {
28
+ const zip = new AdmZip(zipPath);
29
+ const resolvedDest = path.resolve(destDir);
30
+ fs.mkdirSync(resolvedDest, { recursive: true });
31
+
32
+ for (const entry of zip.getEntries()) {
33
+ const targetPath = path.resolve(resolvedDest, entry.entryName);
34
+ if (targetPath !== resolvedDest && !targetPath.startsWith(resolvedDest + path.sep)) {
35
+ throw new Error(`压缩包存在非法路径(Zip Slip):${entry.entryName}`);
36
+ }
37
+ }
38
+ zip.extractAllTo(resolvedDest, true);
39
+ }
40
+
41
+ export function writeManifest(destDir, meta) {
42
+ fs.writeFileSync(path.join(destDir, MANIFEST), JSON.stringify(meta, null, 4) + '\n', 'utf-8');
43
+ }
44
+
45
+ export function readManifest(destDir) {
46
+ try {
47
+ return JSON.parse(fs.readFileSync(path.join(destDir, MANIFEST), 'utf-8'));
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ export function removeDirSafe(destDir) {
54
+ const resolved = path.resolve(destDir);
55
+ const parsed = path.parse(resolved);
56
+ if (resolved === parsed.root || resolved === os.homedir()) {
57
+ throw new Error(`拒绝删除高危目录:${resolved}`);
58
+ }
59
+ fs.rmSync(resolved, { recursive: true, force: true });
60
+ }
61
+
62
+ export function cleanup(tempFile) {
63
+ try {
64
+ fs.rmSync(path.dirname(tempFile), { recursive: true, force: true });
65
+ } catch {
66
+ /* ignore */
67
+ }
68
+ }
@@ -0,0 +1,92 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { loadConfig, resolveServerUrl, REGISTRY_PATH } from './config.js';
4
+
5
+ /** 去除 Windows 写文件常见的 UTF-8 BOM,避免 JSON.parse 失败 */
6
+ export function stripBom(text) {
7
+ return String(text).replace(/^\uFEFF/, '');
8
+ }
9
+
10
+ /**
11
+ * 解析数据源。
12
+ * 优先级:--source > DXKJ_REGISTRY > <serverUrl>/api/plugins/ai-catalog/api/registry
13
+ */
14
+ export function resolveSource(opts = {}, cfg = loadConfig()) {
15
+ if (opts.source) return opts.source;
16
+ if (process.env.DXKJ_REGISTRY) return process.env.DXKJ_REGISTRY;
17
+ return resolveServerUrl(opts, cfg) + REGISTRY_PATH;
18
+ }
19
+
20
+ function normalizeItem(raw, index) {
21
+ const install = raw.install || {};
22
+ return {
23
+ number: raw.number ?? raw.no ?? index + 1,
24
+ id: raw.id || '',
25
+ kind: raw.kind || raw.type || 'unknown',
26
+ name: raw.name || '',
27
+ category: raw.category || '',
28
+ description: raw.description || '',
29
+ intro: raw.intro || '',
30
+ version: raw.version || '',
31
+ status: raw.status || 'active',
32
+ author: raw.author || '',
33
+ tags: Array.isArray(raw.tags) ? raw.tags : [],
34
+ images: Array.isArray(raw.images) ? raw.images : [],
35
+ install: {
36
+ format: install.format || raw.install_format || 'zip',
37
+ url: install.url || raw.downloadUrl || raw.package_url || '',
38
+ entry: install.entry || raw.entry || ''
39
+ },
40
+ raw
41
+ };
42
+ }
43
+
44
+ /** 从 URL 或本地文件读取注册表 JSON */
45
+ export async function loadRegistry(opts = {}, cfg = loadConfig()) {
46
+ const source = resolveSource(opts, cfg);
47
+ let json;
48
+
49
+ if (/^https?:\/\//i.test(source)) {
50
+ const controller = new AbortController();
51
+ const timer = setTimeout(() => controller.abort(), 15000);
52
+ try {
53
+ const res = await fetch(source, {
54
+ signal: controller.signal,
55
+ headers: { 'User-Agent': 'dxkj-cli/0.1.0', Accept: 'application/json' }
56
+ });
57
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
58
+ json = await res.json();
59
+ } catch (err) {
60
+ throw new Error(
61
+ `无法读取目录数据源 ${source}\n ${err.message}\n 提示:站点尚未集成时,可用 --source ./fixtures/sample-registry.json 本地验证`
62
+ );
63
+ } finally {
64
+ clearTimeout(timer);
65
+ }
66
+ } else {
67
+ const file = path.resolve(process.cwd(), source);
68
+ if (!fs.existsSync(file)) throw new Error(`数据源文件不存在:${file}`);
69
+ json = JSON.parse(stripBom(fs.readFileSync(file, 'utf-8')));
70
+ }
71
+
72
+ const list = Array.isArray(json) ? json : json.items || json.plugins || [];
73
+ const items = list.map(normalizeItem);
74
+ return { source, items, schemaVersion: json.schemaVersion || '1.0', raw: json };
75
+ }
76
+
77
+ export function filterItems(items, opts = {}) {
78
+ return items.filter((it) => {
79
+ if (opts.kind && it.kind !== opts.kind) return false;
80
+ if (opts.category && !it.category.toLowerCase().includes(String(opts.category).toLowerCase())) return false;
81
+ if (opts.status && it.status !== opts.status) return false;
82
+ if (opts.tag && !it.tags.map((t) => String(t).toLowerCase()).includes(String(opts.tag).toLowerCase())) return false;
83
+ return true;
84
+ });
85
+ }
86
+
87
+ /** 按编号或 id 查找 */
88
+ export function findByRef(items, ref) {
89
+ const r = String(ref).trim();
90
+ if (/^\d+$/.test(r)) return items.find((it) => String(it.number) === r) || null;
91
+ return items.find((it) => it.id === r || it.name === r) || null;
92
+ }
@@ -0,0 +1,50 @@
1
+ import path from 'node:path';
2
+ import { loadConfig, expandHome } from './config.js';
3
+
4
+ /** 把 id/名称转成安全的目录名 */
5
+ export function slugify(str) {
6
+ return String(str || '')
7
+ .replace(/@v?/g, '-v')
8
+ .replace(/[^a-zA-Z0-9._-]+/g, '-')
9
+ .replace(/^-+|-+$/g, '')
10
+ .toLowerCase();
11
+ }
12
+
13
+ /**
14
+ * 解析某条目在指定 target 下的安装目录。
15
+ * target 三种:ai-editor | navlink | generic
16
+ * @returns {{target:string, dir:string, hint:string}}
17
+ */
18
+ export function resolveTargetDir(item, opts = {}, cfg = loadConfig()) {
19
+ const target = (opts.target || cfg.target || 'generic').toLowerCase();
20
+ const key = slugify(item.name || item.id || `item-${item.number}`);
21
+
22
+ if (target === 'ai-editor' || target === 'ai' || target === 'editor') {
23
+ const editor = (opts.editor || cfg.editor || 'opencode').toLowerCase();
24
+ const preset = cfg.targets?.aiEditor?.[editor];
25
+ if (!preset) {
26
+ throw new Error(`未知编辑器 ${editor}(支持 opencode / claude),可用 dxkj config set targets.aiEditor.${editor}.base <路径> 自定义`);
27
+ }
28
+ const sub = preset.map?.[item.kind] || item.kind || 'misc';
29
+ const base = expandHome(preset.base);
30
+ return {
31
+ target: 'ai-editor',
32
+ dir: path.join(base, sub, key),
33
+ hint: `${editor}:${sub}`
34
+ };
35
+ }
36
+
37
+ if (target === 'navlink') {
38
+ const dirBase = expandHome(opts.dir || cfg.targets?.navlink?.pluginsDir);
39
+ if (!dirBase) throw new Error('navlink 目标未配置安装目录,请用 --dir <NavLink 的 plugins 目录> 或 dxkj config set targets.navlink.pluginsDir <路径>');
40
+ return { target: 'navlink', dir: path.join(dirBase, key), hint: 'navlink:plugins' };
41
+ }
42
+
43
+ if (target === 'generic') {
44
+ const base = expandHome(opts.dir || cfg.targets?.generic?.dir);
45
+ if (!base) throw new Error('generic 目标未配置目录,请用 --dir <目标目录> 或 dxkj config set targets.generic.dir <路径>');
46
+ return { target: 'generic', dir: path.join(base, key), hint: 'generic' };
47
+ }
48
+
49
+ throw new Error(`未知 target:${target}(支持 ai-editor / navlink / generic)`);
50
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * 收录.md 规范 Linter
3
+ * 依据:Skill & Agent Tool 分类与命名规范 v1.0
4
+ */
5
+
6
+ const CATEGORY_CODES = ['IR', 'CL', 'CG', 'DO', 'SI', 'ES', 'AC'];
7
+ const KINDS = ['tool', 'skill', 'prompt', 'agent', 'plugin'];
8
+ const STATUSES = ['experimental', 'active', 'deprecated', 'archived'];
9
+ const ID_RE = /^(tool|skill|prompt|agent|plugin)\.(IR|CL|CG|DO|SI|ES|AC)\.[a-z0-9_]+(\.[a-z0-9_]+)*@v\d+\.\d+$/;
10
+ const VERSION_RE = /^v?\d+\.\d+$/;
11
+ const CJK_RE = /[\u4e00-\u9fff]/;
12
+
13
+ /**
14
+ * @param {object} item
15
+ * @returns {{errors: string[], warnings: string[]}}
16
+ */
17
+ export function validateItem(item, { isNew = true } = {}) {
18
+ const errors = [];
19
+ const warnings = [];
20
+ if (!item || typeof item !== 'object') {
21
+ return { errors: ['条目不是合法对象'], warnings };
22
+ }
23
+
24
+ // 1. id / 命名格式
25
+ if (!item.id) {
26
+ errors.push('缺少必填字段 id');
27
+ } else {
28
+ if (CJK_RE.test(item.id)) errors.push('id 禁止包含中文');
29
+ if (!ID_RE.test(item.id)) {
30
+ errors.push(`id 不符合命名规范:${item.id}(应形如 tool.CL.math_calculator@v1.2 或 skill.CG.ns.name@v1.1)`);
31
+ } else {
32
+ const prefix = item.id.split('.')[0];
33
+ const code = item.id.split('.')[1];
34
+ if (item.kind && prefix !== item.kind) errors.push(`id 前缀(${prefix})与 kind(${item.kind}) 不一致`);
35
+ if (!CATEGORY_CODES.includes(code)) errors.push(`分类简写非法:${code}`);
36
+ }
37
+ }
38
+
39
+ // 2. 必填字段(收录.md 三)
40
+ for (const f of ['name', 'category', 'description', 'status', 'author']) {
41
+ if (!item[f] || (typeof item[f] === 'string' && !item[f].trim())) errors.push(`缺少必填字段 ${f}`);
42
+ }
43
+ if (isNew) {
44
+ for (const f of ['created_at', 'updated_at']) {
45
+ if (!item[f]) warnings.push(`建议补充字段 ${f}`);
46
+ }
47
+ }
48
+
49
+ // 3. kind
50
+ if (item.kind && !KINDS.includes(item.kind)) errors.push(`kind 非法:${item.kind}(应为 ${KINDS.join('/')})`);
51
+
52
+ // 4. status 生命周期
53
+ if (item.status && !STATUSES.includes(item.status)) errors.push(`status 非法:${item.status}(应为 ${STATUSES.join('/')})`);
54
+ if (item.status === 'deprecated' && !item.deprecated_reason) errors.push('status=deprecated 时必须填写 deprecated_reason');
55
+ if (item.deprecated_reason && item.status !== 'deprecated') warnings.push('存在 deprecated_reason 但 status 不是 deprecated');
56
+
57
+ // 5. 版本号
58
+ if (item.version && !VERSION_RE.test(String(item.version))) warnings.push(`version 格式建议为 major.minor:${item.version}`);
59
+
60
+ // 6. tags
61
+ if (item.tags != null && !Array.isArray(item.tags)) errors.push('tags 必须是字符串数组');
62
+ if (Array.isArray(item.tags) && item.tags.some((t) => typeof t !== 'string')) errors.push('tags 必须是字符串数组');
63
+
64
+ // 7. 展示区(本需求)
65
+ if (item.images != null && !Array.isArray(item.images)) errors.push('images 必须是数组');
66
+ if (item.intro == null || item.intro === '') warnings.push('建议补充简介 intro(展示页简介区)');
67
+
68
+ // 8. 安装源
69
+ const install = item.install || {};
70
+ if (!install.url) warnings.push('缺少安装包地址 install.url,CLI 将无法安装');
71
+
72
+ return { errors, warnings };
73
+ }
74
+
75
+ export function formatReport(name, { errors, warnings }) {
76
+ const lines = [];
77
+ if (errors.length === 0 && warnings.length === 0) {
78
+ lines.push(`✓ ${name} 校验通过`);
79
+ return { ok: true, text: lines.join('\n') };
80
+ }
81
+ for (const e of errors) lines.push(`✗ [错误] ${e}`);
82
+ for (const w of warnings) lines.push(`! [警告] ${w}`);
83
+ return { ok: errors.length === 0, text: lines.join('\n') };
84
+ }
@@ -0,0 +1,71 @@
1
+ import { execFile } from 'node:child_process';
2
+
3
+ /**
4
+ * opencode 插件壳
5
+ * 注册方式(opencode.json):{ "plugin": ["dxkj"] }
6
+ * 该模块即包的默认导出(package.json 的 main/exports["."])。
7
+ */
8
+
9
+ async function tryToolHelper() {
10
+ try {
11
+ const mod = await import('@opencode-ai/plugin');
12
+ return mod.tool || null;
13
+ } catch {
14
+ return null;
15
+ }
16
+ }
17
+
18
+ function runCli(args) {
19
+ return new Promise((resolve) => {
20
+ execFile('npx', ['-y', 'dxkj', ...args], { timeout: 120000, maxBuffer: 10 * 1024 * 1024 }, (err, stdout, stderr) => {
21
+ const out = (stdout || '').toString().trim();
22
+ const errText = (stderr || '').toString().trim();
23
+ if (err && !out) resolve(errText || err.message);
24
+ else resolve([out, errText].filter(Boolean).join('\n'));
25
+ });
26
+ });
27
+ }
28
+
29
+ export async function dxkjPlugin() {
30
+ const tool = await tryToolHelper();
31
+ const schema = tool?.schema;
32
+ const def = (spec) => (tool ? tool(spec) : spec);
33
+
34
+ const tools = {
35
+ dxkj_catalog: def({
36
+ description: 'List or search the dxkj catalog of prompts/skills/agents/plugins/tools by keyword and/or kind.',
37
+ args: schema
38
+ ? { keyword: schema.string().optional(), kind: schema.string().optional() }
39
+ : { keyword: { type: 'string' }, kind: { type: 'string' } },
40
+ execute: async (args = {}) => {
41
+ const cliArgs = ['list'];
42
+ if (args.kind) cliArgs.push('--kind', String(args.kind));
43
+ const out = await runCli(cliArgs);
44
+ if (!args.keyword) return out;
45
+ const kw = String(args.keyword).toLowerCase();
46
+ return out
47
+ .split(/\r?\n/)
48
+ .filter((line) => line.toLowerCase().includes(kw) || /^\s*\d+\s/.test(line))
49
+ .join('\n');
50
+ }
51
+ }),
52
+ dxkj_install: def({
53
+ description: 'Install one or more catalog items by number/id using the dxkj CLI.',
54
+ args: schema
55
+ ? { refs: schema.string().describe('逗号分隔的编号或 id,例如 "3,7"'), target: schema.string().optional(), dir: schema.string().optional() }
56
+ : { refs: { type: 'string' }, target: { type: 'string' }, dir: { type: 'string' } },
57
+ execute: async (args = {}) => {
58
+ const refs = String(args.refs || '').split(',').map((s) => s.trim()).filter(Boolean);
59
+ if (refs.length === 0) return '请提供编号,例如 refs="3,7"';
60
+ const cliArgs = ['install', ...refs];
61
+ if (args.target) cliArgs.push('--target', String(args.target));
62
+ if (args.dir) cliArgs.push('--dir', String(args.dir));
63
+ return runCli(cliArgs);
64
+ }
65
+ })
66
+ };
67
+
68
+ return { tool: tools };
69
+ }
70
+
71
+ export default dxkjPlugin;