Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1dc9f1616 | ||
|
|
07b4e14e59 | ||
|
|
ba30c1a6cb | ||
|
|
cf44c7dcdf |
No files matched your search
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.4.0)
|
||||
# hose-use (v0.5.0)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -32,8 +32,9 @@ hose-use corps list # 列出名下所有已配置企
|
||||
hose-use corps switch <corpId> # 切换工作企业
|
||||
hose-use corps current # 查看当前激活企业
|
||||
|
||||
# 3. 运行模式管理 (有状态 vs 无状态)
|
||||
hose-use config show # 查看当前运行模式
|
||||
# 3. 运行模式与多级配置路径管理 (有状态 vs 无状态)
|
||||
hose-use config show # 查看当前运行模式与默认企业
|
||||
hose-use config paths # 查看多级企业目录发现链与配置文件位置
|
||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
|
||||
|
||||
@@ -44,8 +45,10 @@ hose-use workflow find --task=code-js2 # 搜索包含特定节点类型
|
||||
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
|
||||
hose-use platform list # 查看企业下所有启用的自建应用
|
||||
|
||||
# 5. 单据与费用明细管理 (DataLink 字典自动还原)
|
||||
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
|
||||
hose-use bill list # 查看当前企业单据与报销列表 (支持分页/阶段/状态过滤)
|
||||
hose-use bill list --json -o /tmp/bills.json # 自动转储大报文至本地文件,防止打爆上下文
|
||||
hose-use bill list --json --full # 确需完整原始数据时跳过 200KB 限制
|
||||
hose-use bill get <单号|ID> # 根据单号或 ID 查询单据结构化详情
|
||||
hose-use bill schema # 查看企业全部单据实体与数据模型字典
|
||||
|
||||
@@ -56,11 +59,18 @@ hose-use openapi info # 查看 OpenAPI 规范元数据
|
||||
hose-use openapi # 输出包装层标准 OpenAPI 3.1.0 JSON
|
||||
hose-use openapi --raw # 输出原生下游全量 OpenAPI 3.1.0 JSON
|
||||
|
||||
# 7. Agent Skill 与连通性诊断
|
||||
# 7. 内置 HTTP Server 与常驻 Service 守护进程
|
||||
hose-use http --port=8888 # 前台启动 HTTP 服务与 Scalar 交互式文档 (http://localhost:8888/docs)
|
||||
hose-use service start # 后台启动常驻守护进程
|
||||
hose-use service status # 查看常驻服务运行状态、PID 与接口端点
|
||||
hose-use service logs # 查看守护进程日志
|
||||
hose-use service stop # 优雅停止常驻守护进程
|
||||
|
||||
# 8. Agent Skill 与连通性诊断
|
||||
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
|
||||
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
|
||||
|
||||
# 8. MCP Server (单工具网关模式)
|
||||
# 9. MCP Server (单工具网关模式)
|
||||
hose-use mcp # 启动 MCP Server (默认暴露 hose_cli 单工具网关)
|
||||
```
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.4.0
|
||||
version: 0.5.0
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.4.0",
|
||||
"version": "0.5.0",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -84,6 +84,9 @@ hose-use corps current
|
||||
# 查看全局运行模式与配置文件路径
|
||||
hose-use config show
|
||||
|
||||
# 查看多级企业目录发现路径与诊断
|
||||
hose-use config paths
|
||||
|
||||
# 切换为无状态模式 (Stateless)
|
||||
hose-use config mode stateless
|
||||
|
||||
@@ -117,6 +120,11 @@ hose-use platform list
|
||||
hose-use bill list
|
||||
hose-use bill list --stage=expense --state=paid --count=10
|
||||
|
||||
# 大数据量防爆落盘: 使用 -o / --output-file 将完整 JSON 转储至本地文件 (推荐 Agent 处理海量数据时使用)
|
||||
hose-use bill list --json -o /tmp/bills.json
|
||||
# 确需向终端输出完整大报文时附加 --full (跳过 200KB 防爆限制)
|
||||
hose-use bill list --json --full
|
||||
|
||||
# 根据单号或 ID 精确查询单据结构化详情 (DataLink 字典自动还原)
|
||||
hose-use bill get n0GMIM0dkQmKbS
|
||||
hose-use bill get ID01TRzg7HMLcb
|
||||
@@ -155,7 +163,26 @@ hose-use openapi
|
||||
hose-use openapi --raw
|
||||
```
|
||||
|
||||
### 8. 自更新与版本历史 (`hose-use update`)
|
||||
### 8. HTTP 服务与常驻守护进程 (`hose-use http` / `hose-use service`)
|
||||
|
||||
```bash
|
||||
# 启动本地轻量 HTTP 服务并打开 Scalar 交互式文档 (http://127.0.0.1:8888/docs)
|
||||
hose-use http --port=8888
|
||||
|
||||
# 后台启动常驻守护进程服务
|
||||
hose-use service start
|
||||
|
||||
# 查看常驻守护进程运行状态与端点
|
||||
hose-use service status
|
||||
|
||||
# 查看常驻守护进程最近运行日志
|
||||
hose-use service logs
|
||||
|
||||
# 停止后台常驻守护进程
|
||||
hose-use service stop
|
||||
```
|
||||
|
||||
### 9. 自更新与版本历史 (`hose-use update`)
|
||||
|
||||
```bash
|
||||
# 检查最新可用版本与 Release Notes
|
||||
|
||||
+28
-19
@@ -43,13 +43,16 @@ export async function handleBillCommand(
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
total: result.total,
|
||||
returned: result.returned,
|
||||
items: result.items,
|
||||
}),
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
total: result.total,
|
||||
returned: result.returned,
|
||||
items: result.items,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -104,12 +107,15 @@ export async function handleBillCommand(
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
count: bills.length,
|
||||
bills,
|
||||
}),
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
count: bills.length,
|
||||
bills,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -157,12 +163,15 @@ export async function handleBillCommand(
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
totalEntities: entities.length,
|
||||
entities,
|
||||
}),
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
totalEntities: entities.length,
|
||||
entities,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
|
||||
@@ -2,6 +2,9 @@ import {
|
||||
loadGlobalConfig,
|
||||
saveGlobalConfig,
|
||||
resolveGlobalConfigFile,
|
||||
resolveEnterprisesDirs,
|
||||
resolveWritableEnterprisesDir,
|
||||
getEnterprisesDirCandidates,
|
||||
} from "../../core/config/loader.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
@@ -17,6 +20,10 @@ export async function handleConfigCommand(
|
||||
case "get":
|
||||
case "list":
|
||||
return handleShow(parsed, runtime);
|
||||
case "paths":
|
||||
case "path":
|
||||
case "dirs":
|
||||
return handlePaths(parsed, runtime);
|
||||
case "mode":
|
||||
return handleMode(parsed, runtime);
|
||||
case "set":
|
||||
@@ -24,7 +31,7 @@ export async function handleConfigCommand(
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 config 子命令: ${action}。支持: show, mode <stateful|stateless>, set <key> <val>\n`,
|
||||
stderr: `未知 config 子命令: ${action}。支持: show, paths, mode <stateful|stateless>, set <key> <val>\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -125,3 +132,43 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const envDir = process.env.HOSE_ENTERPRISES_DIR;
|
||||
const envUserDir = process.env.HOSE_USER_ENTERPRISES_DIR;
|
||||
const envConfigFile = process.env.HOSE_CONFIG_FILE;
|
||||
const existingDirs = resolveEnterprisesDirs();
|
||||
const writableDir = resolveWritableEnterprisesDir();
|
||||
const configFile = resolveGlobalConfigFile();
|
||||
const candidates = getEnterprisesDirCandidates();
|
||||
|
||||
const data = {
|
||||
configFile,
|
||||
writableDir,
|
||||
existingDirs,
|
||||
env: {
|
||||
HOSE_ENTERPRISES_DIR: envDir || null,
|
||||
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
|
||||
HOSE_CONFIG_FILE: envConfigFile || null,
|
||||
},
|
||||
candidates,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(data), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const output = printKeyValue({
|
||||
"当前生效配置文件": configFile,
|
||||
"凭证保存写入目录": writableDir,
|
||||
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
|
||||
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
|
||||
"全部目录候选链": candidates.join("\n "),
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== 配置路径诊断 (Config Paths) ======\n${output}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -29,10 +29,13 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
corporations: corps,
|
||||
}),
|
||||
stdout: printJson(
|
||||
{
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
corporations: corps,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
@@ -81,7 +84,7 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
|
||||
const current = runtime.corpContext.getCurrent();
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(current), stderr: "", exitCode: 0 };
|
||||
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -98,7 +101,7 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(current), stderr: "", exitCode: 0 };
|
||||
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const pairs: Record<string, unknown> = {
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -36,7 +36,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(platforms), stderr: "", exitCode: 0 };
|
||||
return { stdout: printJson(platforms, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (platforms.length === 0) {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -54,7 +54,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
const result = await listAllWorkflows(clients, { page, pageSize });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result), stderr: "", exitCode: 0 };
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (result.workflows.length === 0) {
|
||||
@@ -96,7 +96,7 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail), stderr: "", exitCode: 0 };
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const summary = printKeyValue({
|
||||
@@ -148,7 +148,7 @@ async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result), stderr: "", exitCode: 0 };
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (result.workflows.length === 0) {
|
||||
@@ -196,7 +196,7 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result), stderr: "", exitCode: 0 };
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
+14
-3
@@ -1,10 +1,10 @@
|
||||
import readline from "readline";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig, getEnterprisesDirCandidates } from "../core/config/loader.js";
|
||||
import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
||||
import { CorpConfig } from "../core/config/types.js";
|
||||
import { createEkbClient } from "../core/auth/ekb.js";
|
||||
import { getEasoClient } from "../core/auth/easo.js";
|
||||
import { CliRuntime } from "./types.js";
|
||||
import { CliRuntime, OutputOptions } from "./types.js";
|
||||
|
||||
export function initCorpRuntime(
|
||||
options: {
|
||||
@@ -12,6 +12,13 @@ export function initCorpRuntime(
|
||||
stateless?: boolean;
|
||||
stateful?: boolean;
|
||||
jsonMode?: boolean;
|
||||
outputOptions?: OutputOptions;
|
||||
appRoot?: string;
|
||||
entryFile?: string;
|
||||
launcher?: {
|
||||
command: string;
|
||||
args?: string[];
|
||||
};
|
||||
} = {}
|
||||
): CliRuntime {
|
||||
const corps = loadCorpConfigs();
|
||||
@@ -31,7 +38,7 @@ export function initCorpRuntime(
|
||||
|
||||
let selectedCorp: CorpConfig | null = null;
|
||||
try {
|
||||
selectedCorp = corpContext.resolve(options.corpId);
|
||||
selectedCorp = corpContext.resolve(options.corpId, getEnterprisesDirCandidates());
|
||||
} catch {
|
||||
selectedCorp = null;
|
||||
}
|
||||
@@ -40,6 +47,10 @@ export function initCorpRuntime(
|
||||
corpContext,
|
||||
selectedCorp,
|
||||
jsonMode: options.jsonMode ?? false,
|
||||
outputOptions: options.outputOptions,
|
||||
appRoot: options.appRoot,
|
||||
entryFile: options.entryFile,
|
||||
launcher: options.launcher,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+24
-2
@@ -1,4 +1,4 @@
|
||||
import type { CliParsedArgs } from "./types.js";
|
||||
import type { CliParsedArgs, OutputOptions } from "./types.js";
|
||||
|
||||
const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"raw",
|
||||
@@ -19,6 +19,10 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"local",
|
||||
"workspace",
|
||||
"external",
|
||||
"full",
|
||||
"allow-full",
|
||||
"allowFull",
|
||||
"summary",
|
||||
]);
|
||||
|
||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
@@ -61,7 +65,17 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
if (flag === "h") options.help = true;
|
||||
else if (flag === "j") options.json = true;
|
||||
else if (flag === "v") options.version = true;
|
||||
else options[flag] = true;
|
||||
else if (flag === "o") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.outputFile = next;
|
||||
i++;
|
||||
} else {
|
||||
options.o = true;
|
||||
}
|
||||
} else {
|
||||
options[flag] = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -121,3 +135,11 @@ export function numberOption(
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function outputOptions(options: Record<string, unknown>): OutputOptions {
|
||||
return {
|
||||
allowFull: booleanOption(options, ["full", "allow-full", "allowFull"]),
|
||||
outputFile: stringOption(options, ["output-file", "outputFile", "o"]),
|
||||
summary: booleanOption(options, ["summary"]),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
|
||||
import { mkdtempSync, rmSync, existsSync, readFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
DEFAULT_OUTPUT_BYTES_LIMIT,
|
||||
protectLargeOutput,
|
||||
printJson,
|
||||
redactSensitiveText,
|
||||
} from "./printer.js";
|
||||
|
||||
describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||
describe("redactSensitiveText 脱敏处理", () => {
|
||||
test("脱敏 URL Query 中的 accessToken / token / returnToken", () => {
|
||||
const input = "https://app.ekuaibao.com/api/test?accessToken=sec_123456&corpId=corpxx&returnToken=ret_789";
|
||||
const redacted = redactSensitiveText(input);
|
||||
expect(redacted).not.toContain("sec_123456");
|
||||
expect(redacted).not.toContain("ret_789");
|
||||
expect(redacted).toContain("accessToken=<redacted>");
|
||||
expect(redacted).toContain("returnToken=<redacted>");
|
||||
expect(redacted).toContain("corpId=corpxx");
|
||||
});
|
||||
|
||||
test("脱敏 Authorization Bearer token", () => {
|
||||
const input = "Request headers: Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz";
|
||||
const redacted = redactSensitiveText(input);
|
||||
expect(redacted).not.toContain("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz");
|
||||
expect(redacted).toContain("Bearer <redacted>");
|
||||
});
|
||||
|
||||
test("脱敏 password、secret、appSecurity 等键值", () => {
|
||||
const input = '{"username": "admin", "password": "super_secret_password_123", "appSecurity": "sec_key"}';
|
||||
const redacted = redactSensitiveText(input);
|
||||
expect(redacted).not.toContain("super_secret_password_123");
|
||||
expect(redacted).not.toContain("sec_key");
|
||||
expect(redacted).toContain('"password": "<redacted>"');
|
||||
expect(redacted).toContain('"appSecurity": "<redacted>"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("protectLargeOutput 与 printJson 体积熔断保护", () => {
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "hose-printer-test-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
try {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
|
||||
test("正常体积的数据可以直接输出 JSON", () => {
|
||||
const normalData = { hello: "world", numbers: [1, 2, 3] };
|
||||
expect(() => protectLargeOutput(normalData)).not.toThrow();
|
||||
const output = printJson(normalData);
|
||||
expect(JSON.parse(output)).toEqual(normalData);
|
||||
});
|
||||
|
||||
test("超过 200KB 的巨型数据默认抛出熔断错误", () => {
|
||||
// 构造超过 200KB 的大数组
|
||||
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
|
||||
id: `id-${i}`,
|
||||
description: "这是一个用于测试大报文熔断拦截的测试长字段内容,模拟企业级海量单据与工作流节点拓扑",
|
||||
nested: { count: i, payload: "x".repeat(120) },
|
||||
}));
|
||||
|
||||
expect(() => protectLargeOutput(bigArray)).toThrow(
|
||||
/输出体积过大.*超过安全阈值.*--output-file.*--full/
|
||||
);
|
||||
|
||||
expect(() => printJson(bigArray)).toThrow(/输出体积过大/);
|
||||
});
|
||||
|
||||
test("显式指定 allowFull 时允许全量输出大报文", () => {
|
||||
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
|
||||
id: `id-${i}`,
|
||||
payload: "y".repeat(150),
|
||||
}));
|
||||
|
||||
expect(() => protectLargeOutput(bigArray, { allowFull: true })).not.toThrow();
|
||||
const output = printJson(bigArray, { allowFull: true });
|
||||
expect(output.length).toBeGreaterThan(DEFAULT_OUTPUT_BYTES_LIMIT);
|
||||
});
|
||||
|
||||
test("指定 outputFile 时大报文直接落盘并返回精简摘要", () => {
|
||||
const targetFile = join(tempDir, "exported-bills.json");
|
||||
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
|
||||
id: `id-${i}`,
|
||||
payload: "z".repeat(150),
|
||||
}));
|
||||
|
||||
const resultJson = printJson(bigArray, { outputFile: targetFile });
|
||||
const summary = JSON.parse(resultJson);
|
||||
|
||||
expect(summary.outputFile).toBe(targetFile);
|
||||
expect(summary.bytes).toBeGreaterThan(DEFAULT_OUTPUT_BYTES_LIMIT);
|
||||
expect(existsSync(targetFile)).toBe(true);
|
||||
|
||||
const savedContent = JSON.parse(readFileSync(targetFile, "utf-8"));
|
||||
expect(savedContent).toHaveLength(1500);
|
||||
expect(savedContent[0].id).toBe("id-0");
|
||||
});
|
||||
});
|
||||
});
|
||||
+51
-8
@@ -1,7 +1,41 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { VERSION } from "../version.js";
|
||||
import type { OutputOptions } from "./types.js";
|
||||
|
||||
export function printJson(data: unknown): string {
|
||||
return JSON.stringify(data, null, 2);
|
||||
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
export function redactSensitiveText(value: string): string {
|
||||
return value
|
||||
.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s"']+/gi, "$1<redacted>")
|
||||
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
|
||||
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
|
||||
}
|
||||
|
||||
export function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
|
||||
if (options.allowFull || options.outputFile) return;
|
||||
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
|
||||
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
|
||||
throw new Error(
|
||||
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function printJson(data: unknown, options: OutputOptions = {}): string {
|
||||
protectLargeOutput(data, options);
|
||||
const json = JSON.stringify(data, null, 2);
|
||||
if (options.outputFile) {
|
||||
writeFileSync(options.outputFile, json, "utf-8");
|
||||
return JSON.stringify(
|
||||
{
|
||||
outputFile: options.outputFile,
|
||||
bytes: Buffer.byteLength(json, "utf-8"),
|
||||
},
|
||||
null,
|
||||
2
|
||||
);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
export function formatSourceLabel(source?: string): string {
|
||||
@@ -83,7 +117,7 @@ export function printHelp(): string {
|
||||
核心命令域:
|
||||
auth 认证与凭证管理 (login, status, refresh, import, accounts)
|
||||
corps 多企业租户管理 (list, switch, current)
|
||||
config 全局运行模式 (show, mode <stateful|stateless>, set)
|
||||
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, toggle)
|
||||
bill 单据与费用明细检索 (list, get <单号|ID>, schema)
|
||||
platform 自建应用管理 (list)
|
||||
@@ -91,26 +125,35 @@ 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 查看版本信息
|
||||
|
||||
全局选项:
|
||||
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
|
||||
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
|
||||
--stateless 单次强制以无状态模式执行
|
||||
--stateful 单次强制以有状态模式执行
|
||||
--help, -h 查看帮助信息
|
||||
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
|
||||
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
|
||||
--output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要
|
||||
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
|
||||
--stateless 单次强制以无状态模式执行
|
||||
--stateful 单次强制以有状态模式执行
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
常用示例:
|
||||
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
|
||||
hose-use auth status # 查看当前登录状态与活跃企业
|
||||
hose-use config paths # 查看多级企业配置目录链
|
||||
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
|
||||
hose-use corps list # 列出名下所有企业
|
||||
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
|
||||
hose-use workflow list # 汇总查看全部工作流
|
||||
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
||||
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 # 自动检查并升级到最新版本
|
||||
|
||||
+33
-6
@@ -1,6 +1,6 @@
|
||||
import { VERSION } from "../version.js";
|
||||
import { parseArgs, stringOption, booleanOption } from "./parser.js";
|
||||
import { printHelp, printJson } from "./printer.js";
|
||||
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
|
||||
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
|
||||
import { initCorpRuntime } from "./helpers.js";
|
||||
import { handleAuthCommand } from "./commands/auth.js";
|
||||
import { handleCorpsCommand } from "./commands/corps.js";
|
||||
@@ -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,
|
||||
@@ -50,8 +66,8 @@ async function runCliOnce(
|
||||
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
|
||||
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
|
||||
return {
|
||||
stdout: extraStdout + (result.stdout || ""),
|
||||
stderr: extraStderr + (result.stderr || ""),
|
||||
stdout: redactSensitiveText(extraStdout + (result.stdout || "")),
|
||||
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
|
||||
exitCode: result.exitCode,
|
||||
};
|
||||
} finally {
|
||||
@@ -78,12 +94,17 @@ async function dispatchCli(
|
||||
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
|
||||
const statelessOption = booleanOption(parsed.options, ["stateless"]);
|
||||
const statefulOption = booleanOption(parsed.options, ["stateful"]);
|
||||
const outputOpts = outputOptions(parsed.options);
|
||||
|
||||
const runtime = initCorpRuntime({
|
||||
corpId: corpIdOption,
|
||||
stateless: statelessOption,
|
||||
stateful: statefulOption,
|
||||
jsonMode,
|
||||
outputOptions: outputOpts,
|
||||
appRoot: options.appRoot,
|
||||
entryFile: options.entryFile,
|
||||
launcher: options.launcher,
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -128,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 };
|
||||
@@ -141,7 +168,7 @@ async function dispatchCli(
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
if (jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ error: true, message: errorMsg }),
|
||||
|
||||
@@ -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"));
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
}
|
||||
+17
-1
@@ -12,7 +12,10 @@ export interface CliParsedArgs {
|
||||
export interface CliRunOptions {
|
||||
appRoot?: string;
|
||||
entryFile?: string;
|
||||
launcher?: string;
|
||||
launcher?: {
|
||||
command: string;
|
||||
args?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface CliResult {
|
||||
@@ -21,8 +24,21 @@ export interface CliResult {
|
||||
exitCode: number;
|
||||
}
|
||||
|
||||
export interface OutputOptions {
|
||||
allowFull?: boolean;
|
||||
outputFile?: string;
|
||||
summary?: boolean;
|
||||
}
|
||||
|
||||
export interface CliRuntime {
|
||||
corpContext: CorpContext;
|
||||
selectedCorp: CorpConfig | null;
|
||||
jsonMode: boolean;
|
||||
outputOptions?: OutputOptions;
|
||||
appRoot?: string;
|
||||
entryFile?: string;
|
||||
launcher?: {
|
||||
command: string;
|
||||
args?: string[];
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
loadCorpConfigs,
|
||||
saveCorpConfig,
|
||||
resolveEnterprisesDirs,
|
||||
resolveWritableEnterprisesDir,
|
||||
loadGlobalConfig,
|
||||
saveGlobalConfig,
|
||||
resolveGlobalConfigFile,
|
||||
} from "./loader.js";
|
||||
import type { CorpConfig } from "./types.js";
|
||||
|
||||
describe("core/config/loader", () => {
|
||||
let tempDir: string;
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "hose-config-test-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
try {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
|
||||
test("resolveEnterprisesDirs prioritizes HOSE_ENTERPRISES_DIR environment variable", () => {
|
||||
const customDir = join(tempDir, "custom-enterprises");
|
||||
mkdirSync(customDir, { recursive: true });
|
||||
process.env.HOSE_ENTERPRISES_DIR = customDir;
|
||||
|
||||
const dirs = resolveEnterprisesDirs();
|
||||
expect(dirs).toEqual([customDir]);
|
||||
});
|
||||
|
||||
test("resolveWritableEnterprisesDir respects HOSE_ENTERPRISES_DIR", () => {
|
||||
const customDir = join(tempDir, "writable-enterprises");
|
||||
mkdirSync(customDir, { recursive: true });
|
||||
process.env.HOSE_ENTERPRISES_DIR = customDir;
|
||||
|
||||
expect(resolveWritableEnterprisesDir()).toBe(customDir);
|
||||
});
|
||||
|
||||
const createMockCorp = (id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig => ({
|
||||
id,
|
||||
name,
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
source: "manual",
|
||||
credentials: {
|
||||
accessToken: `token-${id}`,
|
||||
corpId: id,
|
||||
staffId: `staff-${id}`,
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test("loadCorpConfigs loads valid configs and skips example files", () => {
|
||||
const dirA = join(tempDir, "dirA");
|
||||
mkdirSync(dirA, { recursive: true });
|
||||
|
||||
const validCorp = createMockCorp("corp-1", "企业1");
|
||||
|
||||
// Save valid corp
|
||||
writeFileSync(join(dirA, "corp-1.json"), JSON.stringify(validCorp));
|
||||
// Save example corp
|
||||
writeFileSync(
|
||||
join(dirA, "example.json"),
|
||||
JSON.stringify(createMockCorp("example-corp", "模板企业"))
|
||||
);
|
||||
|
||||
const loaded = loadCorpConfigs([dirA]);
|
||||
expect(loaded).toHaveLength(1);
|
||||
expect(loaded[0]?.id).toBe("corp-1");
|
||||
expect(loaded[0]?.name).toBe("企业1");
|
||||
});
|
||||
|
||||
test("loadCorpConfigs merges multiple directories with earlier directory taking precedence", () => {
|
||||
const dirA = join(tempDir, "dirA");
|
||||
const dirB = join(tempDir, "dirB");
|
||||
mkdirSync(dirA, { recursive: true });
|
||||
mkdirSync(dirB, { recursive: true });
|
||||
|
||||
const corpInA = createMockCorp("corp-common", "本地优先企业", {
|
||||
credentials: { accessToken: "token-a", corpId: "corp-common", staffId: "staff-a" },
|
||||
});
|
||||
|
||||
const corpInB = createMockCorp("corp-common", "全局覆盖企业", {
|
||||
credentials: { accessToken: "token-b", corpId: "corp-common", staffId: "staff-b" },
|
||||
});
|
||||
|
||||
const corpOnlyB = createMockCorp("corp-b-only", "仅在B的企业", {
|
||||
credentials: { accessToken: "token-b2", corpId: "corp-b-only", staffId: "staff-b2" },
|
||||
});
|
||||
|
||||
writeFileSync(join(dirA, "corp-common.json"), JSON.stringify(corpInA));
|
||||
writeFileSync(join(dirB, "corp-common.json"), JSON.stringify(corpInB));
|
||||
writeFileSync(join(dirB, "corp-b-only.json"), JSON.stringify(corpOnlyB));
|
||||
|
||||
const loaded = loadCorpConfigs([dirA, dirB]);
|
||||
expect(loaded).toHaveLength(2);
|
||||
|
||||
const common = loaded.find((c) => c.id === "corp-common");
|
||||
expect(common?.name).toBe("本地优先企业");
|
||||
|
||||
const bOnly = loaded.find((c) => c.id === "corp-b-only");
|
||||
expect(bOnly?.name).toBe("仅在B的企业");
|
||||
});
|
||||
|
||||
test("saveCorpConfig writes validated JSON to target directory", () => {
|
||||
const targetDir = join(tempDir, "save-target");
|
||||
const corp = createMockCorp("corp-save-test", "保存测试企业", {
|
||||
credentials: { accessToken: "tok-123", corpId: "corp-save-test", staffId: "stf-1" },
|
||||
});
|
||||
|
||||
const filePath = saveCorpConfig(corp, targetDir);
|
||||
expect(existsSync(filePath)).toBe(true);
|
||||
|
||||
const saved = JSON.parse(readFileSync(filePath, "utf-8"));
|
||||
expect(saved.id).toBe("corp-save-test");
|
||||
expect(saved.credentials.accessToken).toBe("tok-123");
|
||||
});
|
||||
|
||||
test("loadGlobalConfig and saveGlobalConfig respect HOSE_CONFIG_FILE", () => {
|
||||
const customConfigFile = join(tempDir, "config.json");
|
||||
process.env.HOSE_CONFIG_FILE = customConfigFile;
|
||||
|
||||
expect(resolveGlobalConfigFile()).toBe(customConfigFile);
|
||||
|
||||
const initial = loadGlobalConfig();
|
||||
expect(initial.stateful).toBe(true);
|
||||
|
||||
saveGlobalConfig({ stateful: false, defaultCorpId: "test-corp-123" });
|
||||
const updated = loadGlobalConfig();
|
||||
expect(updated.stateful).toBe(false);
|
||||
expect(updated.defaultCorpId).toBe("test-corp-123");
|
||||
});
|
||||
});
|
||||
+114
-37
@@ -1,30 +1,96 @@
|
||||
import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "fs";
|
||||
import { join, dirname } from "path";
|
||||
import { homedir } from "os";
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
||||
|
||||
const ENTERPRISES_DIR = "./enterprises";
|
||||
const GLOBAL_CONFIG_PATH = join(homedir(), ".cache", "ekb-mcp", "config.json");
|
||||
const ENTERPRISES_DIR = "enterprises";
|
||||
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
|
||||
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
|
||||
const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE";
|
||||
|
||||
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "hose-use", "enterprises");
|
||||
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".cache", "ekb-mcp", "enterprises");
|
||||
export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
|
||||
|
||||
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
|
||||
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
|
||||
|
||||
function ensureDir(dir: string): void {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
export function resolveEnterprisesDirs(): string[] {
|
||||
const configured = process.env[CONFIG_ENV]?.trim();
|
||||
if (configured) {
|
||||
return existsSync(configured) ? [configured] : [];
|
||||
}
|
||||
|
||||
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||
if (configuredUserDir) {
|
||||
return [ENTERPRISES_DIR, configuredUserDir].filter((dir) => existsSync(dir));
|
||||
}
|
||||
|
||||
const dirs = [ENTERPRISES_DIR, PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
|
||||
const uniqueExisting: string[] = [];
|
||||
for (const d of dirs) {
|
||||
if (existsSync(d) && !uniqueExisting.includes(d)) {
|
||||
uniqueExisting.push(d);
|
||||
}
|
||||
}
|
||||
return uniqueExisting;
|
||||
}
|
||||
|
||||
export function resolvePrimaryEnterprisesDir(): string | undefined {
|
||||
const configured = process.env[CONFIG_ENV]?.trim();
|
||||
if (configured) return existsSync(configured) ? configured : undefined;
|
||||
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
|
||||
if (existsSync(PRIMARY_USER_ENTERPRISES_DIR)) return PRIMARY_USER_ENTERPRISES_DIR;
|
||||
if (existsSync(LEGACY_USER_ENTERPRISES_DIR)) return LEGACY_USER_ENTERPRISES_DIR;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function resolveWritableEnterprisesDir(): string {
|
||||
const configured = process.env[CONFIG_ENV]?.trim();
|
||||
if (configured) return configured;
|
||||
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||
if (configuredUserDir) return configuredUserDir;
|
||||
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
|
||||
return PRIMARY_USER_ENTERPRISES_DIR;
|
||||
}
|
||||
|
||||
export function getEnterprisesDirCandidates(): string[] {
|
||||
return [
|
||||
`${CONFIG_ENV}=<path>`,
|
||||
ENTERPRISES_DIR,
|
||||
PRIMARY_USER_ENTERPRISES_DIR,
|
||||
LEGACY_USER_ENTERPRISES_DIR,
|
||||
];
|
||||
}
|
||||
|
||||
export function resolveGlobalConfigFile(): string {
|
||||
return GLOBAL_CONFIG_PATH;
|
||||
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||
if (configured) return configured;
|
||||
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
|
||||
return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
}
|
||||
|
||||
export function loadGlobalConfig(): GlobalConfig {
|
||||
const file = resolveGlobalConfigFile();
|
||||
try {
|
||||
const content = readFileSync(GLOBAL_CONFIG_PATH, "utf-8");
|
||||
return GlobalConfigSchema.parse(JSON.parse(content));
|
||||
if (existsSync(file)) {
|
||||
const content = readFileSync(file, "utf-8");
|
||||
return GlobalConfigSchema.parse(JSON.parse(content));
|
||||
}
|
||||
} catch {
|
||||
return {
|
||||
stateful: true,
|
||||
defaultCorpId: undefined,
|
||||
defaultAccountId: undefined,
|
||||
};
|
||||
// 容错返回默认
|
||||
}
|
||||
|
||||
return {
|
||||
stateful: true,
|
||||
defaultCorpId: undefined,
|
||||
defaultAccountId: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
||||
@@ -33,50 +99,61 @@ export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
||||
...current,
|
||||
...config,
|
||||
});
|
||||
ensureDir(dirname(GLOBAL_CONFIG_PATH));
|
||||
writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(updated, null, 2), "utf-8");
|
||||
|
||||
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||
const targetFile = configured || PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
ensureDir(dirname(targetFile));
|
||||
writeFileSync(targetFile, JSON.stringify(updated, null, 2), "utf-8");
|
||||
return updated;
|
||||
}
|
||||
|
||||
export function loadCorpConfigs(dir: string = ENTERPRISES_DIR): CorpConfig[] {
|
||||
let files: string[];
|
||||
try {
|
||||
ensureDir(dir);
|
||||
files = readdirSync(dir).filter((f) => f.endsWith(".json"));
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[config] failed to read enterprises directory: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
return [];
|
||||
}
|
||||
export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
||||
const dirs = overrideDirs ? overrideDirs.filter(existsSync) : resolveEnterprisesDirs();
|
||||
const byId = new Map<string, CorpConfig>();
|
||||
|
||||
const configs: CorpConfig[] = [];
|
||||
for (const file of files) {
|
||||
for (const dir of dirs) {
|
||||
try {
|
||||
const content = readFileSync(join(dir, file), "utf-8");
|
||||
const parsed = JSON.parse(content);
|
||||
configs.push(CorpConfigSchema.parse(parsed));
|
||||
const files = readdirSync(dir)
|
||||
.filter((item) => item.endsWith(".json"))
|
||||
.filter((item) => !item.startsWith("example."));
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const content = readFileSync(join(dir, file), "utf-8");
|
||||
const parsed = JSON.parse(content);
|
||||
const corp = CorpConfigSchema.parse(parsed);
|
||||
// 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史)
|
||||
if (!byId.has(corp.id)) {
|
||||
byId.set(corp.id, corp);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[config] failed to load ${file} from ${dir}: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[config] failed to load ${file}: ${error instanceof Error ? error.message : String(error)}`
|
||||
`[config] failed to read enterprises directory ${dir}: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return configs;
|
||||
return Array.from(byId.values());
|
||||
}
|
||||
|
||||
export function saveCorpConfig(config: CorpConfig, dir: string = ENTERPRISES_DIR): string {
|
||||
ensureDir(dir);
|
||||
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||
const targetDir = dir || resolveWritableEnterprisesDir();
|
||||
ensureDir(targetDir);
|
||||
const validated = CorpConfigSchema.parse(config);
|
||||
const filePath = join(dir, `${validated.id}.json`);
|
||||
const filePath = join(targetDir, `${validated.id}.json`);
|
||||
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export function saveMultipleCorpConfigs(
|
||||
configs: CorpConfig[],
|
||||
dir: string = ENTERPRISES_DIR
|
||||
dir?: string
|
||||
): string[] {
|
||||
return configs.map((config) => saveCorpConfig(config, dir));
|
||||
}
|
||||
@@ -18,7 +18,8 @@ export function resolveCorpConfig(
|
||||
stateful: boolean;
|
||||
defaultCorpId?: string;
|
||||
corpId?: string;
|
||||
}
|
||||
},
|
||||
candidateDirs?: string[]
|
||||
): CorpConfig {
|
||||
const requestedCorpId = options.corpId?.trim() || undefined;
|
||||
const configuredCorpId = options.stateful
|
||||
@@ -51,7 +52,8 @@ export function resolveCorpConfig(
|
||||
const firstCorp = corps[0];
|
||||
if (firstCorp) return firstCorp;
|
||||
|
||||
throw new Error("未找到任何企业配置。请先运行 `hose auth login` 或在 enterprises/ 目录下添加配置。");
|
||||
const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : "";
|
||||
throw new Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${hintDirs}。`);
|
||||
}
|
||||
|
||||
export class CorpContext {
|
||||
@@ -110,12 +112,16 @@ export class CorpContext {
|
||||
return this.corps.get(corpId);
|
||||
}
|
||||
|
||||
resolve(corpId?: string): CorpConfig {
|
||||
return resolveCorpConfig(Array.from(this.corps.values()), {
|
||||
stateful: this.stateful,
|
||||
defaultCorpId: this.defaultCorpId,
|
||||
corpId,
|
||||
});
|
||||
resolve(corpId?: string, candidateDirs?: string[]): CorpConfig {
|
||||
return resolveCorpConfig(
|
||||
Array.from(this.corps.values()),
|
||||
{
|
||||
stateful: this.stateful,
|
||||
defaultCorpId: this.defaultCorpId,
|
||||
corpId,
|
||||
},
|
||||
candidateDirs
|
||||
);
|
||||
}
|
||||
|
||||
upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { VERSION } from "../version.js";
|
||||
|
||||
export function renderDocsHtml(): string {
|
||||
return `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
|
||||
<title>hose-use API Reference (v${VERSION})</title>
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>" />
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #0f172a;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script
|
||||
id="api-reference"
|
||||
data-url="/openapi.json"
|
||||
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
|
||||
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
|
||||
></script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { URL } from "node:url";
|
||||
import { runCli } from "../cli/runner.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
||||
import { getOpenApiSchema } from "../core/embedded-openapi.js";
|
||||
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import { renderDocsHtml } from "./docs.js";
|
||||
|
||||
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
// 1. CORS headers
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Hose-Corp");
|
||||
|
||||
if (req.method === "OPTIONS") {
|
||||
res.writeHead(204);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const host = req.headers.host || "localhost";
|
||||
const protocol = req.headers["x-forwarded-proto"] || "http";
|
||||
const url = new URL(req.url || "/", `${protocol}://${host}`);
|
||||
const pathname = url.pathname.replace(/\/+$/, "") || "/";
|
||||
const method = (req.method || "GET").toUpperCase();
|
||||
|
||||
try {
|
||||
// 2. Metadata & Health
|
||||
if (method === "GET" && pathname === "/") {
|
||||
sendJson(res, 200, {
|
||||
name: "hose-use",
|
||||
version: VERSION,
|
||||
description: "合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",
|
||||
docs: "/docs",
|
||||
openapi: "/openapi.json",
|
||||
rawOpenapi: "/raw-openapi.json",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
corps: "GET /v1/corps",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/health") {
|
||||
sendJson(res, 200, {
|
||||
status: "ok",
|
||||
name: "hose-use",
|
||||
version: VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/docs") {
|
||||
sendHtml(res, 200, renderDocsHtml());
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/openapi.json") {
|
||||
sendJson(res, 200, getOpenApiSchema("wrapped"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/raw-openapi.json") {
|
||||
sendJson(res, 200, getOpenApiSchema("raw"));
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Command Execution Endpoint: POST /api/cli
|
||||
if (method === "POST" && pathname === "/api/cli") {
|
||||
const body = (await parseJsonBody(req)) as Record<string, unknown> | null;
|
||||
const command = (typeof body?.command === "string" ? body.command : "").trim();
|
||||
if (!command) {
|
||||
sendError(res, 400, "Missing 'command' property in request body");
|
||||
return;
|
||||
}
|
||||
|
||||
const tokens = tokenizeCommand(command);
|
||||
const cliArgs = normalizeCliArgs(tokens);
|
||||
const result = await runCli(cliArgs);
|
||||
|
||||
let parsedData: unknown = undefined;
|
||||
const trimmedStdout = result.stdout.trim();
|
||||
try {
|
||||
if (trimmedStdout.startsWith("{") || trimmedStdout.startsWith("[")) {
|
||||
parsedData = JSON.parse(trimmedStdout);
|
||||
}
|
||||
} catch {
|
||||
// keep string
|
||||
}
|
||||
|
||||
sendJson(res, result.exitCode === 0 ? 200 : 400, {
|
||||
success: result.exitCode === 0,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
exitCode: result.exitCode,
|
||||
...(parsedData !== undefined ? { data: parsedData } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// 4. RESTful: GET /v1/corps
|
||||
if (method === "GET" && pathname === "/v1/corps") {
|
||||
const configs = loadCorpConfigs();
|
||||
const globalConfig = loadGlobalConfig();
|
||||
sendJson(res, 200, {
|
||||
count: configs.length,
|
||||
mode: globalConfig.stateful ? "stateful" : "stateless",
|
||||
defaultCorpId: globalConfig.defaultCorpId,
|
||||
corps: configs.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
source: c.source,
|
||||
staffId: c.credentials.staffId,
|
||||
baseUrl: c.baseUrl,
|
||||
expiresAt: c.auth?.expiresAt || c.session?.expTime,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
sendError(res, 500, message);
|
||||
}
|
||||
}
|
||||
|
||||
function sendJson(res: ServerResponse, status: number, data: unknown): void {
|
||||
if (res.headersSent) return;
|
||||
const payload = JSON.stringify(data, null, 2);
|
||||
res.writeHead(status, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Content-Length": Buffer.byteLength(payload, "utf-8"),
|
||||
});
|
||||
res.end(payload);
|
||||
}
|
||||
|
||||
function sendHtml(res: ServerResponse, status: number, html: string): void {
|
||||
if (res.headersSent) return;
|
||||
res.writeHead(status, {
|
||||
"Content-Type": "text/html; charset=utf-8",
|
||||
"Content-Length": Buffer.byteLength(html, "utf-8"),
|
||||
});
|
||||
res.end(html);
|
||||
}
|
||||
|
||||
function sendError(res: ServerResponse, status: number, message: string): void {
|
||||
sendJson(res, status, { error: true, message });
|
||||
}
|
||||
|
||||
async function parseJsonBody(req: IncomingMessage): Promise<unknown> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let raw = "";
|
||||
req.on("data", (chunk) => {
|
||||
raw += chunk;
|
||||
if (raw.length > 5 * 1024 * 1024) {
|
||||
// 5MB max payload
|
||||
reject(new Error("Request payload too large (max 5MB)"));
|
||||
}
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (!raw.trim()) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
resolve(JSON.parse(raw));
|
||||
} catch (err) {
|
||||
reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`));
|
||||
}
|
||||
});
|
||||
req.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, expect, test, afterAll, beforeAll } from "bun:test";
|
||||
import type { Server } from "node:http";
|
||||
import { startHttpServer } from "./server.js";
|
||||
import { VERSION } from "../version.js";
|
||||
|
||||
describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
|
||||
let server: Server;
|
||||
const testPort = 18888;
|
||||
const baseUrl = `http://127.0.0.1:${testPort}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = await startHttpServer({ port: testPort, host: "127.0.0.1", silent: true });
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
test("GET / 返回服务概览与 CORS 标头", async () => {
|
||||
const res = await fetch(`${baseUrl}/`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("*");
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.name).toBe("hose-use");
|
||||
expect(json.version).toBe(VERSION);
|
||||
expect(json.docs).toBe("/docs");
|
||||
expect(json.openapi).toBe("/openapi.json");
|
||||
expect(json.health).toBe("/health");
|
||||
expect(json.endpoints.cli).toBe("POST /api/cli");
|
||||
});
|
||||
|
||||
test("GET /health 返回存活探针状态", async () => {
|
||||
const res = await fetch(`${baseUrl}/health`);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.status).toBe("ok");
|
||||
expect(json.name).toBe("hose-use");
|
||||
expect(json.version).toBe(VERSION);
|
||||
expect(json.timestamp).toBeDefined();
|
||||
});
|
||||
|
||||
test("GET /openapi.json 返回标准包装层 OpenAPI 规范", async () => {
|
||||
const res = await fetch(`${baseUrl}/openapi.json`);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.openapi).toBe("3.1.0");
|
||||
expect(json.info.title).toContain("hose-use");
|
||||
});
|
||||
|
||||
test("GET /raw-openapi.json 返回原生下游 OpenAPI 规范", async () => {
|
||||
const res = await fetch(`${baseUrl}/raw-openapi.json`);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.openapi).toBe("3.1.0");
|
||||
expect(json.info.title).toContain("Downstream");
|
||||
});
|
||||
|
||||
test("GET /docs 返回 Scalar 交互式文档 HTML 页面", async () => {
|
||||
const res = await fetch(`${baseUrl}/docs`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toContain("text/html");
|
||||
const html = await res.text();
|
||||
expect(html).toContain("<html");
|
||||
expect(html).toContain("api-reference");
|
||||
expect(html).toContain("data-url=\"/openapi.json\"");
|
||||
});
|
||||
|
||||
test("POST /api/cli 允许同进程执行 CLI 指令", async () => {
|
||||
const res = await fetch(`${baseUrl}/api/cli`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ command: "version" }),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as any;
|
||||
expect(json.success).toBe(true);
|
||||
expect(json.exitCode).toBe(0);
|
||||
expect(json.stdout).toContain(`hose-use v${VERSION}`);
|
||||
});
|
||||
|
||||
test("GET /v1/corps 返回企业列表与运行模式", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`);
|
||||
expect(res.status).toBe(200);
|
||||
const json = (await res.json()) as any;
|
||||
expect(json).toHaveProperty("count");
|
||||
expect(json).toHaveProperty("mode");
|
||||
expect(Array.isArray(json.corps)).toBe(true);
|
||||
});
|
||||
|
||||
test("OPTIONS /v1/corps 处理 CORS 跨域预检", async () => {
|
||||
const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" });
|
||||
expect(res.status).toBe(204);
|
||||
expect(res.headers.get("access-control-allow-methods")).toContain("GET");
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("*");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { handleHttpRequest } from "./routes.js";
|
||||
import { VERSION } from "../version.js";
|
||||
|
||||
export type HttpServerOptions = {
|
||||
port?: number;
|
||||
host?: string;
|
||||
silent?: boolean;
|
||||
};
|
||||
|
||||
export const DEFAULT_HTTP_PORT = 8888;
|
||||
export const DEFAULT_HTTP_HOST = "127.0.0.1";
|
||||
|
||||
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
|
||||
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
|
||||
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
await handleHttpRequest(req, res);
|
||||
} catch (err) {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
|
||||
res.end(JSON.stringify({ error: true, message: err instanceof Error ? err.message : String(err) }));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
server.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
|
||||
server.listen(port, host, () => {
|
||||
if (!options.silent) {
|
||||
console.error(`\n⚡ hose-use HTTP Server (v${VERSION}) 已启动`);
|
||||
console.error(` 主服务地址: http://${host}:${port}`);
|
||||
console.error(` 交互式文档: http://${host}:${port}/docs`);
|
||||
console.error(` OpenAPI规范: http://${host}:${port}/openapi.json`);
|
||||
console.error(` CLI执行网关: POST http://${host}:${port}/api/cli`);
|
||||
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
|
||||
}
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
+2
-1
@@ -94,7 +94,8 @@ describe("hose-use MCP server & hose_cli single-gate pattern", () => {
|
||||
});
|
||||
expect(corpsResult.isError).not.toBe(true);
|
||||
const corpsContent = corpsResult.content as Array<{ type: "text"; text: string }>;
|
||||
expect(corpsContent[0]?.text).toContain("已配置企业列表");
|
||||
const text = corpsContent[0]?.text || "";
|
||||
expect(text.includes("已配置企业列表") || text.includes("未找到任何企业配置")).toBe(true);
|
||||
|
||||
// Execute invalid command
|
||||
const invalidResult = await client.callTool({
|
||||
|
||||
@@ -16,6 +16,7 @@ import { authTools } from "./core/auth/tools.js";
|
||||
import { platformTools } from "./domains/platform/tools.js";
|
||||
import { billTools } from "./domains/bill/tools.js";
|
||||
import { runCli } from "./cli/runner.js";
|
||||
import { redactSensitiveText } from "./cli/printer.js";
|
||||
import { VERSION } from "./version.js";
|
||||
import type { CliResult } from "./cli/types.js";
|
||||
|
||||
@@ -114,6 +115,7 @@ export function cliResult(result: CliResult): {
|
||||
} {
|
||||
const isError = result.exitCode !== 0;
|
||||
let text = isError ? (result.stderr || result.stdout || "Command failed") : (result.stdout || result.stderr || "Success");
|
||||
text = redactSensitiveText(text);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
export const VERSION = "0.4.0";
|
||||
export const VERSION = "0.5.0";
|
||||
Reference in new issue
Block a user