1. 架构对称性与声明式注册表抽取:
- 新增 src/cli/aipro-registry.ts,声明式定义 AIPRO_COMMAND_REGISTRY 及其别名映射与 mutating 突变检查
- 重构 src/aipro-cli.ts,移除过程式 switch-case 分发,改为查表式声明分发,与 hose-use 的 CLI_COMMAND_REGISTRY 保持 100% 对称
- 在 src/cli/registry.ts 统一重导出 aipro-registry,巩固其作为顶层声明注册表的单一事实源地位
- 增加 aipro-cli 测试用例,强制校验 COMMAND_METADATA["hose-aipro"] 与声明式注册表双向一致性
2. 双 Skill 独立打包与内嵌部署:
- 注册两个独立技能:skills/hose-use 与 skills/hose-aipro,互相关联引用
- src/packaging/embedded-skill.ts 增加双 Skill 编译期嵌入与 installSkillFiles 全量同步
- hose-use / hose-aipro 下的 skill status/dump/install 完全对齐
3. 守护服务交叉治理:
- src/cli/service.ts 支持 ServiceTargetName ("hose-use" | "hose-aipro"),默认端口 8888 与 8889
- 支持 hose-use aipro <start|stop|...> 与 hose-aipro hose-use <start|stop|...> 双向服务纳管
- 误触非本领域业务命令时提供友好互导拦截
4. 审批领域数据层防御加固:
- 迁移 004:approval_runs 增加 short_id 唯一约束
- 增加 allocateUniqueShortId 冲突重试,多步写操作纳入事务
5. 版本升级至 v0.9.0:
- package.json、README.md、specs、.zcode-plugin 及两套 Skill 同步更新至 0.9.0
- bump-version 脚本适配多 Skill 自动递增
321 lines
9.7 KiB
TypeScript
321 lines
9.7 KiB
TypeScript
import { spawn, execFileSync } from "node:child_process";
|
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { homedir } from "node:os";
|
|
import {
|
|
startHttpServer,
|
|
DEFAULT_HTTP_PORT,
|
|
DEFAULT_AIPRO_HTTP_PORT,
|
|
DEFAULT_HTTP_HOST,
|
|
} from "../http/server.js";
|
|
import { VERSION } from "../version.js";
|
|
import type { CliRuntime } from "./types.js";
|
|
|
|
export type ServiceTargetName = "hose-use" | "hose-aipro";
|
|
|
|
export const SERVICE_STATE_DIR =
|
|
process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
|
|
|
export type ServiceConfig = {
|
|
serviceName?: ServiceTargetName;
|
|
serviceTitle?: string;
|
|
appRoot: string;
|
|
entryFile: string;
|
|
stateDir: string;
|
|
version?: string;
|
|
launcher?: {
|
|
command: string;
|
|
args?: string[];
|
|
};
|
|
port?: number;
|
|
host?: string;
|
|
pidFileName?: string;
|
|
logFileName?: string;
|
|
};
|
|
|
|
export function getHoseUseServiceConfig(
|
|
runtime?: Partial<CliRuntime>,
|
|
options?: { port?: number; host?: string }
|
|
): ServiceConfig {
|
|
const appRoot = runtime?.appRoot || process.cwd();
|
|
return {
|
|
serviceName: "hose-use",
|
|
serviceTitle: "hose-use 常驻服务管理 (Service)",
|
|
appRoot,
|
|
entryFile: runtime?.entryFile || join(appRoot, "src", "cli.ts"),
|
|
stateDir: SERVICE_STATE_DIR,
|
|
version: VERSION,
|
|
launcher: runtime?.launcher,
|
|
port: options?.port,
|
|
host: options?.host,
|
|
pidFileName: "service.pid",
|
|
logFileName: "service.log",
|
|
};
|
|
}
|
|
|
|
export function getAiProServiceConfig(
|
|
runtime?: Partial<CliRuntime>,
|
|
options?: { port?: number; host?: string }
|
|
): ServiceConfig {
|
|
const appRoot = runtime?.appRoot || process.cwd();
|
|
return {
|
|
serviceName: "hose-aipro",
|
|
serviceTitle: "hose-aipro 审批网关常驻服务 (Service)",
|
|
appRoot,
|
|
entryFile: join(appRoot, "src", "aipro-cli.ts"),
|
|
stateDir: SERVICE_STATE_DIR,
|
|
version: VERSION,
|
|
launcher: runtime?.launcher,
|
|
port: options?.port,
|
|
host: options?.host,
|
|
pidFileName: "aipro-service.pid",
|
|
logFileName: "aipro-service.log",
|
|
};
|
|
}
|
|
|
|
export async function runServiceCommand(
|
|
action: string | undefined,
|
|
config: ServiceConfig,
|
|
options: { quiet?: boolean } = {}
|
|
) {
|
|
const targetLabel = config.serviceName || "hose-use";
|
|
switch (action) {
|
|
case "run":
|
|
await runService(config);
|
|
return undefined;
|
|
case "start":
|
|
return startService(config);
|
|
case "stop":
|
|
return stopService(config, options);
|
|
case "restart":
|
|
stopService(config, { quiet: true });
|
|
return startService(config);
|
|
case "logs":
|
|
case "log":
|
|
return readServiceLogs(config);
|
|
case "status":
|
|
case undefined:
|
|
return serviceStatus(config);
|
|
default:
|
|
throw new Error(`用法: ${targetLabel} service <start|stop|restart|status|logs|poll>`);
|
|
}
|
|
}
|
|
|
|
export function serviceStatus(config: ServiceConfig) {
|
|
const pidFile = getPidFile(config);
|
|
const pid = readServicePid(pidFile);
|
|
const running = pid ? isHoseServiceProcess(pid, config.appRoot, config.serviceName) : false;
|
|
|
|
if (pid && !running) {
|
|
rmSync(pidFile, { force: true });
|
|
}
|
|
|
|
const isAiPro = config.serviceName === "hose-aipro";
|
|
const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT;
|
|
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort);
|
|
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
|
|
|
return {
|
|
running,
|
|
serviceName: config.serviceName || "hose-use",
|
|
serviceTitle:
|
|
config.serviceTitle ||
|
|
(isAiPro
|
|
? "hose-aipro 审批网关常驻服务 (Service)"
|
|
: "hose-use 常驻服务管理 (Service)"),
|
|
pid: running ? pid : undefined,
|
|
version: config.version,
|
|
port,
|
|
host,
|
|
url: running ? `http://${host}:${port}` : undefined,
|
|
appRoot: config.appRoot,
|
|
stateDir: config.stateDir,
|
|
pidFile,
|
|
logFile: getLogFile(config),
|
|
};
|
|
}
|
|
|
|
async function runService(config: ServiceConfig) {
|
|
const pidFile = getPidFile(config);
|
|
const logFile = getLogFile(config);
|
|
ensureStateDir(config.stateDir);
|
|
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
|
|
|
|
const isAiPro = config.serviceName === "hose-aipro";
|
|
const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT;
|
|
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort);
|
|
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
|
|
|
appendLog(logFile, `${config.serviceName || "hose-use"} service starting on http://${host}:${port} pid=${process.pid}`);
|
|
|
|
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
|
|
try {
|
|
server = await startHttpServer({
|
|
port,
|
|
host,
|
|
silent: true,
|
|
app: isAiPro ? "hose-aipro" : "hose-use",
|
|
});
|
|
appendLog(logFile, `${config.serviceName || "hose-use"} service listening pid=${process.pid}`);
|
|
} catch (err: unknown) {
|
|
appendLog(logFile, `${config.serviceName || "hose-use"} service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
|
|
if (readServicePid(pidFile) === process.pid) {
|
|
rmSync(pidFile, { force: true });
|
|
}
|
|
throw err;
|
|
}
|
|
|
|
const cleanup = () => {
|
|
if (server) {
|
|
server.close();
|
|
server = null;
|
|
}
|
|
if (readServicePid(pidFile) === process.pid) {
|
|
rmSync(pidFile, { force: true });
|
|
}
|
|
appendLog(logFile, `${config.serviceName || "hose-use"} service stopped pid=${process.pid}`);
|
|
};
|
|
|
|
await new Promise<void>((resolve) => {
|
|
let stopped = false;
|
|
const stop = () => {
|
|
if (stopped) return;
|
|
stopped = true;
|
|
cleanup();
|
|
process.off("SIGTERM", stop);
|
|
process.off("SIGINT", stop);
|
|
resolve();
|
|
};
|
|
process.once("SIGTERM", stop);
|
|
process.once("SIGINT", stop);
|
|
});
|
|
}
|
|
|
|
function startService(config: ServiceConfig) {
|
|
ensureStateDir(config.stateDir);
|
|
const current = serviceStatus(config);
|
|
if (current.running) {
|
|
return current;
|
|
}
|
|
|
|
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
|
|
const serviceArgs = [...(launcher.args ?? []), "service", "run"];
|
|
if (config.port) serviceArgs.push(`--port=${config.port}`);
|
|
if (config.host) serviceArgs.push(`--host=${config.host}`);
|
|
|
|
const child = spawn(launcher.command, serviceArgs, {
|
|
cwd: config.appRoot,
|
|
detached: true,
|
|
stdio: ["ignore", "ignore", "ignore"],
|
|
env: process.env,
|
|
});
|
|
child.unref();
|
|
|
|
const pidFile = getPidFile(config);
|
|
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
|
|
appendLog(getLogFile(config), `${config.serviceName || "hose-use"} service started pid=${child.pid}`);
|
|
return { started: true, ...serviceStatus(config) };
|
|
}
|
|
|
|
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
|
|
const pidFile = getPidFile(config);
|
|
const pid = readServicePid(pidFile);
|
|
if (!pid || !isHoseServiceProcess(pid, config.appRoot, config.serviceName)) {
|
|
rmSync(pidFile, { force: true });
|
|
return options.quiet ? undefined : { stopped: false, reason: "服务未处于运行状态" };
|
|
}
|
|
|
|
try {
|
|
process.kill(pid, "SIGTERM");
|
|
} catch {
|
|
// ignore
|
|
}
|
|
rmSync(pidFile, { force: true });
|
|
appendLog(getLogFile(config), `${config.serviceName || "hose-use"} service stop requested pid=${pid}`);
|
|
return options.quiet ? undefined : { stopped: true, pid };
|
|
}
|
|
|
|
function readServiceLogs(config: ServiceConfig, maxLines = 50) {
|
|
const logFile = getLogFile(config);
|
|
if (!existsSync(logFile)) {
|
|
return { logFile, lines: [], content: "暂无服务运行日志" };
|
|
}
|
|
const content = readFileSync(logFile, "utf-8");
|
|
const lines = content.trim().split("\n").filter(Boolean).slice(-maxLines);
|
|
return {
|
|
logFile,
|
|
lines,
|
|
content: lines.join("\n"),
|
|
};
|
|
}
|
|
|
|
export function isHoseServiceProcess(
|
|
pid: number,
|
|
appRoot: string,
|
|
targetName?: ServiceTargetName
|
|
): boolean {
|
|
if (!isProcessRunning(pid)) return false;
|
|
|
|
try {
|
|
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
|
|
const isRun = command.includes("service") && command.includes("run");
|
|
if (!isRun) return false;
|
|
|
|
if (targetName === "hose-aipro") {
|
|
return command.includes("hose-aipro") || command.includes("aipro-cli");
|
|
}
|
|
if (targetName === "hose-use") {
|
|
return (
|
|
(command.includes("hose-use") || command.includes("src/cli.ts") || command.includes(appRoot)) &&
|
|
!command.includes("hose-aipro") &&
|
|
!command.includes("aipro-cli")
|
|
);
|
|
}
|
|
return (
|
|
command.includes(appRoot) ||
|
|
command.includes("hose-use") ||
|
|
command.includes("src/cli.ts") ||
|
|
command.includes("hose-aipro")
|
|
);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function isProcessRunning(pid: number): boolean {
|
|
try {
|
|
process.kill(pid, 0);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export function getPidFile(config: ServiceConfig): string {
|
|
const fileName =
|
|
config.pidFileName ||
|
|
(config.serviceName === "hose-aipro" ? "aipro-service.pid" : "service.pid");
|
|
return join(config.stateDir, fileName);
|
|
}
|
|
|
|
export function getLogFile(config: ServiceConfig): string {
|
|
const fileName =
|
|
config.logFileName ||
|
|
(config.serviceName === "hose-aipro" ? "aipro-service.log" : "service.log");
|
|
return join(config.stateDir, fileName);
|
|
}
|
|
|
|
export function readServicePid(path: string): number | undefined {
|
|
if (!existsSync(path)) return undefined;
|
|
const pid = Number(readFileSync(path, "utf-8").trim());
|
|
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
|
|
}
|
|
|
|
function ensureStateDir(stateDir: string): void {
|
|
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
}
|
|
|
|
function appendLog(path: string, message: string): void {
|
|
writeFileSync(path, `${new Date().toISOString()} ${message}\n`, { flag: "a", mode: 0o600 });
|
|
}
|