feat: 发布 1.1.11-beta.1,Skill 导入官方目录并加正式/测试通道

设置页可导入压缩包或文件夹到官方 skills;导入约束路径与符号链接,保存保留官方 frontmatter。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
叫我小杨同学andCursor committed 2026-09-20 16:02:53 +08:00
1 parent d30f3a76e9
commit cff7ebcbb5
8 files changed
+1628 -86

No files matched your search

+337 -47
View File
@@ -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(),
});
}
}