mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 08:40:22 +08:00
feat: 发布 1.1.12,测试版 Skill 进入正式版
正式版带上 Skill 导入,并保留不再钉上一轮全文、按提交号标当前和拒绝跨站请求。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
9c1a002cf5
9 files changed
+1389
-108
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);
|
||||
|
||||
+207
-3
@@ -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,
|
||||
@@ -398,7 +399,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>)",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -512,6 +514,106 @@ async function handleRulesCommand(rawInput) {
|
||||
}
|
||||
}
|
||||
|
||||
function renderSkillsStatus(st) {
|
||||
const out = [];
|
||||
out.push("官方用户 Skill / $DSH_HOME/skills");
|
||||
out.push(` ${st.skills_dir}`);
|
||||
out.push(" 插件只安装目录。调用走官方:任务对上 description/whenToUse 时模型调 skill 工具;聊天输入 /名称 立即加载。");
|
||||
out.push(" 正文里写「激活」不会触发。官方认 name、description、whenToUse、disable-model-invocation、user-invocable。");
|
||||
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 || "(无说明)";
|
||||
const how = item.valid
|
||||
? [
|
||||
item.userInvocable ? `/${item.id}` : "不可 /名称",
|
||||
item.modelInvocable ? "模型可调" : "模型不可调",
|
||||
].join(" · ")
|
||||
: "";
|
||||
out.push(` ${mark} ${item.id} ${desc} (${skills.formatSize(item.size)})`);
|
||||
if (how) out.push(` ${how}`);
|
||||
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" +
|
||||
" 调用:聊天输入 /<id>,或让模型按 description 调 skill 工具\n" +
|
||||
" 不注入 systemPrompt,不替代提示词",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function apply(ctx, config) {
|
||||
const cfg = { ...DEFAULTS, ...(config || {}) };
|
||||
if (!cfg.enabled) return;
|
||||
@@ -573,6 +675,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",
|
||||
@@ -796,6 +904,7 @@ function installWebServer(ctx, cfg) {
|
||||
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) });
|
||||
@@ -1131,6 +1240,7 @@ function installWebServer(ctx, cfg) {
|
||||
},
|
||||
}, "dsh-purge: override");
|
||||
installRulesHttp(host.webServer);
|
||||
installSkillsHttp(host.webServer);
|
||||
registerPluginRoute({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/restart",
|
||||
@@ -1235,6 +1345,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, {
|
||||
@@ -1290,13 +1493,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();
|
||||
|
||||
+592
@@ -0,0 +1,592 @@
|
||||
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;
|
||||
}
|
||||
|
||||
function yamlBoolField(head, key) {
|
||||
const re = new RegExp(`^${key}:\\s*(.*)$`, "m");
|
||||
const match = String(head || "").match(re);
|
||||
if (!match) return { present: false };
|
||||
let value = match[1].trim();
|
||||
if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1).trim();
|
||||
}
|
||||
const comment = value.indexOf(" #");
|
||||
if (comment >= 0) value = value.slice(0, comment).trim();
|
||||
const norm = value.toLowerCase();
|
||||
if (["true", "yes", "on", "1"].includes(norm)) return { present: true, value: true };
|
||||
if (["false", "no", "off", "0"].includes(norm)) return { present: true, value: false };
|
||||
return { present: true, invalid: true };
|
||||
}
|
||||
|
||||
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 必填(单行)" };
|
||||
const disableModel = yamlBoolField(parts.head, "disable-model-invocation");
|
||||
const userInvocable = yamlBoolField(parts.head, "user-invocable");
|
||||
if (disableModel.invalid) return { ok: false, error: "disable-model-invocation 必须是布尔值(true/false)" };
|
||||
if (userInvocable.invalid) return { ok: false, error: "user-invocable 必须是布尔值(true/false)" };
|
||||
return {
|
||||
ok: true,
|
||||
name,
|
||||
description,
|
||||
whenToUse: yamlLineField(parts.head, "whenToUse"),
|
||||
modelInvocable: disableModel.value !== true,
|
||||
userInvocable: userInvocable.value !== false,
|
||||
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 : "",
|
||||
whenToUse: parsed.ok ? parsed.whenToUse : "",
|
||||
modelInvocable: parsed.ok ? parsed.modelInvocable : false,
|
||||
userInvocable: parsed.ok ? parsed.userInvocable : false,
|
||||
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),
|
||||
})),
|
||||
};
|
||||
}
|
||||
+18
-7
@@ -70,6 +70,11 @@ function isBetaName(name) {
|
||||
return /(?:^|[-._])(beta|rc|pre|preview|test)(?:\d|$|[-._])/i.test(String(name || ""));
|
||||
}
|
||||
|
||||
function withdrawnVersion(item) {
|
||||
const text = [item?.version, item?.ref, item?.id].filter(Boolean).join(" ");
|
||||
return /(?:^|[\sv])1\.1\.11-beta/i.test(String(text).replace(/^v/i, " "));
|
||||
}
|
||||
|
||||
function splitVersion(raw) {
|
||||
const text = String(raw || "").trim().replace(/^v/i, "");
|
||||
const cut = text.split("-");
|
||||
@@ -124,7 +129,8 @@ function currentChannelRef(state = readChannelState()) {
|
||||
|
||||
function readHistory() {
|
||||
const raw = readJson(historyPath());
|
||||
return Array.isArray(raw) ? raw : [];
|
||||
const rows = Array.isArray(raw) ? raw : [];
|
||||
return rows.filter((item) => item && !withdrawnVersion(item));
|
||||
}
|
||||
|
||||
function pushHistory(entry) {
|
||||
@@ -564,9 +570,11 @@ async function listRemoteVersions() {
|
||||
latest: true,
|
||||
});
|
||||
}
|
||||
for (const tag of tags) add(tag);
|
||||
for (const tag of tags) {
|
||||
if (!withdrawnVersion(tag)) add(tag);
|
||||
}
|
||||
for (const item of readHistory()) {
|
||||
if (!item || !item.ref) continue;
|
||||
if (!item || !item.ref || withdrawnVersion(item)) continue;
|
||||
add({
|
||||
...item,
|
||||
label: item.label || versionLabel(item.version, item.channel, item.sha),
|
||||
@@ -577,7 +585,7 @@ async function listRemoteVersions() {
|
||||
const localVer = localVersion();
|
||||
const localSha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || readStamp();
|
||||
return {
|
||||
versions: markCurrent(out, state, localVer, localSha),
|
||||
versions: markCurrent(out.filter((item) => !withdrawnVersion(item)), state, localVer, localSha),
|
||||
hasBeta: Boolean(betaSha || out.some((item) => item.channel === "beta" && item.kind === "tag")),
|
||||
stableSha,
|
||||
betaSha,
|
||||
@@ -840,7 +848,7 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) {
|
||||
await overlayFromZip(zipDirs, ref);
|
||||
vias.add("zip");
|
||||
}
|
||||
const sha = (await remoteHeadSha(ref)) || (gitOk() ? gitHead(PLUGIN_ROOT) : "");
|
||||
const sha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || (await remoteHeadSha(ref).catch(() => ""));
|
||||
if (sha) writeStamp(sha);
|
||||
const via = vias.size > 1 ? "mixed" : [...vias][0] || detectVia();
|
||||
const pin = options.pin === false ? "" : (options.pin || state.pin || "");
|
||||
@@ -866,7 +874,8 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) {
|
||||
remoteVersion: localVer,
|
||||
localSha: sha ? String(sha).slice(0, 7) : "",
|
||||
remoteSha: sha ? String(sha).slice(0, 7) : "",
|
||||
needRestart: true,
|
||||
needRestart: false,
|
||||
reloadClient: true,
|
||||
via,
|
||||
versions: listed.versions,
|
||||
lanes: lanesOf(listed, saved, localVer, sha),
|
||||
@@ -915,7 +924,9 @@ function listedUpdateRef(target, listed) {
|
||||
}
|
||||
|
||||
export async function switchVersion(ref) {
|
||||
const target = safeUpdateRef(ref);
|
||||
const raw = String(ref || "").trim();
|
||||
if (withdrawnVersion({ ref: raw, version: raw })) throw new Error("该版本已下线");
|
||||
const target = safeUpdateRef(raw);
|
||||
if (!target) throw new Error("请选择要回退的版本");
|
||||
const listed = await listRemoteVersions();
|
||||
const resolved = listedUpdateRef(target, listed);
|
||||
|
||||
Reference in new issue
Block a user