@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.
- package/LICENSE +21 -0
- package/README.md +178 -3
- package/cordis.patch.yml +9 -0
- package/icons/folder-zip-line.svg +1 -0
- package/lib/ball.js +597 -0
- package/lib/client.js +2934 -0
- package/lib/host.js +51745 -0
- package/lib/migrate-helper.js +35346 -0
- package/lib/progress-main.cjs +79 -0
- package/lib/progress-window.ps1 +114 -0
- package/lib/progress.html +126 -0
- package/lib/publish-to-github/SKILL.md +132 -0
- package/package.json +77 -4
- package/src/ball-entry.js +5 -0
- package/src/ball-host.js +99 -0
- package/src/ball-settings.js +352 -0
- package/src/ball.js +418 -0
- package/src/channel.js +12 -0
- package/src/client-plugin.js +58 -0
- package/src/client-rpc.js +14 -0
- package/src/client.js +5 -0
- package/src/core/discovery.js +192 -0
- package/src/core/dspack.js +93 -0
- package/src/core/extension-files.js +102 -0
- package/src/core/extension-install.js +295 -0
- package/src/core/extension-patch.js +369 -0
- package/src/core/extension-skills.js +164 -0
- package/src/core/extension-validate.js +127 -0
- package/src/core/extensions.js +207 -0
- package/src/core/home-store.js +32 -0
- package/src/core/host.js +149 -0
- package/src/core/index.js +59 -0
- package/src/core/inspect.js +162 -0
- package/src/core/install.js +775 -0
- package/src/core/managed-install.js +84 -0
- package/src/core/manifest.js +717 -0
- package/src/core/market.js +268 -0
- package/src/core/mcp-composition.js +189 -0
- package/src/core/mcp-install.js +112 -0
- package/src/core/mcp-transport.js +116 -0
- package/src/core/pack.js +371 -0
- package/src/core/plugin-metadata.js +355 -0
- package/src/core/registry.js +316 -0
- package/src/core/repo.js +339 -0
- package/src/core/scan.js +78 -0
- package/src/core/security.js +101 -0
- package/src/core/special.js +50 -0
- package/src/core/tar.js +103 -0
- package/src/core/update-config.js +234 -0
- package/src/core/update.js +792 -0
- package/src/core/vendored.js +715 -0
- package/src/core/workspace.js +95 -0
- package/src/endpoints.js +455 -0
- package/src/ensure-manager.js +186 -0
- package/src/host-node.js +625 -0
- package/src/host.js +17 -0
- package/src/index.d.ts +7 -0
- package/src/index.js +39 -0
- package/src/junction.js +142 -0
- package/src/migrate-helper.js +225 -0
- package/src/migrate.js +56 -0
- package/src/packaged.js +9 -0
- package/src/profiles.js +106 -0
- package/src/progress-main.cjs +79 -0
- package/src/progress-window.ps1 +114 -0
- package/src/progress.html +126 -0
- package/src/progress.js +132 -0
- package/src/rpc.js +157 -0
- package/src/runtime.js +43 -0
- package/src/section-gate.js +50 -0
- package/src/settings-nav-icon.js +188 -0
- package/src/settings.js +1611 -0
- package/src/skills/index.js +90 -0
- package/src/skills/publish-to-github/SKILL.md +132 -0
- package/src/tasks.js +145 -0
- package/src/v6-dialogs.js +312 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// 仅把可直接交给 DSH 凭据模板解析器的参数转换为引用。遇到脚本或不透明的端点时整条 MCP 留在选择列表外。
|
|
2
|
+
const secretKey = /api[-_.]?key|secret|pass(?:word|wd)?|token|credential|auth(?:orization)?|cookie|signature|private[-_.]?key|^(?:sig|key|pwd|user|u)$/i;
|
|
3
|
+
const token = /(?:\b(?:Bearer|Basic)\s+|\bsk-[\w-]{8,}|\bgh[pousr]_|-----BEGIN .*PRIVATE KEY)/i;
|
|
4
|
+
const reference = /^\$\{credential:([A-Za-z_][A-Za-z_0-9]*)\}$/;
|
|
5
|
+
const flag = /^(--?[A-Za-z][\w.-]*=)([\s\S]*)$/;
|
|
6
|
+
const envAssignment = /^([A-Za-z_][\w]*=)([\s\S]*)$/;
|
|
7
|
+
const header = /^([A-Za-z][A-Za-z0-9-]*:[ \t]*)([\s\S]*)$/;
|
|
8
|
+
const headerFlag = /^(?:-H|--header|--headers)$/i;
|
|
9
|
+
const urlStart = /^[A-Za-z][\w+.-]*:\/\//;
|
|
10
|
+
const unsupported = () => { throw new Error('MCP 传输字段含无法安全移植的脚本、参数或地址'); };
|
|
11
|
+
const optionName = (key) => key.replace(/^-+|=$/g,'');
|
|
12
|
+
|
|
13
|
+
function checkUrl(value) {
|
|
14
|
+
let url;
|
|
15
|
+
try { url = new URL(value); } catch { unsupported(); }
|
|
16
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash ||
|
|
17
|
+
/\$\{|[\s\\]/.test(value)) unsupported();
|
|
18
|
+
// 签名查询、回调和各类私有连接串无法在不暴露凭据的同时向用户展示真实目的地。
|
|
19
|
+
if ([...url.searchParams].some(([k,v]) => !(
|
|
20
|
+
/^(?:v|version|page|limit|offset)$/i.test(k) && /^[\d.]{1,16}$/.test(v) ||
|
|
21
|
+
/^(?:lang|locale|format)$/i.test(k) && /^[a-z]{2,8}(?:[-_][a-z]{2,8})?$/i.test(v)
|
|
22
|
+
))) unsupported();
|
|
23
|
+
let path;
|
|
24
|
+
try { path = decodeURIComponent(url.pathname); } catch { unsupported(); }
|
|
25
|
+
if (token.test(path) || /\b(?:hooks?|webhooks?|services)\/.{12,}|[\w-]{28,}/i.test(path)) unsupported();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function shellSnippet(command, args) {
|
|
29
|
+
const words = [command,...args];
|
|
30
|
+
for (let i = 0; i < words.length; i++) {
|
|
31
|
+
if (typeof words[i] !== 'string') continue;
|
|
32
|
+
const executable = words[i].split(/[\\/]/).at(-1).toLowerCase().replace(/\.(?:exe|cmd|bat)$/, '');
|
|
33
|
+
const rest = words.slice(i+1).filter(s => typeof s === 'string');
|
|
34
|
+
if (/^(?:sh|bash|dash|zsh|ksh|fish|ash|cmd|pwsh|powershell)$/.test(executable) &&
|
|
35
|
+
rest.some(s => /^(?:-[a-z]*c[a-z]*|\/[ck]|-command(?:withargs)?|-e(?:nc(?:oded(?:command|arguments))?)?)$/i.test(s))) return true;
|
|
36
|
+
if (/^(?:node|deno|bun|python[\d.]*|ruby|perl|php)$/.test(executable) &&
|
|
37
|
+
rest.some(s => /^(?:-[cep]|--eval(?:=|$)|--print(?:=|$)|eval$)/i.test(s))) return true;
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function readPrefix(prefix) {
|
|
43
|
+
let rest = prefix;
|
|
44
|
+
const assigned = (flag.exec(rest) || envAssignment.exec(rest));
|
|
45
|
+
if (assigned) {
|
|
46
|
+
if (!secretKey.test(optionName(assigned[1])) && !headerFlag.test(assigned[1].slice(0,-1))) return false;
|
|
47
|
+
rest = assigned[2];
|
|
48
|
+
} else if (rest.startsWith('-H')) rest = rest.slice(2);
|
|
49
|
+
const pair = header.exec(rest);
|
|
50
|
+
if (pair) rest = pair[2];
|
|
51
|
+
return rest === '' || /^(Bearer|Basic) $/i.test(rest);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function validMcpArgumentPrefix(prefix) {
|
|
55
|
+
return typeof prefix === 'string' && prefix.length <= 160 && !/[\r\n]/.test(prefix) && readPrefix(prefix);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function maskArg(arg, previous, ref, refs, archived) {
|
|
59
|
+
if (archived && arg && typeof arg === 'object' && !Array.isArray(arg) && arg.$credential) {
|
|
60
|
+
if (arg.prefix !== undefined && !validMcpArgumentPrefix(arg.prefix)) unsupported();
|
|
61
|
+
return arg;
|
|
62
|
+
}
|
|
63
|
+
if (typeof arg !== 'string' || /[\0\r\n]/.test(arg)) unsupported();
|
|
64
|
+
const inline = flag.exec(arg) || envAssignment.exec(arg);
|
|
65
|
+
const attachedHeader = !inline && /^-H[A-Za-z][A-Za-z0-9-]*:/.test(arg);
|
|
66
|
+
let prefix = inline?.[1] || (attachedHeader ? '-H' : '');
|
|
67
|
+
let value = inline?.[2] ?? (attachedHeader ? arg.slice(2) : arg);
|
|
68
|
+
const takesSecret = name => name.startsWith('-') && !name.includes('=') && secretKey.test(optionName(name));
|
|
69
|
+
const previousName = typeof previous === 'string' ? previous : '';
|
|
70
|
+
const isHeader = attachedHeader || headerFlag.test(inline ? inline[1].slice(0,-1) : previousName);
|
|
71
|
+
const pair = header.exec(value);
|
|
72
|
+
let hide = !!inline && secretKey.test(optionName(inline[1])) || !inline && takesSecret(previousName);
|
|
73
|
+
if (isHeader || pair && secretKey.test(pair[1].split(':')[0])) {
|
|
74
|
+
if (!pair) unsupported();
|
|
75
|
+
prefix += pair[1];
|
|
76
|
+
value = pair[2];
|
|
77
|
+
hide = true;
|
|
78
|
+
}
|
|
79
|
+
if (urlStart.test(value)) checkUrl(value);
|
|
80
|
+
if (/^(?:Bearer|Basic)\s/i.test(value)) {
|
|
81
|
+
const scheme = /^(?:Bearer|Basic) /i.exec(value);
|
|
82
|
+
if (!scheme) unsupported();
|
|
83
|
+
prefix += scheme[0];
|
|
84
|
+
value = value.slice(scheme[0].length);
|
|
85
|
+
hide = true;
|
|
86
|
+
}
|
|
87
|
+
const native = reference.exec(value);
|
|
88
|
+
if (hide || native || token.test(value)) {
|
|
89
|
+
if (archived || !validMcpArgumentPrefix(prefix)) unsupported();
|
|
90
|
+
const key = native?.[1] || ref;
|
|
91
|
+
refs.add(key);
|
|
92
|
+
return prefix ? {$credential:key,prefix} : {$credential:key};
|
|
93
|
+
}
|
|
94
|
+
if (/\$\{|[;&|]\s*(?:\w|\$)|(?:https?|ssh|postgres(?:ql)?):\/\//i.test(value) && !urlStart.test(value) ||
|
|
95
|
+
/(?:^|\s)--?[\w.-]*(?:key|pass|token|secret|auth|cookie)[\w.-]*(?:=|\s)/i.test(value)) unsupported();
|
|
96
|
+
return arg;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function portableMcpTransport(config, id, refs, archived = false) {
|
|
100
|
+
if (!config || Array.isArray(config) || typeof config !== 'object') unsupported();
|
|
101
|
+
const result = {...config};
|
|
102
|
+
if (config.oauth !== undefined && (config.transport !== 'streamable-http' ||
|
|
103
|
+
!/^mcp-client\/[a-z][a-z0-9-]*$/.test(config.oauth?.credentialKey))) unsupported();
|
|
104
|
+
if (config.enabled !== undefined && typeof config.enabled !== 'boolean') unsupported();
|
|
105
|
+
if (config.url !== undefined) {
|
|
106
|
+
if (typeof config.url !== 'string') unsupported();
|
|
107
|
+
checkUrl(config.url);
|
|
108
|
+
}
|
|
109
|
+
if (config.command !== undefined && (typeof config.command !== 'string' ||
|
|
110
|
+
/[;&|\r\n]|\$\{|\s--?[\w-]+(?:\s|=|$)/.test(config.command))) unsupported();
|
|
111
|
+
if (config.args !== undefined) {
|
|
112
|
+
if (!Array.isArray(config.args) || shellSnippet(config.command || '',config.args)) unsupported();
|
|
113
|
+
result.args = config.args.map((arg,index) => maskArg(arg,config.args[index-1],id+'_ARG_'+index,refs,archived));
|
|
114
|
+
}
|
|
115
|
+
return result;
|
|
116
|
+
}
|
package/src/core/pack.js
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import { collectPluginMetadata, validatePluginAssets } from './plugin-metadata.js';
|
|
2
|
+
import { collectExtensions, validateExtensions } from './extensions.js';
|
|
3
|
+
import { scanProfile, selectFiles } from './scan.js';
|
|
4
|
+
import { buildManifest, buildHomeManifest, validateManifest } from './manifest.js';
|
|
5
|
+
import { buildDspack, encodeText, dspackMarker, DSPACK_CONTAINER_VERSION } from './dspack.js';
|
|
6
|
+
import { collectVendoredForExport, listProfileDependencies, expandVendorSelection } from './vendored.js';
|
|
7
|
+
|
|
8
|
+
// 常规快照中的机器文件写入根目录,用户文件写入 overrides/。
|
|
9
|
+
const ROOT_MACHINE = new Set(['package.json', 'pnpm-workspace.yaml', 'pnpm-lock.yaml']);
|
|
10
|
+
|
|
11
|
+
// 体积阈值(publishing v1 §8 体积礼仪):>500 MB 警告;>2 GiB 拒绝(GitHub Release 单资产上限)。
|
|
12
|
+
const SIZE_WARN_BYTES = 500 * 1024 * 1024;
|
|
13
|
+
const SIZE_MAX_BYTES = 2 * 1024 * 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
function fmtBytes(n) {
|
|
16
|
+
if (n >= 1024 * 1024 * 1024) return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GiB`;
|
|
17
|
+
if (n >= 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
|
18
|
+
return `${(n / 1024).toFixed(0)} KB`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 归档体积阈值检查:超上限抛错拒绝打包;超警告线记日志(opts.sizeLimits 可覆盖,测试用)。 */
|
|
22
|
+
function checkPackSize(entries, opts, log) {
|
|
23
|
+
const limits = opts.sizeLimits ?? { warn: SIZE_WARN_BYTES, max: SIZE_MAX_BYTES };
|
|
24
|
+
const total = Object.values(entries).reduce((s, b) => s + (b?.length ?? 0), 0);
|
|
25
|
+
if (limits.max > 0 && total > limits.max) {
|
|
26
|
+
throw new Error(`整合包体积 ${fmtBytes(total)} 超过上限 ${fmtBytes(limits.max)}(GitHub Release 单资产上限 2 GiB,见 publishing v1 §8)。请改用 files[] 指针制或减小 vendored 覆盖范围`);
|
|
27
|
+
}
|
|
28
|
+
if (limits.warn > 0 && total > limits.warn) {
|
|
29
|
+
log(`警告:整合包体积 ${fmtBytes(total)} 超过 ${fmtBytes(limits.warn)}——建议优先 files[] 指针制(重内容按需下载),仅在确需离线时全量 vendoring(publishing v1 §8)`);
|
|
30
|
+
}
|
|
31
|
+
return total;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* v5 r2:按 vendor 档位 + UI 手动勾选内嵌 vendor/ + 改写 manifest。
|
|
36
|
+
* 档位(workspace-config v1 r2):`'off'` 禁用;`'auto'`(默认)= 手动 ∪ round-trip(不联网探测);
|
|
37
|
+
* `'full'` = 手动 ∪ 全部直接依赖 ∪ 传递闭包(沿 lockText 的 pnpm-lock.yaml 收齐,离线包形态)。
|
|
38
|
+
*/
|
|
39
|
+
async function applyVendorSelection(host, manifest, lookupDirs, opts, progress, lockText = null) {
|
|
40
|
+
if (opts.vendor === 'off') return null;
|
|
41
|
+
const log = (s) => { if (typeof opts.onOutput === 'function') opts.onOutput(String(s) + '\n'); };
|
|
42
|
+
const manual = opts.vendorCoords && typeof opts.vendorCoords === 'object' ? opts.vendorCoords : {};
|
|
43
|
+
const { selection, probed } = await expandVendorSelection(host, lookupDirs, manual, opts.vendor, {
|
|
44
|
+
registry: opts.registry,
|
|
45
|
+
log,
|
|
46
|
+
});
|
|
47
|
+
if (!Object.keys(selection).length && opts.vendor !== 'full') return null;
|
|
48
|
+
if (probed.length) log(`自动补选内嵌:${probed.join(', ')}`);
|
|
49
|
+
progress('vendor', `内嵌 ${Object.keys(selection).length} 个 vendored 依赖(档位 ${opts.vendor ?? 'auto'})`);
|
|
50
|
+
const vr = await collectVendoredForExport(host, lookupDirs, manifest.dependencies ?? {}, selection, {
|
|
51
|
+
registry: opts.registry,
|
|
52
|
+
log,
|
|
53
|
+
pluginSources: manifest.plugins,
|
|
54
|
+
profileUnits: Object.values(manifest.profiles ?? {}),
|
|
55
|
+
closure: opts.vendor === 'full',
|
|
56
|
+
lockText,
|
|
57
|
+
});
|
|
58
|
+
manifest.dependencies = vr.dependencies;
|
|
59
|
+
manifest.vendored = vr.vendored;
|
|
60
|
+
for (const note of vr.notes) log(`注意:${note}`);
|
|
61
|
+
progress('vendor', `vendored 完成:${Object.keys(vr.vendored).length} 个 tarball 已内嵌`);
|
|
62
|
+
return vr;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 打包前强校验(含 v5 r2 字段:dshVersions ∋ dshVersion、launchers 结构等)——错误在导出时报出,不带病出厂。
|
|
66
|
+
* lockText(随包 pnpm-lock.yaml)供 vendored 闭包条目对账放行(§12 约束 1)。 */
|
|
67
|
+
function assertManifestValid(manifest, lockText = null) {
|
|
68
|
+
const errors = validateManifest(manifest, { lockText });
|
|
69
|
+
if (errors.length) {
|
|
70
|
+
throw new Error(`导出的 manifest 不合法(${errors.join(';')})——请检查「兼容性」等表单项后重试`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 确定配置档所属 DSH_HOME,独立目录须由调用方提供位置。 */
|
|
75
|
+
export function profileHome(host, profile, explicit) {
|
|
76
|
+
if (explicit) return host.resolvePath(explicit);
|
|
77
|
+
const parent = host.joinPath(profile.dir, '..');
|
|
78
|
+
return host.basename(parent).toLowerCase() === 'profiles' ? host.joinPath(parent, '..') : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 在公开清单中预览已选择的资源,仅保留展示字段。 */
|
|
82
|
+
function summarizeResources(manifest, extensions) {
|
|
83
|
+
const groups = {
|
|
84
|
+
'path.json': Object.values(extensions.paths.plugins).flat(),
|
|
85
|
+
'provider.json': extensions.providers.items,
|
|
86
|
+
'mcp.json': extensions.mcp.items,
|
|
87
|
+
'skill.json': extensions.skills.items,
|
|
88
|
+
};
|
|
89
|
+
for (const [file, rows] of Object.entries(groups)) {
|
|
90
|
+
if (!rows.length) continue;
|
|
91
|
+
manifest.resources ??= {};
|
|
92
|
+
const fields = ['id', 'scope', 'name', 'desc', 'plugin', 'ref', 'commit'];
|
|
93
|
+
manifest.resources[file] = rows.map((row) => Object.fromEntries(
|
|
94
|
+
fields.filter((key) => row[key] !== undefined).map((key) => [key, row[key]]),
|
|
95
|
+
));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 将扫描到的文件映射为归档条目。 */
|
|
100
|
+
export function dspackEntryPath(rel) {
|
|
101
|
+
const r = String(rel).replace(/\\/g, '/');
|
|
102
|
+
return ROOT_MACHINE.has(r) ? r : `overrides/${r}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 一键导出(单 profile):扫描 Profile → 生成 manifest v6 → 打包 .dspack(dspack.json version 4)。
|
|
107
|
+
* 全程只读用户 Profile 目录,在内存中拼 ZIP 后一次写盘,不落暂存清单。
|
|
108
|
+
*
|
|
109
|
+
* @param {Host} host
|
|
110
|
+
* @param {{name: string, dir: string}} profile
|
|
111
|
+
* @param {object} opts 见 buildManifest + { out, force }
|
|
112
|
+
* @returns {Promise<{manifest, output, sha256, size, included, excluded}>}
|
|
113
|
+
*/
|
|
114
|
+
export async function prepareProfileArchive(host, profile, opts = {}) {
|
|
115
|
+
const progress = (stage, detail) => {
|
|
116
|
+
if (typeof opts.onProgress === 'function') opts.onProgress(stage, detail);
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
progress('scan', `扫描 Profile「${profile.name}」`);
|
|
120
|
+
const scan = await scanProfile(host, profile.dir);
|
|
121
|
+
if (scan.files.length === 0) {
|
|
122
|
+
throw new Error(`Profile「${profile.name}」没有可打包的文件(全部被过滤或目录为空)`);
|
|
123
|
+
}
|
|
124
|
+
// opts.include(rel 白名单)指定要包含的文件;未给则全量。
|
|
125
|
+
const files = selectFiles(scan.files, opts.include);
|
|
126
|
+
if (files.length === 0) {
|
|
127
|
+
throw new Error(`没有选中的文件(请至少勾选一个文件/目录)`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
progress('manifest', '生成 manifest v6');
|
|
131
|
+
const manifest = await buildManifest(host, profile, opts, scan);
|
|
132
|
+
|
|
133
|
+
// home 级内容(上一级目录):用户勾选的全局 skill / 预设等,进 home/ 目录(安装落到 $DSH_HOME 根)。
|
|
134
|
+
const homeDir = profileHome(host, profile, opts.home);
|
|
135
|
+
const homeFiles = homeDir && opts.homeInclude?.length !== 0 && opts.homeInclude
|
|
136
|
+
? (await scanProfile(host, homeDir)).files.filter((f) => !f.rel.startsWith('profiles/')) : [];
|
|
137
|
+
const homeSet = opts.homeInclude instanceof Set ? opts.homeInclude : (opts.homeInclude ? new Set(opts.homeInclude) : null);
|
|
138
|
+
// 前缀匹配:允许 homeInclude 传 `skills/` 等目录前缀(精确名或目录前缀皆可命中)。
|
|
139
|
+
const selectedHome = homeSet
|
|
140
|
+
? homeFiles.filter((f) => [...homeSet].some((p) => f.rel === p || f.rel.startsWith(p)))
|
|
141
|
+
: [];
|
|
142
|
+
|
|
143
|
+
progress('collect', '读取文件内容');
|
|
144
|
+
const entries = {};
|
|
145
|
+
for (const f of files) {
|
|
146
|
+
const data = await host.readFile(f.abs);
|
|
147
|
+
if (!data) continue; // 读不到:跳过
|
|
148
|
+
entries[dspackEntryPath(f.rel)] = data;
|
|
149
|
+
}
|
|
150
|
+
for (const f of selectedHome) {
|
|
151
|
+
const data = await host.readFile(f.abs);
|
|
152
|
+
if (!data) continue;
|
|
153
|
+
entries[`home/${f.rel}`] = data;
|
|
154
|
+
}
|
|
155
|
+
await collectPluginMetadata(host, profile.dir, manifest, { plugins: opts.plugins, entries });
|
|
156
|
+
const extensions = await collectExtensions(host, { home: homeDir, profiles: [profile], manifest, entries, selection: opts.selection });
|
|
157
|
+
summarizeResources(manifest, extensions);
|
|
158
|
+
// v5 r2:手动勾选的依赖内嵌(UI 依赖清单)→ vendor/ 条目 + manifest.vendored + dependencies 三处一致
|
|
159
|
+
// full 档闭包收集以 profile 的 pnpm-lock.yaml 为准(与归档内快照同源)
|
|
160
|
+
const lockText = await host.readTextFile(host.joinPath(profile.dir, 'pnpm-lock.yaml'));
|
|
161
|
+
const vendorResult = await applyVendorSelection(host, manifest, [profile.dir], opts, progress, lockText);
|
|
162
|
+
if (vendorResult) Object.assign(entries, vendorResult.entries);
|
|
163
|
+
|
|
164
|
+
// 打包前强校验(r2 字段结构 / dshVersion ∈ dshVersions 等;闭包条目按 lockfile 放行)
|
|
165
|
+
assertManifestValid(manifest, lockText);
|
|
166
|
+
|
|
167
|
+
// manifest.json 始终在归档根(契约头,覆盖任何扫描残留);dspack.json 为容器标记。
|
|
168
|
+
validatePluginAssets(manifest, entries);
|
|
169
|
+
validateExtensions(manifest, entries);
|
|
170
|
+
entries['manifest.json'] = encodeText(JSON.stringify(manifest, null, 2) + '\n');
|
|
171
|
+
entries['dspack.json'] = encodeText(JSON.stringify(dspackMarker(DSPACK_CONTAINER_VERSION)) + '\n');
|
|
172
|
+
|
|
173
|
+
checkPackSize(entries, opts, (s) => { if (typeof opts.onOutput === 'function') opts.onOutput(s + '\n'); });
|
|
174
|
+
|
|
175
|
+
progress('pack', '打包 .dspack');
|
|
176
|
+
return { manifest, entries, scan, excluded: scan.excluded.length };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 导出与源仓库使用完全相同的归档内容。 */
|
|
180
|
+
export async function packProfile(host, profile, opts = {}) {
|
|
181
|
+
return writeProfileArchive(host, await prepareProfileArchive(host, profile, opts), opts);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export async function writeProfileArchive(host, { manifest, entries, excluded }, opts = {}) {
|
|
185
|
+
const bytes = buildDspack(entries);
|
|
186
|
+
const outDir = opts.out ? host.resolvePath(opts.out) : host.cwd();
|
|
187
|
+
const outPath = host.joinPath(outDir, `${manifest.name}-${manifest.version}.dspack`);
|
|
188
|
+
|
|
189
|
+
if ((await host.stat(outPath)) != null && !opts.force) {
|
|
190
|
+
throw new Error(`输出文件已存在:${outPath}(使用 --force 覆盖)`);
|
|
191
|
+
}
|
|
192
|
+
await host.mkdir(outDir);
|
|
193
|
+
opts.onProgress?.('write', `写盘 ${outPath}`);
|
|
194
|
+
await host.writeFile(outPath, bytes);
|
|
195
|
+
|
|
196
|
+
return {
|
|
197
|
+
manifest,
|
|
198
|
+
output: outPath,
|
|
199
|
+
sha256: await host.sha256(bytes),
|
|
200
|
+
size: bytes.length,
|
|
201
|
+
included: Object.keys(entries).length,
|
|
202
|
+
excluded,
|
|
203
|
+
vendored: Object.keys(manifest.vendored ?? {}),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* 一键导出(dshhome):扫描整个 $DSH_HOME → 识别四类单元 → 生成 manifest v6 → 打包 .dspack(dspack.json version 4)。
|
|
209
|
+
* overrides/ 按 home 相对路径平铺:profiles/、.agent-presets/、skills/、AGENTS.md、data/。
|
|
210
|
+
*
|
|
211
|
+
* @param {Host} host
|
|
212
|
+
* @param {{name: string, dir: string}} home home 根目录
|
|
213
|
+
* @param {object} opts { name, displayName, version, description, author, icon, dshVersion,
|
|
214
|
+
* defaultProfile, include, out, force }
|
|
215
|
+
* @returns {Promise<{manifest, output, sha256, size, included, excluded, summary}>}
|
|
216
|
+
*/
|
|
217
|
+
export async function packHome(host, home, opts = {}) {
|
|
218
|
+
const progress = (stage, detail) => {
|
|
219
|
+
if (typeof opts.onProgress === 'function') opts.onProgress(stage, detail);
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
progress('scan', `扫描 DSH_HOME「${home.name}」`);
|
|
223
|
+
const scan = await scanProfile(host, home.dir);
|
|
224
|
+
if (scan.files.length === 0) {
|
|
225
|
+
throw new Error(`DSH_HOME「${home.name}」没有可打包的文件(全部被过滤或目录为空)`);
|
|
226
|
+
}
|
|
227
|
+
let files = selectFiles(scan.files, opts.include);
|
|
228
|
+
// exclude:黑名单(rel 前缀),供「导出内容」开关排除 skill / preset / 指令 / 数据
|
|
229
|
+
const excludes = opts.exclude ?? [];
|
|
230
|
+
if (excludes.length) {
|
|
231
|
+
files = files.filter((f) => !excludes.some((p) => f.rel === p || f.rel.startsWith(p)));
|
|
232
|
+
}
|
|
233
|
+
if (files.length === 0) {
|
|
234
|
+
throw new Error(`没有选中的文件(请至少勾选一个文件/目录)`);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// 从扫描结果识别四类单元;web/headless(安装基线)不进包。
|
|
238
|
+
const summary = summarizeHome(files);
|
|
239
|
+
const profiles = [...summary.profiles.keys()]
|
|
240
|
+
.filter((name) => name !== 'web' && name !== 'headless')
|
|
241
|
+
.map((name) => ({ name, dir: host.joinPath(home.dir, 'profiles', name) }));
|
|
242
|
+
const presets = {};
|
|
243
|
+
for (const [id, path] of summary.presets) presets[id] = { path };
|
|
244
|
+
|
|
245
|
+
const manifest = await buildHomeManifest(host, home, {
|
|
246
|
+
name: opts.name,
|
|
247
|
+
displayName: opts.displayName,
|
|
248
|
+
version: opts.version,
|
|
249
|
+
description: opts.description,
|
|
250
|
+
author: opts.author,
|
|
251
|
+
icon: opts.icon,
|
|
252
|
+
dshVersion: opts.dshVersion,
|
|
253
|
+
defaultProfile: opts.defaultProfile,
|
|
254
|
+
profiles,
|
|
255
|
+
presets,
|
|
256
|
+
skills: summary.skills,
|
|
257
|
+
instructions: summary.instructions || 'AGENTS.md',
|
|
258
|
+
files: opts.files ?? [],
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
progress('collect', '读取文件内容');
|
|
262
|
+
const entries = {};
|
|
263
|
+
for (const f of files) {
|
|
264
|
+
const data = await host.readFile(f.abs);
|
|
265
|
+
if (!data) continue;
|
|
266
|
+
entries[dspackEntryPath(f.rel)] = data;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
for (const profile of profiles) {
|
|
270
|
+
await collectPluginMetadata(host, profile.dir, manifest.profiles[profile.name], {
|
|
271
|
+
plugins: opts.profilePlugins?.[profile.name], entries,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
const extensions = await collectExtensions(host, { home: home.dir, profiles, manifest, entries, selection: opts.selection });
|
|
275
|
+
summarizeResources(manifest, extensions);
|
|
276
|
+
// v5 r2:vendor 档位 + 手动勾选内嵌(vendor/ 是包级目录;依赖在各 profile 的 node_modules 里查找)。
|
|
277
|
+
// 收集时按「坐标 → 版本」聚合,再回写每个 ProfileUnit(file:vendor-blobs 旧 key 一并替换)。
|
|
278
|
+
// full 档闭包收集以 home 根的 pnpm-lock.yaml 为准(与归档内快照同源)。
|
|
279
|
+
const lookupDirs = profiles.map((p) => p.dir);
|
|
280
|
+
const lockText = await host.readTextFile(host.joinPath(home.dir, 'pnpm-lock.yaml'));
|
|
281
|
+
const vendorResult = await applyVendorSelection(host, manifest, lookupDirs, opts, progress, lockText);
|
|
282
|
+
if (vendorResult) {
|
|
283
|
+
Object.assign(entries, vendorResult.entries);
|
|
284
|
+
for (const [name, unit] of Object.entries(manifest.profiles)) {
|
|
285
|
+
const dir = host.joinPath(home.dir, 'profiles', name);
|
|
286
|
+
const localList = await listProfileDependencies(host, [dir]);
|
|
287
|
+
const deps = { ...(unit.dependencies ?? {}) };
|
|
288
|
+
for (const item of localList) {
|
|
289
|
+
if (!Object.hasOwn(manifest.vendored ?? {}, item.coord)) continue;
|
|
290
|
+
delete deps[item.pkgName];
|
|
291
|
+
delete deps[item.coord];
|
|
292
|
+
deps[item.coord] = manifest.dependencies[item.coord];
|
|
293
|
+
}
|
|
294
|
+
unit.dependencies = deps;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// 打包前强校验(r2 字段结构 / dshVersion ∈ dshVersions 等;闭包条目按 lockfile 放行)
|
|
299
|
+
assertManifestValid(manifest, lockText);
|
|
300
|
+
|
|
301
|
+
validatePluginAssets(manifest, entries);
|
|
302
|
+
validateExtensions(manifest, entries);
|
|
303
|
+
entries['manifest.json'] = encodeText(JSON.stringify(manifest, null, 2) + '\n');
|
|
304
|
+
entries['dspack.json'] = encodeText(JSON.stringify(dspackMarker(DSPACK_CONTAINER_VERSION)) + '\n');
|
|
305
|
+
|
|
306
|
+
checkPackSize(entries, opts, (s) => { if (typeof opts.onOutput === 'function') opts.onOutput(s + '\n'); });
|
|
307
|
+
|
|
308
|
+
progress('pack', '打包 .dspack');
|
|
309
|
+
const bytes = buildDspack(entries);
|
|
310
|
+
const outDir = opts.out ? host.resolvePath(opts.out) : host.cwd();
|
|
311
|
+
const outPath = host.joinPath(outDir, `${manifest.name}-${manifest.version}.dspack`);
|
|
312
|
+
|
|
313
|
+
if ((await host.stat(outPath)) != null && !opts.force) {
|
|
314
|
+
throw new Error(`输出文件已存在:${outPath}(使用 --force 覆盖)`);
|
|
315
|
+
}
|
|
316
|
+
await host.mkdir(outDir);
|
|
317
|
+
progress('write', `写盘 ${outPath}`);
|
|
318
|
+
await host.writeFile(outPath, bytes);
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
manifest,
|
|
322
|
+
output: outPath,
|
|
323
|
+
sha256: await host.sha256(bytes),
|
|
324
|
+
size: bytes.length,
|
|
325
|
+
included: Object.keys(entries).length,
|
|
326
|
+
excluded: scan.excluded.length,
|
|
327
|
+
summary,
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* 从扫描文件识别 dshhome 四类单元(相对 $DSH_HOME 根):
|
|
333
|
+
* - profiles:profiles/<name>/package.json
|
|
334
|
+
* - presets:.agent-presets/<id>/agent.cordis.yml
|
|
335
|
+
* - skills:skills/<name>.md(平铺)或 skills/<name>/SKILL.md(目录 bundle)
|
|
336
|
+
* - instructions:根 AGENTS.md
|
|
337
|
+
*/
|
|
338
|
+
export function summarizeHome(files) {
|
|
339
|
+
const profiles = new Map();
|
|
340
|
+
const presets = new Map();
|
|
341
|
+
const skills = [];
|
|
342
|
+
const skillNames = new Set();
|
|
343
|
+
let instructions = null;
|
|
344
|
+
|
|
345
|
+
for (const f of files ?? []) {
|
|
346
|
+
const rel = String(f.rel || '').replace(/\\/g, '/');
|
|
347
|
+
if (!rel) continue;
|
|
348
|
+
const seg = rel.split('/');
|
|
349
|
+
|
|
350
|
+
if (seg[0] === 'profiles' && seg.length >= 3 && seg[2] === 'package.json') {
|
|
351
|
+
profiles.set(seg[1], true);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
if (seg[0] === '.agent-presets' && seg.length >= 3 && seg[2] === 'agent.cordis.yml') {
|
|
355
|
+
presets.set(seg[1], `.agent-presets/${seg[1]}`);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (seg[0] === 'skills') {
|
|
359
|
+
if (seg.length === 2 && seg[1].endsWith('.md')) {
|
|
360
|
+
const name = seg[1].slice(0, -3);
|
|
361
|
+
if (!skillNames.has(name)) { skillNames.add(name); skills.push({ path: `skills/${name}` }); }
|
|
362
|
+
} else if (seg.length >= 3 && seg[2] === 'SKILL.md') {
|
|
363
|
+
if (!skillNames.has(seg[1])) { skillNames.add(seg[1]); skills.push({ path: `skills/${seg[1]}` }); }
|
|
364
|
+
}
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (rel === 'AGENTS.md') instructions = 'AGENTS.md';
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
return { profiles, presets, skills, instructions };
|
|
371
|
+
}
|