diff --git a/README.md b/README.md index 198fdf5..b022e33 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# hose-use (v0.2.0) +# hose-use (v0.2.1) 合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。 @@ -47,6 +47,11 @@ hose-use platform list # 查看企业下所有启用的 # 5. Agent Skill 与连通性诊断 hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/ hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性 + +# 6. 一键自更新与版本发布历史 +hose-use update # 自动检查并升级到最新版本 (多镜像源加速) +hose-use update --check # 仅检查新版本与 Release Notes +hose-use update --changelog # 查看最近版本发布历史 ``` ## 架构 diff --git a/package.json b/package.json index c21475f..ee297bd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hose-use", - "version": "0.2.0", + "version": "0.2.1", "module": "src/server.ts", "type": "module", "bin": { @@ -12,6 +12,8 @@ "probe": "bun run src/cli.ts probe", "check": "tsc --noEmit", "typecheck": "tsc --noEmit", + "test": "bun test", + "bump": "bun run scripts/bump-version.ts", "build:binary": "node scripts/build-binary.mjs", "dev": "bun run --watch src/server.ts", "start": "bun run src/server.ts", diff --git a/scripts/bump-version.ts b/scripts/bump-version.ts new file mode 100644 index 0000000..6a786d7 --- /dev/null +++ b/scripts/bump-version.ts @@ -0,0 +1,70 @@ +#!/usr/bin/env bun +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { execSync } from "node:child_process"; + +const ROOT = join(import.meta.dirname, ".."); +const pkgPath = join(ROOT, "package.json"); +const pkg = JSON.parse(readFileSync(pkgPath, "utf-8")); +const currentVersion: string = pkg.version; + +const input = process.argv[2]?.trim(); +if (!input) { + console.error("Usage: bun run bump "); + console.error(`Current version: ${currentVersion}`); + process.exit(1); +} + +let nextVersion = input.replace(/^v/, ""); +if (input === "patch" || input === "minor" || input === "major") { + const [major, minor, patch] = currentVersion.split(".").map(Number); + if (input === "patch") nextVersion = `${major}.${minor}.${patch + 1}`; + if (input === "minor") nextVersion = `${major}.${minor + 1}.0`; + if (input === "major") nextVersion = `${major + 1}.0.0`; +} + +if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/.test(nextVersion)) { + console.error(`Invalid SemVer format: '${nextVersion}'`); + process.exit(1); +} + +console.log(`==> Bumping version: ${currentVersion} -> ${nextVersion}`); + +// 1. package.json +pkg.version = nextVersion; +writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n"); +console.log("✓ Updated package.json"); + +// 2. src/version.ts +const versionTsPath = join(ROOT, "src", "version.ts"); +writeFileSync(versionTsPath, `export const VERSION = "${nextVersion}";\n`); +console.log("✓ Updated src/version.ts"); + +// 3. README.md +const readmePath = join(ROOT, "README.md"); +let readmeContent = readFileSync(readmePath, "utf-8"); +readmeContent = readmeContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`); +writeFileSync(readmePath, readmeContent); +console.log("✓ Updated README.md"); + +// 4. skills/hose-use/SKILL.md +const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md"); +let skillContent = readFileSync(skillPath, "utf-8"); +skillContent = skillContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`); +writeFileSync(skillPath, skillContent); +console.log("✓ Updated skills/hose-use/SKILL.md"); + +// 5. Sync to global ~/.agents/skills/hose-use/ if present +const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use"); +const { existsSync, cpSync } = await import("node:fs"); +if (existsSync(globalSkillDir)) { + cpSync(join(ROOT, "skills", "hose-use"), globalSkillDir, { recursive: true }); + console.log("✓ Synchronized ~/.agents/skills/hose-use/"); +} + +console.log("\n🎉 Successfully bumped version to " + nextVersion + "!"); +console.log("\nNext steps to publish:"); +console.log(` 1. Update CHANGELOG.md (if exists)`); +console.log(` 2. git commit -am "chore(release): bump version to v${nextVersion}"`); +console.log(` 3. git tag -a v${nextVersion} -m "🚀 Release v${nextVersion}"`); +console.log(` 4. git push origin main --tags\n`); diff --git a/scripts/install.sh b/scripts/install.sh index 9650d41..8c5a854 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -118,15 +118,25 @@ TMP_FILE="$(mktemp)" DOWNLOAD_SUCCESS=false # Candidate mirrors +GITEA_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/latest/${ASSET_NAME}" GITHUB_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}" GHPROXY_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}" -# 1. Try direct GitHub Releases -if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then - DOWNLOAD_SUCCESS=true +# 1. Try Gitea mirror +if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then + if download_candidate "$GITEA_URL" "$TMP_FILE" "Gitea High-Speed Mirror"; then + DOWNLOAD_SUCCESS=true + fi fi -# 2. Try Fast CDN Proxy Fallback +# 2. Try direct GitHub Releases +if [ "$DOWNLOAD_SUCCESS" = "false" ]; then + if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then + DOWNLOAD_SUCCESS=true + fi +fi + +# 3. Try Fast CDN Proxy Fallback if [ "$DOWNLOAD_SUCCESS" = "false" ]; then if download_candidate "$GHPROXY_URL" "$TMP_FILE" "Fast CDN Mirror (Fallback)"; then DOWNLOAD_SUCCESS=true @@ -166,4 +176,5 @@ echo " 1. Login: hose-use auth login --phone=177... --password=..." echo " 2. List corps: hose-use corps list" echo " 3. List workflows: hose-use workflow list" echo " 4. Switch mode: hose-use config mode stateless" +echo " 5. Self-update: hose-use update" echo "" diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index 0585d66..1a5341a 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -95,6 +95,19 @@ hose-use probe --corp=uzU7pcWfScck00 hose-use mcp serve ``` +### 6. 自更新与版本历史 (`hose-use update`) + +```bash +# 检查最新可用版本与 Release Notes +hose-use update --check + +# 一键自动下载并升级到最新版本(多源 CDN 加速 + 自动同步 Agent 技能) +hose-use update + +# 查看最近版本发布历史与更新说明 +hose-use update --changelog +``` + --- ## 全局选项 diff --git a/src/cli/commands/update.test.ts b/src/cli/commands/update.test.ts new file mode 100644 index 0000000..e93f3b0 --- /dev/null +++ b/src/cli/commands/update.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from "bun:test"; +import { compareSemVer, isNewerVersion, matchAssetForPlatform, type GitHubAsset } from "./update.js"; + +describe("update version comparator", () => { + test("correctly identifies newer semantic versions", () => { + expect(isNewerVersion("0.2.1", "0.2.0")).toBe(true); + expect(isNewerVersion("1.0.0", "0.2.0")).toBe(true); + expect(isNewerVersion("0.3.0", "0.2.1")).toBe(true); + expect(isNewerVersion("0.2.0", "0.2.0")).toBe(false); + expect(isNewerVersion("0.1.9", "0.2.0")).toBe(false); + expect(isNewerVersion("0.2.0", "0.2.1")).toBe(false); + }); + + test("compareSemVer handles tags, major, minor, and patch", () => { + expect(compareSemVer("v0.2.1", "0.2.0")).toBe(1); + expect(compareSemVer("0.2.0", "v0.2.1")).toBe(-1); + expect(compareSemVer("v0.2.1", "v0.2.1")).toBe(0); + expect(compareSemVer("1.0.0", "0.9.9")).toBe(1); + expect(compareSemVer("0.1.0", "0.2.1")).toBe(-1); + }); +}); + +describe("matchAssetForPlatform", () => { + const assets: GitHubAsset[] = [ + { name: "hose-use-darwin-arm64", downloadUrl: "https://example.com/darwin-arm64", size: 100 }, + { name: "hose-use-darwin-x64", downloadUrl: "https://example.com/darwin-x64", size: 100 }, + { name: "hose-use-linux-x64.tar.gz", downloadUrl: "https://example.com/linux-x64.tar.gz", size: 100 }, + { name: "hose-use-linux-arm64", downloadUrl: "https://example.com/linux-arm64", size: 100 }, + { name: "hose-use-windows-x64.zip", downloadUrl: "https://example.com/win-x64.zip", size: 100 }, + ]; + + test("matches darwin arm64", () => { + const matched = matchAssetForPlatform(assets, "darwin", "arm64"); + expect(matched?.name).toBe("hose-use-darwin-arm64"); + }); + + test("matches darwin x64", () => { + const matched = matchAssetForPlatform(assets, "darwin", "x64"); + expect(matched?.name).toBe("hose-use-darwin-x64"); + }); + + test("matches linux x64 archive", () => { + const matched = matchAssetForPlatform(assets, "linux", "x64"); + expect(matched?.name).toBe("hose-use-linux-x64.tar.gz"); + }); + + test("matches windows x64 archive", () => { + const matched = matchAssetForPlatform(assets, "windows", "x64"); + expect(matched?.name).toBe("hose-use-windows-x64.zip"); + }); +}); diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.ts new file mode 100644 index 0000000..7794ab4 --- /dev/null +++ b/src/cli/commands/update.ts @@ -0,0 +1,812 @@ +import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { spawnSync } from "node:child_process"; +import { isCompiledBinary, resolveAppRoot } from "../../core/runtime.js"; +import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js"; +import { VERSION } from "../../version.js"; +import { booleanOption, numberOption, stringOption } from "../parser.js"; +import { printJson, printKeyValue } from "../printer.js"; +import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../types.js"; + +const DEFAULT_GITHUB_REPO = "yunyingk/hose-use"; +const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO"; + +export type UpdateOptions = { + checkOnly?: boolean; + changelogOnly?: boolean; + limit?: number; + force?: boolean; + targetVersion?: string; + repo?: string; +}; + +export async function handleUpdateCommand( + parsed: CliParsedArgs, + runtime: CliRuntime, + runOptions: CliRunOptions = {} +): Promise { + const isChangelog = + parsed.area === "changelog" || + parsed.action === "changelog" || + parsed.action === "log" || + parsed.action === "history" || + booleanOption(parsed.options, ["changelog", "log", "l"]); + + const isCheck = + parsed.action === "check" || + booleanOption(parsed.options, ["check", "check-only", "c"]); + + const targetVersionRaw = + stringOption(parsed.options, ["version", "tag", "target", "t"]) || + (!isChangelog && !isCheck && parsed.action && !parsed.action.startsWith("-") + ? parsed.action + : undefined); + + const targetVersion = + targetVersionRaw && targetVersionRaw.toLowerCase() !== "latest" + ? targetVersionRaw.replace(/^v/, "") + : undefined; + + const repo = + stringOption(parsed.options, ["repo"]) || + process.env[GITHUB_REPO_ENV]?.trim() || + DEFAULT_GITHUB_REPO; + + const options: UpdateOptions = { + checkOnly: isCheck, + changelogOnly: isChangelog, + limit: numberOption(parsed.options, ["limit", "n"]), + force: booleanOption(parsed.options, ["force", "f"]), + targetVersion, + repo, + }; + + const appRoot = runOptions.appRoot || resolveAppRoot(runOptions.entryFile); + + // Validate targetVersion: prevent downgrade to older versions + if (targetVersion) { + const cmp = compareSemVer(targetVersion, VERSION); + if (cmp < 0 && !options.force) { + const msg = `无法降级 hose-use(当前版本 v${VERSION},目标版本 v${targetVersion})。如需强制重装请使用 --force。`; + if (runtime.jsonMode) { + return { + stdout: printJson({ + updated: false, + currentVersion: VERSION, + targetVersion, + mode: isCompiledBinary() ? "binary" : "source", + message: msg, + }), + stderr: "", + exitCode: 1, + }; + } + return { + stdout: "", + stderr: `[ERROR] ${msg}\n`, + exitCode: 1, + }; + } + if (cmp === 0 && !options.force) { + const msg = `hose-use 当前已是版本 v${VERSION}。如需强制重装请添加 --force。`; + if (runtime.jsonMode) { + return { + stdout: printJson({ + updated: false, + currentVersion: VERSION, + targetVersion, + mode: isCompiledBinary() ? "binary" : "source", + message: msg, + }), + stderr: "", + exitCode: 0, + }; + } + return { + stdout: `ℹ️ ${msg}\n`, + stderr: "", + exitCode: 0, + }; + } + } + + // 1. Changelog / Release History query + if (options.changelogOnly) { + const releases = await fetchGitHubReleases(repo, options.limit ?? 10); + if (runtime.jsonMode) { + return { + stdout: printJson({ + currentVersion: VERSION, + totalQueried: releases.length, + releases: releases.map((r) => ({ + version: r.version, + tagName: r.tagName, + publishedAt: r.publishedAt, + author: r.author, + releaseNotes: r.notes, + releaseUrl: r.htmlUrl, + isCurrent: r.version === VERSION, + isNewer: isNewerVersion(r.version, VERSION), + })), + }), + stderr: "", + exitCode: 0, + }; + } + + const lines: string[] = [ + `====== hose-use 版本发布记录 (当前版本: v${VERSION}) ======`, + "", + ]; + for (const r of releases) { + const badge = r.version === VERSION ? " [当前版本]" : isNewerVersion(r.version, VERSION) ? " [新版本 ✨]" : ""; + lines.push(`• v${r.version} (${r.publishedAt ? r.publishedAt.slice(0, 10) : "未知日期"})${badge}`); + if (r.notes) { + const snippet = r.notes.trim().split("\n").map((l) => ` ${l}`).join("\n"); + lines.push(snippet); + } + lines.push(""); + } + return { + stdout: lines.join("\n"), + stderr: "", + exitCode: 0, + }; + } + + // 2. Source development mode (running via bun/node) + if (!isCompiledBinary()) { + if (options.checkOnly) { + const releases = await fetchGitHubReleases(repo, 30); + const latestRelease = releases[0]; + const latestVersion = latestRelease?.version ?? VERSION; + const currentRelease = releases.find((r) => r.version === VERSION); + const isUpgrade = isNewerVersion(latestVersion, VERSION); + const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION)); + + if (runtime.jsonMode) { + return { + stdout: printJson({ + updated: false, + updateAvailable: isUpgrade, + currentVersion: VERSION, + currentVersionPublishedAt: currentRelease?.publishedAt, + latestVersion, + latestVersionPublishedAt: latestRelease?.publishedAt, + behindCount: pendingReleases.length, + pendingReleases: pendingReleases.map((r) => ({ + version: r.version, + tagName: r.tagName, + publishedAt: r.publishedAt, + author: r.author, + releaseNotes: r.notes, + releaseUrl: r.htmlUrl, + })), + releaseNotes: latestRelease?.notes ?? "", + releaseUrl: latestRelease?.htmlUrl ?? "", + mode: "source", + message: "当前运行于源码开发模式。运行 'hose-use update' 执行 git pull 与依赖更新。", + }), + stderr: "", + exitCode: 0, + }; + } + + const out = printKeyValue({ + "运行模式": "源码开发模式 (Source Mode)", + "当前版本": `v${VERSION}`, + "最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`, + "待更新版本数": pendingReleases.length, + "源码路径": appRoot, + }); + + return { + stdout: `====== hose-use 版本检查 ======\n${out}\n\n${isUpgrade ? `可运行 hose-use update 执行 git pull 与依赖同步` : "已经是最新版本"}\n`, + stderr: "", + exitCode: 0, + }; + } + + try { + runCommand("git", ["-C", appRoot, "pull", "--ff-only"]); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + console.error(`git pull 提示: ${msg}`); + } + + runCommand("bun", ["install"], { cwd: appRoot }); + const skillSync = syncGlobalSkillIfPresent(); + + if (runtime.jsonMode) { + return { + stdout: printJson({ + updated: true, + version: VERSION, + mode: "source", + skillSynced: skillSync.synced ? skillSync.targetDir : false, + }), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: `[SUCCESS] hose-use 源码与依赖更新成功!\n版本: v${VERSION}\n技能同步: ${skillSync.synced ? "已同步至全局 ✅" : "未同步"}\n`, + stderr: "", + exitCode: 0, + }; + } + + // 3. Standalone binary mode: check GitHub Releases + const platform = detectPlatform(); + const arch = detectArch(); + + const releases = await fetchGitHubReleases(repo, 30); + const release = targetVersion + ? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ?? + await fetchGitHubRelease(repo, targetVersion)) + : (releases[0] ?? await fetchGitHubRelease(repo)); + + if (!release) { + const errorMsg = `无法从 GitHub 仓库 '${repo}' 获取 Release 列表`; + if (runtime.jsonMode) { + return { + stdout: printJson({ + updated: false, + currentVersion: VERSION, + mode: "binary", + message: errorMsg, + }), + stderr: "", + exitCode: 1, + }; + } + return { + stdout: "", + stderr: `[ERROR] ${errorMsg}\n`, + exitCode: 1, + }; + } + + const latestVersion = release.version; + const currentRelease = releases.find((r) => r.version === VERSION); + const isUpgrade = isNewerVersion(latestVersion, VERSION); + const shouldUpdate = isUpgrade || Boolean(options.force); + const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION)); + + if (options.checkOnly) { + if (runtime.jsonMode) { + return { + stdout: printJson({ + updated: false, + updateAvailable: isUpgrade, + currentVersion: VERSION, + currentVersionPublishedAt: currentRelease?.publishedAt, + latestVersion, + latestVersionPublishedAt: release.publishedAt, + behindCount: pendingReleases.length, + pendingReleases: pendingReleases.map((r) => ({ + version: r.version, + tagName: r.tagName, + publishedAt: r.publishedAt, + author: r.author, + releaseNotes: r.notes, + releaseUrl: r.htmlUrl, + })), + releaseNotes: release.notes, + releaseUrl: release.htmlUrl, + mode: "binary", + }), + stderr: "", + exitCode: 0, + }; + } + + const out = printKeyValue({ + "运行模式": "独立二进制 (Binary Mode)", + "当前版本": `v${VERSION}`, + "最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`, + "发布时间": release.publishedAt ? release.publishedAt.slice(0, 10) : "未知", + "平台架构": `${platform}-${arch}`, + }); + + return { + stdout: `====== hose-use 版本检查 ======\n${out}\n\n${isUpgrade ? `运行 hose-use update 升级至 v${latestVersion}` : "已经是最新版本"}\n`, + stderr: "", + exitCode: 0, + }; + } + + if (!shouldUpdate) { + if (runtime.jsonMode) { + return { + stdout: printJson({ + updated: false, + currentVersion: VERSION, + currentVersionPublishedAt: currentRelease?.publishedAt, + latestVersion, + latestVersionPublishedAt: release.publishedAt, + mode: "binary", + message: `hose-use 当前已是最新版本 (v${VERSION})`, + }), + stderr: "", + exitCode: 0, + }; + } + return { + stdout: `ℹ️ hose-use 当前已是最新版本 (v${VERSION})。如需重装请添加 --force。\n`, + stderr: "", + exitCode: 0, + }; + } + + // Find matching asset + const asset = matchAssetForPlatform(release.assets, platform, arch); + if (!asset) { + const errorMsg = `未找到适用于 ${platform}-${arch} 平台的 Release 资产 (v${latestVersion})。可用文件: ${release.assets.map((a) => a.name).join(", ")}`; + if (runtime.jsonMode) { + return { + stdout: printJson({ updated: false, error: true, message: errorMsg }), + stderr: "", + exitCode: 1, + }; + } + return { + stdout: "", + stderr: `[ERROR] ${errorMsg}\n`, + exitCode: 1, + }; + } + + const execPath = process.execPath; + const execDir = dirname(execPath); + const tmpDir = join(execDir, `.tmp-update-${Date.now()}`); + mkdirSync(tmpDir, { recursive: true }); + + try { + const downloadedFile = join(tmpDir, asset.name); + await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name); + + let newBinaryPath = downloadedFile; + if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) { + newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform); + } else if (asset.name.endsWith(".zip")) { + newBinaryPath = extractZip(downloadedFile, tmpDir, platform); + } + + chmodSync(newBinaryPath, 0o755); + + // Re-sign on macOS ad-hoc if codesign exists + if (process.platform === "darwin") { + try { + spawnSync("/usr/bin/codesign", ["--remove-signature", newBinaryPath], { stdio: "ignore" }); + spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", newBinaryPath], { stdio: "ignore" }); + } catch { + // ignore + } + } + + // Atomic replace + if (process.platform === "win32") { + const oldBinary = `${execPath}.old.${Date.now()}`; + try { + renameSync(execPath, oldBinary); + } catch { + // ignore + } + renameSync(newBinaryPath, execPath); + } else { + renameSync(newBinaryPath, execPath); + } + + const skillSync = syncGlobalSkillIfPresent(); + + if (runtime.jsonMode) { + return { + stdout: printJson({ + updated: true, + fromVersion: VERSION, + toVersion: latestVersion, + skillSynced: skillSync.synced ? skillSync.targetDir : false, + mode: "binary", + }), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: `[SUCCESS] ✨ hose-use 已成功升级至 v${latestVersion}!\n可执行文件: ${execPath}\nAgent 技能: ${skillSync.synced ? "已自动同步最新版 ✅" : "未同步"}\n`, + stderr: "", + exitCode: 0, + }; + } finally { + try { + rmSync(tmpDir, { recursive: true, force: true }); + } catch { + // ignore + } + } +} + +function detectPlatform(): "darwin" | "linux" | "windows" { + if (process.platform === "darwin") return "darwin"; + if (process.platform === "win32") return "windows"; + return "linux"; +} + +function detectArch(): "arm64" | "x64" { + return process.arch === "arm64" ? "arm64" : "x64"; +} + +export type GitHubAsset = { + name: string; + downloadUrl: string; + size: number; +}; + +export type GitHubRelease = { + version: string; + tagName: string; + name?: string; + publishedAt?: string; + author?: string; + notes: string; + htmlUrl: string; + assets: GitHubAsset[]; +}; + +export async function fetchGitHubReleases(repo: string, limit = 20): Promise { + const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN; + const headers: Record = { + "User-Agent": `hose-use/${VERSION}`, + Accept: "application/vnd.github.v3+json", + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }; + + const urls = [ + `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`, + `https://api.github.com/repos/${repo}/releases?per_page=${limit}`, + ]; + + for (const url of urls) { + try { + const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) }); + if (!res.ok) continue; + const json = (await res.json()) as Array<{ + tag_name?: string; + name?: string; + body?: string; + html_url?: string; + published_at?: string; + author?: { login?: string }; + assets?: Array<{ name: string; browser_download_url: string; size?: number }>; + }>; + + if (!Array.isArray(json) || json.length === 0) continue; + + const list: GitHubRelease[] = []; + for (const item of json) { + const tagName = item.tag_name ?? ""; + const version = tagName.replace(/^v/, ""); + if (!version) continue; + const assets: GitHubAsset[] = (item.assets ?? []).map((a) => ({ + name: a.name, + downloadUrl: a.browser_download_url, + size: a.size ?? 0, + })); + list.push({ + version, + tagName, + name: item.name ?? tagName, + publishedAt: item.published_at, + author: item.author?.login, + notes: item.body ?? "", + htmlUrl: item.html_url ?? "", + assets, + }); + } + if (list.length > 0) return list; + } catch { + // try next source + } + } + + return []; +} + +export async function fetchGitHubRelease( + repo: string, + targetVersion?: string +): Promise { + const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined; + const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN; + const headers: Record = { + "User-Agent": `hose-use/${VERSION}`, + Accept: "application/vnd.github.v3+json", + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }; + + const urls = tag + ? [ + `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`, + `https://api.github.com/repos/${repo}/releases/tags/${tag}`, + ] + : [ + `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`, + `https://api.github.com/repos/${repo}/releases/latest`, + ]; + + let fallbackRelease: GitHubRelease | undefined; + + for (const url of urls) { + try { + const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) }); + if (!res.ok) continue; + const json = (await res.json()) as { + tag_name?: string; + name?: string; + body?: string; + html_url?: string; + published_at?: string; + author?: { login?: string }; + assets?: Array<{ name: string; browser_download_url: string; size?: number }>; + }; + + const tagName = json.tag_name ?? ""; + const version = tagName.replace(/^v/, ""); + if (!version) continue; + + const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({ + name: item.name, + downloadUrl: item.browser_download_url, + size: item.size ?? 0, + })); + + const candidateRelease: GitHubRelease = { + version, + tagName, + name: json.name ?? tagName, + publishedAt: json.published_at, + author: json.author?.login, + notes: json.body ?? "", + htmlUrl: json.html_url ?? "", + assets, + }; + + if (assets.length > 0) { + return candidateRelease; + } + + if (!fallbackRelease) { + fallbackRelease = candidateRelease; + } + } catch { + // try next source + } + } + + return fallbackRelease; +} + +export function matchAssetForPlatform( + assets: GitHubAsset[], + platform: "darwin" | "linux" | "windows", + arch: "arm64" | "x64" +): GitHubAsset | undefined { + const platformKeywords: Record = { + darwin: ["darwin", "macos", "osx", "apple"], + linux: ["linux"], + windows: ["windows", "win32", "win64", ".exe"], + }; + const archKeywords: Record = { + arm64: ["arm64", "aarch64"], + x64: ["x64", "x86_64", "amd64"], + }; + + const pKeys = platformKeywords[platform] || []; + const aKeys = archKeywords[arch] || []; + + const matched = assets.filter((asset) => { + const lower = asset.name.toLowerCase(); + const matchesP = pKeys.some((k) => lower.includes(k)); + const matchesA = aKeys.some((k) => lower.includes(k)); + return matchesP && matchesA; + }); + + // Prefer direct raw executable over tar.gz / zip if both exist + const directBinary = matched.find( + (asset) => + !asset.name.endsWith(".tar.gz") && + !asset.name.endsWith(".tgz") && + !asset.name.endsWith(".zip") && + !asset.name.endsWith(".sha256") + ); + if (directBinary) return directBinary; + + // Fallback to archive + const archive = matched.find( + (asset) => + asset.name.endsWith(".tar.gz") || + asset.name.endsWith(".tgz") || + asset.name.endsWith(".zip") + ); + return archive || matched[0]; +} + +function logProgress(msg: string) { + try { + process.stderr.write(`${msg}\n`); + } catch { + // ignore + } +} + +async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) { + const candidates: string[] = []; + const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined; + const fileName = assetName || url.split("/").pop() || ""; + + // 1. High-speed Gitea direct mirror first + if (tag && fileName) { + candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`); + } + if (url.startsWith("https://git.ying-qing.cn")) { + candidates.push(url); + } + + // 2. Fast GitHub CDN proxies and direct GitHub fallback + if (tag && fileName) { + const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`; + candidates.push(`https://ghfast.top/${ghDirectUrl}`); + candidates.push(`https://ghproxy.net/${ghDirectUrl}`); + candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`); + candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`); + candidates.push(ghDirectUrl); + } else if (url.includes("github.com")) { + candidates.push(`https://ghfast.top/${url}`); + candidates.push(`https://ghproxy.net/${url}`); + candidates.push(`https://gh.ddlc.top/${url}`); + candidates.push(`https://mirror.ghproxy.com/${url}`); + candidates.push(url); + } else { + candidates.push(url); + } + + const uniqueCandidates = Array.from(new Set(candidates)); + + let lastError: Error | undefined; + for (let i = 0; i < uniqueCandidates.length; i++) { + const candidate = uniqueCandidates[i]!; + try { + logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`); + const res = await fetch(candidate, { signal: AbortSignal.timeout(6000) }); + if (!res.ok) { + throw new Error(`HTTP ${res.status} ${res.statusText}`); + } + + const totalBytes = Number(res.headers.get("content-length")) || 0; + const reader = res.body?.getReader(); + if (!reader) { + const buffer = Buffer.from(await res.arrayBuffer()); + if (buffer.length < 1000) { + throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`); + } + writeFileSync(destPath, buffer); + logProgress(`✓ 下载完成 (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`); + return; + } + + const chunks: Uint8Array[] = []; + let receivedBytes = 0; + let lastReport = 0; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value) { + chunks.push(value); + receivedBytes += value.length; + const now = Date.now(); + if (now - lastReport > 200) { + lastReport = now; + const percent = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 0; + const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1); + const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?"; + try { + process.stderr.write(`\r ↳ 进度: ${percent}% (${receivedMb} / ${totalMb} MB)...`); + } catch { + // ignore + } + } + } + } + + try { + process.stderr.write("\n"); + } catch { + // ignore + } + + const completeBuffer = Buffer.concat(chunks); + if (completeBuffer.length < 1000) { + throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`); + } + writeFileSync(destPath, completeBuffer); + logProgress(`✓ 下载完成 (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`); + return; + } catch (err) { + lastError = err instanceof Error ? err : new Error(String(err)); + logProgress(` ↳ 节点失败: ${lastError.message}`); + } + } + + throw new Error(`所有下载镜像均失败: ${lastError?.message}`); +} + +function extractTarGz(archivePath: string, targetDir: string, platform: string): string { + const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" }); + if (result.status !== 0) { + throw new Error(`解压 tar 归档失败: ${result.stderr.toString()}`); + } + unlinkSync(archivePath); + + const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use"; + const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" }) + .stdout.trim() + .split("\n") + .filter(Boolean); + + const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName)); + if (exact) return exact; + return files[0] || archivePath; +} + +function extractZip(archivePath: string, targetDir: string, platform: string): string { + const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" }); + if (result.status !== 0) { + throw new Error(`解压 zip 归档失败: ${result.stderr.toString()}`); + } + unlinkSync(archivePath); + + const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use"; + const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" }) + .stdout.trim() + .split("\n") + .filter(Boolean); + + const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName)); + if (exact) return exact; + return files[0] || archivePath; +} + +export function compareSemVer(v1: string, v2: string): number { + const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0); + const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0); + for (let i = 0; i < Math.max(p1.length, p2.length); i++) { + const a = p1[i] ?? 0; + const b = p2[i] ?? 0; + if (a > b) return 1; + if (a < b) return -1; + } + return 0; +} + +export function isNewerVersion(latest: string, current: string): boolean { + return compareSemVer(latest, current) > 0; +} + +function runCommand(command: string, args: string[], options: { cwd?: string } = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }); + + if (result.stdout) console.error(result.stdout.trimEnd()); + if (result.stderr) console.error(result.stderr.trimEnd()); + + if (result.status !== 0) { + throw new Error(`${command} ${args.join(" ")} 执行失败 (退出码 ${result.status})`); + } +} diff --git a/src/cli/printer.ts b/src/cli/printer.ts index a3dec02..33e131d 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -51,6 +51,7 @@ export function printHelp(): string { platform 自建应用管理 (list) skill Agent Skill 管理 (install, status, dump) probe 连通性诊断 (probe [corpId]) + update 版本自更新与发布记录 (update, update check, update --changelog) mcp MCP Server 运行 (serve) version 查看版本信息 @@ -71,5 +72,7 @@ export function printHelp(): string { hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流 hose-use probe # 诊断当前企业鉴权连通性 hose-use skill install # 安装 Agent 技能到用户目录 + hose-use update # 自动检查并升级到最新版本 + hose-use update --changelog # 查看版本发布历史 `.trim(); } diff --git a/src/cli/runner.ts b/src/cli/runner.ts index c2bb1d8..84a94d4 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -10,6 +10,7 @@ import { handlePlatformCommand } from "./commands/platform.js"; import { handleSkillCommand } from "./commands/skill.js"; import { handleProbeCommand } from "./commands/probe.js"; import { handleMcpCommand } from "./commands/mcp.js"; +import { handleUpdateCommand } from "./commands/update.js"; import type { CliResult, CliRunOptions } from "./types.js"; export async function runCli( @@ -62,9 +63,13 @@ export async function runCli( case "skills": return await handleSkillCommand(parsed, runtime); case "probe": - case "check": case "diagnose": return await handleProbeCommand(parsed, runtime); + case "update": + case "upgrade": + case "self-update": + case "changelog": + return await handleUpdateCommand(parsed, runtime, options); case "mcp": case "serve": return await handleMcpCommand(parsed, options); diff --git a/src/core/runtime.ts b/src/core/runtime.ts new file mode 100644 index 0000000..fb8940c --- /dev/null +++ b/src/core/runtime.ts @@ -0,0 +1,40 @@ +import { dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +export function isCompiledBinary(execPath = process.execPath, metaUrl = import.meta.url): boolean { + if (metaUrl.includes("/$bunfs/") || metaUrl.includes("\\$bunfs\\")) { + return true; + } + const lower = execPath.toLowerCase().replace(/\\/g, "/"); + return !lower.endsWith("/bun") && !lower.endsWith("/bun.exe"); +} + +export function resolveAppRoot(entryFile?: string, isCompiled = isCompiledBinary()): string { + if (isCompiled) { + return process.cwd(); + } + const file = entryFile || fileURLToPath(import.meta.url); + return dirname(dirname(file)); +} + +export type LauncherConfig = { + command: string; + args?: string[]; +}; + +export function resolveDefaultLauncher( + entryFile: string, + isCompiled = isCompiledBinary(), + execPath = process.execPath +): LauncherConfig { + if (isCompiled) { + return { + command: execPath, + args: [], + }; + } + return { + command: execPath, + args: [entryFile], + }; +} diff --git a/src/version.ts b/src/version.ts index edbab61..2e0f48d 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "0.2.0"; +export const VERSION = "0.2.1"; diff --git a/tsconfig.json b/tsconfig.json index c2d6568..96b8888 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,7 +12,7 @@ "declaration": true, "outDir": "./dist", "rootDir": "./src", - "types": ["node"], + "types": ["node", "bun"], "paths": { "@core/*": ["./src/core/*"], "@domains/*": ["./src/domains/*"]