feat(cli): 分离 hose-aipro 独立命令体系并升级至 v0.9.0

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 自动递增
This commit is contained in:
gitea committed 2026-11-03 19:16:12 +08:00
1 parent c3e39fe77a
commit 362acfba58
38 files changed
+1380 -690

No files matched your search

+2 -1
View File
@@ -4,7 +4,8 @@
## 文件职责
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)。新增命令先声明元数据,再在此注册处理器。
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层处理器注册表(`area` / 共享命令元数据 / `standing` 常驻属性 / `handler`)及统一导出。新增命令先声明元数据,再在此注册处理器。
- `aipro-registry.ts`:`AIPRO_COMMAND_REGISTRY` AI PRO 确定性审批命令的声明式注册表(命令名称、别名、突变标记 `mutating`、处理器 `handler`)与 SaaS 重定向判定。与 `registry.ts` 保持完全一致的声明式设计。
- `command-metadata.ts`:命令描述、用法、子命令及别名、布尔/取值选项的共享静态定义;不导入处理器,供分发、解析与帮助共用。
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
- `parser.ts`:严格参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`);未知选项和缺值返回用法错误 `2`,相近拼写给出建议。同名参数按命令语境确定类型,例如 `bill --fields` 取值、`feetype --fields` 为布尔值,`workflow create -f` 取模板、`workflow tail -f` 为持续监听。
+234
View File
@@ -0,0 +1,234 @@
import { handleAiProHelp, handleAiProLogs, handleAiProStatus } from "./commands/aipro/status.js";
import {
handleAiProChecklist,
handleAiProPoints,
handleAiProRules,
handleAiProScopes,
} from "./commands/aipro/rules.js";
import {
handleAiProBind,
handleAiProDecide,
handleAiProInit,
handleAiProReview,
handleAiProTranslate,
} from "./commands/aipro/session.js";
import { handleUpdateCommand } from "./commands/update/index.js";
import { handleSkillCommand } from "./commands/skill.js";
import { handleServiceCommand } from "./commands/service.js";
import { formatVersionLabel, getVersionInfo } from "../version.js";
import { printJson } from "./printer.js";
import type { AiProExecutionContext } from "./commands/aipro/types.js";
import type { CliParsedArgs, CliResult } from "./types.js";
export type AiProMutatingCheck =
| boolean
| ((parsed: CliParsedArgs, positional: string[]) => boolean);
export interface AiProCommandDefinition {
name: string;
summary: string;
aliases?: readonly string[];
mutating?: AiProMutatingCheck;
handler: (ctx: AiProExecutionContext) => Promise<CliResult> | CliResult;
}
export const AIPRO_COMMAND_REGISTRY: readonly AiProCommandDefinition[] = [
{
name: "status",
summary: "查看网关状态",
aliases: ["whoami", "context", "info"],
handler: (ctx) => handleAiProStatus(ctx),
},
{
name: "init",
summary: "初始化审批上下文",
aliases: ["start"],
mutating: true,
handler: (ctx) => handleAiProInit(ctx),
},
{
name: "scopes",
summary: "列出审批规则场景",
aliases: ["index", "indexes"],
handler: (ctx) => handleAiProScopes(ctx),
},
{
name: "translate",
summary: "转译单据",
aliases: ["doc", "markdown", "render"],
handler: (ctx) => handleAiProTranslate(ctx),
},
{
name: "rules",
summary: "查看审批规则",
aliases: ["rule"],
handler: (ctx) => handleAiProRules(ctx),
},
{
name: "bind",
summary: "绑定单据",
aliases: ["mount"],
mutating: true,
handler: (ctx) => handleAiProBind(ctx),
},
{
name: "points",
summary: "查看审核要点",
aliases: ["clauses"],
mutating: (_parsed, positional) => positional.length >= 3,
handler: (ctx) => handleAiProPoints(ctx),
},
{
name: "checklist",
summary: "查看核验清单",
aliases: ["list"],
handler: (ctx) => handleAiProChecklist(ctx),
},
{
name: "review",
summary: "核验要点",
aliases: ["eval", "evaluate"],
mutating: true,
handler: (ctx) => handleAiProReview(ctx),
},
{
name: "decide",
summary: "执行仲裁",
aliases: ["approve", "reject"],
mutating: true,
handler: (ctx) => handleAiProDecide(ctx),
},
{
name: "logs",
summary: "查看审批日志",
aliases: ["log", "history", "trail"],
handler: (ctx) => handleAiProLogs(ctx),
},
{
name: "service",
summary: "管理本机 hose-aipro 常驻服务",
aliases: ["daemon"],
handler: async (ctx) => {
const subTarget = ctx.positional[1]?.toLowerCase();
if (subTarget === "hose-use" || subTarget === "hose") {
return handleServiceCommand(
{ ...ctx.parsed, action: ctx.positional[2] || "status", args: ctx.positional.slice(3) },
ctx.runtime,
"hose-use"
);
}
return handleServiceCommand(
{ ...ctx.parsed, action: ctx.positional[1] || "status", args: ctx.positional.slice(2) },
ctx.runtime,
"hose-aipro"
);
},
},
{
name: "hose-use",
summary: "管理本机 hose-use 常驻服务",
aliases: ["hose"],
handler: async (ctx) => {
const subAction = (ctx.positional[1] || "status").toLowerCase();
const serviceActions = ["start", "stop", "restart", "status", "logs", "log", "run"];
if (serviceActions.includes(subAction)) {
return handleServiceCommand(
{ ...ctx.parsed, action: subAction, args: ctx.positional.slice(2) },
ctx.runtime,
"hose-use"
);
}
return {
stdout: "",
stderr:
`[提示] 运行 hose-use ${subAction} 可直接调用合思企业平台命令。\n` +
`如需管理本机的 hose-use 常驻服务,请运行:\n` +
` hose-aipro hose-use <start|stop|restart|status|logs>\n`,
exitCode: 1,
};
},
},
{
name: "update",
summary: "检查并升级版本",
aliases: ["self-update"],
handler: async (ctx) => handleUpdateCommand(ctx.parsed, ctx.runtime),
},
{
name: "skill",
summary: "管理 Agent 技能",
aliases: ["skills"],
handler: async (ctx) => handleSkillCommand(ctx.parsed, ctx.runtime),
},
{
name: "version",
summary: "查看版本信息",
aliases: ["v"],
handler: async (ctx) => ({
stdout: ctx.jsonMode
? printJson(getVersionInfo("hose-aipro")) + "\n"
: `${formatVersionLabel("hose-aipro")}\n`,
stderr: "",
exitCode: 0,
}),
},
{
name: "help",
summary: "查看帮助说明",
handler: (ctx) => handleAiProHelp(ctx),
},
];
const aiproCommandMap = new Map<string, AiProCommandDefinition>();
for (const def of AIPRO_COMMAND_REGISTRY) {
aiproCommandMap.set(def.name.toLowerCase(), def);
for (const alias of def.aliases || []) {
aiproCommandMap.set(alias.toLowerCase(), def);
}
}
export function findAiProCommand(name: string): AiProCommandDefinition | undefined {
return aiproCommandMap.get(name.toLowerCase());
}
export const SAAS_PLATFORM_COMMANDS = [
"bill",
"flow",
"workflow",
"platform",
"datalink",
"auth",
"corps",
"contact",
"feetype",
"dimension",
"role",
"permission",
"keys",
"store",
"message",
"task",
"config",
"mcp",
"assist-platform",
] as const;
export function isSaasPlatformCommand(command: string): boolean {
return (SAAS_PLATFORM_COMMANDS as readonly string[]).includes(command.toLowerCase());
}
export function handleSaasPlatformRedirect(
command: string,
positional: string[] = []
): CliResult {
const subArgs = positional.slice(1).join(" ");
return {
stdout: "",
stderr:
`[提示] ${command} 属于合思企业平台能力,由 hose-use 命令行提供。\n` +
`请直接运行: hose-use ${command}${subArgs ? ` ${subArgs}` : ""}\n\n` +
`如需管理本机的 hose-use 常驻服务,请运行:\n` +
` hose-aipro hose-use <start|stop|restart|status|logs>\n`,
exitCode: 1,
};
}
+9 -6
View File
@@ -5,10 +5,12 @@ import { tmpdir } from "node:os";
import { runAiProCli } from "../aipro-cli.js";
import { runCli } from "./runner.js";
import { closeDatabase } from "../core/db/index.js";
const keys = ["HOSE_APPROVAL_DB", "HOSE_ENTERPRISES_DIR", "HOSE_CONFIG_FILE"] as const;
const original = keys.map(key => process.env[key]);
afterEach(() => { closeDatabase(); keys.forEach((key, i) => { if (original[i] === undefined) delete process.env[key]; else process.env[key] = original[i]; }); });
test("approval and aipro dry-runs override apply/yes without requests or database creation", async () => {
test("aipro dry-runs override apply/yes without requests or database creation", async () => {
const root = mkdtempSync(join(tmpdir(), "hose-approval-preview-"));
const corps = join(root, "corps"); mkdirSync(corps);
writeFileSync(join(corps, "corp.json"), JSON.stringify({ id: "corp", name: "Preview", source: "manual", credentials: { accessToken: "fixture", corpId: "corp", staffId: "staff" } }));
@@ -19,15 +21,16 @@ test("approval and aipro dry-runs override apply/yes without requests or databas
let requests = 0;
globalThis.fetch = (async () => { requests++; throw new Error("No network during preview"); }) as any;
try {
for (const action of ["points", "review", "decide", "approve", "reject"]) {
const result = await runCli(["approval", action, "SN", "--apply", "--yes", "--dry-run", "--json"]);
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
}
for (const action of ["init", "bind", "review", "decide", "approve", "reject"]) {
const result = await runAiProCli([action, "approve", "--run", "ABC123", "--apply", "--yes", "--dry-run", "--json"]);
expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).dryRun).toBe(true);
expect(JSON.parse(result.stdout).nextAction).toStartWith("hose-use aipro ");
expect(JSON.parse(result.stdout).nextAction).toStartWith("hose-aipro ");
}
// hose-use approval 重定向测试
const redirect = await runCli(["approval", "decide", "S123"]);
expect(redirect.exitCode).toBe(1);
expect(redirect.stderr).toContain("hose-aipro");
expect(requests).toBe(0); expect(existsSync(process.env.HOSE_APPROVAL_DB)).toBe(false);
} finally { globalThis.fetch = originalFetch; }
});
+71 -16
View File
@@ -32,20 +32,23 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
flags: { ...flagList("offline cached", "boolean") }
},
"aipro": {
"summary": "AI PRO 确定性审批仲裁",
"usage": "hose-use aipro <子命令>",
"summary": "管理本机 hose-aipro 审批网关常驻服务",
"usage": "hose-use aipro <start|stop|restart|status|logs>",
"commands": {
"status": "查看网关状态",
"bind": "绑定单据",
"review": "核验要点",
"decide": "执行仲裁",
"init": "初始化审批上下文",
"scopes": "列出审批规则场景",
"translate": "转译单据",
"rules": "查看审批规则",
"points": "查看审核要点",
"checklist": "查看核验清单",
"logs": "查看审批日志",
"start": "启动本机 hose-aipro 网关服务",
"stop": "停止本机 hose-aipro 网关服务",
"restart": "重启本机 hose-aipro 网关服务",
"status": "查看本机 hose-aipro 网关服务状态",
"logs": "查看本机 hose-aipro 网关服务日志",
"bind": "绑定单据 (已独立为 hose-aipro bind)",
"review": "核验要点 (已独立为 hose-aipro review)",
"decide": "执行仲裁 (已独立为 hose-aipro decide)",
"init": "初始化审批会话 (已独立为 hose-aipro init)",
"scopes": "列出审批规则场景 (已独立为 hose-aipro scopes)",
"translate": "转译单据 (已独立为 hose-aipro translate)",
"rules": "查看审批规则 (已独立为 hose-aipro rules)",
"points": "查看审核要点 (已独立为 hose-aipro points)",
"checklist": "查看核验清单 (已独立为 hose-aipro checklist)",
"help": "help 命令"
},
"aliases": [],
@@ -71,7 +74,59 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"history": "logs",
"trail": "logs"
},
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings i id index indexes limit m message n opinion p point proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings host i id index indexes limit m message n opinion p point port proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
},
"hose-aipro": {
"summary": "合思 AI PRO 确定性审批仲裁网关",
"usage": "hose-aipro <子命令>",
"commands": {
"status": "查看网关状态",
"bind": "绑定单据",
"review": "核验要点",
"decide": "执行仲裁",
"init": "初始化审批上下文",
"scopes": "列出审批规则场景",
"translate": "转译单据",
"rules": "查看审批规则",
"points": "查看审核要点",
"checklist": "查看核验清单",
"logs": "查看审批日志",
"service": "管理本机 hose-aipro 常驻服务",
"hose-use": "管理本机 hose-use 常驻服务",
"update": "检查并升级版本",
"skill": "管理 Agent 技能",
"version": "查看版本信息",
"help": "help 命令"
},
"aliases": [],
"commandAliases": {
"whoami": "status",
"context": "status",
"info": "status",
"start": "init",
"index": "scopes",
"indexes": "scopes",
"doc": "translate",
"markdown": "translate",
"render": "translate",
"rule": "rules",
"mount": "bind",
"clauses": "points",
"list": "checklist",
"eval": "review",
"evaluate": "review",
"approve": "decide",
"reject": "decide",
"log": "logs",
"history": "logs",
"trail": "logs",
"self-update": "update",
"skills": "skill",
"daemon": "service",
"hose": "hose-use",
"v": "version"
},
flags: { ...flagList("apply confirm do execute j json v version y yes", "boolean"), ...flagList("run a action c code codes comment corp e eval evidence findings host i id index indexes limit m message n opinion p point port proof r reason reasoning rule rules s scope scopes sn state status target 审批意见 意见", "value") }
},
"auth": {
"summary": "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
@@ -869,11 +924,11 @@ export function localCommandFlags(area?: string, action?: string): Record<string
|| (["bill", "flow"].includes(resolved?.area || "") && ["list", "link"].includes(canonical || "list"))
|| (resolved?.area === "workflow" && canonical === "node")
|| (resolved?.area === "platform" && canonical === "record")
|| (resolved?.area === "aipro" && canonical === "bind");
|| (["aipro", "hose-aipro"].includes(resolved?.area || "") && canonical === "bind");
if (!localC) delete flags.c;
if (resolved?.area === "workflow" && canonical === "create") flags.f = "value";
// --run historically accepts a session ID and, for decide, an apply boolean.
if (resolved?.area === "aipro" && canonical === "decide") flags.run = "boolean-or-value";
if (["aipro", "hose-aipro"].includes(resolved?.area || "") && canonical === "decide") flags.run = "boolean-or-value";
return flags;
}
-335
View File
@@ -1,335 +0,0 @@
import { isDryRun, mutationPreview } from "../mutation.js";
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.js";
import { stringOption, booleanOption, numberOption } from "../parser.js";
import { createSessionClient } from "../../core/http/session-client.js";
import {
ApprovalService,
ApprovalGatewayBlockedError,
FindingCheckStatus,
} from "../../domains/approval/index.js";
export async function handleApprovalCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
throw new Error(
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
);
}
const corpId = corp.corpId || corp.id;
// 解析命令层级:
// 形式 A: hose-use approval audit points S26000001
// 形式 B: hose-use approval points S26000001
// 形式 C: hose-use approval audit S26000001
let subAction = parsed.action?.toLowerCase();
let args = [...parsed.args];
if (subAction === "audit" && args.length > 0) {
const candidateSub = args[0]?.toLowerCase();
if (["points", "inject", "checklist", "list", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(candidateSub)) {
subAction = candidateSub;
args.shift();
}
}
const targetSn = args[0] || stringOption(parsed.options, ["code", "sn", "target", "id"]);
if (targetSn && isDryRun(parsed, runtime) && ["audit", "points", "inject", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(subAction || "audit")) {
return mutationPreview(parsed, runtime, "预览审批操作", targetSn, { action: subAction || "audit", corpId, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
}
const client = await createSessionClient(corp);
const service = new ApprovalService();
switch (subAction) {
// ── 1. 规则注入与出明细级审核要点清单 ─────────────────────────────────────
case "points":
case "inject": {
if (!targetSn) {
throw new Error("请提供单号或单据 ID: hose-use approval audit points <单号>");
}
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
const result = await service.injectAuditPoints(client, corpId, targetSn, {
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
sn: result.bill.billCode,
scope: result.scope,
runId: result.run.id,
count: result.findings.length,
findings: result.findings,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
const rows = result.findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus,
]);
const table = printTable(headers, rows);
const title = `====== 单据 ${result.bill.billCode} 明细级审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
const tip =
`\n[要点注入完成] 审核要点已固化至审批实例,审批链路已激活!\n` +
`下一步: 请对要点进行事实核验判定: hose-use approval audit review ${result.bill.billCode} --eval "1=PASS; 2=FAIL:证据说明; ..."\n` +
`完成核验后,由确定性网关仲裁审批: hose-use approval audit decide ${result.bill.billCode} --apply --yes\n`;
return {
stdout: title + table + tip,
stderr: "",
exitCode: 0,
};
}
// ── 2. 查看当前审核要点清单与核验状态 ─────────────────────────────────────
case "checklist":
case "list":
case "status": {
if (!targetSn) {
throw new Error("请提供单号或单据 ID: hose-use approval audit checklist <单号>");
}
const { run, findings } = service.getAuditChecklist(targetSn, corpId);
if (!run || findings.length === 0) {
const errorMsg =
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`审批链路当前物理不通!请先执行: hose-use approval audit points ${targetSn} 注入审核要点清单。\n`;
return { stdout: "", stderr: errorMsg, exitCode: 1 };
}
if (runtime.jsonMode) {
return {
stdout: printJson({ run, findings }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 推理说明"];
const rows = findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
const title = `====== 单据 ${targetSn} 审核要点核验进度 (总计: ${findings.length} | 待核验: ${pendingCount} | 运行决策: ${run.decision}) ======\n`;
return {
stdout: title + table,
stderr: "",
exitCode: 0,
};
}
// ── 3. 逐项核验事实打标 ──────────────────────────────────────────────────
case "review":
case "eval":
case "evaluate": {
if (!targetSn) {
throw new Error("请提供单号: hose-use approval audit review <单号> --eval '...'");
}
const evalStr = stringOption(parsed.options, ["eval", "findings", "data", "e"]);
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined;
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]);
const updates: Array<{
index?: number;
id?: string;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}> = [];
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
updates.push({
index: pointIndex,
status: statusInput,
evidence,
reasoning,
});
} else if (evalStr) {
// 解析便捷语法: "1=FAIL:未上传发票; 2=PASS; 3=SKIP; 4=FAIL:大连住宿超标且无特批"
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
for (const seg of segments) {
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
if (match) {
const idx = parseInt(match[1], 10);
const status = match[2].toUpperCase() as FindingCheckStatus;
const desc = match[3]?.trim();
updates.push({
index: idx,
status,
evidence: desc,
reasoning: desc,
});
}
}
}
if (updates.length === 0) {
throw new Error(
`请提供核验判定参数,例如:\n` +
` hose-use approval audit review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
` 或: hose-use approval audit review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
);
}
try {
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, corpId);
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
const rows = updatedFindings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
const msg =
`====== 单据 ${targetSn} 核验判定已更新 (待核验剩余: ${pendingCount} 项) ======\n` +
table +
(pendingCount === 0
? `\n[核验全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-use approval audit decide ${targetSn} --apply --yes\n`
: `\n[待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
return { stdout: msg, stderr: "", exitCode: 0 };
} catch (err: any) {
if (err instanceof ApprovalGatewayBlockedError) {
return { stdout: "", stderr: `${err.message}\n`, exitCode: 1 };
}
throw err;
}
}
// ── 4. 确定性网关仲裁与审批决断 ──────────────────────────────────────────
case "decide":
case "approve":
case "reject": {
if (!targetSn) {
throw new Error("请提供单号: hose-use approval audit decide <单号> [--apply] [--yes]");
}
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
if (apply) {
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
if (!confirmed) {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
}
const { prompt } = await import("../helpers.js");
const ans = await prompt("网关将向合思系统真实执行审批/驳回/留痕,确认继续?输入 yes: ");
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
}
}
const requestedAction = subAction === "approve" ? "approve" : subAction === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
try {
const decisionResult = await service.decideAudit(client, corpId, targetSn, {
requestedAction,
apply,
comment: userComment,
});
if (runtime.jsonMode) {
return {
stdout: printJson(decisionResult, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const outLines: string[] = [];
outLines.push(`\n====== 合思 AI 确定性网关仲裁裁决书 (单号: ${targetSn}) ======`);
outLines.push(`网关决策 : ${decisionResult.decision}`);
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
if (apply) {
outLines.push(`下游动作 : 已安全执行 [${decisionResult.appliedAction}] 动作`);
} else {
outLines.push(`执行模式 : 预审仿真 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
}
outLines.push(`\n--- 审计意见文本快照 ---\n${decisionResult.decisionSummary}\n`);
return {
stdout: outLines.join("\n"),
stderr: "",
exitCode: 0,
};
} catch (err: any) {
if (err instanceof ApprovalGatewayBlockedError) {
return {
stdout: "",
stderr: `\n${err.message}\n`,
exitCode: 1,
};
}
throw err;
}
}
// ── 5. 缺省:智能引导 (未注入则出要点,已注入则显示清单) ─────────────────────
case "audit":
case undefined: {
if (!targetSn) {
return {
stdout:
`====== 合思 AI 确定性审批网关 (hose-use approval) ======\n` +
`用法:\n` +
` 1. 出明细级审核要点 (规则注入) : hose-use approval audit points <单号> [--scope <场景>]\n` +
` 2. 查看当前审核要点清单 : hose-use approval audit checklist <单号>\n` +
` 3. 逐项录入事实核验判定 : hose-use approval audit review <单号> --eval "1=PASS; 2=FAIL:说明"\n` +
` 4. 网关确定性仲裁与执行审批 : hose-use approval audit decide <单号> [--apply] [--yes]\n`,
stderr: "",
exitCode: 0,
};
}
// 检查当前是否已注入要点
const { run } = service.getAuditChecklist(targetSn, corpId);
if (!run) {
// 自动触发第一步:注入并出审核要点
return await handleApprovalCommand(
{ ...parsed, action: "points", args: [targetSn] },
runtime
);
} else {
// 已有要点,展示清单与进度
return await handleApprovalCommand(
{ ...parsed, action: "checklist", args: [targetSn] },
runtime
);
}
}
default:
throw new Error(`未知的审批网关动作: ${subAction}。请运行 hose-use approval audit 查看帮助。`);
}
}
+4 -3
View File
@@ -79,13 +79,14 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
expect(data.sessions).toBeDefined();
});
test("hose-use aipro status 双向桥接成功转发", async () => {
test("hose-use aipro status 管理本机 aipro 守护进程状态", async () => {
const res = await runCli(["aipro", "status", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.tool).toBe("hose-aipro");
expect(data.ruleEngine.scopesCount).toBe(2);
expect(data.serviceName).toBe("hose-aipro");
expect(data.port).toBe(8889);
expect(data.running).toBe(false);
});
test("hose-aipro 帮助页在顶部动态展示当前企业页眉", async () => {
+20 -1
View File
@@ -1,7 +1,12 @@
import { expect, spyOn, test } from "bun:test";
import * as service from "../service.js";
import { parseArgs } from "../parser.js";
import { handleServiceCommand } from "./service.js";
import {
handleServiceCommand,
handleAiProServiceCommand,
handleApprovalRedirectCommand,
} from "./service.js";
test("service lifecycle previews never dispatch process or state mutations", async () => {
const dispatch = spyOn(service, "runServiceCommand").mockResolvedValue({ running: false } as any);
try {
@@ -13,5 +18,19 @@ test("service lifecycle previews never dispatch process or state mutations", asy
expect(dispatch).not.toHaveBeenCalled();
await handleServiceCommand(parseArgs(["service", "status"]), { jsonMode: true } as any);
expect(dispatch).toHaveBeenCalledTimes(1);
// hose-use aipro status
await handleAiProServiceCommand(parseArgs(["aipro", "status"]), { jsonMode: true } as any);
expect(dispatch).toHaveBeenCalledTimes(2);
// hose-use aipro bind 重定向阻断提示
const bindRedirect = await handleAiProServiceCommand(parseArgs(["aipro", "bind", "S123"]), { jsonMode: true } as any);
expect(bindRedirect.exitCode).toBe(1);
expect(bindRedirect.stderr).toContain("hose-aipro");
// hose-use approval 重定向提示
const approvalRedirect = await handleApprovalRedirectCommand(parseArgs(["approval", "decide", "S123"]), { jsonMode: true } as any);
expect(approvalRedirect.exitCode).toBe(1);
expect(approvalRedirect.stderr).toContain("hose-aipro");
} finally { dispatch.mockRestore(); }
});
+100 -21
View File
@@ -1,8 +1,14 @@
import { isDryRun, mutationPreview } from "../mutation.js";
import { homedir } from "node:os";
import { join } from "node:path";
import { VERSION } from "../../version.js";
import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../service.js";
import {
runServiceCommand,
getHoseUseServiceConfig,
getAiProServiceConfig,
getPidFile,
getLogFile,
SERVICE_STATE_DIR,
type ServiceConfig,
type ServiceTargetName,
} from "../service.js";
import { printJson, printKeyValue } from "../printer.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
@@ -10,13 +16,30 @@ import { createSessionClient } from "../../core/http/session-client.js";
import { EventStore } from "../../domains/events/store.js";
import { pollEvents } from "../../domains/events/poller.js";
export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
export { SERVICE_STATE_DIR };
export async function handleServiceCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
runtime: CliRuntime,
forcedTarget?: ServiceTargetName
): Promise<CliResult> {
const action = parsed.action || parsed.args[0] || "status";
const firstPos = (parsed.action || parsed.args[0] || "").toLowerCase();
const secondPos = (parsed.args[0] || parsed.args[1] || "").toLowerCase();
let target: ServiceTargetName = forcedTarget || "hose-use";
let action = parsed.action || parsed.args[0] || "status";
// 支持 hose-use service aipro <start|stop|status>
if (!forcedTarget) {
if (firstPos === "aipro" || firstPos === "hose-aipro") {
target = "hose-aipro";
action = secondPos || "status";
} else if (firstPos === "hose-use" || firstPos === "hose") {
target = "hose-use";
action = secondPos || "status";
}
}
const port = numberOption(parsed.options, ["port", "p"]);
const host = stringOption(parsed.options, ["host", "h"]);
@@ -30,22 +53,34 @@ export async function handleServiceCommand(
const store = new EventStore(stateFile || `corp:${corpId}`);
const result = await pollEvents(client, corpId, store, limit);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "存储后端": stateFile || "SQLite (observed_events)" })}\n`, stderr: "", exitCode: 0 };
return {
stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({
"待办扫描": result.scanned.todo,
"未读消息扫描": result.scanned.messages,
"新增事件": result.newEvents.length,
"重复事件": result.duplicateCount,
"存储后端": stateFile || "SQLite (observed_events)",
})}\n`,
stderr: "",
exitCode: 0,
};
}
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 config: ServiceConfig =
target === "hose-aipro"
? getAiProServiceConfig(runtime, { port, host })
: getHoseUseServiceConfig(runtime, { port, host });
if (["start", "stop", "restart", "run"].includes(action) && isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "管理 hose-use 服务", action, { action, port, host, stateDir: config.stateDir });
return mutationPreview(
parsed,
runtime,
`管理 ${config.serviceName} 服务`,
action,
{ action, port, host, stateDir: config.stateDir }
);
}
const result = await runServiceCommand(action, config);
if (result === undefined) {
@@ -60,7 +95,7 @@ export async function handleServiceCommand(
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`,
stdout: `====== ${config.serviceName} 守护进程日志 (${logsResult.logFile}) ======\n${logsResult.content}\n`,
stderr: "",
exitCode: 0,
};
@@ -73,7 +108,7 @@ export async function handleServiceCommand(
"服务状态": isRunning ? "🟢 正在运行 (Running)" : "⚪ 已停止 (Stopped)",
...(status.pid ? { "进程 PID": status.pid } : {}),
...(status.url ? { "服务地址": status.url } : {}),
...(status.url ? { "交互式文档": `${status.url}/docs` } : {}),
...(target === "hose-use" && status.url ? { "交互式文档": `${status.url}/docs` } : {}),
...(status.url ? { "CLI 网关": `POST ${status.url}/api/cli` } : {}),
"运行版本": status.version || config.version,
"状态目录": status.stateDir || config.stateDir,
@@ -81,10 +116,54 @@ export async function handleServiceCommand(
"日志文件": status.logFile || getLogFile(config),
};
const title = (status.serviceTitle as string) || config.serviceTitle || "常驻服务管理 (Service)";
const formatted = printKeyValue(displayPairs);
return {
stdout: `====== hose-use 常驻服务管理 (Service) ======\n${formatted}\n`,
stdout: `====== ${title} ======\n${formatted}\n`,
stderr: "",
exitCode: 0,
};
}
export async function handleAiProServiceCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = (parsed.action || parsed.args[0] || "status").toLowerCase();
const serviceActions = ["start", "stop", "restart", "status", "logs", "log", "run"];
if (!serviceActions.includes(action)) {
return {
stdout: "",
stderr:
`[提示] AI PRO 确定性审批仲裁命令已完全独立为 hose-aipro 命令行。\n` +
`请直接运行: hose-aipro ${action} ${parsed.args.join(" ")}\n\n` +
`如需管理本机的 AI PRO 网关常驻服务,请运行:\n` +
` hose-use aipro <start|stop|restart|status|logs>\n`,
exitCode: 1,
};
}
return handleServiceCommand(parsed, runtime, "hose-aipro");
}
export async function handleApprovalRedirectCommand(
parsed: CliParsedArgs,
_runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action || parsed.args[0] || "";
const subArgs = parsed.args.slice(1).join(" ");
return {
stdout: "",
stderr:
`[提示] 确定性审批仲裁命令已独立为 hose-aipro 命令行。\n` +
`请直接运行: hose-aipro ${action}${subArgs ? ` ${subArgs}` : ""}\n\n` +
`常用命令推荐:\n` +
` • 查看要点: hose-aipro points <单号>\n` +
` • 事实证据核验: hose-aipro review <单号> --findings='[...]'\n` +
` • 执行审批仲裁: hose-aipro decide <单号> --apply --yes\n` +
` • 审批日志溯源: hose-aipro logs <单号>\n` +
` • 网关服务启停: hose-use aipro <start|stop|status>\n`,
exitCode: 1,
};
}
+97 -29
View File
@@ -1,10 +1,15 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
EMBEDDED_SKILL_FILES,
EMBEDDED_HOSE_USE_SKILL_FILES,
EMBEDDED_AIPRO_SKILL_FILES,
getDefaultGlobalSkillDir,
getDefaultAiProGlobalSkillDir,
getSkillContent,
getAiProSkillContent,
installSkillFiles,
installHoseUseSkillFiles,
installAiProSkillFiles,
} from "../../packaging/embedded-skill.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
@@ -16,13 +21,16 @@ export async function handleSkillCommand(
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action || "status";
const isAiProCaller =
parsed.area === "hose-aipro" ||
parsed.raw.some((arg) => arg.includes("hose-aipro") || arg === "aipro");
switch (action) {
case "dump":
case "cat":
case "show":
return {
stdout: `${getSkillContent()}\n`,
stdout: `${isAiProCaller ? getAiProSkillContent() : getSkillContent()}\n`,
stderr: "",
exitCode: 0,
};
@@ -36,30 +44,71 @@ export async function handleSkillCommand(
const customDir =
stringOption(parsed.options, ["dir", "target"]) || parsed.args[0];
const targetDir = customDir
? customDir
: isLocal
? join(process.cwd(), ".agents", "skills", "hose-use")
: getDefaultGlobalSkillDir();
const globalHoseDir = getDefaultGlobalSkillDir();
const globalAiProDir = getDefaultAiProGlobalSkillDir();
const localHoseDir = join(process.cwd(), ".agents", "skills", "hose-use");
const localAiProDir = join(process.cwd(), ".agents", "skills", "hose-aipro");
const targetPolicy = customDir ? "explicit" : isLocal ? "workspace" : "global-canonical";
const totalFiles =
Object.keys(EMBEDDED_HOSE_USE_SKILL_FILES).length +
Object.keys(EMBEDDED_AIPRO_SKILL_FILES).length;
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "安装 Agent Skill 文件", targetDir, {
fileCount: Object.keys(EMBEDDED_SKILL_FILES).length,
local: isLocal,
targetPolicy: customDir ? "explicit" : isLocal ? "workspace" : "global-canonical",
});
return mutationPreview(
parsed,
runtime,
"安装 Agent Skill 文件 (hose-use 与 hose-aipro)",
customDir || (isLocal ? `${localHoseDir} & ${localAiProDir}` : `${globalHoseDir} & ${globalAiProDir}`),
{
fileCount: totalFiles,
local: isLocal,
targetPolicy,
skills: ["hose-use", "hose-aipro"],
}
);
}
requireMutationConfirmation(parsed, runtime, "安装 Agent Skill 文件", `hose-use skill install${customDir ? ` --dir=${customDir}` : ""} --yes`);
requireMutationConfirmation(
parsed,
runtime,
"安装 Agent Skill 文件",
`${isAiProCaller ? "hose-aipro" : "hose-use"} skill install${customDir ? ` --dir=${customDir}` : ""} --yes`
);
const result = installSkillFiles(targetDir);
let installedReport: { targetDirs: string[]; filesCount: number; skills: string[] };
if (customDir) {
const res = installSkillFiles(customDir);
installedReport = {
targetDirs: [res.targetDir],
filesCount: res.files.length,
skills: ["hose-use"],
};
} else if (isLocal) {
const hoseRes = installHoseUseSkillFiles(localHoseDir);
const aiproRes = installAiProSkillFiles(localAiProDir);
installedReport = {
targetDirs: [hoseRes.targetDir, aiproRes.targetDir],
filesCount: hoseRes.files.length + aiproRes.files.length,
skills: ["hose-use", "hose-aipro"],
};
} else {
const hoseRes = installHoseUseSkillFiles(globalHoseDir);
const aiproRes = installAiProSkillFiles(globalAiProDir);
installedReport = {
targetDirs: [hoseRes.targetDir, aiproRes.targetDir],
filesCount: hoseRes.files.length + aiproRes.files.length,
skills: ["hose-use", "hose-aipro"],
};
}
if (runtime.jsonMode) {
return {
stdout: printJson({
installed: true,
targetDir: result.targetDir,
fileCount: result.files.length,
files: result.files,
targetDirs: installedReport.targetDirs,
fileCount: installedReport.filesCount,
skills: installedReport.skills,
}),
stderr: "",
exitCode: 0,
@@ -67,7 +116,10 @@ export async function handleSkillCommand(
}
return {
stdout: `[SUCCESS] hose-use 技能已成功安装至: ${result.targetDir}\n包含文件: ${result.files.join(", ")}\n`,
stdout:
`[SUCCESS] Agent 技能已成功安装:\n` +
installedReport.targetDirs.map((d) => ` • ${d}`).join("\n") +
`\n共 ${installedReport.filesCount} 个文件。\n`,
stderr: "",
exitCode: 0,
};
@@ -75,17 +127,31 @@ export async function handleSkillCommand(
case "status":
case "get": {
const globalDir = getDefaultGlobalSkillDir();
const localDir = join(process.cwd(), ".agents", "skills", "hose-use");
const globalHoseDir = getDefaultGlobalSkillDir();
const globalAiProDir = getDefaultAiProGlobalSkillDir();
const localHoseDir = join(process.cwd(), ".agents", "skills", "hose-use");
const localAiProDir = join(process.cwd(), ".agents", "skills", "hose-aipro");
const statusObj = {
global: {
dir: globalDir,
installed: existsSync(join(globalDir, "SKILL.md")),
"hose-use": {
global: {
dir: globalHoseDir,
installed: existsSync(join(globalHoseDir, "SKILL.md")),
},
local: {
dir: localHoseDir,
installed: existsSync(join(localHoseDir, "SKILL.md")),
},
},
local: {
dir: localDir,
installed: existsSync(join(localDir, "SKILL.md")),
"hose-aipro": {
global: {
dir: globalAiProDir,
installed: existsSync(join(globalAiProDir, "SKILL.md")),
},
local: {
dir: localAiProDir,
installed: existsSync(join(localAiProDir, "SKILL.md")),
},
},
};
@@ -94,12 +160,14 @@ export async function handleSkillCommand(
}
const output = printKeyValue({
"全局 Skill 目录": `${globalDir} [${statusObj.global.installed ? "已安装 ✅" : "未安装 ❌"}]`,
"本地 Skill 目录": `${localDir} [${statusObj.local.installed ? "已安装 ✅" : "未安装 ❌"}]`,
"hose-use (全局)": `${globalHoseDir} [${statusObj["hose-use"].global.installed ? "已安装 ✅" : "未安装 ❌"}]`,
"hose-aipro (全局)": `${globalAiProDir} [${statusObj["hose-aipro"].global.installed ? "已安装 ✅" : "未安装 ❌"}]`,
"hose-use (本地)": `${localHoseDir} [${statusObj["hose-use"].local.installed ? "已安装 ✅" : "未安装 ❌"}]`,
"hose-aipro (本地)": `${localAiProDir} [${statusObj["hose-aipro"].local.installed ? "已安装 ✅" : "未安装 ❌"}]`,
});
return {
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 hose-use skill install --yes 进行全局安装\n`,
stdout: `====== Agent Skill 状态 ======\n${output}\n\n提示: 运行 ${isAiProCaller ? "hose-aipro" : "hose-use"} skill install --yes 进行全局安装\n`,
stderr: "",
exitCode: 0,
};
+7 -1
View File
@@ -53,7 +53,13 @@ export function mutationPreview(
changes: Record<string, unknown>
): CliResult {
const confirmedArgs = parsed.raw.filter((arg) => !["--dry-run", "--dryRun", "--dryrun"].includes(arg));
const nextAction = `hose-use ${confirmedArgs.join(" ")} --yes`;
const isAiPro = confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "aipro";
const binaryPrefix = isAiPro ? "hose-aipro" : "hose-use";
const cleanArgs =
confirmedArgs[0] === "hose-aipro" || confirmedArgs[0] === "hose-use" || confirmedArgs[0] === "aipro"
? confirmedArgs.slice(1)
: confirmedArgs;
const nextAction = `${binaryPrefix} ${cleanArgs.join(" ")} --yes`;
const payload = {
dryRun: true,
operation,
+1 -1
View File
@@ -229,7 +229,7 @@ ${Object.entries(HELP_REGISTRY).map(([area, topic]) => ` ${area.padEnd(12)}${to
常用示例:
hose-use context # 一键查看全局运行上下文与身份诊断 (免读源码)
hose-use aipro status # 查看 AI PRO 审批网关状态与当前连接企业
hose-aipro status # 查看 AI PRO 审批网关状态与当前连接企业
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
hose-use auth status # 查看当前登录状态与活跃企业
hose-use config paths # 查看多级企业配置目录链
+14 -9
View File
@@ -13,7 +13,11 @@ import { handleOpenApiCommand } from "./commands/openapi.js";
import { handleBillCommand } from "./commands/bill/index.js";
import { handleFlowCommand } from "./commands/flow.js";
import { handleContactCommand } from "./commands/contact.js";
import { handleServiceCommand } from "./commands/service.js";
import {
handleServiceCommand,
handleAiProServiceCommand,
handleApprovalRedirectCommand,
} from "./commands/service.js";
import { handleHttpCommand } from "./commands/http.js";
import { handleTaskCommand } from "./commands/task.js";
import { handleMessageCommand } from "./commands/message.js";
@@ -21,7 +25,6 @@ import { handleDimensionCommand } from "./commands/dimension.js";
import { handleRoleCommand } from "./commands/role.js";
import { handlePermissionCommand } from "./commands/permission.js";
import { handleRuleCommand } from "./commands/rule.js";
import { handleApprovalCommand } from "./commands/approval.js";
import { handleContextCommand } from "./commands/context.js";
import { handleKeysCommand } from "./commands/keys.js";
import { handleStoreCommand } from "./commands/store.js";
@@ -30,6 +33,8 @@ import { handleAssistPlatformCommand } from "./commands/assist-platform/index.js
import { COMMAND_METADATA, type CliCommandMetadata } from "./command-metadata.js";
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
export * from "./aipro-registry.js";
export type CliCommandHandler = (
parsed: CliParsedArgs,
runtime: CliRuntime,
@@ -51,12 +56,12 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
{
area: "aipro",
...COMMAND_METADATA.aipro,
handler: async (parsed) => {
const { runAiProCli } = await import("../aipro-cli.js");
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
const subArgs = aiproIdx !== -1 ? parsed.raw.slice(aiproIdx + 1) : parsed.raw.slice(1);
return runAiProCli(subArgs);
},
handler: (parsed, runtime) => handleAiProServiceCommand(parsed, runtime),
},
{
area: "hose-aipro",
...COMMAND_METADATA["hose-aipro"],
handler: (parsed, runtime) => handleAiProServiceCommand(parsed, runtime),
},
{
area: "auth",
@@ -126,7 +131,7 @@ export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
{
area: "approval",
...COMMAND_METADATA.approval,
handler: (parsed, runtime) => handleApprovalCommand(parsed, runtime),
handler: (parsed, runtime) => handleApprovalRedirectCommand(parsed, runtime),
},
{
area: "message",
+116 -19
View File
@@ -1,9 +1,24 @@
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";
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;
@@ -14,13 +29,56 @@ export type ServiceConfig = {
};
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);
@@ -39,24 +97,32 @@ export async function runServiceCommand(
case undefined:
return serviceStatus(config);
default:
throw new Error("用法: hose-use service <start|stop|restart|status|logs|poll>");
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) : false;
const running = pid ? isHoseServiceProcess(pid, config.appRoot, config.serviceName) : 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 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,
@@ -75,17 +141,24 @@ async function runService(config: ServiceConfig) {
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 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, `service starting on http://${host}:${port} pid=${process.pid}`);
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 });
appendLog(logFile, `service listening pid=${process.pid}`);
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, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
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 });
}
@@ -100,7 +173,7 @@ async function runService(config: ServiceConfig) {
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
}
appendLog(logFile, `service stopped pid=${process.pid}`);
appendLog(logFile, `${config.serviceName || "hose-use"} service stopped pid=${process.pid}`);
};
await new Promise<void>((resolve) => {
@@ -140,14 +213,14 @@ function startService(config: ServiceConfig) {
const pidFile = getPidFile(config);
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
appendLog(getLogFile(config), `service started pid=${child.pid}`);
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)) {
if (!pid || !isHoseServiceProcess(pid, config.appRoot, config.serviceName)) {
rmSync(pidFile, { force: true });
return options.quiet ? undefined : { stopped: false, reason: "服务未处于运行状态" };
}
@@ -158,7 +231,7 @@ function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
// ignore
}
rmSync(pidFile, { force: true });
appendLog(getLogFile(config), `service stop requested pid=${pid}`);
appendLog(getLogFile(config), `${config.serviceName || "hose-use"} service stop requested pid=${pid}`);
return options.quiet ? undefined : { stopped: true, pid };
}
@@ -176,16 +249,34 @@ function readServiceLogs(config: ServiceConfig, maxLines = 50) {
};
}
export function isHoseServiceProcess(pid: number, appRoot: string): boolean {
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 matchesTarget =
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");
return matchesTarget && command.includes("service") && command.includes("run");
command.includes("src/cli.ts") ||
command.includes("hose-aipro")
);
} catch {
return false;
}
@@ -201,11 +292,17 @@ function isProcessRunning(pid: number): boolean {
}
export function getPidFile(config: ServiceConfig): string {
return join(config.stateDir, "service.pid");
const fileName =
config.pidFileName ||
(config.serviceName === "hose-aipro" ? "aipro-service.pid" : "service.pid");
return join(config.stateDir, fileName);
}
export function getLogFile(config: ServiceConfig): string {
return join(config.stateDir, "service.log");
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 {