feat: install development build globally

This commit is contained in:
gitea committed 2026-09-11 17:35:29 +08:00
1 parent 7cfb68e434
commit 3e072b490e
9 files changed
+249 -9

No files matched your search

+13
View File
@@ -17,6 +17,19 @@ bun install
bun run cli <command>
```
### 方式三:将当前工作区安装为全局开发版
开发过程中需要让 PATH 中的 `hose-use` 立即使用当前源码时:
```bash
bun run dev:override
hose-use version
```
该命令会构建本机二进制、原子替换全局 `hose-use`,同步 `~/.agents/skills/hose-use`,并保留 `hose-aipro` 别名;后台服务若正在运行会自动重启。只预览动作可运行 `bun run dev:override -- --dry-run`。
> 开发版安装会覆盖当前 PATH 中的 `hose-use`,适合本机测试;发布环境请使用正式 Release 安装脚本。不要用 `npm install -g .` 代替,它会留下不会随源码更新的旧副本。
---
### CLI 常用命令速查 (`hose-use`)
+2
View File
@@ -22,6 +22,8 @@
"openapi:all": "bun run scripts/generate-raw-openapi.ts && bun run scripts/bundle-openapi.ts",
"build:binary": "node scripts/build-binary.mjs",
"build:plugin": "node scripts/build-plugin.mjs",
"dev:override": "bun run scripts/dev-override.ts",
"dev:link": "bun run scripts/dev-override.ts",
"dev": "bun run --watch src/server.ts",
"start": "bun run src/server.ts",
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, test } from "bun:test";
import { globalBinCandidates, parseDevOverrideArgs } from "./dev-override.js";
describe("dev:override", () => {
test("parses dry-run and explicit target path without touching the host", () => {
expect(parseDevOverrideArgs(["--dry-run", "--target-path=/tmp/hose-use-test"])).toEqual({
dryRun: true,
targetPath: "/tmp/hose-use-test",
});
});
test("uses stable global binary locations", () => {
const candidates = globalBinCandidates("hose-use-test");
expect(candidates.some((candidate) => candidate.endsWith("/hose-use-test"))).toBe(true);
expect(candidates).toHaveLength(4);
});
});
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env bun
import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
export interface DevOverrideOptions {
dryRun: boolean;
targetPath?: string;
}
export function parseDevOverrideArgs(argv: string[]): DevOverrideOptions {
return {
dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"),
targetPath: argv.find((arg) => arg.startsWith("--target-path="))?.slice("--target-path=".length),
};
}
export function globalBinCandidates(commandName = "hose-use"): string[] {
return [
"/opt/homebrew/bin",
"/usr/local/bin",
join(homedir(), ".local", "bin"),
join(homedir(), "bin"),
].map((dir) => join(dir, commandName));
}
export function resolveTargetBinaryPath(commandName = "hose-use"): string {
try {
const whichRes = spawnSync("which", [commandName], { encoding: "utf8" });
if (whichRes.status === 0 && whichRes.stdout) {
const path = whichRes.stdout.trim();
if (path && existsSync(path)) return path;
}
} catch {
// Fall back to conventional user-level locations.
}
for (const candidate of globalBinCandidates(commandName)) {
if (existsSync(dirname(candidate))) return candidate;
}
const defaultDir = join(homedir(), ".local", "bin");
mkdirSync(defaultDir, { recursive: true });
return join(defaultDir, commandName);
}
function runBuild(): string {
const result = spawnSync("node", ["scripts/build-binary.mjs"], {
cwd: ROOT,
stdio: ["ignore", "inherit", "inherit"],
});
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(`构建开发版二进制失败,退出码: ${result.status ?? 1}`);
const localBinary = join(ROOT, "dist", "bin", "hose-use");
if (!existsSync(localBinary)) throw new Error(`未找到构建产物: ${localBinary}`);
return localBinary;
}
function stopRunningService(targetPath: string): boolean {
try {
const statusRes = spawnSync(targetPath, ["service", "status", "--json"], { encoding: "utf8" });
if (statusRes.status !== 0 || !statusRes.stdout) return false;
const status = JSON.parse(statusRes.stdout) as { running?: boolean };
if (!status.running) return false;
console.error("==> [dev:override] 停止正在运行的后台服务...");
const stopRes = spawnSync(targetPath, ["service", "stop"], { stdio: "ignore" });
if (stopRes.status !== 0) throw new Error("无法停止后台服务,已中止替换操作");
return true;
} catch (error) {
if (error instanceof Error && error.message.includes("无法停止")) throw error;
return false;
}
}
function installBinary(localBinary: string, targetPath: string): void {
const targetDir = dirname(targetPath);
mkdirSync(targetDir, { recursive: true });
const temporaryPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
try {
copyFileSync(localBinary, temporaryPath);
chmodSync(temporaryPath, 0o755);
if (process.platform === "darwin") {
spawnSync("/usr/bin/codesign", ["--remove-signature", temporaryPath], { stdio: "ignore" });
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", temporaryPath], { stdio: "ignore" });
}
// copyFileSync follows an existing symlink, so a package-manager shim is not
// accidentally replaced by a regular file.
copyFileSync(temporaryPath, targetPath);
chmodSync(targetPath, 0o755);
} finally {
rmSync(temporaryPath, { force: true });
}
}
function syncAgentSkill(): string | undefined {
const source = join(ROOT, "skills", "hose-use");
const target = join(homedir(), ".agents", "skills", "hose-use");
if (!existsSync(source)) return undefined;
mkdirSync(dirname(target), { recursive: true });
cpSync(source, target, { recursive: true, force: true });
return target;
}
export async function main(argv = process.argv.slice(2)): Promise<number> {
const options = parseDevOverrideArgs(argv);
const targetPath = options.targetPath || resolveTargetBinaryPath();
console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use");
console.error(` 工作区: ${ROOT}`);
console.error(` 目标: ${targetPath}`);
if (options.dryRun) {
console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/hose-use");
return 0;
}
const builtBinary = runBuild();
const serviceWasRunning = stopRunningService(targetPath);
installBinary(builtBinary, targetPath);
const aiproPath = join(dirname(targetPath), "hose-aipro");
if (aiproPath !== targetPath) {
rmSync(aiproPath, { force: true });
symlinkSync(targetPath, aiproPath);
}
try {
const skillTarget = syncAgentSkill();
if (skillTarget) console.error(`✓ [dev:override] 已同步 Agent Skill: ${skillTarget}`);
} catch (error) {
console.error(`⚠️ [dev:override] Agent Skill 同步失败: ${error}`);
}
if (serviceWasRunning) {
console.error("==> [dev:override] 使用新二进制重启后台服务...");
const startRes = spawnSync(targetPath, ["service", "start"], { stdio: "ignore" });
if (startRes.status !== 0) console.error("⚠️ [dev:override] 后台服务重启失败,请手动运行 hose-use service start");
}
const versionRes = spawnSync(targetPath, ["version"], { encoding: "utf8" });
if (versionRes.status !== 0) throw new Error(versionRes.stderr || "开发版安装后校验失败");
console.error("✨ [dev:override] 全局开发版安装完成");
process.stdout.write(versionRes.stdout || "");
return 0;
}
if (import.meta.main) {
main().catch((error) => {
console.error(`❌ [dev:override] ${error instanceof Error ? error.message : String(error)}`);
process.exitCode = 1;
});
}
+1
View File
@@ -25,6 +25,7 @@ metadata:
4. **密钥安全**:`keys` 默认在表格和 JSON 中脱敏 `appSecurity`;只有用户明确需要完整凭证时才使用 `--reveal`/`-r`。不要把明文密钥写入日志、共享文件、提示词或聊天回复;尤其不要组合 `--reveal -o <path>`。
5. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
6. **写操作两阶段确认**:所有 CLI 写操作先使用 `--dry-run` 查看目标和变更,再使用同一命令追加 `--yes` 或 `--confirm` 执行;未确认时不会发起写请求或写入本地状态。
7. **开发版全局安装**:需要让 PATH 中的命令立即跟随当前工作区时,运行 `bun run dev:override`;它会构建本机二进制、同步 Agent Skill,并更新全局 `hose-use` / `hose-aipro`。可先用 `bun run dev:override -- --dry-run` 查看计划;不要使用 `npm install -g .` 留下静态旧副本。
---
+10
View File
@@ -25,6 +25,16 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
delete process.env.HOSE_APPROVAL_DB;
});
test("version/help --json only emit machine-readable stdout", async () => {
const version = await runAiProCli(["version", "--json"]);
const help = await runAiProCli(["help", "--json"]);
expect(JSON.parse(version.stdout)).toEqual({ name: "hose-aipro", version: expect.any(String) });
expect(JSON.parse(help.stdout).help).toContain("hose-aipro");
expect(version.stderr).toBe("");
expect(help.stderr).toBe("");
});
test("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => {
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
+22 -5
View File
@@ -53,6 +53,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
}
const command = (positional[0] || "help").toLowerCase();
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
const args = positional.slice(1);
const corpId = corp?.corpId || corp?.id;
@@ -73,6 +74,16 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
};
try {
if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) {
return {
stdout: jsonMode
? printJson({ name: "hose-aipro", version: VERSION }) + "\n"
: `hose-aipro v${VERSION}\n`,
stderr: "",
exitCode: 0,
};
}
switch (command) {
// ── 0. 运行时上下文与身份诊断 (status / whoami / context / info) ────────
case "status":
@@ -1136,7 +1147,11 @@ ${corpBanner}
7. 全流程监控日志流水查看:
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
`;
return { stdout: helpText.trim() + "\n", stderr: "", exitCode: 0 };
return {
stdout: jsonMode ? printJson({ help: helpText.trim() }) + "\n" : helpText.trim() + "\n",
stderr: "",
exitCode: 0,
};
}
}
} catch (err: any) {
@@ -1151,8 +1166,8 @@ ${corpBanner}
summary: err.message.replace(/\n+/g, " "),
});
return {
stdout: "",
stderr: `\n${err.message}\n`,
stdout: jsonMode ? printJson({ error: true, message: err.message, exitCode: 1 }) + "\n" : "",
stderr: jsonMode ? "" : `\n${err.message}\n`,
exitCode: 1,
};
}
@@ -1167,8 +1182,10 @@ ${corpBanner}
});
return {
stdout: "",
stderr: `[AI PRO 错误] ${err?.message || err}\n`,
stdout: jsonMode
? printJson({ error: true, message: String(err?.message || err), exitCode: 1 }) + "\n"
: "",
stderr: jsonMode ? "" : `[AI PRO 错误] ${err?.message || err}\n`,
exitCode: 1,
};
}
+10
View File
@@ -88,4 +88,14 @@ describe("CLI runner - version and help aliases", () => {
expect(command.stdout).toContain("publish");
expect(command.stdout).toContain("发布并启用工作流");
});
it("keeps help and version machine-readable when --json is requested", async () => {
const help = await runCli(["help", "workflow", "--json"]);
const version = await runCli(["version", "--json"]);
expect(JSON.parse(help.stdout).help).toContain("workflow -");
expect(JSON.parse(version.stdout)).toEqual({ name: "hose-use", version: VERSION });
expect(help.stderr).toBe("");
expect(version.stderr).toBe("");
});
});
+15 -4
View File
@@ -66,11 +66,13 @@ async function runCliOnce(
): Promise<CliResult> {
const stdoutChunks: string[] = [];
const stderrChunks: string[] = [];
const machineJson = booleanOption(parseArgs(rawArgs).options, ["json", "j"]);
const originalLog = console.log;
const originalError = console.error;
console.log = (...values: unknown[]) => {
stdoutChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
const line = values.map((v) => (typeof v === "string" ? v : String(v))).join(" ");
(machineJson ? stderrChunks : stdoutChunks).push(line);
};
console.error = (...values: unknown[]) => {
stderrChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
@@ -129,16 +131,25 @@ async function dispatchCli(
options: CliRunOptions = {}
): Promise<CliResult> {
const parsed = parseArgs(rawArgs);
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
if (isHelpRequested(parsed)) {
return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 };
const help = printHelp(resolveHelpTarget(parsed));
return {
stdout: jsonMode ? printJson({ help }) : `${help}\n`,
stderr: "",
exitCode: 0,
};
}
if (isVersionRequested(parsed)) {
return { stdout: `hose-use v${VERSION}\n`, stderr: "", exitCode: 0 };
return {
stdout: jsonMode ? printJson({ name: "hose-use", version: VERSION }) : `hose-use v${VERSION}\n`,
stderr: "",
exitCode: 0,
};
}
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
const statelessOption = booleanOption(parsed.options, ["stateless"]);
const statefulOption = booleanOption(parsed.options, ["stateful"]);