@dsh-plugin/dsh-pack-plugin 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -3
  3. package/cordis.patch.yml +9 -0
  4. package/icons/folder-zip-line.svg +1 -0
  5. package/lib/ball.js +597 -0
  6. package/lib/client.js +2934 -0
  7. package/lib/host.js +51745 -0
  8. package/lib/migrate-helper.js +35346 -0
  9. package/lib/progress-main.cjs +79 -0
  10. package/lib/progress-window.ps1 +114 -0
  11. package/lib/progress.html +126 -0
  12. package/lib/publish-to-github/SKILL.md +132 -0
  13. package/package.json +77 -4
  14. package/src/ball-entry.js +5 -0
  15. package/src/ball-host.js +99 -0
  16. package/src/ball-settings.js +352 -0
  17. package/src/ball.js +418 -0
  18. package/src/channel.js +12 -0
  19. package/src/client-plugin.js +58 -0
  20. package/src/client-rpc.js +14 -0
  21. package/src/client.js +5 -0
  22. package/src/core/discovery.js +192 -0
  23. package/src/core/dspack.js +93 -0
  24. package/src/core/extension-files.js +102 -0
  25. package/src/core/extension-install.js +295 -0
  26. package/src/core/extension-patch.js +369 -0
  27. package/src/core/extension-skills.js +164 -0
  28. package/src/core/extension-validate.js +127 -0
  29. package/src/core/extensions.js +207 -0
  30. package/src/core/home-store.js +32 -0
  31. package/src/core/host.js +149 -0
  32. package/src/core/index.js +59 -0
  33. package/src/core/inspect.js +162 -0
  34. package/src/core/install.js +775 -0
  35. package/src/core/managed-install.js +84 -0
  36. package/src/core/manifest.js +717 -0
  37. package/src/core/market.js +268 -0
  38. package/src/core/mcp-composition.js +189 -0
  39. package/src/core/mcp-install.js +112 -0
  40. package/src/core/mcp-transport.js +116 -0
  41. package/src/core/pack.js +371 -0
  42. package/src/core/plugin-metadata.js +355 -0
  43. package/src/core/registry.js +316 -0
  44. package/src/core/repo.js +339 -0
  45. package/src/core/scan.js +78 -0
  46. package/src/core/security.js +101 -0
  47. package/src/core/special.js +50 -0
  48. package/src/core/tar.js +103 -0
  49. package/src/core/update-config.js +234 -0
  50. package/src/core/update.js +792 -0
  51. package/src/core/vendored.js +715 -0
  52. package/src/core/workspace.js +95 -0
  53. package/src/endpoints.js +455 -0
  54. package/src/ensure-manager.js +186 -0
  55. package/src/host-node.js +625 -0
  56. package/src/host.js +17 -0
  57. package/src/index.d.ts +7 -0
  58. package/src/index.js +39 -0
  59. package/src/junction.js +142 -0
  60. package/src/migrate-helper.js +225 -0
  61. package/src/migrate.js +56 -0
  62. package/src/packaged.js +9 -0
  63. package/src/profiles.js +106 -0
  64. package/src/progress-main.cjs +79 -0
  65. package/src/progress-window.ps1 +114 -0
  66. package/src/progress.html +126 -0
  67. package/src/progress.js +132 -0
  68. package/src/rpc.js +157 -0
  69. package/src/runtime.js +43 -0
  70. package/src/section-gate.js +50 -0
  71. package/src/settings-nav-icon.js +188 -0
  72. package/src/settings.js +1611 -0
  73. package/src/skills/index.js +90 -0
  74. package/src/skills/publish-to-github/SKILL.md +132 -0
  75. package/src/tasks.js +145 -0
  76. package/src/v6-dialogs.js +312 -0
@@ -0,0 +1,164 @@
1
+ import { parse } from 'yaml';
2
+ import { digestFiles, localized, readJson, readTree, relativePath, safePath, segment } from './extension-files.js';
3
+
4
+ const sha = /^(?:[a-f\d]{40}|[a-f\d]{64})$/i;
5
+
6
+ function repository(value) {
7
+ const raw = String(value ?? '');
8
+ const [address, fragment = ''] = raw.split('#');
9
+ // SSH 用户名可以发布,HTTP 地址中的认证信息、查询参数不可进入清单。
10
+ let url;
11
+ if (/^git@[A-Za-z0-9.-]+:[A-Za-z0-9._/-]+$/.test(address)) url = address;
12
+ else {
13
+ let parsed;
14
+ try { parsed = new URL(address); } catch { throw new Error('技能仓库地址无效'); }
15
+ if (!['https:','ssh:'].includes(parsed.protocol) || parsed.password || parsed.search ||
16
+ (parsed.protocol === 'https:' && parsed.username)) throw new Error('技能仓库须使用无内嵌凭据的 HTTPS 或 SSH 地址');
17
+ url = parsed.href;
18
+ }
19
+ const subdir = fragment.replace(/^\/|\/$/g, '');
20
+ if (subdir) relativePath(subdir);
21
+ return { repository: url, subdir };
22
+ }
23
+
24
+ export function checkSkillSource(source) {
25
+ const parsed = repository(source.repository);
26
+ const subdir = source.subdir || parsed.subdir;
27
+ if (subdir) relativePath(subdir);
28
+ const ref = source.ref || (source.mode === 'fixed' ? source.commit : 'HEAD');
29
+ if (source.mode === 'fixed') {
30
+ if (!sha.test(ref)) throw new Error('固定技能要求完整的 Git commit SHA');
31
+ } else if (source.mode !== 'track' || typeof ref !== 'string' ||
32
+ !/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(ref) || /(?:\.\.|\/\/|\/\.|\.lock$|[/.]$)/.test(ref)) {
33
+ throw new Error('跟踪技能需要有效的分支名或标签');
34
+ }
35
+ return { mode: source.mode, repository: parsed.repository, subdir, ref };
36
+ }
37
+
38
+ async function findSkill(host, root, subdir, id) {
39
+ const base = subdir ? await safePath(host, root, subdir) : root;
40
+ if ((await host.readdir(base))?.some(e => e.type === 'file' && e.name === 'SKILL.md')) return base;
41
+ const matches = [];
42
+ async function visit(dir) {
43
+ for (const e of await host.readdir(dir) ?? []) {
44
+ if (e.type !== 'dir' || e.name === '.git' || e.name === 'node_modules') continue;
45
+ if (e.name === id && (await host.readdir(e.abs))?.some(f => f.type === 'file' && f.name === 'SKILL.md')) matches.push(e.abs);
46
+ else await visit(e.abs);
47
+ }
48
+ }
49
+ await visit(base);
50
+ if (matches.length !== 1) throw new Error('仓库内无法唯一定位技能,请指定 subdir:' + id);
51
+ return matches[0];
52
+ }
53
+
54
+ export async function checkoutSkill(host, source, id) {
55
+ const config = checkSkillSource(source);
56
+ if (typeof host.git !== 'function') throw new Error('宿主无法运行 Git');
57
+ const temp = await host.mkdtemp('dspack-skill-');
58
+ try {
59
+ async function git(args) {
60
+ const r = await host.git(args, {cwd:temp});
61
+ if (r.status !== 0) throw new Error('技能仓库操作失败:' + args[0]);
62
+ return r.stdout.trim();
63
+ }
64
+ await git(['init', '--quiet']);
65
+ await git(['config','core.autocrlf','false']);
66
+ await git(['config','core.eol','lf']);
67
+ await git(['fetch','--quiet','--depth=1','--no-tags','--',config.repository,config.ref]);
68
+ const commit = await git(['rev-parse','--verify','FETCH_HEAD^{commit}']);
69
+ if (!sha.test(commit) || (config.mode === 'fixed' && commit.toLowerCase() !== config.ref.toLowerCase())) {
70
+ throw new Error('技能仓库返回的 SHA 与指定版本不符');
71
+ }
72
+ await git(['checkout','--quiet','--detach',commit]);
73
+ const dir = await findSkill(host, temp, config.subdir, id);
74
+ const files = await readTree(host, dir, {rejectLinks:true});
75
+ const tree = await git(['-C',dir,'ls-tree','-r','-z',commit,'--','.']);
76
+ const executables = new Set();
77
+ for (const entry of tree.split('\0')) {
78
+ const tab = entry.indexOf('\t');
79
+ const path = entry.slice(tab+1);
80
+ if (entry.startsWith('100755 blob ') && tab !== -1 && files.has(path)) executables.add(path);
81
+ }
82
+ return { ...config, commit, files, executables, digest: await digestFiles(host, files) };
83
+ } finally { await host.rm(temp, {recursive:true,force:true}); }
84
+ }
85
+
86
+ export async function skillRoots(host,home,profiles,wholeHome) {
87
+ const roots = new Map();
88
+ if (!home) return roots;
89
+ const store = host.joinPath(home,'.dsh-pack','skills');
90
+ const slots = new Set((await host.readdir(store) || []).filter(e=>e.type === 'dir').map(e=>e.name));
91
+ const common = (await host.readdir(home) || []).find(e=>e.name === 'skills');
92
+ if (!wholeHome && profiles.length === 1 && slots.has(profiles[0].name)) {
93
+ roots.set('home',host.joinPath(store,segment(profiles[0].name)));
94
+ return roots;
95
+ }
96
+ if (common?.type === 'dir') roots.set('home',common.abs);
97
+ if (wholeHome) for (const p of profiles) {
98
+ const slot = slots.has(p.name) ? p.name : (p.name === 'desktop' && slots.has('default') ? 'default' : null);
99
+ if (slot) roots.set('profile:'+segment(p.name),host.joinPath(store,slot));
100
+ }
101
+ return roots;
102
+ }
103
+
104
+ export async function discoverSkills(host,root,scope) {
105
+ const result = [];
106
+ for (const e of await host.readdir(root) ?? []) {
107
+ if (e.name.startsWith('.') || e.type === 'symlink') continue;
108
+ if (!(e.type === 'dir' || (e.type === 'file' && e.name.endsWith('.md')))) continue;
109
+ const text = await host.readTextFile(e.type === 'dir' ? host.joinPath(e.abs, 'SKILL.md') : e.abs);
110
+ if (text == null) continue;
111
+ const header = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
112
+ let name=e.name,desc='',warning;
113
+ if (header) {
114
+ try {
115
+ const meta = parse(header[1]);
116
+ name = localized(meta?.name,e.name);
117
+ desc = localized(meta?.description,'');
118
+ } catch { warning = '技能头信息无法解析,使用目录名显示'; }
119
+ }
120
+ const entry = { kind:'skill', key:'skill:'+scope+':' + e.name, scope, id:segment(e.name),
121
+ name,desc,flat:e.type === 'file' };
122
+ if (warning) entry.sourceWarning=warning;
123
+ if (e.type === 'dir') {
124
+ let origin;
125
+ try { origin = await readJson(host, host.joinPath(e.abs, '.dsh-skill.json')); }
126
+ catch { entry.sourceWarning = '来源记录无法解析,可内嵌文件或重新指定仓库'; }
127
+ if (origin?.repo) {
128
+ try {
129
+ const parsed = repository(origin.repo);
130
+ entry.source = { ...parsed, commit:sha.test(origin.commit) ? origin.commit : '', ref:origin.ref || origin.tag || 'HEAD' };
131
+ Object.assign(entry, parsed, {commit:entry.source.commit,ref:origin.ref || origin.tag || ''});
132
+ } catch { entry.sourceWarning = '来源地址含凭据或格式不受支持,请填写无凭据的仓库地址'; }
133
+ }
134
+ }
135
+ result.push(entry);
136
+ }
137
+ return result;
138
+ }
139
+
140
+ export async function exportSkill(host, root, candidate, choice) {
141
+ const id = segment(candidate.id);
142
+ const dir = root ? host.joinPath(root,id) : null;
143
+ const exists = dir ? await host.stat(dir) : null;
144
+ let local = null;
145
+ if (exists?.isDirectory) local = await readTree(host,dir);
146
+ if (exists?.isFile) local = new Map([[id,await host.readFile(dir)]]);
147
+ const mode = choice.mode || 'embedded';
148
+ if (mode === 'embedded') {
149
+ if (!local?.size) throw new Error('内嵌技能没有本地文件:' + id);
150
+ return { mode, files:local, digest:await digestFiles(host,local) };
151
+ }
152
+ const source = { ...candidate.source, ...Object.fromEntries(Object.entries(choice).filter(([,v])=>v !== '' && v != null)), mode };
153
+ if (mode === 'fixed') source.ref = choice.ref || source.commit;
154
+ const fetched = await checkoutSkill(host,source,id);
155
+ if (local) {
156
+ let baseline = fetched.digest;
157
+ if (candidate.source?.commit && candidate.source.commit !== fetched.commit) {
158
+ baseline = (await checkoutSkill(host,{...candidate.source,mode:'fixed',ref:candidate.source.commit},id)).digest;
159
+ }
160
+ if (await digestFiles(host,local) !== baseline) throw new Error('本地技能内容与来源不同,请选择内嵌:' + id);
161
+ }
162
+ const {executables, ...metadata} = fetched;
163
+ return { ...metadata, files:null };
164
+ }
@@ -0,0 +1,127 @@
1
+ import { localized, expandTemplate, protectedTarget, relativePath, segment } from './extension-files.js';
2
+ import { checkSkillSource } from './extension-skills.js';
3
+ import { credentialRefs } from './extension-patch.js';
4
+ import { portableMcpTransport } from './mcp-transport.js';
5
+
6
+ const decoder = new TextDecoder('utf-8',{fatal:true});
7
+ const sha256 = /^[a-f0-9]{64}$/;
8
+ const sha = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
9
+ const fileKinds = {'path.json':'path','provider.json':'provider','mcp.json':'mcp','skill.json':'skill'};
10
+ const own = (v,k)=>Object.hasOwn(v ?? {},k);
11
+
12
+ export function validatedItems(manifest,entries) {
13
+ const items = [], keys = new Set(), blobs = new Set(), targets = new Set(), emptyDirectories = new Set();
14
+ const check = (ok,context) => { if (!ok) throw new Error('扩展资源格式无效:'+context); };
15
+ function blob(file,kind) {
16
+ check(sha256.test(file?.sha256) && file.entry === 'extension-data/'+kind+'/'+file.sha256 &&
17
+ own(entries,file.entry) && entries[file.entry] instanceof Uint8Array,'文件引用');
18
+ blobs.add(file.entry);
19
+ }
20
+ function register(item,kind,plugin) {
21
+ check(item?.kind === kind && typeof item.key === 'string' && !keys.has(item.key),'资源类型或重复标识');
22
+ check(typeof item.id === 'string' && item.id.length > 0 && !['__proto__','prototype','constructor'].includes(item.id),'id');
23
+ check(typeof item.scope === 'string' && (item.scope === 'home' || item.scope.startsWith('profile:')),'scope');
24
+ const profile = item.scope === 'home' ? manifest.profileName : segment(item.scope.slice(8));
25
+ if (manifest.type === 'dshhome' && item.scope !== 'home') check(own(manifest.profiles,profile),'未知 profile');
26
+ check(item.name != null && localized(item.name) != null,'name');
27
+ localized(item.desc,'');
28
+ keys.add(item.key);
29
+ if (kind === 'path') {
30
+ check(typeof plugin === 'string' && /^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(plugin) && item.plugin === plugin &&
31
+ item.key === [kind,item.scope,plugin,item.id].join(':'),'plugin');
32
+ check(Array.isArray(item.paths) && item.paths.length && Array.isArray(item.files),'paths/files');
33
+ check(item.directories === undefined || Array.isArray(item.directories),'directories');
34
+ const roots = item.paths.map(p=>expandTemplate(p,profile));
35
+ for (const root of roots) check(!protectedTarget(root),'路径占用系统配置');
36
+ const directories = item.directories ?? [];
37
+ const fileTargets = new Set(item.files);
38
+ for (const f of [...item.files,...directories]) {
39
+ check(Number.isInteger(f?.index) && own(roots,f.index) && typeof f.tail === 'string','路径规则编号');
40
+ if (f.tail) relativePath(f.tail);
41
+ const target = roots[f.index]+(f.tail ? '/'+f.tail : '');
42
+ check(f.path === target && !protectedTarget(target) && !targets.has(target.toLowerCase()),'插件文件目标');
43
+ targets.add(target.toLowerCase());
44
+ if (fileTargets.has(f)) blob(f,'path');
45
+ else {
46
+ check(Object.keys(f).every(k=>['index','tail','path'].includes(k)),'空目录记录');
47
+ emptyDirectories.add(target.toLowerCase());
48
+ }
49
+ }
50
+ } else {
51
+ check(item.key === kind+':'+item.scope+':'+item.id,'key');
52
+ if (kind === 'skill') {
53
+ segment(item.id);
54
+ check((item.scope === 'home' || manifest.type === 'dshhome') && sha256.test(item.digest),'技能作用域与摘要');
55
+ if (item.mode === 'embedded') {
56
+ check(Array.isArray(item.files) && item.files.length,'技能文件清单');
57
+ const paths = new Set();
58
+ for (const f of item.files) {
59
+ const p = relativePath(f.path).toLowerCase();
60
+ check(!paths.has(p) && p !== '.dsh-skill.json','技能文件重复');
61
+ paths.add(p); blob(f,'skill');
62
+ }
63
+ check(item.flat ? item.files.length === 1 && item.files[0].path === item.id : paths.has('skill.md'),'技能入口');
64
+ } else {
65
+ checkSkillSource(item);
66
+ check(!item.flat && item.files == null && sha.test(item.commit) && (item.mode !== 'fixed' || item.commit === item.ref),'远程技能来源');
67
+ }
68
+ } else {
69
+ check(item.value && typeof item.value === 'object' && !Array.isArray(item.value),'配置对象');
70
+ if (kind === 'mcp') {
71
+ const config = item.value.config;
72
+ check(item.value.name === '@deepseek-ai/dsh-mcp-client' && item.value.id === item.id &&
73
+ typeof config?.serverName === 'string' && /^[a-z0-9_-]{1,32}$/i.test(config.serverName),'MCP 标识');
74
+ check(['stdio','streamable-http'].includes(config.transport || 'stdio'),'MCP transport');
75
+ portableMcpTransport(config,'MCP',new Set(),true);
76
+ for (const map of [config.env,config.headers]) {
77
+ if (map == null) continue;
78
+ check(typeof map === 'object' && !Array.isArray(map),'MCP 变量表');
79
+ for (const v of Object.values(map)) check(v === '' || v?.$credential ||
80
+ (typeof v === 'string' && /^\$\{credential:[A-Za-z_][A-Za-z0-9_]*\}$/.test(v)),'MCP 字段含未脱敏值');
81
+ }
82
+ }
83
+ const refs = credentialRefs(item);
84
+ check(Array.isArray(item.credentialRefs) && refs.length === item.credentialRefs.length &&
85
+ refs.every(r=>item.credentialRefs.includes(r)),'凭据引用清单');
86
+ }
87
+ }
88
+ items.push(item);
89
+ }
90
+ for (const [name,kind] of Object.entries(fileKinds)) {
91
+ if (!own(entries,name)) continue;
92
+ let data;
93
+ try { data = JSON.parse(decoder.decode(entries[name])); } catch { throw new Error('扩展清单无法解码:'+name); }
94
+ if (kind === 'path') {
95
+ check(data?.plugins && typeof data.plugins === 'object' && !Array.isArray(data.plugins),name);
96
+ for (const [plugin,rows] of Object.entries(data.plugins)) {
97
+ check(Array.isArray(rows),name); rows.forEach(item=>register(item,kind,plugin));
98
+ }
99
+ } else { check(Array.isArray(data?.items),name); data.items.forEach(item=>register(item,kind)); }
100
+ }
101
+ for (const path of targets) {
102
+ let parent = path;
103
+ while (parent.includes('/')) {
104
+ parent = parent.slice(0,parent.lastIndexOf('/'));
105
+ check(!targets.has(parent),'文件或空目录含有其他目标');
106
+ }
107
+ }
108
+ for (const path of Object.keys(entries)) {
109
+ if (path.startsWith('extension-data/')) check(blobs.has(path),'未被声明的扩展文件');
110
+ if (!emptyDirectories.size || path.endsWith('/')) continue;
111
+ let target;
112
+ if (path.startsWith('home/') && manifest.type !== 'dshhome') target = path.slice(5);
113
+ if (path.startsWith('overrides/')) target = (manifest.type === 'dshhome' ? '' : 'profiles/'+manifest.profileName+'/') + path.slice(10);
114
+ if (target) {
115
+ const parts = target.toLowerCase().split('/');
116
+ while (parts.length) {
117
+ check(!emptyDirectories.has(parts.join('/')),'空目录与快照文件重复');
118
+ parts.pop();
119
+ }
120
+ }
121
+ }
122
+ return items;
123
+ }
124
+
125
+ export function validateExtensions(manifest,entries) {
126
+ validatedItems(manifest,entries);
127
+ }
@@ -0,0 +1,207 @@
1
+ import { discoverSkills, exportSkill, skillRoots } from './extension-skills.js';
2
+ import { splitPatch } from './extension-patch.js';
3
+ import { expandTemplate, localized, protectedTarget, readJson, readTree, safePath, segment } from './extension-files.js';
4
+
5
+ export { planExtensionInstall } from './extension-install.js';
6
+ export { validateExtensions } from './extension-validate.js';
7
+
8
+ const utf8 = new TextEncoder();
9
+ const sidecars = {paths:'path.json', providers:'provider.json', mcp:'mcp.json', skills:'skill.json'};
10
+ const npmName = /^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/i;
11
+
12
+ function scopeOf(profile) { return 'profile:' + segment(profile.name); }
13
+ function choiceMap(list = []) {
14
+ if (!Array.isArray(list)) throw new Error('扩展资源选择需要数组');
15
+ const selected = new Map();
16
+ for (const value of list) {
17
+ const choice = typeof value === 'string' ? {key:value} : value;
18
+ if (typeof choice?.key !== 'string' || !choice.key || selected.has(choice.key)) throw new Error('已选资源的键缺失或重复');
19
+ selected.set(choice.key,choice);
20
+ }
21
+ return selected;
22
+ }
23
+
24
+ async function declaredPaths(host, home, profiles) {
25
+ const resources = new Map();
26
+ for (const profile of profiles) {
27
+ const pkg = await readJson(host,host.joinPath(profile.dir,'package.json'));
28
+ const names = new Set([...Object.keys(pkg?.dependencies || {}), ...(pkg?.dsh?.profile?.bundles || [])]);
29
+ for (const plugin of names) {
30
+ if (!npmName.test(plugin)) continue;
31
+ const declaration = await readJson(host, host.joinPath(profile.dir,'node_modules',...plugin.split('/'),'dsh_pack','paths.json'));
32
+ if (!declaration) continue;
33
+ const rules = Array.isArray(declaration) ? declaration : [declaration];
34
+ for (const [index,rule] of rules.entries()) {
35
+ if (!rule?.name || !Array.isArray(rule.paths) || !rule.paths.length) throw new Error('插件路径声明缺少 name 或 paths:' + plugin);
36
+ const scope = rule.paths.some(p=>typeof p==='string' && p.includes('<profile>')) ? scopeOf(profile) : 'home';
37
+ const id = String(index);
38
+ const key = ['path',scope,plugin,id].join(':');
39
+ const item = {key,id,plugin,scope,kind:'path',name:localized(rule.name),desc:localized(rule.desc,''),paths:rule.paths};
40
+ for (const p of item.paths) {
41
+ const expanded = expandTemplate(p,profile.name);
42
+ if (protectedTarget(expanded)) throw new Error('插件声明占用了保留资源路径:' + expanded);
43
+ }
44
+ if (resources.has(key) && JSON.stringify(resources.get(key)) !== JSON.stringify(item)) {
45
+ throw new Error('同一插件对全局数据声明不一致:' + plugin);
46
+ }
47
+ resources.set(key,item);
48
+ }
49
+ }
50
+ }
51
+ return [...resources.values()];
52
+ }
53
+
54
+ async function inspect(host, {home,profiles,wholeHome=false}) {
55
+ const patches = new Map();
56
+ const providers = [], mcp = [];
57
+ for (const [scope,dir] of [...(home ? [['home',home]] : []), ...profiles.map(p=>[scopeOf(p),p.dir])]) {
58
+ const raw = await host.readTextFile(host.joinPath(dir,'cordis.patch.yml'));
59
+ const patch = splitPatch(raw,scope);
60
+ patches.set(scope,patch.patch);
61
+ for (const item of patch.items) (item.kind === 'provider' ? providers : mcp).push(item);
62
+ }
63
+ const paths = await declaredPaths(host,home,profiles);
64
+ const roots = await skillRoots(host,home,profiles,wholeHome);
65
+ const skills = [];
66
+ for (const [scope,root] of roots) skills.push(...await discoverSkills(host,root,scope));
67
+ return {patches,roots,paths,providers,mcp,skills};
68
+ }
69
+
70
+ export async function discoverExtensions(host, location) {
71
+ const {patches,roots,...result} = await inspect(host,location);
72
+ for (const kind of ['providers','mcp']) result[kind] = result[kind].map(({value,...item})=>item);
73
+ return result;
74
+ }
75
+
76
+ function ordinaryHomePath(path,manifest,profileName) {
77
+ if (manifest.type === 'dshhome') return path.startsWith('overrides/') ? path.slice(10) : '';
78
+ if (path.startsWith('home/')) return path.slice(5);
79
+ if (path.startsWith('overrides/')) return 'profiles/' + profileName + '/' + path.slice(10);
80
+ return '';
81
+ }
82
+
83
+ function stripPath(entries,manifest,profileName,rel) {
84
+ const norm = rel.toLowerCase();
85
+ for (const path of Object.keys(entries)) {
86
+ const homePath = ordinaryHomePath(path,manifest,profileName).toLowerCase();
87
+ if (homePath === norm || homePath.startsWith(norm+'/')) delete entries[path];
88
+ }
89
+ }
90
+
91
+ function withLabel(item,selection) {
92
+ return { ...item,name:localized(selection.name || item.name,item.id),desc:localized(selection.desc,item.desc) };
93
+ }
94
+
95
+ async function capturePath(host,home,profiles,entries,item,claimed,profileName) {
96
+ const files = [];
97
+ const directories = [];
98
+ const profile = item.scope.startsWith('profile:') ? item.scope.slice(8) : profileName;
99
+ for (const [index,template] of item.paths.entries()) {
100
+ const rel = expandTemplate(template,profile);
101
+ const resolved = profiles.find(p=>p.name === profile);
102
+ const prefix = 'profiles/'+profile+'/';
103
+ const target = resolved && rel.startsWith(prefix) ? await safePath(host,resolved.dir,rel.slice(prefix.length)) : await safePath(host,home,rel);
104
+ const stat = await host.stat(target);
105
+ if (!stat) continue;
106
+ const emptyDirs = [];
107
+ const tree = stat.isDirectory ? await readTree(host,target,{emptyDirs}) : new Map([['',await host.readFile(target)]]);
108
+ for (const tail of emptyDirs) {
109
+ const path = rel + (tail ? '/'+tail : '');
110
+ const key = path.toLowerCase();
111
+ if (protectedTarget(path) || claimed.has(key)) throw new Error('插件目录目标受保护或重复:' + path);
112
+ claimed.add(key);
113
+ directories.push({path,index,tail});
114
+ }
115
+ for (const [tail,bytes] of tree) {
116
+ const path = rel + (tail ? '/'+tail : '');
117
+ if (protectedTarget(path) || !bytes) throw new Error('无法捕获插件数据:' + path);
118
+ const key = path.toLowerCase();
119
+ if (claimed.has(key)) throw new Error('多个插件数据规则声明了同一文件:' + path);
120
+ claimed.add(key);
121
+ const hash = await host.sha256(bytes);
122
+ const entry = 'extension-data/path/' + hash;
123
+ entries[entry] = bytes;
124
+ files.push({path,index,tail,entry,sha256:hash});
125
+ }
126
+ }
127
+ return { ...item, files, ...(directories.length ? {directories} : {}) };
128
+ }
129
+
130
+ export async function collectExtensions(host,{home,profiles,manifest,entries,selection = {}}) {
131
+ const all = await inspect(host,{home,profiles,wholeHome:manifest.type === 'dshhome'});
132
+ const profileName = profiles[0]?.name || '';
133
+ const single = manifest.type !== 'dshhome';
134
+ if (single && profiles.length) {
135
+ manifest.patch = all.patches.get('profile:' + profileName);
136
+ } else if (!single) {
137
+ for (const [name, unit] of Object.entries(manifest.profiles)) unit.patch = all.patches.get('profile:' + name);
138
+ }
139
+ // 每份随包发布的补丁都必须对应已清理的作用域,包括按白名单部分导出的整机快照。
140
+ for (const path of Object.keys(entries)) {
141
+ const rel = ordinaryHomePath(path, manifest, profileName);
142
+ const match = /^(?:profiles\/([^/]+)\/)?cordis\.patch\.yml$/i.exec(rel);
143
+ if (!match) continue;
144
+ const scope = match[1] ? 'profile:' + match[1] : 'home';
145
+ if (!all.patches.has(scope)) throw new Error('导出配置档补丁时须同时选择 profiles/' + match[1] + '/package.json:' + path);
146
+ entries[path] = utf8.encode(all.patches.get(scope));
147
+ }
148
+ const selected = Object.fromEntries(Object.keys(sidecars).map(kind=>[kind,choiceMap(selection?.[kind])]));
149
+ const output = {paths:{plugins:Object.create(null)},providers:{items:[]},mcp:{items:[]},skills:{items:[]}};
150
+ const claimed = new Set();
151
+ for (const candidate of all.paths) {
152
+ for (const template of candidate.paths) stripPath(entries,manifest,profileName,
153
+ expandTemplate(template,candidate.scope === 'home' ? profileName : candidate.scope.slice(8)));
154
+ const choice = selected.paths.get(candidate.key);
155
+ if (choice) {
156
+ if (!home) throw new Error('导出插件声明路径需要指定 DSH_HOME(--home)');
157
+ const item = await capturePath(host,home,profiles,entries,withLabel(candidate,choice),claimed,profileName);
158
+ (output.paths.plugins[item.plugin] ??= []).push(item);
159
+ selected.paths.delete(candidate.key);
160
+ }
161
+ }
162
+ for (const kind of ['providers','mcp']) {
163
+ for (const candidate of all[kind]) {
164
+ const choice = selected[kind].get(candidate.key);
165
+ if (!choice) continue;
166
+ if (candidate.unsupported) throw new Error('所选配置含无法安全移植的脚本、地址、凭据或 YAML 表达式(含别名):'+candidate.id);
167
+ const {unsupported,...safe} = candidate;
168
+ output[kind].items.push(withLabel(safe,choice));
169
+ selected[kind].delete(candidate.key);
170
+ }
171
+ }
172
+ stripPath(entries,manifest,profileName,'skills');
173
+ // .dsh-skill.json 中的历史仓库地址可能携带认证信息。
174
+ for (const path of Object.keys(entries)) if (/(^|\/)\.dsh-skill\.json$/.test(path)) delete entries[path];
175
+ if (manifest.skills) manifest.skills = manifest.skills.filter(s=>typeof s.path !== 'string' || !s.path.startsWith('skills/'));
176
+ for (const [key,choice] of selected.skills) {
177
+ let candidate = all.skills.find(s=>s.key === key);
178
+ if (!candidate) {
179
+ const match = /^skill:(home|profile:([^:]+)):([^:]+)$/.exec(key);
180
+ if (!match || !choice.repository || (match[2] && (single || !profiles.some(p=>p.name === match[2])))) throw new Error('未找到已选技能:' + key);
181
+ const id = segment(choice.id || match[3]);
182
+ if (id !== match[3]) throw new Error('技能标识与键不一致');
183
+ candidate = {key,kind:'skill',id,scope:match[1],name:id,desc:''};
184
+ }
185
+ if (!home && choice.mode === 'embedded') throw new Error('导出本地技能需要指定 DSH_HOME(--home)');
186
+ const {files,...result} = await exportSkill(host,all.roots.get(candidate.scope),candidate,choice);
187
+ const {source,sourceWarning,repository,subdir,commit,ref,...item} = withLabel(candidate,choice);
188
+ const data = {...item,...result};
189
+ if (files) {
190
+ data.files = [];
191
+ for (const [path,bytes] of files) {
192
+ const hash = await host.sha256(bytes);
193
+ const entry = 'extension-data/skill/' + hash;
194
+ entries[entry] = bytes;
195
+ data.files.push({path,entry,sha256:hash});
196
+ }
197
+ }
198
+ output.skills.items.push(data);
199
+ }
200
+ for (const kind of ['paths','providers','mcp']) if (selected[kind].size) throw new Error('未找到已选扩展资源:'+[...selected[kind].keys()].join(', '));
201
+ for (const [kind,path] of Object.entries(sidecars)) {
202
+ const result = output[kind];
203
+ if (Object.keys(result.plugins ?? result.items).length) entries[path] = utf8.encode(JSON.stringify(result,null,2)+'\n');
204
+ else delete entries[path];
205
+ }
206
+ return output;
207
+ }
@@ -0,0 +1,32 @@
1
+ // home 级「可换指」目录(skills / .agent-presets)的落盘布局:
2
+ // 真实数据放 $DSH_HOME/.dsh-pack/<store>/<profileName>/,$DSH_HOME 下的 <artifact> 是 junction 指针。
3
+ // install(写入)、junction(换指)、scan(跟随指针)共用,避免三处路径漂移。
4
+
5
+ /** artifact 名(home 根目录名)→ .dsh-pack 下 store 目录名。 */
6
+ export const HOME_ARTIFACT_STORE = {
7
+ skills: 'skills',
8
+ '.agent-presets': 'agent-presets',
9
+ };
10
+
11
+ /** 参与换指的 artifact 名集合(供扫描器判断「顶层指针需跟随」)。 */
12
+ export const HOME_ARTIFACTS = new Set(Object.keys(HOME_ARTIFACT_STORE));
13
+
14
+ /** 判断 home 相对路径落在哪个 artifact 下(否则 null)。 */
15
+ function matchHomeArtifact(rel) {
16
+ for (const artifact of HOME_ARTIFACTS) {
17
+ if (rel === artifact || rel.startsWith(`${artifact}/`)) return artifact;
18
+ }
19
+ return null;
20
+ }
21
+
22
+ /**
23
+ * 把 home 相对路径重写到 .dsh-pack/<store>/<profileName>/ 下('/' 分隔);
24
+ * 非换指目录原样返回。`rest` 用 slice 保留前导 '/',精确命中时为空串。
25
+ */
26
+ export function storeHomeRel(rel, profileName) {
27
+ const artifact = matchHomeArtifact(rel);
28
+ if (!artifact) return rel;
29
+ const store = HOME_ARTIFACT_STORE[artifact];
30
+ const rest = rel === artifact ? '' : rel.slice(artifact.length);
31
+ return `.dsh-pack/${store}/${profileName}${rest}`;
32
+ }