mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 05:20:22 +08:00
feat: 发布 1.1.11-beta.1,Skill 导入官方目录并加正式/测试通道
设置页可导入压缩包或文件夹到官方 skills;导入约束路径与符号链接,保存保留官方 frontmatter。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
d30f3a76e9
commit
cff7ebcbb5
8 files changed
+1628
-86
No files matched your search
+43
-4
@@ -1318,7 +1318,37 @@ export function normPath(p) {
|
||||
|
||||
export function isDshHomeDir(dir) {
|
||||
if (!dir || !isDir(dir)) return false;
|
||||
return path.basename(path.normalize(dir)) === ".dsh";
|
||||
const base = path.basename(path.normalize(dir)).toLowerCase();
|
||||
return base === ".dsh" || base === "dsh-home";
|
||||
}
|
||||
|
||||
function desktopHomeCandidates() {
|
||||
const out = [];
|
||||
const push = (dir) => {
|
||||
if (!dir) return;
|
||||
const root = path.normalize(dir);
|
||||
out.push(root);
|
||||
out.push(path.join(root, ".dsh"));
|
||||
out.push(path.join(root, "dsh-home"));
|
||||
};
|
||||
try {
|
||||
const exe = desktop.findDesktopAppExecutable();
|
||||
if (exe) push(path.dirname(exe));
|
||||
} catch { /* ignore */ }
|
||||
try {
|
||||
if (process.resourcesPath) push(path.dirname(path.normalize(process.resourcesPath)));
|
||||
} catch { /* ignore */ }
|
||||
try {
|
||||
for (const root of desktop.listDesktopInstallRoots()) push(root);
|
||||
} catch { /* ignore */ }
|
||||
for (const guess of desktopDshHomeGuesses()) out.push(guess);
|
||||
const seen = new Set();
|
||||
return out.filter((item) => {
|
||||
const key = path.normalize(item).replace(/\\/g, "/").toLowerCase();
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
export function portableHomeFromLauncher(shimDir, prefix) {
|
||||
@@ -1350,15 +1380,24 @@ function desktopDshHomeGuesses() {
|
||||
];
|
||||
}
|
||||
|
||||
// DSH_HOME → 启动器旁 .dsh → ~/.dsh
|
||||
// DSH_HOME → 桌面进程旁 .dsh/dsh-home → 启动器旁 .dsh → ~/.dsh
|
||||
// 不写死盘符;桌面端不借用 Web 启动器旁的主目录。
|
||||
export function findDshHome(options = {}) {
|
||||
const env = options.env ?? process.env;
|
||||
const fromEnv = env.DSH_HOME;
|
||||
if (fromEnv && String(fromEnv).trim()) return path.normalize(fromEnv.trim());
|
||||
const desktopHost = adapterFor(detectSurface(options)) === "desktop";
|
||||
if (desktopHost) {
|
||||
for (const cand of desktopHomeCandidates()) {
|
||||
if (isDshHomeDir(cand)) return path.normalize(cand);
|
||||
}
|
||||
}
|
||||
const shimDir = options.shimDir !== undefined ? options.shimDir : findShimDir();
|
||||
const prefix = options.prefix !== undefined ? options.prefix : findNpmPrefix();
|
||||
const portable = portableHomeFromLauncher(shimDir, prefix);
|
||||
if (portable) return portable;
|
||||
if (!desktopHost) {
|
||||
const portable = portableHomeFromLauncher(shimDir, prefix);
|
||||
if (portable) return portable;
|
||||
}
|
||||
const unix = path.join(os.homedir(), ".dsh");
|
||||
if (isDir(unix)) return unix;
|
||||
const wslWin = findWslWindowsDshHome(env);
|
||||
|
||||
+200
-7
@@ -3,6 +3,7 @@ import { promises as fsp } from "node:fs";
|
||||
import * as core from "./core.js";
|
||||
import * as hostctl from "./host.js";
|
||||
import * as rules from "./rules.js";
|
||||
import * as skills from "./skills.js";
|
||||
import * as updater from "./update.js";
|
||||
import {
|
||||
GLOBAL_PROMPT_ORDER,
|
||||
@@ -397,7 +398,8 @@ async function handlePurgeCommand(rawInput, config) {
|
||||
" /purge uninstall 卸载插件(已应用则先还原)\n" +
|
||||
" /purge edit 编辑注入文件 prompt-inject.md\n" +
|
||||
" /purge help 显示帮助\n" +
|
||||
"规则集切换见 /rules(list | use <id> | create | delete | reset)",
|
||||
"规则集切换见 /rules(list | use <id> | create | delete | reset)\n" +
|
||||
"官方 Skill 安装见 /skills(list | import <路径> | create <id> [说明] | delete <id>)",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -511,6 +513,97 @@ async function handleRulesCommand(rawInput) {
|
||||
}
|
||||
}
|
||||
|
||||
function renderSkillsStatus(st) {
|
||||
const out = [];
|
||||
out.push("官方用户 Skill / $DSH_HOME/skills");
|
||||
out.push(` ${st.skills_dir}`);
|
||||
out.push(" 命中与加载由官方 skill 工具负责;插件只安装和删除目录。");
|
||||
out.push("");
|
||||
if (!st.skills.length) {
|
||||
out.push(" (暂无用户 Skill — 用 /skills import <压缩包或文件夹> 或设置页导入)");
|
||||
return out.join("\n");
|
||||
}
|
||||
for (const item of st.skills) {
|
||||
const mark = item.valid ? "·" : "!";
|
||||
const desc = item.description || "(无说明)";
|
||||
out.push(` ${mark} ${item.id} ${desc} (${skills.formatSize(item.size)})`);
|
||||
if (!item.valid && item.error) out.push(` ${item.error}`);
|
||||
}
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
async function handleSkillsCommand(rawInput) {
|
||||
const args = (rawInput || "").trim().split(/\s+/).filter(Boolean);
|
||||
const sub = (args[0] || "list").toLowerCase();
|
||||
const dshHome = core.findDshHome();
|
||||
|
||||
switch (sub) {
|
||||
case "list":
|
||||
case "ls":
|
||||
case "s":
|
||||
return { kind: "success", text: renderSkillsStatus(await skills.skillsStatus(dshHome)) };
|
||||
case "create":
|
||||
case "new":
|
||||
case "c": {
|
||||
const id = args[1];
|
||||
if (!id) return { kind: "error", text: "用法: /skills create <id> [说明]" };
|
||||
if (!skills.validSkillName(id)) {
|
||||
return { kind: "error", text: "id 必须是 kebab-case,例如 code-review" };
|
||||
}
|
||||
const description = args.slice(2).join(" ").trim() || id;
|
||||
try {
|
||||
const saved = skills.toPublicSkill(dshHome, await skills.saveSkill(dshHome, id, "", description));
|
||||
return {
|
||||
kind: "success",
|
||||
text: `✓ 已写入官方目录 ${saved.path}\n新会话会进官方 Skill 目录;任务对上或输入 /${id} 时由官方加载。`,
|
||||
};
|
||||
} catch (e) {
|
||||
return { kind: "error", text: `安装失败: ${e.message}` };
|
||||
}
|
||||
}
|
||||
case "import":
|
||||
case "i": {
|
||||
const src = args.slice(1).join(" ").trim();
|
||||
if (!src) return { kind: "error", text: "用法: /skills import <压缩包或文件夹>" };
|
||||
try {
|
||||
const packed = await skills.importFromPath(dshHome, src);
|
||||
const names = packed.imported.map((item) => item.id).join(", ");
|
||||
return { kind: "success", text: `✓ 已导入到官方 $DSH_HOME/skills:${names}` };
|
||||
} catch (e) {
|
||||
return { kind: "error", text: `导入失败: ${e.message}` };
|
||||
}
|
||||
}
|
||||
case "delete":
|
||||
case "rm":
|
||||
case "d": {
|
||||
const id = args[1];
|
||||
if (!id) return { kind: "error", text: "用法: /skills delete <id>" };
|
||||
try {
|
||||
const removed = skills.toPublicSkill(dshHome, await skills.deleteSkill(dshHome, id));
|
||||
return {
|
||||
kind: "success",
|
||||
text: `✓ 已从官方目录删除 ${id}${removed.backup ? `\n备份:${removed.backup}` : ""}`,
|
||||
};
|
||||
} catch (e) {
|
||||
return { kind: "error", text: `删除失败: ${e.message}` };
|
||||
}
|
||||
}
|
||||
case "help":
|
||||
case "h":
|
||||
default:
|
||||
return {
|
||||
kind: "success",
|
||||
text: "官方 Skill 安装:\n" +
|
||||
" /skills list 列出 $DSH_HOME/skills\n" +
|
||||
" /skills create <id> [说明] 写入 <id>/SKILL.md\n" +
|
||||
" /skills import <路径> 导入压缩包或文件夹到官方目录\n" +
|
||||
" /skills delete <id> 删除该目录(官方会从目录拿掉)\n" +
|
||||
" 也可自己删 $DSH_HOME/skills/<id>\n" +
|
||||
" 不注入 systemPrompt,不替代提示词",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function apply(ctx, config) {
|
||||
const cfg = { ...DEFAULTS, ...(config || {}) };
|
||||
if (!cfg.enabled) return;
|
||||
@@ -572,6 +665,12 @@ export function apply(ctx, config) {
|
||||
input: { hint: "list | use <id> | create <id> [别名] [目标] | delete <id> | reset | help" },
|
||||
handler: async (invocation) => handleRulesCommand(invocation.rawInput ?? ""),
|
||||
});
|
||||
commands.register({
|
||||
name: "skills",
|
||||
description: "官方用户 Skill($DSH_HOME/skills):list | import <路径> | create <id> [说明] | delete <id> | help",
|
||||
input: { hint: "list | import <路径> | create <id> [说明] | delete <id> | help" },
|
||||
handler: async (invocation) => handleSkillsCommand(invocation.rawInput ?? ""),
|
||||
});
|
||||
commands.register({
|
||||
name: "rewind",
|
||||
description: "回退:子代理直接回退一次;主代理 /rewind once 或 /rewind round",
|
||||
@@ -744,6 +843,8 @@ function installWebServer(ctx, cfg) {
|
||||
dsh_home: state.dsh_home,
|
||||
plugin_version: updater.localVersion(),
|
||||
update: updater.lastUpdateResult(),
|
||||
...updater.channelPublic(),
|
||||
...(await skills.skillsStatus(core.findDshHome()).catch(() => ({ skills: [] }))),
|
||||
});
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
@@ -908,10 +1009,7 @@ function installWebServer(ctx, cfg) {
|
||||
if (request.method === "POST") {
|
||||
try {
|
||||
const body = await readJsonBody(request);
|
||||
const result = body && body.auto
|
||||
? await updater.autoUpdateIfNeeded()
|
||||
: await updater.applyUpdate();
|
||||
sendJson(response, 200, result);
|
||||
sendJson(response, 200, await updater.handleUpdateOp(body || {}));
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e) });
|
||||
}
|
||||
@@ -1082,6 +1180,7 @@ function installWebServer(ctx, cfg) {
|
||||
},
|
||||
}, "dsh-purge: override");
|
||||
installRulesHttp(host.webServer);
|
||||
installSkillsHttp(host.webServer);
|
||||
host.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/restart",
|
||||
@@ -1186,6 +1285,99 @@ function rulesHttpHandler(forcedOp) {
|
||||
};
|
||||
}
|
||||
|
||||
async function handleSkillsOp(op, body, queryId) {
|
||||
const dshHome = core.findDshHome();
|
||||
const id = typeof body?.id === "string" ? body.id : String(queryId || "");
|
||||
if (op === "status") {
|
||||
return { ok: true, ...(await skills.skillsStatus(dshHome)) };
|
||||
}
|
||||
if (op === "read") {
|
||||
if (!skills.validSkillName(id)) return { status: 400, ok: false, error: "invalid skill name" };
|
||||
const item = await skills.readSkill(dshHome, id);
|
||||
if (!item) return { status: 404, ok: false, error: `skill not found: ${id}` };
|
||||
return { ok: true, ...skills.toPublicSkill(dshHome, item) };
|
||||
}
|
||||
if (op === "save") {
|
||||
if (!skills.validSkillName(id)) return { status: 400, ok: false, error: "id 必须是 kebab-case,例如 code-review" };
|
||||
const content = typeof body?.content === "string" ? body.content : "";
|
||||
const description = typeof body?.description === "string" ? body.description : "";
|
||||
const saved = await skills.saveSkill(dshHome, id, content, description);
|
||||
return { ok: true, ...skills.toPublicSkill(dshHome, saved) };
|
||||
}
|
||||
if (op === "delete") {
|
||||
if (!skills.validSkillName(id)) return { status: 400, ok: false, error: "invalid skill name" };
|
||||
const removed = await skills.deleteSkill(dshHome, id);
|
||||
return { ok: true, ...skills.toPublicSkill(dshHome, removed) };
|
||||
}
|
||||
if (op === "import") {
|
||||
if (body?.path || body?.source || body?.folder) {
|
||||
return { status: 400, ok: false, error: "请在本机选择压缩包或文件夹导入" };
|
||||
}
|
||||
if (typeof body?.data === "string" && body.data.trim()) {
|
||||
const packed = await skills.importArchive(dshHome, Buffer.from(body.data, "base64"), body.name || "skill.zip");
|
||||
return { ok: true, ...packed };
|
||||
}
|
||||
if (Array.isArray(body?.files) && body.files.length) {
|
||||
const packed = await skills.importFileTree(dshHome, body.files, body.name || "");
|
||||
return { ok: true, ...packed };
|
||||
}
|
||||
return { status: 400, ok: false, error: "请选择压缩包或文件夹" };
|
||||
}
|
||||
return { status: 400, ok: false, error: `unknown op: ${op}` };
|
||||
}
|
||||
|
||||
function skillsHttpHandler(forcedOp) {
|
||||
return async (request, response) => {
|
||||
if (request.method === "OPTIONS") {
|
||||
sendOptions(response);
|
||||
return;
|
||||
}
|
||||
if (request.method !== "GET" && request.method !== "POST") {
|
||||
response.writeHead(405, { allow: "GET, POST, OPTIONS" });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const url = new URL(request.url ?? "", "http://127.0.0.1");
|
||||
const tail = skillRouteTail(url.pathname);
|
||||
const body = request.method === "POST" ? await readJsonBody(request, 14 * 1024 * 1024) : {};
|
||||
const op = forcedOp
|
||||
|| body.op
|
||||
|| tail
|
||||
|| url.searchParams.get("op")
|
||||
|| (url.searchParams.get("id") ? "read" : "status");
|
||||
const result = await handleSkillsOp(op, body, url.searchParams.get("id"));
|
||||
sendJson(response, result.status || 200, result);
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e && e.message ? e.message : e) });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function skillRouteTail(pathname) {
|
||||
const match = String(pathname || "").match(/^\/dsh-purge\/skills?(?:\/(.*))?$/i);
|
||||
if (!match) return "";
|
||||
return String(match[1] || "").replace(/\/$/, "");
|
||||
}
|
||||
|
||||
function installSkillsHttp(webServer) {
|
||||
const stop = [];
|
||||
const add = (spec) => stop.push(registerRoute(webServer, spec));
|
||||
for (const routePath of ["/dsh-purge/skills", "/dsh-purge/skill"]) {
|
||||
add({ kind: "exact", path: routePath, handler: skillsHttpHandler("") });
|
||||
}
|
||||
add({ kind: "prefix", path: "/dsh-purge/skills", handler: skillsHttpHandler("") });
|
||||
for (const op of ["status", "read", "save", "delete", "import"]) {
|
||||
add({ kind: "exact", path: `/dsh-purge/skills/${op}`, handler: skillsHttpHandler(op) });
|
||||
add({ kind: "exact", path: `/dsh-purge/skill/${op}`, handler: skillsHttpHandler(op) });
|
||||
}
|
||||
return () => {
|
||||
for (let i = stop.length - 1; i >= 0; i -= 1) {
|
||||
try { stop[i]?.(); } catch { /* ignore */ }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function installRulesHttp(webServer) {
|
||||
const stop = [];
|
||||
stop.push(registerRoute(webServer, {
|
||||
@@ -1241,13 +1433,14 @@ function registerRoute(webServer, spec) {
|
||||
}
|
||||
}
|
||||
|
||||
async function readJsonBody(request) {
|
||||
async function readJsonBody(request, maxBytes = 512 * 1024) {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
const limit = Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : 512 * 1024;
|
||||
for await (const chunk of request) {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
size += buffer.length;
|
||||
if (size > 512 * 1024) throw new Error("request body too large");
|
||||
if (size > limit) throw new Error("request body too large");
|
||||
chunks.push(buffer);
|
||||
}
|
||||
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
||||
|
||||
+560
@@ -0,0 +1,560 @@
|
||||
import { promises as fsp } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { findDshHome } from "./core.js";
|
||||
|
||||
export { findDshHome };
|
||||
|
||||
/** 与官方 @deepseek-ai/dsh-skill 一致:kebab-case。 */
|
||||
const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
const MAX_SKILL_BYTES = 256 * 1024;
|
||||
const MAX_ARCHIVE_BYTES = 12 * 1024 * 1024;
|
||||
const MAX_IMPORT_FILES = 200;
|
||||
const MAX_DESCRIPTION = 500;
|
||||
const SKIP_COPY_NAMES = new Set([".", "..", ".system", ".git", "node_modules", "__MACOSX", ".DS_Store"]);
|
||||
|
||||
export function validSkillName(id) {
|
||||
return typeof id === "string" && SKILL_NAME_RE.test(id);
|
||||
}
|
||||
|
||||
export function skillsDir(dshHome) {
|
||||
return path.join(dshHome, "skills");
|
||||
}
|
||||
|
||||
export function skillBackupDir(dshHome) {
|
||||
return path.join(dshHome, "dsh-purge-backups", "skills");
|
||||
}
|
||||
|
||||
export function skillBundleDir(dshHome, id) {
|
||||
return path.join(skillsDir(dshHome), id);
|
||||
}
|
||||
|
||||
export function skillBundleFile(dshHome, id) {
|
||||
return path.join(skillBundleDir(dshHome, id), "SKILL.md");
|
||||
}
|
||||
|
||||
export function skillFlatFile(dshHome, id) {
|
||||
return path.join(skillsDir(dshHome), `${id}.md`);
|
||||
}
|
||||
|
||||
/** 对外只报 $DSH_HOME/...,不暴露本机盘符或安装目录。 */
|
||||
export function displayUnderHome(dshHome, absPath) {
|
||||
if (!absPath) return "";
|
||||
const home = path.resolve(dshHome);
|
||||
const abs = path.resolve(absPath);
|
||||
if (abs === home) return "$DSH_HOME";
|
||||
const rel = path.relative(home, abs);
|
||||
if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return "$DSH_HOME";
|
||||
return `$DSH_HOME/${rel.split(/[/\\]/).join("/")}`;
|
||||
}
|
||||
|
||||
export function toPublicSkill(dshHome, item) {
|
||||
if (!item || typeof item !== "object") return item;
|
||||
const next = { ...item };
|
||||
if (typeof next.path === "string") next.path = displayUnderHome(dshHome, next.path);
|
||||
if (typeof next.backup === "string") next.backup = displayUnderHome(dshHome, next.backup);
|
||||
return next;
|
||||
}
|
||||
|
||||
function assertInside(root, target) {
|
||||
const a = path.resolve(root);
|
||||
const b = path.resolve(target);
|
||||
const prefix = a.endsWith(path.sep) ? a : a + path.sep;
|
||||
if (b !== a && !b.startsWith(prefix)) {
|
||||
throw new Error("skill path escaped official skills directory");
|
||||
}
|
||||
}
|
||||
|
||||
function yamlScalar(value) {
|
||||
const text = String(value ?? "").trim();
|
||||
if (!text) return '""';
|
||||
if (/^[A-Za-z0-9._+/-]+$/.test(text)) return text;
|
||||
return JSON.stringify(text);
|
||||
}
|
||||
|
||||
export function splitFrontmatter(raw) {
|
||||
const text = String(raw || "").replace(/^\uFEFF/, "");
|
||||
if (!text.startsWith("---")) return null;
|
||||
const afterOpen = text.slice(3);
|
||||
if (!/^\r?\n/.test(afterOpen)) return null;
|
||||
const rest = afterOpen.replace(/^\r?\n/, "");
|
||||
const close = rest.match(/\r?\n---(?:\r?\n|$)/);
|
||||
if (!close || close.index == null) return null;
|
||||
return {
|
||||
head: rest.slice(0, close.index),
|
||||
body: rest.slice(close.index + close[0].length),
|
||||
};
|
||||
}
|
||||
|
||||
function yamlLineField(head, key) {
|
||||
const re = new RegExp(`^${key}:\\s*(.*)$`, "m");
|
||||
const match = String(head || "").match(re);
|
||||
if (!match) return "";
|
||||
let value = match[1].trim();
|
||||
if (!value) return "";
|
||||
if (value === "|" || value === ">" || value === "|-" || value === ">-") return "";
|
||||
if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
try {
|
||||
return value.startsWith("\"") ? JSON.parse(value) : value.slice(1, -1);
|
||||
} catch {
|
||||
return value.slice(1, -1);
|
||||
}
|
||||
}
|
||||
const comment = value.indexOf(" #");
|
||||
if (comment >= 0) value = value.slice(0, comment).trim();
|
||||
return value;
|
||||
}
|
||||
|
||||
export function parseSkillDocument(raw) {
|
||||
const parts = splitFrontmatter(raw);
|
||||
if (!parts) return { ok: false, error: "缺少 YAML frontmatter(须以 --- 包围)" };
|
||||
const name = yamlLineField(parts.head, "name");
|
||||
const description = yamlLineField(parts.head, "description");
|
||||
if (!validSkillName(name)) return { ok: false, error: "frontmatter.name 必须是 kebab-case,例如 code-review" };
|
||||
if (!description) return { ok: false, error: "frontmatter.description 必填(单行)" };
|
||||
return { ok: true, name, description, body: parts.body, head: parts.head };
|
||||
}
|
||||
|
||||
export function renderSkillDocument(id, description, body = "") {
|
||||
if (!validSkillName(id)) throw new Error("invalid skill name");
|
||||
const desc = String(description || "").trim() || id;
|
||||
const text = String(body || "").replace(/^\uFEFF/, "");
|
||||
const parts = splitFrontmatter(text);
|
||||
const inner = parts ? parts.body : text;
|
||||
return `---\nname: ${id}\ndescription: ${yamlScalar(desc.slice(0, MAX_DESCRIPTION))}\n---\n\n${inner.replace(/^\r?\n/, "")}`;
|
||||
}
|
||||
|
||||
function upsertYamlLine(head, key, value) {
|
||||
const line = `${key}: ${yamlScalar(value)}`;
|
||||
const re = new RegExp(`^${key}:\\s*.*$`, "m");
|
||||
if (re.test(head)) return head.replace(re, line);
|
||||
return `${line}\n${String(head || "").replace(/^\r?\n/, "")}`;
|
||||
}
|
||||
|
||||
/** 保留官方 whenToUse / invocation / metadata,只改 name 与 description。 */
|
||||
export function mergeSkillDocument(id, description, raw = "") {
|
||||
const parsed = parseSkillDocument(raw);
|
||||
const desc = String(description || "").trim() || (parsed.ok ? parsed.description : "") || id;
|
||||
if (!parsed.ok) return renderSkillDocument(id, desc, raw);
|
||||
const head = upsertYamlLine(upsertYamlLine(parsed.head, "name", id), "description", desc.slice(0, MAX_DESCRIPTION));
|
||||
return `---\n${head.replace(/^\r?\n/, "").replace(/\r?\n$/, "")}\n---\n\n${parsed.body.replace(/^\r?\n/, "")}`;
|
||||
}
|
||||
|
||||
export function formatSize(bytes) {
|
||||
if (!Number.isFinite(bytes) || bytes < 0) return "0 B";
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const kb = bytes / 1024;
|
||||
return `${kb >= 100 ? Math.round(kb) : kb.toFixed(1)} KB`;
|
||||
}
|
||||
|
||||
async function fileSize(fp) {
|
||||
try {
|
||||
return (await fsp.stat(fp)).size;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
async function pathExists(fp) {
|
||||
try {
|
||||
await fsp.access(fp);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function skillFromFile(id, fp, kind) {
|
||||
const content = await fsp.readFile(fp, "utf8");
|
||||
const parsed = parseSkillDocument(content);
|
||||
return {
|
||||
id,
|
||||
kind,
|
||||
path: fp,
|
||||
content,
|
||||
description: parsed.ok ? parsed.description : "",
|
||||
valid: parsed.ok,
|
||||
error: parsed.ok ? null : parsed.error,
|
||||
size: Buffer.byteLength(content, "utf8"),
|
||||
};
|
||||
}
|
||||
|
||||
export async function readSkill(dshHome, id) {
|
||||
if (!validSkillName(id)) throw new Error(`invalid skill name: ${id}`);
|
||||
const bundle = skillBundleFile(dshHome, id);
|
||||
if (await pathExists(bundle)) return skillFromFile(id, bundle, "bundle");
|
||||
const flat = skillFlatFile(dshHome, id);
|
||||
if (await pathExists(flat)) return skillFromFile(id, flat, "flat");
|
||||
const dir = skillsDir(dshHome);
|
||||
let entries = [];
|
||||
try {
|
||||
entries = await fsp.readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory() || entry.name === ".system") continue;
|
||||
const fp = path.join(dir, entry.name, "SKILL.md");
|
||||
if (!(await pathExists(fp))) continue;
|
||||
const parsed = parseSkillDocument(await fsp.readFile(fp, "utf8"));
|
||||
if (parsed.ok && parsed.name === id) return skillFromFile(id, fp, "bundle");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function listSkills(dshHome) {
|
||||
const dir = skillsDir(dshHome);
|
||||
const out = [];
|
||||
let entries = [];
|
||||
try {
|
||||
entries = await fsp.readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return out;
|
||||
}
|
||||
const seen = new Set();
|
||||
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
if (entry.name === ".system") continue;
|
||||
if (entry.isDirectory()) {
|
||||
const fp = path.join(dir, entry.name, "SKILL.md");
|
||||
if (!(await pathExists(fp))) continue;
|
||||
const parsed = parseSkillDocument(await fsp.readFile(fp, "utf8"));
|
||||
const id = parsed.ok ? parsed.name : (validSkillName(entry.name) ? entry.name : "");
|
||||
if (!id || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
out.push(await skillFromFile(id, fp, "bundle"));
|
||||
continue;
|
||||
}
|
||||
if (!entry.isFile() || !entry.name.endsWith(".md") || entry.name === "SKILL.md") continue;
|
||||
const fallback = entry.name.slice(0, -3);
|
||||
const fp = path.join(dir, entry.name);
|
||||
const parsed = parseSkillDocument(await fsp.readFile(fp, "utf8"));
|
||||
const id = parsed.ok ? parsed.name : (validSkillName(fallback) ? fallback : "");
|
||||
if (!id || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
out.push(await skillFromFile(id, fp, "flat"));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function copyDir(src, dest) {
|
||||
await fsp.mkdir(dest, { recursive: true });
|
||||
for (const entry of await fsp.readdir(src, { withFileTypes: true })) {
|
||||
if (SKIP_COPY_NAMES.has(entry.name) || entry.name.startsWith("._")) continue;
|
||||
if (entry.isSymbolicLink()) continue;
|
||||
const from = path.join(src, entry.name);
|
||||
const to = path.join(dest, entry.name);
|
||||
assertInside(dest, to);
|
||||
if (entry.isDirectory()) await copyDir(from, to);
|
||||
else if (entry.isFile()) await fsp.copyFile(from, to);
|
||||
}
|
||||
}
|
||||
|
||||
async function backupExisting(dshHome, id) {
|
||||
const existing = await readSkill(dshHome, id).catch(() => null);
|
||||
const root = skillsDir(dshHome);
|
||||
const bundleDir = existing?.kind === "bundle" ? path.dirname(existing.path) : skillBundleDir(dshHome, id);
|
||||
const flat = existing?.kind === "flat" ? existing.path : skillFlatFile(dshHome, id);
|
||||
const hasBundle = await pathExists(bundleDir);
|
||||
const hasFlat = await pathExists(flat);
|
||||
if (!hasBundle && !hasFlat) return null;
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const dest = path.join(skillBackupDir(dshHome), `${id}_${stamp}`);
|
||||
assertInside(path.join(dshHome, "dsh-purge-backups"), dest);
|
||||
await fsp.mkdir(dest, { recursive: true });
|
||||
if (hasBundle) {
|
||||
assertInside(root, bundleDir);
|
||||
await copyDir(bundleDir, path.join(dest, id));
|
||||
}
|
||||
if (hasFlat) {
|
||||
assertInside(root, flat);
|
||||
await fsp.copyFile(flat, path.join(dest, `${id}.md`));
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
async function removeOfficialSkill(dshHome, id) {
|
||||
const existing = await readSkill(dshHome, id).catch(() => null);
|
||||
const root = skillsDir(dshHome);
|
||||
const bundleDir = existing?.kind === "bundle" ? path.dirname(existing.path) : skillBundleDir(dshHome, id);
|
||||
const flat = existing?.kind === "flat" ? existing.path : skillFlatFile(dshHome, id);
|
||||
if (await pathExists(bundleDir)) {
|
||||
assertInside(root, bundleDir);
|
||||
await fsp.rm(bundleDir, { recursive: true, force: true });
|
||||
}
|
||||
if (await pathExists(flat)) {
|
||||
assertInside(root, flat);
|
||||
await fsp.rm(flat, { force: true });
|
||||
}
|
||||
const canonical = skillBundleDir(dshHome, id);
|
||||
if (canonical !== bundleDir && await pathExists(canonical)) {
|
||||
assertInside(root, canonical);
|
||||
await fsp.rm(canonical, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveSkill(dshHome, id, content, description) {
|
||||
if (!validSkillName(id)) throw new Error(`invalid skill name: ${id}`);
|
||||
const parsed = parseSkillDocument(content);
|
||||
const desc = String(description || "").trim() || (parsed.ok ? parsed.description : "");
|
||||
const document = mergeSkillDocument(id, desc, String(content || ""));
|
||||
if (Buffer.byteLength(document, "utf8") > MAX_SKILL_BYTES) {
|
||||
throw new Error("skill too large (max 256KB)");
|
||||
}
|
||||
const check = parseSkillDocument(document);
|
||||
if (!check.ok) throw new Error(check.error);
|
||||
const root = skillsDir(dshHome);
|
||||
const dest = skillBundleFile(dshHome, id);
|
||||
assertInside(root, dest);
|
||||
const backup = await backupExisting(dshHome, id);
|
||||
await removeOfficialSkill(dshHome, id);
|
||||
await fsp.mkdir(skillBundleDir(dshHome, id), { recursive: true });
|
||||
await fsp.writeFile(dest, document, "utf8");
|
||||
return {
|
||||
id,
|
||||
path: dest,
|
||||
description: check.description,
|
||||
backup,
|
||||
size: Buffer.byteLength(document, "utf8"),
|
||||
content: document,
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteSkill(dshHome, id) {
|
||||
if (!validSkillName(id)) throw new Error(`invalid skill name: ${id}`);
|
||||
const existing = await readSkill(dshHome, id);
|
||||
if (!existing) throw new Error(`skill not found: ${id}`);
|
||||
const backup = await backupExisting(dshHome, id);
|
||||
await removeOfficialSkill(dshHome, id);
|
||||
return { id, backup, path: existing.path };
|
||||
}
|
||||
|
||||
function kebabFromLabel(name) {
|
||||
const base = String(name || "")
|
||||
.replace(/\.(zip|tgz|tar\.gz|tar|skill)$/i, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
return validSkillName(base) ? base : "";
|
||||
}
|
||||
|
||||
function isUnsafeArchiveEntry(name) {
|
||||
const rel = String(name || "").replace(/\\/g, "/").replace(/^\.?\//, "").replace(/\/+$/, "");
|
||||
if (!rel) return false;
|
||||
if (rel.startsWith("/") || /^[A-Za-z]:/.test(rel)) return true;
|
||||
return rel.split("/").some((part) => part === ".." || part === "");
|
||||
}
|
||||
|
||||
function listArchiveEntries(archivePath) {
|
||||
const result = spawnSync("tar", ["-tf", archivePath], {
|
||||
windowsHide: true,
|
||||
encoding: "utf8",
|
||||
timeout: 15000,
|
||||
});
|
||||
if (result.status !== 0) return null;
|
||||
return String(result.stdout || "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function extractArchive(archivePath, dest) {
|
||||
const entries = listArchiveEntries(archivePath);
|
||||
if (entries && entries.some(isUnsafeArchiveEntry)) {
|
||||
throw new Error("压缩包路径不合法");
|
||||
}
|
||||
if (entries && entries.length > MAX_IMPORT_FILES) {
|
||||
throw new Error("压缩包里文件太多");
|
||||
}
|
||||
const result = spawnSync("tar", ["-xf", archivePath, "-C", dest], {
|
||||
windowsHide: true,
|
||||
encoding: "utf8",
|
||||
timeout: 30000,
|
||||
});
|
||||
if (result.status === 0) return;
|
||||
if (/\.zip$/i.test(archivePath) && process.platform === "win32") {
|
||||
const ps = spawnSync("powershell", [
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
`Expand-Archive -LiteralPath '${String(archivePath).replace(/'/g, "''")}' -DestinationPath '${String(dest).replace(/'/g, "''")}' -Force`,
|
||||
], {
|
||||
windowsHide: true,
|
||||
encoding: "utf8",
|
||||
timeout: 30000,
|
||||
});
|
||||
if (ps.status === 0) return;
|
||||
}
|
||||
const detail = String(result.stderr || result.stdout || "").trim();
|
||||
throw new Error(detail || "无法解压,请改用文件夹导入");
|
||||
}
|
||||
|
||||
async function walkFiles(root, onFile, depth = 0) {
|
||||
if (depth > 6) return;
|
||||
let entries = [];
|
||||
try {
|
||||
entries = await fsp.readdir(root, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.name === "." || entry.name === ".." || entry.name === ".system" || entry.name === "__MACOSX" || entry.name === ".DS_Store") continue;
|
||||
if (entry.name.startsWith("._")) continue;
|
||||
const full = path.join(root, entry.name);
|
||||
assertInside(root, full);
|
||||
if (entry.isDirectory()) await walkFiles(full, onFile, depth + 1);
|
||||
else if (entry.isFile()) await onFile(full);
|
||||
}
|
||||
}
|
||||
|
||||
export async function findSkillRoots(root) {
|
||||
const dirs = [];
|
||||
const flats = [];
|
||||
async function visit(dir, depth) {
|
||||
if (depth > 4) return;
|
||||
let entries = [];
|
||||
try {
|
||||
entries = await fsp.readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (entries.some((entry) => entry.isFile() && entry.name === "SKILL.md")) {
|
||||
dirs.push(dir);
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.name === "." || entry.name === "..") continue;
|
||||
if (entry.isFile() && entry.name.endsWith(".md") && entry.name !== "SKILL.md") {
|
||||
const raw = await fsp.readFile(path.join(dir, entry.name), "utf8");
|
||||
if (parseSkillDocument(raw).ok) flats.push(path.join(dir, entry.name));
|
||||
}
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
if (entry.name === "." || entry.name === ".." || entry.name === ".system" || entry.name === "__MACOSX") continue;
|
||||
const next = path.join(dir, entry.name);
|
||||
assertInside(root, next);
|
||||
await visit(next, depth + 1);
|
||||
}
|
||||
}
|
||||
await visit(root, 0);
|
||||
return { dirs, flats };
|
||||
}
|
||||
|
||||
async function installBundleDir(dshHome, srcDir, fallbackId) {
|
||||
const mdPath = path.join(srcDir, "SKILL.md");
|
||||
const raw = await fsp.readFile(mdPath, "utf8");
|
||||
const parsed = parseSkillDocument(raw);
|
||||
const id = parsed.ok ? parsed.name : kebabFromLabel(fallbackId || path.basename(srcDir));
|
||||
if (!validSkillName(id)) throw new Error("压缩包/文件夹里没有合法的 Skill 名称");
|
||||
const dest = skillBundleDir(dshHome, id);
|
||||
assertInside(skillsDir(dshHome), dest);
|
||||
const backup = await backupExisting(dshHome, id);
|
||||
await removeOfficialSkill(dshHome, id);
|
||||
await copyDir(srcDir, dest);
|
||||
const destMd = path.join(dest, "SKILL.md");
|
||||
if (parsed.ok && parsed.name !== id) {
|
||||
await fsp.writeFile(destMd, mergeSkillDocument(id, parsed.description, raw), "utf8");
|
||||
} else if (!parsed.ok && !String(raw).replace(/^\uFEFF/, "").startsWith("---")) {
|
||||
await fsp.writeFile(destMd, renderSkillDocument(id, id, raw), "utf8");
|
||||
}
|
||||
return { id, path: destMd, backup, description: parsed.ok ? parsed.description : id };
|
||||
}
|
||||
|
||||
async function installFlatFile(dshHome, srcFile, fallbackId) {
|
||||
const raw = await fsp.readFile(srcFile, "utf8");
|
||||
const parsed = parseSkillDocument(raw);
|
||||
const id = parsed.ok ? parsed.name : kebabFromLabel(fallbackId || path.basename(srcFile, ".md"));
|
||||
if (!parsed.ok) throw new Error(parsed.error);
|
||||
return saveSkill(dshHome, id, raw, parsed.description);
|
||||
}
|
||||
|
||||
async function installFoundSkills(dshHome, root, fallbackId) {
|
||||
const found = await findSkillRoots(root);
|
||||
const imported = [];
|
||||
for (const dir of found.dirs) {
|
||||
imported.push(await installBundleDir(dshHome, dir, fallbackId || path.basename(dir)));
|
||||
}
|
||||
if (!imported.length) {
|
||||
for (const file of found.flats) {
|
||||
imported.push(await installFlatFile(dshHome, file, fallbackId));
|
||||
}
|
||||
}
|
||||
if (!imported.length) throw new Error("未找到 SKILL.md 或合法的 Skill 文件");
|
||||
return imported;
|
||||
}
|
||||
|
||||
export async function importArchive(dshHome, buffer, filename = "skill.zip") {
|
||||
const bytes = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
|
||||
if (!bytes.length) throw new Error("压缩包是空的");
|
||||
if (bytes.length > MAX_ARCHIVE_BYTES) throw new Error("压缩包太大(最大 12MB)");
|
||||
const temp = await fsp.mkdtemp(path.join(os.tmpdir(), "dshp-skill-"));
|
||||
const archive = path.join(temp, path.basename(filename) || "skill.zip");
|
||||
const unpacked = path.join(temp, "unpacked");
|
||||
try {
|
||||
await fsp.mkdir(unpacked, { recursive: true });
|
||||
await fsp.writeFile(archive, bytes);
|
||||
extractArchive(archive, unpacked);
|
||||
await walkFiles(unpacked, async () => {});
|
||||
const imported = await installFoundSkills(dshHome, unpacked, kebabFromLabel(filename));
|
||||
return { imported: imported.map((item) => toPublicSkill(dshHome, item)) };
|
||||
} finally {
|
||||
await fsp.rm(temp, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export async function importFileTree(dshHome, files, fallbackId = "") {
|
||||
if (!Array.isArray(files) || !files.length) throw new Error("文件夹是空的");
|
||||
if (files.length > MAX_IMPORT_FILES) throw new Error("文件夹里文件太多");
|
||||
const temp = await fsp.mkdtemp(path.join(os.tmpdir(), "dshp-skill-"));
|
||||
try {
|
||||
let total = 0;
|
||||
for (const file of files) {
|
||||
const rel = String(file?.path || file?.name || "").replace(/\\/g, "/").replace(/^\/+/, "");
|
||||
if (!rel || rel.includes("..") || path.isAbsolute(rel) || isUnsafeArchiveEntry(rel)) {
|
||||
throw new Error("文件夹路径不合法");
|
||||
}
|
||||
const dest = path.join(temp, rel);
|
||||
assertInside(temp, dest);
|
||||
await fsp.mkdir(path.dirname(dest), { recursive: true });
|
||||
const text = typeof file.content === "string" ? file.content : "";
|
||||
const raw = file.encoding === "base64" ? Buffer.from(text, "base64") : Buffer.from(text, "utf8");
|
||||
total += raw.length;
|
||||
if (raw.length > MAX_ARCHIVE_BYTES || total > MAX_ARCHIVE_BYTES) throw new Error("文件太大");
|
||||
await fsp.writeFile(dest, raw);
|
||||
}
|
||||
const imported = await installFoundSkills(dshHome, temp, fallbackId);
|
||||
return { imported: imported.map((item) => toPublicSkill(dshHome, item)) };
|
||||
} finally {
|
||||
await fsp.rm(temp, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export async function importFromPath(dshHome, sourcePath) {
|
||||
const src = path.resolve(String(sourcePath || ""));
|
||||
const stat = await fsp.stat(src);
|
||||
if (stat.isDirectory()) {
|
||||
const imported = await installFoundSkills(dshHome, src, kebabFromLabel(path.basename(src)));
|
||||
return { imported: imported.map((item) => toPublicSkill(dshHome, item)) };
|
||||
}
|
||||
if (stat.isFile()) {
|
||||
const name = path.basename(src);
|
||||
if (/\.(zip|tgz|tar\.gz|tar|skill)$/i.test(name)) {
|
||||
return importArchive(dshHome, await fsp.readFile(src), name);
|
||||
}
|
||||
return { imported: [toPublicSkill(dshHome, await installFlatFile(dshHome, src, kebabFromLabel(name)))] };
|
||||
}
|
||||
throw new Error("只能导入压缩包或文件夹");
|
||||
}
|
||||
|
||||
export async function skillsStatus(dshHome) {
|
||||
const listed = await listSkills(dshHome);
|
||||
return {
|
||||
skills_dir: "$DSH_HOME/skills",
|
||||
skills: listed.map((item) => ({
|
||||
id: item.id,
|
||||
description: item.description,
|
||||
kind: item.kind,
|
||||
valid: item.valid,
|
||||
error: item.error,
|
||||
size: item.size,
|
||||
path: displayUnderHome(dshHome, item.path),
|
||||
})),
|
||||
};
|
||||
}
|
||||
+337
-47
@@ -9,11 +9,14 @@ import { adapterFor, detectSurface } from "./surface.js";
|
||||
import { cliInvocation } from "./desktop.js";
|
||||
|
||||
const REPO = "YuJunZhiXue/dsh-purge";
|
||||
const BRANCH = "master";
|
||||
const ZIP_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.zip`;
|
||||
export const TARBALL_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.tar.gz`;
|
||||
const GITHUB_SPEC = `github:${REPO}#${BRANCH}`;
|
||||
const STABLE_REF = "master";
|
||||
const BETA_REF = "beta";
|
||||
export const TARBALL_URL = `https://github.com/${REPO}/archive/refs/heads/${STABLE_REF}.tar.gz`;
|
||||
const PLUGIN_ROOT = path.resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
|
||||
const CHANNELS = {
|
||||
stable: { id: "stable", ref: STABLE_REF, label: "正式版" },
|
||||
beta: { id: "beta", ref: BETA_REF, label: "测试版" },
|
||||
};
|
||||
const COPY_NAMES = [
|
||||
"lib",
|
||||
"bin",
|
||||
@@ -47,10 +50,86 @@ export function localVersion() {
|
||||
}
|
||||
}
|
||||
|
||||
function channelStatePath() {
|
||||
return path.join(findDshHome(), "dsh-purge", "channel.json");
|
||||
}
|
||||
|
||||
function historyPath() {
|
||||
return path.join(findDshHome(), "dsh-purge", "version-history.json");
|
||||
}
|
||||
|
||||
function stampPath() {
|
||||
return path.join(findDshHome(), "dsh-purge", "installed-rev");
|
||||
}
|
||||
|
||||
export function normalizeChannel(value) {
|
||||
return String(value || "").toLowerCase() === "beta" ? "beta" : "stable";
|
||||
}
|
||||
|
||||
function isBetaName(name) {
|
||||
return /(?:^|[-._])(beta|rc|pre|preview|test)(?:\d|$|[-._])/i.test(String(name || ""));
|
||||
}
|
||||
|
||||
export function readChannelState() {
|
||||
const raw = readJson(channelStatePath()) || {};
|
||||
return {
|
||||
channel: normalizeChannel(raw.channel),
|
||||
pin: typeof raw.pin === "string" ? raw.pin.trim() : "",
|
||||
};
|
||||
}
|
||||
|
||||
function writeChannelState(next) {
|
||||
const state = {
|
||||
channel: normalizeChannel(next?.channel),
|
||||
pin: typeof next?.pin === "string" ? next.pin.trim() : "",
|
||||
};
|
||||
fs.mkdirSync(path.dirname(channelStatePath()), { recursive: true });
|
||||
fs.writeFileSync(channelStatePath(), `${JSON.stringify(state, null, 2)}\n`, "utf8");
|
||||
return state;
|
||||
}
|
||||
|
||||
export function channelPublic(state = readChannelState()) {
|
||||
const meta = CHANNELS[state.channel] || CHANNELS.stable;
|
||||
return {
|
||||
channel: meta.id,
|
||||
channelLabel: meta.label,
|
||||
pin: state.pin || "",
|
||||
};
|
||||
}
|
||||
|
||||
function currentChannelRef(state = readChannelState()) {
|
||||
return (CHANNELS[state.channel] || CHANNELS.stable).ref;
|
||||
}
|
||||
|
||||
function readHistory() {
|
||||
const raw = readJson(historyPath());
|
||||
return Array.isArray(raw) ? raw : [];
|
||||
}
|
||||
|
||||
function pushHistory(entry) {
|
||||
const next = [entry, ...readHistory().filter((item) => item && item.ref !== entry.ref)].slice(0, 20);
|
||||
fs.mkdirSync(path.dirname(historyPath()), { recursive: true });
|
||||
fs.writeFileSync(historyPath(), `${JSON.stringify(next, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
function archiveZipUrl(ref) {
|
||||
const value = String(ref || STABLE_REF);
|
||||
if (/^[0-9a-f]{40}$/i.test(value)) return `https://github.com/${REPO}/archive/${value}.zip`;
|
||||
if (/^v?\d/.test(value)) return `https://github.com/${REPO}/archive/refs/tags/${encodeURIComponent(value)}.zip`;
|
||||
return `https://github.com/${REPO}/archive/refs/heads/${encodeURIComponent(value)}.zip`;
|
||||
}
|
||||
|
||||
function archiveTarballUrl(ref) {
|
||||
const value = String(ref || STABLE_REF);
|
||||
if (/^[0-9a-f]{40}$/i.test(value)) return `https://github.com/${REPO}/archive/${value}.tar.gz`;
|
||||
if (/^v?\d/.test(value)) return `https://github.com/${REPO}/archive/refs/tags/${encodeURIComponent(value)}.tar.gz`;
|
||||
return `https://github.com/${REPO}/archive/refs/heads/${encodeURIComponent(value)}.tar.gz`;
|
||||
}
|
||||
|
||||
function githubSpec(ref) {
|
||||
return `github:${REPO}#${ref || STABLE_REF}`;
|
||||
}
|
||||
|
||||
function readStamp() {
|
||||
try {
|
||||
return fs.readFileSync(stampPath(), "utf8").trim();
|
||||
@@ -205,15 +284,15 @@ export function runDshPlugin(profile, args) {
|
||||
});
|
||||
}
|
||||
|
||||
export function pluginAddSpec(spec) {
|
||||
export function pluginAddSpec(spec, ref = currentChannelRef()) {
|
||||
const s = String(spec || "");
|
||||
if (/\.(zip|tgz|tar\.gz)(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return TARBALL_URL;
|
||||
if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return GITHUB_SPEC;
|
||||
if (/\.(zip|tgz|tar\.gz)(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return archiveTarballUrl(ref);
|
||||
if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return githubSpec(ref);
|
||||
return "";
|
||||
}
|
||||
|
||||
function dshReinstall(profile, spec) {
|
||||
const addSpec = pluginAddSpec(spec);
|
||||
function dshReinstall(profile, spec, ref = currentChannelRef()) {
|
||||
const addSpec = pluginAddSpec(spec, ref);
|
||||
if (addSpec) {
|
||||
runDshPlugin(profile, ["add", "--force", addSpec]);
|
||||
return;
|
||||
@@ -221,7 +300,7 @@ function dshReinstall(profile, spec) {
|
||||
try {
|
||||
runDshPlugin(profile, ["update", "dsh-purge"]);
|
||||
} catch {
|
||||
runDshPlugin(profile, ["add", "--force", TARBALL_URL]);
|
||||
runDshPlugin(profile, ["add", "--force", archiveTarballUrl(ref)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,8 +391,8 @@ function versionFromPackageText(text) {
|
||||
return pkg && pkg.version ? String(pkg.version) : "";
|
||||
}
|
||||
|
||||
async function remotePackageVersion(sha = "") {
|
||||
const ref = sha || BRANCH;
|
||||
async function remotePackageVersion(sha = "", fallbackRef = STABLE_REF) {
|
||||
const ref = sha || fallbackRef;
|
||||
const urls = [
|
||||
sha ? `https://cdn.jsdelivr.net/gh/${REPO}@${sha}/package.json` : "",
|
||||
`https://raw.githubusercontent.com/${REPO}/${ref}/package.json`,
|
||||
@@ -340,11 +419,12 @@ async function remotePackageVersion(sha = "") {
|
||||
return "";
|
||||
}
|
||||
|
||||
async function remoteHeadSha() {
|
||||
const fromApi = fetchJson(`https://api.github.com/repos/${REPO}/commits/${BRANCH}`)
|
||||
async function remoteHeadSha(ref = STABLE_REF) {
|
||||
const target = encodeURIComponent(ref || STABLE_REF);
|
||||
const fromApi = fetchJson(`https://api.github.com/repos/${REPO}/commits/${target}`)
|
||||
.then((data) => (data?.sha ? String(data.sha) : ""))
|
||||
.catch(() => "");
|
||||
const fromAtom = fetchText(`https://github.com/${REPO}/commits/${BRANCH}.atom`)
|
||||
const fromAtom = fetchText(`https://github.com/${REPO}/commits/${ref}.atom`)
|
||||
.then((atom) => {
|
||||
const hit = atom.match(/<id>tag:github\.com,2008:Grit::Commit\/([0-9a-f]{40})<\/id>/);
|
||||
return hit ? hit[1] : "";
|
||||
@@ -354,31 +434,163 @@ async function remoteHeadSha() {
|
||||
return apiSha || atomSha || "";
|
||||
}
|
||||
|
||||
export async function checkUpdate() {
|
||||
function versionLabel(version, channel, sha = "") {
|
||||
const ver = String(version || "").replace(/^v/, "") || (sha ? String(sha).slice(0, 7) : "");
|
||||
const mark = channel === "beta" ? "测试" : "正式";
|
||||
return ver ? `${ver}(${mark})` : mark;
|
||||
}
|
||||
|
||||
function rememberVersion(item, seen) {
|
||||
if (!item || !item.ref) return null;
|
||||
const key = `${item.sha || ""}|${item.ref}`.toLowerCase();
|
||||
if (seen.has(key)) return null;
|
||||
seen.add(key);
|
||||
return item;
|
||||
}
|
||||
|
||||
async function listGithubTags() {
|
||||
try {
|
||||
const rows = await fetchJson(`https://api.github.com/repos/${REPO}/tags?per_page=50`);
|
||||
if (!Array.isArray(rows)) return [];
|
||||
return rows.map((row) => {
|
||||
const name = String(row?.name || "").trim();
|
||||
if (!name || !/^v?\d+\.\d+/.test(name)) return null;
|
||||
const sha = row?.commit?.sha ? String(row.commit.sha) : "";
|
||||
const channel = isBetaName(name) ? "beta" : "stable";
|
||||
return {
|
||||
id: name,
|
||||
ref: name,
|
||||
sha,
|
||||
version: name.replace(/^v/, ""),
|
||||
channel,
|
||||
label: versionLabel(name, channel, sha),
|
||||
kind: "tag",
|
||||
};
|
||||
}).filter(Boolean);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function listRemoteVersions() {
|
||||
const state = readChannelState();
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
const add = (item) => {
|
||||
const next = rememberVersion(item, seen);
|
||||
if (next) out.push(next);
|
||||
};
|
||||
|
||||
const [stableSha, betaSha, tags] = await Promise.all([
|
||||
remoteHeadSha(STABLE_REF),
|
||||
remoteHeadSha(BETA_REF),
|
||||
listGithubTags(),
|
||||
]);
|
||||
|
||||
if (stableSha) {
|
||||
const version = await remotePackageVersion(stableSha, STABLE_REF).catch(() => "");
|
||||
add({
|
||||
id: STABLE_REF,
|
||||
ref: STABLE_REF,
|
||||
sha: stableSha,
|
||||
version: version || "",
|
||||
channel: "stable",
|
||||
label: `${versionLabel(version, "stable", stableSha)} · 最新`,
|
||||
kind: "head",
|
||||
latest: true,
|
||||
});
|
||||
}
|
||||
if (betaSha) {
|
||||
const version = await remotePackageVersion(betaSha, BETA_REF).catch(() => "");
|
||||
add({
|
||||
id: BETA_REF,
|
||||
ref: BETA_REF,
|
||||
sha: betaSha,
|
||||
version: version || "",
|
||||
channel: "beta",
|
||||
label: `${versionLabel(version, "beta", betaSha)} · 最新`,
|
||||
kind: "head",
|
||||
latest: true,
|
||||
});
|
||||
}
|
||||
for (const tag of tags) add(tag);
|
||||
for (const item of readHistory()) {
|
||||
if (!item || !item.ref) continue;
|
||||
add({
|
||||
...item,
|
||||
label: item.label || versionLabel(item.version, item.channel, item.sha),
|
||||
kind: item.kind || "history",
|
||||
});
|
||||
}
|
||||
|
||||
const localVer = localVersion();
|
||||
const remoteSha = await remoteHeadSha();
|
||||
const remoteVer = await remotePackageVersion(remoteSha);
|
||||
if (!remoteSha && !remoteVer) throw new Error("无法读取 GitHub master");
|
||||
const localSha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || readStamp();
|
||||
return {
|
||||
versions: out.map((item) => ({
|
||||
...item,
|
||||
shaShort: item.sha ? String(item.sha).slice(0, 7) : "",
|
||||
current: Boolean(
|
||||
(localSha && item.sha && sameRev(localSha, item.sha))
|
||||
|| (state.pin && item.ref === state.pin)
|
||||
|| (!state.pin && item.latest && item.channel === state.channel && item.version && item.version === localVer),
|
||||
),
|
||||
})),
|
||||
hasBeta: Boolean(betaSha || out.some((item) => item.channel === "beta" && item.kind === "tag")),
|
||||
stableSha,
|
||||
betaSha,
|
||||
};
|
||||
}
|
||||
|
||||
export async function checkUpdate() {
|
||||
const state = readChannelState();
|
||||
const localVer = localVersion();
|
||||
const listed = await listRemoteVersions();
|
||||
const channelRef = currentChannelRef(state);
|
||||
const remoteSha = state.channel === "beta" ? listed.betaSha : listed.stableSha;
|
||||
const remoteVer = remoteSha ? await remotePackageVersion(remoteSha, channelRef) : "";
|
||||
if (!remoteSha && !remoteVer) {
|
||||
if (state.channel === "beta") {
|
||||
return rememberUpdate({
|
||||
ok: true,
|
||||
hasUpdate: false,
|
||||
hasBeta: false,
|
||||
error: "还没有测试版",
|
||||
localVersion: localVer,
|
||||
remoteVersion: "",
|
||||
localSha: ((gitOk() ? gitHead(PLUGIN_ROOT) : "") || readStamp()).slice(0, 7),
|
||||
remoteSha: "",
|
||||
via: detectVia(),
|
||||
versions: listed.versions,
|
||||
...channelPublic(state),
|
||||
});
|
||||
}
|
||||
throw new Error("无法读取 GitHub master");
|
||||
}
|
||||
const gitSha = gitOk() ? gitHead(PLUGIN_ROOT) : "";
|
||||
const stamp = readStamp();
|
||||
const localRev = gitSha || stamp;
|
||||
let hasUpdate = false;
|
||||
if (remoteSha && localRev) {
|
||||
if (state.pin) {
|
||||
hasUpdate = Boolean(remoteSha && localRev && !sameRev(localRev, remoteSha));
|
||||
} else if (remoteSha && localRev) {
|
||||
hasUpdate = !sameRev(localRev, remoteSha);
|
||||
} else if (remoteVer && localVer && remoteVer !== localVer) {
|
||||
hasUpdate = true;
|
||||
} else if (remoteSha && !localRev) {
|
||||
// zip / dsh 安装没有 stamp,按有更新处理,拉一次与 master 对齐。
|
||||
hasUpdate = true;
|
||||
}
|
||||
const result = {
|
||||
ok: true,
|
||||
hasUpdate,
|
||||
hasBeta: listed.hasBeta,
|
||||
pinned: Boolean(state.pin),
|
||||
localVersion: localVer,
|
||||
remoteVersion: remoteVer || (remoteSha ? remoteSha.slice(0, 7) : ""),
|
||||
localSha: localRev ? localRev.slice(0, 7) : "",
|
||||
remoteSha: remoteSha ? remoteSha.slice(0, 7) : "",
|
||||
via: detectVia(),
|
||||
versions: listed.versions,
|
||||
...channelPublic(state),
|
||||
};
|
||||
rememberUpdate(result);
|
||||
return result;
|
||||
@@ -422,21 +634,26 @@ function runGit(dir, args, timeout = 20000) {
|
||||
}
|
||||
}
|
||||
|
||||
function gitPull(dir) {
|
||||
try {
|
||||
runGit(dir, ["pull", "--ff-only", "origin", BRANCH], 60000);
|
||||
return;
|
||||
} catch (pullErr) {
|
||||
try {
|
||||
runGit(dir, ["fetch", "origin", BRANCH], 60000);
|
||||
runGit(dir, ["reset", "--hard", `origin/${BRANCH}`], 60000);
|
||||
return;
|
||||
} catch (resetErr) {
|
||||
throw new Error(
|
||||
`git 更新失败(${dir}):${String(resetErr.message || resetErr).slice(0, 240)};${String(pullErr.message || pullErr).slice(0, 160)}`,
|
||||
);
|
||||
}
|
||||
function gitResetTo(dir, ref, { force = false } = {}) {
|
||||
if (!force && gitTrackedDirty(dir)) {
|
||||
throw new Error("本地插件文件有未提交改动,未覆盖");
|
||||
}
|
||||
const target = String(ref || STABLE_REF);
|
||||
try {
|
||||
if (target === STABLE_REF || target === BETA_REF) {
|
||||
runGit(dir, ["pull", "--ff-only", "origin", target], 60000);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// 再走 fetch + reset。
|
||||
}
|
||||
try {
|
||||
runGit(dir, ["fetch", "origin", "--tags", target], 60000);
|
||||
} catch {
|
||||
runGit(dir, ["fetch", "origin", "--tags"], 60000);
|
||||
}
|
||||
const remote = (target === STABLE_REF || target === BETA_REF) ? `origin/${target}` : target;
|
||||
runGit(dir, ["reset", "--hard", remote], 60000);
|
||||
}
|
||||
|
||||
function extractZip(zip, dest) {
|
||||
@@ -457,12 +674,12 @@ function extractZip(zip, dest) {
|
||||
);
|
||||
}
|
||||
|
||||
async function overlayFromZip(dests) {
|
||||
async function overlayFromZip(dests, ref = STABLE_REF) {
|
||||
const unique = [...new Set(dests.filter(Boolean).map((d) => realPath(d)))];
|
||||
if (!unique.length) return;
|
||||
const tmp = await fsp.mkdtemp(path.join(os.tmpdir(), "dsh-purge-upd-"));
|
||||
const zip = path.join(tmp, "master.zip");
|
||||
const res = await fetchRes(ZIP_URL, 45000);
|
||||
const zip = path.join(tmp, "plugin.zip");
|
||||
const res = await fetchRes(archiveZipUrl(ref), 45000);
|
||||
await fsp.writeFile(zip, Buffer.from(await res.arrayBuffer()));
|
||||
extractZip(zip, tmp);
|
||||
const names = await fsp.readdir(tmp);
|
||||
@@ -484,23 +701,31 @@ async function overlayFromZip(dests) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyUpdate(jobs = planUpdates()) {
|
||||
export async function applyUpdate(jobs = planUpdates(), options = {}) {
|
||||
if (!Array.isArray(jobs)) {
|
||||
options = jobs && typeof jobs === "object" ? jobs : {};
|
||||
jobs = planUpdates();
|
||||
}
|
||||
const state = readChannelState();
|
||||
const ref = String(options.ref || currentChannelRef(state) || STABLE_REF);
|
||||
const force = options.force !== false;
|
||||
const zipDirs = [];
|
||||
const vias = new Set();
|
||||
for (const job of jobs) {
|
||||
if (job.kind === "git") {
|
||||
try {
|
||||
gitPull(job.dir);
|
||||
gitResetTo(job.dir, ref, { force });
|
||||
vias.add("git");
|
||||
continue;
|
||||
} catch {
|
||||
} catch (e) {
|
||||
if (!force && /未提交改动/.test(String(e && e.message))) throw e;
|
||||
zipDirs.push(job.dir);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (job.kind === "dsh") {
|
||||
try {
|
||||
dshReinstall(job.profile, job.spec);
|
||||
dshReinstall(job.profile, job.spec, ref);
|
||||
vias.add("dsh");
|
||||
continue;
|
||||
} catch {
|
||||
@@ -511,28 +736,92 @@ export async function applyUpdate(jobs = planUpdates()) {
|
||||
}
|
||||
}
|
||||
if (zipDirs.length) {
|
||||
await overlayFromZip(zipDirs);
|
||||
await overlayFromZip(zipDirs, ref);
|
||||
vias.add("zip");
|
||||
}
|
||||
const sha = (await remoteHeadSha()) || (gitOk() ? gitHead(PLUGIN_ROOT) : "");
|
||||
const sha = (await remoteHeadSha(ref)) || (gitOk() ? gitHead(PLUGIN_ROOT) : "");
|
||||
if (sha) writeStamp(sha);
|
||||
const via = vias.size > 1 ? "mixed" : [...vias][0] || detectVia();
|
||||
const pin = options.pin === false ? "" : (options.pin || state.pin || "");
|
||||
const channel = normalizeChannel(options.channel || state.channel);
|
||||
const saved = writeChannelState({ channel, pin });
|
||||
const localVer = localVersion();
|
||||
pushHistory({
|
||||
ref,
|
||||
sha: sha || "",
|
||||
version: localVer,
|
||||
channel,
|
||||
label: versionLabel(localVer, channel, sha),
|
||||
at: new Date().toISOString(),
|
||||
});
|
||||
const listed = await listRemoteVersions().catch(() => ({ versions: [], hasBeta: saved.channel === "beta" }));
|
||||
return rememberUpdate({
|
||||
ok: true,
|
||||
applied: true,
|
||||
hasUpdate: false,
|
||||
localVersion: localVersion(),
|
||||
remoteVersion: localVersion(),
|
||||
hasBeta: listed.hasBeta,
|
||||
pinned: Boolean(saved.pin),
|
||||
localVersion: localVer,
|
||||
remoteVersion: localVer,
|
||||
localSha: sha ? String(sha).slice(0, 7) : "",
|
||||
remoteSha: sha ? String(sha).slice(0, 7) : "",
|
||||
needRestart: true,
|
||||
via,
|
||||
versions: listed.versions,
|
||||
...channelPublic(saved),
|
||||
});
|
||||
}
|
||||
|
||||
export async function switchChannel(channel, { apply = true } = {}) {
|
||||
const next = normalizeChannel(channel);
|
||||
writeChannelState({ channel: next, pin: "" });
|
||||
if (next === "beta") {
|
||||
const betaSha = await remoteHeadSha(BETA_REF);
|
||||
const tags = await listGithubTags();
|
||||
const hasBeta = Boolean(betaSha || tags.some((item) => item.channel === "beta"));
|
||||
if (!hasBeta) {
|
||||
const stable = writeChannelState({ channel: "stable", pin: "" });
|
||||
return rememberUpdate({
|
||||
ok: false,
|
||||
error: "还没有测试版",
|
||||
hasBeta: false,
|
||||
...channelPublic(stable),
|
||||
versions: [],
|
||||
});
|
||||
}
|
||||
if (!betaSha && apply) {
|
||||
const tag = tags.find((item) => item.channel === "beta");
|
||||
if (tag) return applyUpdate(planUpdates(), { ref: tag.ref, channel: "beta", pin: false, force: true });
|
||||
}
|
||||
}
|
||||
if (!apply) return checkUpdate();
|
||||
return applyUpdate(planUpdates(), { ref: currentChannelRef(), channel: next, pin: false, force: true });
|
||||
}
|
||||
|
||||
export async function switchVersion(ref) {
|
||||
const target = String(ref || "").trim();
|
||||
if (!target) throw new Error("请选择要回退的版本");
|
||||
const listed = await listRemoteVersions();
|
||||
const hit = listed.versions.find((item) => item.ref === target || item.id === target || item.version === target || item.sha === target);
|
||||
const resolved = hit?.ref || target;
|
||||
const channel = hit?.channel || readChannelState().channel;
|
||||
const pin = hit?.latest ? "" : resolved;
|
||||
return applyUpdate(planUpdates(), { ref: resolved, channel, pin, force: true });
|
||||
}
|
||||
|
||||
export async function handleUpdateOp(body = {}) {
|
||||
const op = String(body.op || (body.auto ? "auto" : "apply")).toLowerCase();
|
||||
if (op === "check" || op === "status" || op === "versions") return checkUpdate();
|
||||
if (op === "channel") return switchChannel(body.channel, { apply: body.apply !== false });
|
||||
if (op === "switch" || op === "rollback") return switchVersion(body.ref || body.version || body.id);
|
||||
if (op === "auto") return autoUpdateIfNeeded();
|
||||
return applyUpdate(planUpdates(), { ref: body.ref || currentChannelRef(), pin: false, force: true });
|
||||
}
|
||||
|
||||
export async function autoUpdateIfNeeded() {
|
||||
try {
|
||||
const check = await checkUpdate();
|
||||
if (check.pinned) return rememberUpdate({ ...check, auto: true, skipped: "pinned" });
|
||||
if (!check.hasUpdate) return rememberUpdate({ ...check, auto: true, skipped: "latest" });
|
||||
const jobs = planUpdates();
|
||||
const dirtyGit = jobs.filter((j) => j.kind === "git" && gitTrackedDirty(j.dir));
|
||||
@@ -545,7 +834,7 @@ export async function autoUpdateIfNeeded() {
|
||||
error: "本地插件文件有未提交改动,未自动覆盖",
|
||||
});
|
||||
}
|
||||
const applied = await applyUpdate(runnable);
|
||||
const applied = await applyUpdate(runnable, { ref: currentChannelRef(), pin: false, force: false });
|
||||
return rememberUpdate({ ...applied, auto: true });
|
||||
} catch (e) {
|
||||
return rememberUpdate({
|
||||
@@ -553,6 +842,7 @@ export async function autoUpdateIfNeeded() {
|
||||
auto: true,
|
||||
hasUpdate: false,
|
||||
error: String(e && e.message ? e.message : e),
|
||||
...channelPublic(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user