feat: release v0.5.0 with embedded HTTP server and resident daemon service
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled

This commit is contained in:
gitea committed 2026-09-03 15:19:12 +08:00
1 parent 07b4e14e59
commit c1dc9f1616
17 files changed
+838 -9

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
import { startHttpServer } from "../../http/server.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleHttpCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const port = numberOption(parsed.options, ["port", "p"]);
const host = stringOption(parsed.options, ["host", "h"]);
const server = await startHttpServer({ port, host, silent: runtime.jsonMode });
// Handle graceful shutdown
const shutdown = () => {
server.close(() => {
process.exit(0);
});
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
// Keep alive in foreground
await new Promise<void>(() => {});
return { stdout: "", stderr: "", exitCode: 0 };
}
+70
View File
@@ -0,0 +1,70 @@
import { homedir } from "node:os";
import { join } from "node:path";
import { VERSION } from "../../version.js";
import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../service.js";
import { printJson, printKeyValue } from "../printer.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
export async function handleServiceCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action || parsed.args[0] || "status";
const port = numberOption(parsed.options, ["port", "p"]);
const host = stringOption(parsed.options, ["host", "h"]);
const config: ServiceConfig = {
appRoot: runtime.appRoot || process.cwd(),
entryFile: runtime.entryFile || join(runtime.appRoot || process.cwd(), "src", "cli.ts"),
stateDir: SERVICE_STATE_DIR,
version: VERSION,
launcher: runtime.launcher,
port,
host,
};
const result = await runServiceCommand(action, config);
if (result === undefined) {
// 'run' keeps running, resolves on shutdown
return { stdout: "", stderr: "", exitCode: 0 };
}
if (runtime.jsonMode) {
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (action === "logs" || action === "log") {
const logsResult = result as { logFile: string; lines: string[]; content: string };
return {
stdout: `====== hose-use 守护进程日志 (${logsResult.logFile}) ======\n${logsResult.content}\n`,
stderr: "",
exitCode: 0,
};
}
const status = result as Record<string, unknown>;
const isRunning = Boolean(status.running);
const displayPairs: Record<string, unknown> = {
"服务状态": isRunning ? "🟢 正在运行 (Running)" : "⚪ 已停止 (Stopped)",
...(status.pid ? { "进程 PID": status.pid } : {}),
...(status.url ? { "服务地址": status.url } : {}),
...(status.url ? { "交互式文档": `${status.url}/docs` } : {}),
...(status.url ? { "CLI 网关": `POST ${status.url}/api/cli` } : {}),
"运行版本": status.version || config.version,
"状态目录": status.stateDir || config.stateDir,
"PID 文件": status.pidFile || getPidFile(config),
"日志文件": status.logFile || getLogFile(config),
};
const formatted = printKeyValue(displayPairs);
return {
stdout: `====== hose-use 常驻服务管理 (Service) ======\n${formatted}\n`,
stderr: "",
exitCode: 0,
};
}
+9
View File
@@ -13,6 +13,12 @@ export function initCorpRuntime(
stateful?: boolean;
jsonMode?: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;
launcher?: {
command: string;
args?: string[];
};
} = {}
): CliRuntime {
const corps = loadCorpConfigs();
@@ -42,6 +48,9 @@ export function initCorpRuntime(
selectedCorp,
jsonMode: options.jsonMode ?? false,
outputOptions: options.outputOptions,
appRoot: options.appRoot,
entryFile: options.entryFile,
launcher: options.launcher,
};
}
+5
View File
@@ -125,6 +125,8 @@ export function printHelp(): string {
probe 连通性诊断 (probe [corpId])
update 版本自更新与发布记录 (update, update check, update --changelog)
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
service 常驻守护进程管理 (service start|stop|restart|status|logs)
mcp MCP Server 运行 (serve)
version 查看版本信息
@@ -149,6 +151,9 @@ export function printHelp(): string {
hose-use bill list # 查看当前企业单据与报销列表
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档
hose-use service start # 后台启动常驻守护进程服务
hose-use service status # 查看守护进程运行状态与接口地址
hose-use probe # 诊断当前企业鉴权连通性
hose-use skill install # 安装 Agent 技能到用户目录
hose-use update # 自动检查并升级到最新版本
+26 -1
View File
@@ -13,14 +13,30 @@ import { handleMcpCommand } from "./commands/mcp.js";
import { handleUpdateCommand } from "./commands/update.js";
import { handleOpenApiCommand } from "./commands/openapi.js";
import { handleBillCommand } from "./commands/bill.js";
import { handleServiceCommand } from "./commands/service.js";
import { handleHttpCommand } from "./commands/http.js";
import type { CliResult, CliRunOptions } from "./types.js";
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
function isStandingCommand(args: string[]): boolean {
if (!args.length) return false;
const first = args[0]?.toLowerCase();
const second = args[1]?.toLowerCase();
if (STANDING_COMMANDS.has(first)) return true;
if ((first === "service" || first === "daemon") && second === "run") return true;
return false;
}
let runQueue = Promise.resolve<any>(undefined);
export function runCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
if (isStandingCommand(rawArgs)) {
return dispatchCli(rawArgs, options);
}
const run = runQueue.then(() => runCliOnce(rawArgs, options));
runQueue = run.then(
() => undefined,
@@ -86,6 +102,9 @@ async function dispatchCli(
stateful: statefulOption,
jsonMode,
outputOptions: outputOpts,
appRoot: options.appRoot,
entryFile: options.entryFile,
launcher: options.launcher,
});
try {
@@ -130,8 +149,14 @@ async function dispatchCli(
case "schema":
case "spec":
return await handleOpenApiCommand(parsed, runtime);
case "http":
case "server":
case "web":
return await handleHttpCommand(parsed, runtime);
case "service":
case "daemon":
return await handleServiceCommand(parsed, runtime);
case "mcp":
case "serve":
return await handleMcpCommand(parsed, options);
case undefined:
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
serviceStatus,
getPidFile,
getLogFile,
isHoseServiceProcess,
ServiceConfig,
} from "./service.js";
describe("cli/service - 守护进程状态与自愈管理", () => {
let tempDir: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "hose-service-test-"));
});
afterEach(() => {
try {
rmSync(tempDir, { recursive: true, force: true });
} catch {
// ignore
}
});
test("服务未运行时返回 running: false 并生成规范状态对象", () => {
const config: ServiceConfig = {
appRoot: tempDir,
entryFile: join(tempDir, "entry.js"),
stateDir: tempDir,
version: "0.5.0",
port: 8888,
host: "127.0.0.1",
};
const status = serviceStatus(config);
expect(status.running).toBe(false);
expect(status.pid).toBeUndefined();
expect(status.version).toBe("0.5.0");
expect(status.port).toBe(8888);
expect(status.pidFile).toBe(join(tempDir, "service.pid"));
expect(status.logFile).toBe(join(tempDir, "service.log"));
});
test("发现失效的孤儿 PID 时自动自愈清理 pidFile", () => {
const config: ServiceConfig = {
appRoot: tempDir,
entryFile: join(tempDir, "entry.js"),
stateDir: tempDir,
version: "0.5.0",
};
const pidFile = getPidFile(config);
// 写入一个不存在的荒谬 PID
writeFileSync(pidFile, "9999999\n", "utf-8");
expect(existsSync(pidFile)).toBe(true);
const status = serviceStatus(config);
expect(status.running).toBe(false);
// 验证旧文件已被自愈删除
expect(existsSync(pidFile)).toBe(false);
});
test("isHoseServiceProcess 正确识别非 hose 进程", () => {
// 当前测试进程自身不是后台 service run 守护进程
expect(isHoseServiceProcess(process.pid, "/non/existent/path")).toBe(false);
// 不存在的进程
expect(isHoseServiceProcess(9999999, tempDir)).toBe(false);
});
test("路径辅助函数返回规范的子路径", () => {
const config: ServiceConfig = {
appRoot: tempDir,
entryFile: join(tempDir, "entry.js"),
stateDir: tempDir,
};
expect(getPidFile(config)).toBe(join(tempDir, "service.pid"));
expect(getLogFile(config)).toBe(join(tempDir, "service.log"));
});
});
+223
View File
@@ -0,0 +1,223 @@
import { spawn, execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
export type ServiceConfig = {
appRoot: string;
entryFile: string;
stateDir: string;
version?: string;
launcher?: {
command: string;
args?: string[];
};
port?: number;
host?: string;
};
export async function runServiceCommand(
action: string | undefined,
config: ServiceConfig,
options: { quiet?: boolean } = {}
) {
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("用法: hose service <start|stop|restart|status|logs>");
}
}
export function serviceStatus(config: ServiceConfig) {
const pidFile = getPidFile(config);
const pid = readServicePid(pidFile);
const running = pid ? isHoseServiceProcess(pid, config.appRoot) : false;
if (pid && !running) {
rmSync(pidFile, { force: true });
}
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
return {
running,
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 port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
appendLog(logFile, `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 });
appendLog(logFile, `service listening pid=${process.pid}`);
} catch (err: unknown) {
appendLog(logFile, `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, `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), `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)) {
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), `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): boolean {
if (!isProcessRunning(pid)) return false;
try {
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
const matchesTarget =
command.includes(appRoot) ||
command.includes("hose-use") ||
command.includes("src/cli.ts");
return matchesTarget && command.includes("service") && command.includes("run");
} catch {
return false;
}
}
function isProcessRunning(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
export function getPidFile(config: ServiceConfig): string {
return join(config.stateDir, "service.pid");
}
export function getLogFile(config: ServiceConfig): string {
return join(config.stateDir, "service.log");
}
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 });
}
+10 -1
View File
@@ -12,7 +12,10 @@ export interface CliParsedArgs {
export interface CliRunOptions {
appRoot?: string;
entryFile?: string;
launcher?: string;
launcher?: {
command: string;
args?: string[];
};
}
export interface CliResult {
@@ -32,4 +35,10 @@ export interface CliRuntime {
selectedCorp: CorpConfig | null;
jsonMode: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;
launcher?: {
command: string;
args?: string[];
};
}