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:
1 parent
c3e39fe77a
commit
362acfba58
38 files changed
+1380
-690
No files matched your search
@@ -3,6 +3,13 @@ import { runAiProCli } from "./aipro-cli.js";
|
||||
import { closeDatabase, getDatabase } from "./core/db/index.js";
|
||||
import { ApprovalRepository } from "./domains/approval/repository.js";
|
||||
import { getVersionInfo } from "./version.js";
|
||||
import { COMMAND_METADATA } from "./cli/command-metadata.js";
|
||||
import {
|
||||
AIPRO_COMMAND_REGISTRY,
|
||||
findAiProCommand,
|
||||
isSaasPlatformCommand,
|
||||
SAAS_PLATFORM_COMMANDS,
|
||||
} from "./cli/aipro-registry.js";
|
||||
|
||||
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
beforeEach(() => {
|
||||
@@ -159,4 +166,60 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
expect(blockReject.stderr).toContain("不存在任何【硬性】或【弹性】违规条款");
|
||||
expect(blockReject.stderr).toContain("严禁无故或恶意驳回");
|
||||
});
|
||||
|
||||
test("二级公共命令一致性:update、skill 与 service 正常执行", async () => {
|
||||
// 1. update --dry-run
|
||||
const updateRes = await runAiProCli(["update", "--dry-run", "--json"]);
|
||||
expect(updateRes.exitCode).toBe(0);
|
||||
const updateData = JSON.parse(updateRes.stdout);
|
||||
expect(updateData.dryRun).toBe(true);
|
||||
|
||||
// 2. skill status
|
||||
const skillRes = await runAiProCli(["skill", "status", "--json"]);
|
||||
expect(skillRes.exitCode).toBe(0);
|
||||
const skillData = JSON.parse(skillRes.stdout);
|
||||
expect(skillData["hose-use"]).toBeDefined();
|
||||
expect(skillData["hose-aipro"]).toBeDefined();
|
||||
|
||||
// 3. service status (hose-aipro 自身)
|
||||
const serviceRes = await runAiProCli(["service", "status", "--json"]);
|
||||
expect(serviceRes.exitCode).toBe(0);
|
||||
const serviceData = JSON.parse(serviceRes.stdout);
|
||||
expect(serviceData.serviceName).toBe("hose-aipro");
|
||||
expect(serviceData.port).toBe(8889);
|
||||
|
||||
// 4. hose-use 服务跨进程管理 (hose-aipro hose-use status)
|
||||
const peerRes = await runAiProCli(["hose-use", "status", "--json"]);
|
||||
expect(peerRes.exitCode).toBe(0);
|
||||
const peerData = JSON.parse(peerRes.stdout);
|
||||
expect(peerData.serviceName).toBe("hose-use");
|
||||
expect(peerData.port).toBe(8888);
|
||||
|
||||
// 5. SaaS 命令在 hose-aipro 下友好重定向提示
|
||||
const billRes = await runAiProCli(["bill", "list"]);
|
||||
expect(billRes.exitCode).toBe(1);
|
||||
expect(billRes.stderr).toContain("属于合思企业平台能力,由 hose-use 命令行提供");
|
||||
});
|
||||
|
||||
test("声明式注册表规范性:所有命令与别名同元数据严格对齐", () => {
|
||||
const meta = COMMAND_METADATA["hose-aipro"];
|
||||
expect(meta).toBeDefined();
|
||||
|
||||
// 1. 注册表中的每一个命令都在 metadata.commands 中有说明
|
||||
for (const cmd of AIPRO_COMMAND_REGISTRY) {
|
||||
expect(meta.commands[cmd.name]).toBeDefined();
|
||||
}
|
||||
|
||||
// 2. 所有的别名都能正确通过 findAiProCommand 查找到原命令
|
||||
for (const [alias, canonical] of Object.entries(meta.commandAliases)) {
|
||||
const def = findAiProCommand(alias);
|
||||
expect(def).toBeDefined();
|
||||
expect(def?.name).toBe(canonical);
|
||||
}
|
||||
|
||||
// 3. 所有的 SaaS 重定向命令都正确标记
|
||||
for (const saasCmd of SAAS_PLATFORM_COMMANDS) {
|
||||
expect(isSaasPlatformCommand(saasCmd)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
+31
-82
@@ -9,21 +9,12 @@ import {
|
||||
ApprovalRepository,
|
||||
ApprovalGatewayBlockedError,
|
||||
} from "./domains/approval/index.js";
|
||||
import { formatVersionLabel, getVersionInfo } from "./version.js";
|
||||
import { handleAiProHelp, handleAiProLogs, handleAiProStatus } from "./cli/commands/aipro/status.js";
|
||||
import {
|
||||
handleAiProChecklist,
|
||||
handleAiProPoints,
|
||||
handleAiProRules,
|
||||
handleAiProScopes,
|
||||
} from "./cli/commands/aipro/rules.js";
|
||||
import {
|
||||
handleAiProBind,
|
||||
handleAiProDecide,
|
||||
handleAiProInit,
|
||||
handleAiProReview,
|
||||
handleAiProTranslate,
|
||||
} from "./cli/commands/aipro/session.js";
|
||||
findAiProCommand,
|
||||
isSaasPlatformCommand,
|
||||
handleSaasPlatformRedirect,
|
||||
} from "./cli/aipro-registry.js";
|
||||
import { handleAiProHelp } from "./cli/commands/aipro/status.js";
|
||||
import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
|
||||
|
||||
export async function runAiProCli(
|
||||
@@ -51,10 +42,21 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
const corp = runtime.selectedCorp;
|
||||
const previewPositional = parsed.positional || [];
|
||||
const previewCommand = (previewPositional[0] || "help").toLowerCase();
|
||||
const mutating = ["init", "start", "bind", "mount", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(previewCommand) || (["points", "clauses"].includes(previewCommand) && previewPositional.length >= 3);
|
||||
if (mutating && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview({ ...parsed, raw: ["aipro", ...rawArgs] }, runtime, "预览 AI PRO 审批操作", stringOption(parsed.options, ["run", "r", "code", "sn", "id", "target"]) || previewPositional[1] || "未指定", { action: previewCommand, corpId: corp?.corpId || corp?.id, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) });
|
||||
const previewDef = findAiProCommand(previewCommand);
|
||||
const isMutating = typeof previewDef?.mutating === "function"
|
||||
? previewDef.mutating(parsed, previewPositional)
|
||||
: Boolean(previewDef?.mutating);
|
||||
|
||||
if (isMutating && isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
{ ...parsed, raw: ["hose-aipro", ...rawArgs] },
|
||||
runtime,
|
||||
"预览 AI PRO 审批操作",
|
||||
stringOption(parsed.options, ["run", "r", "code", "sn", "id", "target"]) || previewPositional[1] || "未指定",
|
||||
{ action: previewCommand, corpId: corp?.corpId || corp?.id, apply: booleanOption(parsed.options, ["apply", "execute", "run", "do"]) }
|
||||
);
|
||||
}
|
||||
|
||||
const repo = new ApprovalRepository();
|
||||
const service = new ApprovalService(repo);
|
||||
let cachedSession: Awaited<ReturnType<typeof getSessionClientForRuntime>> | undefined;
|
||||
@@ -95,74 +97,21 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
};
|
||||
|
||||
try {
|
||||
if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) {
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson(getVersionInfo("hose-aipro")) + "\n"
|
||||
: `${formatVersionLabel("hose-aipro")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
if (booleanOption(parsed.options, ["version", "v"])) {
|
||||
const versionDef = findAiProCommand("version");
|
||||
if (versionDef) return await versionDef.handler(ctx);
|
||||
}
|
||||
|
||||
switch (command) {
|
||||
case "status":
|
||||
case "whoami":
|
||||
case "context":
|
||||
case "info":
|
||||
return await handleAiProStatus(ctx);
|
||||
|
||||
case "init":
|
||||
case "start":
|
||||
return await handleAiProInit(ctx);
|
||||
|
||||
case "scopes":
|
||||
case "index":
|
||||
case "indexes":
|
||||
return await handleAiProScopes(ctx);
|
||||
|
||||
case "translate":
|
||||
case "doc":
|
||||
case "markdown":
|
||||
case "render":
|
||||
return await handleAiProTranslate(ctx);
|
||||
|
||||
case "rules":
|
||||
case "rule":
|
||||
return await handleAiProRules(ctx);
|
||||
|
||||
case "bind":
|
||||
case "mount":
|
||||
return await handleAiProBind(ctx);
|
||||
|
||||
case "points":
|
||||
case "clauses":
|
||||
return await handleAiProPoints(ctx);
|
||||
|
||||
case "checklist":
|
||||
case "list":
|
||||
return await handleAiProChecklist(ctx);
|
||||
|
||||
case "review":
|
||||
case "eval":
|
||||
case "evaluate":
|
||||
return await handleAiProReview(ctx);
|
||||
|
||||
case "decide":
|
||||
case "approve":
|
||||
case "reject":
|
||||
return await handleAiProDecide(ctx);
|
||||
|
||||
case "logs":
|
||||
case "log":
|
||||
case "history":
|
||||
case "trail":
|
||||
return await handleAiProLogs(ctx);
|
||||
|
||||
case "help":
|
||||
default:
|
||||
return handleAiProHelp(ctx);
|
||||
const commandDef = findAiProCommand(command);
|
||||
if (commandDef) {
|
||||
return await commandDef.handler(ctx);
|
||||
}
|
||||
|
||||
if (isSaasPlatformCommand(command)) {
|
||||
return handleSaasPlatformRedirect(command, positional);
|
||||
}
|
||||
|
||||
return await handleAiProHelp(ctx);
|
||||
} catch (err: any) {
|
||||
if (err instanceof ApprovalGatewayBlockedError) {
|
||||
repo.logAiProAction({
|
||||
|
||||
@@ -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` 为持续监听。
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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 查看帮助。`);
|
||||
}
|
||||
}
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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 {
|
||||
|
||||
@@ -216,6 +216,32 @@ export const migrations: DatabaseMigration[] = [
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_workflow_alerts_scope ON workflow_error_alerts(scope_key);");
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 4,
|
||||
name: "004_approval_runs_unique_short_id",
|
||||
up(db: Database): void {
|
||||
// 存量纠偏:历史短 ID 若发生大小写不敏感碰撞,仅保留每组最新一条,其余置空
|
||||
// (被置空的记录仍可通过 UUID / 单号定位,不影响既有会话)
|
||||
db.run(`
|
||||
UPDATE approval_runs
|
||||
SET short_id = NULL
|
||||
WHERE short_id IS NOT NULL
|
||||
AND id NOT IN (
|
||||
SELECT id FROM (
|
||||
SELECT id, ROW_NUMBER() OVER (
|
||||
PARTITION BY UPPER(short_id) ORDER BY created_at DESC, id DESC
|
||||
) AS rn
|
||||
FROM approval_runs
|
||||
WHERE short_id IS NOT NULL
|
||||
) WHERE rn = 1
|
||||
);
|
||||
`);
|
||||
// short_id 必须大小写不敏感全局唯一,杜绝碰撞导致按短 ID 取错审批会话
|
||||
db.run(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_runs_short_id_unique ON approval_runs(UPPER(short_id)) WHERE short_id IS NOT NULL;"
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
|
||||
@@ -298,9 +298,25 @@ export class ApprovalRepository {
|
||||
|
||||
// ===================== 审批运行与要点清单 (Runs & Findings) =====================
|
||||
|
||||
/**
|
||||
* 生成库内唯一的 6 位短 ID。
|
||||
* 迁移层已用 UPPER(short_id) 唯一索引兜底,这里再显式探测重试,
|
||||
* 避免极小概率碰撞直接把会话写到同一个短 ID 上。
|
||||
*/
|
||||
private allocateUniqueShortId(maxAttempts = 20): string {
|
||||
for (let i = 0; i < maxAttempts; i++) {
|
||||
const candidate = generateShortRunId();
|
||||
const hit = this.db
|
||||
.query("SELECT 1 FROM approval_runs WHERE UPPER(short_id) = UPPER(?) LIMIT 1")
|
||||
.get(candidate);
|
||||
if (!hit) return candidate;
|
||||
}
|
||||
throw new BusinessError("生成唯一审批会话短 ID 失败(连续碰撞),请稍后重试");
|
||||
}
|
||||
|
||||
public createApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord {
|
||||
const id = crypto.randomUUID();
|
||||
const shortId = input.shortId ?? generateShortRunId();
|
||||
const shortId = input.shortId ?? this.allocateUniqueShortId();
|
||||
const now = Date.now();
|
||||
const expiresAt = input.expiresAt ?? (now + 6 * 3600 * 1000); // 6 小时有效期
|
||||
|
||||
@@ -335,28 +351,31 @@ export class ApprovalRepository {
|
||||
const existing = this.getLatestRunBySn(input.documentSn, input.corpId ?? undefined);
|
||||
const now = Date.now();
|
||||
if (existing) {
|
||||
// 清理旧要点,重置运行记录
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [existing.id]);
|
||||
this.db.run(
|
||||
`
|
||||
// 清理旧要点与重置运行记录必须原子完成,避免删了旧要点却没更新主记录
|
||||
const reset = this.db.transaction(() => {
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [existing.id]);
|
||||
this.db.run(
|
||||
`
|
||||
UPDATE approval_runs
|
||||
SET expires_at = ?, flow_id = ?, corp_id = ?, scope = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
[
|
||||
input.expiresAt ?? (now + 6 * 3600 * 1000),
|
||||
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
|
||||
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
|
||||
(input.scope !== undefined ? input.scope : existing.scope) ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
(input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
(input.documentSnapshot !== undefined ? input.documentSnapshot : existing.documentSnapshot) ?? null,
|
||||
now,
|
||||
existing.id,
|
||||
]
|
||||
);
|
||||
[
|
||||
input.expiresAt ?? (now + 6 * 3600 * 1000),
|
||||
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
|
||||
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
|
||||
(input.scope !== undefined ? input.scope : existing.scope) ?? null,
|
||||
input.decision ?? "PENDING",
|
||||
(input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null,
|
||||
input.matchedRulesCount ?? 0,
|
||||
input.failedRulesCount ?? 0,
|
||||
(input.documentSnapshot !== undefined ? input.documentSnapshot : existing.documentSnapshot) ?? null,
|
||||
now,
|
||||
existing.id,
|
||||
]
|
||||
);
|
||||
});
|
||||
reset();
|
||||
return this.getRunById(existing.id)!;
|
||||
}
|
||||
|
||||
@@ -491,39 +510,44 @@ export class ApprovalRepository {
|
||||
throw new NotFoundError(`审批运行记录不存在: ${runId}`);
|
||||
}
|
||||
|
||||
// 校验必须在事务外先行完成:任何非法状态都不应触发旧要点被删除
|
||||
for (const finding of findings) {
|
||||
if (!isValidFindingCheckStatus(finding.checkStatus ?? "PENDING")) throw new ValidationError("核验状态必须为 PENDING、PASS、FAIL 或 SKIP");
|
||||
}
|
||||
|
||||
// 重新挂载时清空旧要点
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [runId]);
|
||||
|
||||
const now = Date.now();
|
||||
const insertStmt = this.db.prepare(`
|
||||
INSERT INTO approval_findings (
|
||||
id, run_id, rule_id, clause_text, strictness, check_status, evidence, reasoning, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
for (const f of findings) {
|
||||
const id = crypto.randomUUID();
|
||||
insertStmt.run(
|
||||
id,
|
||||
runId,
|
||||
f.ruleId ?? null,
|
||||
f.clauseText.trim(),
|
||||
f.strictness,
|
||||
f.checkStatus ?? "PENDING",
|
||||
f.evidence ?? null,
|
||||
f.reasoning ?? null,
|
||||
now
|
||||
// 清空旧要点 + 批量写入 + 回写计数必须原子完成,避免中途失败留下半残清单
|
||||
const persist = this.db.transaction(() => {
|
||||
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [runId]);
|
||||
|
||||
const insertStmt = this.db.prepare(`
|
||||
INSERT INTO approval_findings (
|
||||
id, run_id, rule_id, clause_text, strictness, check_status, evidence, reasoning, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
for (const f of findings) {
|
||||
insertStmt.run(
|
||||
crypto.randomUUID(),
|
||||
runId,
|
||||
f.ruleId ?? null,
|
||||
f.clauseText.trim(),
|
||||
f.strictness,
|
||||
f.checkStatus ?? "PENDING",
|
||||
f.evidence ?? null,
|
||||
f.reasoning ?? null,
|
||||
now
|
||||
);
|
||||
}
|
||||
|
||||
this.db.run(
|
||||
"UPDATE approval_runs SET matched_rules_count = ?, updated_at = ? WHERE id = ?",
|
||||
[findings.length, now, runId]
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
this.db.run(
|
||||
"UPDATE approval_runs SET matched_rules_count = ?, updated_at = ? WHERE id = ?",
|
||||
[findings.length, now, runId]
|
||||
);
|
||||
persist();
|
||||
|
||||
return this.getFindingsByRunId(runId);
|
||||
}
|
||||
|
||||
@@ -91,8 +91,16 @@ export class ApprovalService {
|
||||
matchedSummary = allScopes.find((s) => /差旅|出差/i.test(s.scope));
|
||||
}
|
||||
|
||||
// 默认回退至第一个场景
|
||||
matchedSummary = matchedSummary ?? allScopes[0];
|
||||
// 严禁静默回退到首个场景:用错规则集审单据(如差旅规则审办公费)比直接报错危险得多
|
||||
if (!matchedSummary) {
|
||||
const available = allScopes.map((s) => s.scope).join("、");
|
||||
if (options.scope !== undefined) {
|
||||
throw new NotFoundError(`指定场景 [${options.scope}] 不存在或无效,当前可用场景: ${available}`);
|
||||
}
|
||||
throw new ValidationError(
|
||||
`无法为单据 [${documentSn}] 自动匹配适用场景,请通过 --scope 显式指定。当前可用场景: ${available}`
|
||||
);
|
||||
}
|
||||
scopeDetail = this.repo.getScopeDetail(matchedSummary.index);
|
||||
}
|
||||
|
||||
@@ -181,7 +189,7 @@ export class ApprovalService {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何审核要点清单(要点列表为空)。\n` +
|
||||
`在没有注入审核要点的情况下,无法进行事实核验!\n` +
|
||||
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点清单。`
|
||||
`请先执行: hose-aipro points ${documentSn} 注入审核要点清单。`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -225,7 +233,7 @@ export class ApprovalService {
|
||||
throw new ApprovalGatewayBlockedError(
|
||||
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
|
||||
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点。`
|
||||
`请先执行: hose-aipro points ${documentSn} 注入审核要点。`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+49
-16
@@ -1,6 +1,7 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { URL } from "node:url";
|
||||
import { runCli } from "../cli/runner.js";
|
||||
import { runAiProCli } from "../aipro-cli.js";
|
||||
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
|
||||
import { getOpenApiSchema } from "../packaging/embedded-openapi.js";
|
||||
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
|
||||
@@ -28,7 +29,12 @@ function checkHttpAuth(req: IncomingMessage): boolean {
|
||||
return authHeader === `Bearer ${requiredToken}`;
|
||||
}
|
||||
|
||||
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
export async function handleHttpRequest(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
options: { app?: "hose-use" | "hose-aipro" } = {}
|
||||
): Promise<void> {
|
||||
const isAiPro = options.app === "hose-aipro";
|
||||
const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;
|
||||
const trustedOrigin = isTrustedOrigin(origin);
|
||||
|
||||
@@ -59,32 +65,59 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
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",
|
||||
},
|
||||
});
|
||||
sendJson(
|
||||
res,
|
||||
200,
|
||||
isAiPro
|
||||
? {
|
||||
name: "hose-aipro",
|
||||
version: VERSION,
|
||||
description: "合思 AI PRO 确定性审批仲裁网关 HTTP 服务",
|
||||
health: "/health",
|
||||
endpoints: {
|
||||
cli: "POST /api/cli",
|
||||
status: "GET /v1/status",
|
||||
},
|
||||
}
|
||||
: {
|
||||
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",
|
||||
name: isAiPro ? "hose-aipro" : "hose-use",
|
||||
version: VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isAiPro && method === "GET" && pathname === "/v1/status") {
|
||||
const statusRes = await runAiProCli(["status", "--json"]);
|
||||
let parsedData: any = {};
|
||||
try {
|
||||
parsedData = JSON.parse(statusRes.stdout);
|
||||
} catch {
|
||||
parsedData = { stdout: statusRes.stdout };
|
||||
}
|
||||
sendJson(res, 200, parsedData);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === "GET" && pathname === "/docs") {
|
||||
sendHtml(res, 200, renderDocsHtml());
|
||||
return;
|
||||
@@ -119,7 +152,7 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
|
||||
|
||||
const tokens = tokenizeCommand(command);
|
||||
const cliArgs = normalizeCliArgs(tokens);
|
||||
const result = await runCli(cliArgs);
|
||||
const result = isAiPro ? await runAiProCli(cliArgs) : await runCli(cliArgs);
|
||||
|
||||
let parsedData: unknown = undefined;
|
||||
const trimmedStdout = result.stdout.trim();
|
||||
|
||||
+17
-6
@@ -6,18 +6,22 @@ export type HttpServerOptions = {
|
||||
port?: number;
|
||||
host?: string;
|
||||
silent?: boolean;
|
||||
app?: "hose-use" | "hose-aipro";
|
||||
};
|
||||
|
||||
export const DEFAULT_HTTP_PORT = 8888;
|
||||
export const DEFAULT_AIPRO_HTTP_PORT = 8889;
|
||||
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 isAiPro = options.app === "hose-aipro";
|
||||
const defaultPort = isAiPro ? DEFAULT_AIPRO_HTTP_PORT : DEFAULT_HTTP_PORT;
|
||||
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : defaultPort);
|
||||
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
await handleHttpRequest(req, res);
|
||||
await handleHttpRequest(req, res, { app: options.app || "hose-use" });
|
||||
} catch (err) {
|
||||
if (!res.headersSent) {
|
||||
res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
|
||||
@@ -33,12 +37,19 @@ export async function startHttpServer(options: HttpServerOptions = {}): Promise<
|
||||
|
||||
server.listen(port, host, () => {
|
||||
if (!options.silent) {
|
||||
console.error(`\n⚡ hose-use HTTP Server (v${VERSION}) 已启动`);
|
||||
const appName = isAiPro ? "hose-aipro" : "hose-use";
|
||||
console.error(`\n⚡ ${appName} HTTP Server (v${VERSION}) 已启动`);
|
||||
console.error(` 主服务地址: http://${host}:${port}`);
|
||||
console.error(` 交互式文档: http://${host}:${port}/docs`);
|
||||
console.error(` OpenAPI规范: http://${host}:${port}/openapi.json`);
|
||||
if (!isAiPro) {
|
||||
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`);
|
||||
if (!isAiPro) {
|
||||
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
|
||||
} else {
|
||||
console.error(` 网关状态接口: GET http://${host}:${port}/v1/status\n`);
|
||||
}
|
||||
}
|
||||
resolve(server);
|
||||
});
|
||||
|
||||
@@ -2,65 +2,86 @@ import { describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, existsSync } from "node:fs";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { EMBEDDED_SKILL_FILES, getDefaultGlobalSkillDir, getSkillContent, installSkillFiles } from "./embedded-skill.js";
|
||||
import {
|
||||
EMBEDDED_HOSE_USE_SKILL_FILES,
|
||||
EMBEDDED_AIPRO_SKILL_FILES,
|
||||
getDefaultGlobalSkillDir,
|
||||
getDefaultAiProGlobalSkillDir,
|
||||
getSkillContent,
|
||||
getAiProSkillContent,
|
||||
installSkillFiles,
|
||||
installHoseUseSkillFiles,
|
||||
installAiProSkillFiles,
|
||||
} from "./embedded-skill.js";
|
||||
|
||||
describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
test("全局 Skill 目录固定为 ~/.agents/skills/hose-use", () => {
|
||||
describe("embedded-skill - 双 Skill 体系内嵌与分发 (hose-use 与 hose-aipro)", () => {
|
||||
test("全局 Skill 目录分别固定为 ~/.agents/skills/hose-use 与 hose-aipro", () => {
|
||||
expect(getDefaultGlobalSkillDir()).toBe(join(homedir(), ".agents", "skills", "hose-use"));
|
||||
expect(getDefaultAiProGlobalSkillDir()).toBe(join(homedir(), ".agents", "skills", "hose-aipro"));
|
||||
});
|
||||
|
||||
test("正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
|
||||
test("hose-use: 正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
|
||||
expect(getSkillContent()).toContain("name: hose-use");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toContain("hose_cli");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["agents/openai.yaml"]).toContain("hose_cli");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toContain("RSA");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/auth.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/auth.md"]).toContain("RSA");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toContain("bill get");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/bill.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/bill.md"]).toContain("bill get");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toContain("workflow find");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/workflow.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/workflow.md"]).toContain("workflow find");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toContain("POST /api/cli");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/service.md"]).toContain("hose-use aipro");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toContain("contact search");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/contact.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/contact.md"]).toContain("contact search");
|
||||
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toContain("hose-aipro");
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toContain("feetype");
|
||||
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toContain("hose-use keys");
|
||||
expect(EMBEDDED_SKILL_FILES["references/assist-platform.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/assist-platform.md"]).toContain("assist-platform");
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("--reveal -o <path>");
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("references/store.md");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/feetype.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/feetype.md"]).toContain("feetype");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/store.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/store.md"]).toContain("hose-use keys");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/assist-platform.md"]).toBeDefined();
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["references/assist-platform.md"]).toContain("assist-platform");
|
||||
|
||||
// 套件结构:根入口路由到 multi/ 下的子技能
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("multi/ekuaibao-mvel/SKILL.md");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-mvel/SKILL.md"]).toContain("name: ekuaibao-mvel");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-mvel/agents/openai.yaml"]).toContain("ekuaibao-mvel");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-nodes/SKILL.md"]).toContain("name: ekuaibao-nodes");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-nodes/references/gray-nodes.md"]).toContain("灰度节点清单");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"]).toContain("multi/ekuaibao-mvel/SKILL.md");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-mvel/SKILL.md"]).toContain("name: ekuaibao-mvel");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-mvel/agents/openai.yaml"]).toContain("ekuaibao-mvel");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-nodes/SKILL.md"]).toContain("name: ekuaibao-nodes");
|
||||
expect(EMBEDDED_HOSE_USE_SKILL_FILES["multi/ekuaibao-nodes/references/gray-nodes.md"]).toContain("灰度节点清单");
|
||||
});
|
||||
|
||||
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
|
||||
test("hose-aipro: 正确内嵌 SKILL.md、agents/openai.yaml、approval.md 与 service.md", () => {
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["SKILL.md"]).toContain("name: hose-aipro");
|
||||
expect(getAiProSkillContent()).toContain("name: hose-aipro");
|
||||
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["agents/openai.yaml"]).toContain("command: \"hose-aipro\"");
|
||||
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/approval.md"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/approval.md"]).toContain("hose-aipro decide");
|
||||
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/service.md"]).toBeDefined();
|
||||
expect(EMBEDDED_AIPRO_SKILL_FILES["references/service.md"]).toContain("8889");
|
||||
});
|
||||
|
||||
test("installSkillFiles 显式路径安装保留层级结构", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "hose-skill-test-"));
|
||||
try {
|
||||
const res = installSkillFiles(tmp);
|
||||
const res = installHoseUseSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(19);
|
||||
expect(res.files.length).toBe(18);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "approval.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "bill.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "contact.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "feetype.md"))).toBe(true);
|
||||
@@ -74,4 +95,19 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("installAiProSkillFiles 正确落盘 hose-aipro 专属技能文件", () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), "aipro-skill-test-"));
|
||||
try {
|
||||
const res = installAiProSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(5);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "approval.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
// ── hose-use Skill 文件 ────────────────────────────────────────────────────────
|
||||
import skillMain from "../../skills/hose-use/SKILL.md" with { type: "text" };
|
||||
import agentOpenAi from "../../skills/hose-use/agents/openai.yaml" with { type: "text" };
|
||||
import refAuth from "../../skills/hose-use/references/auth.md" with { type: "text" };
|
||||
@@ -13,7 +14,6 @@ import refTask from "../../skills/hose-use/references/task.md" with { type: "tex
|
||||
import refMessage from "../../skills/hose-use/references/message.md" with { type: "text" };
|
||||
import refDimension from "../../skills/hose-use/references/dimension.md" with { type: "text" };
|
||||
import refRole from "../../skills/hose-use/references/role.md" with { type: "text" };
|
||||
import refApproval from "../../skills/hose-use/references/approval.md" with { type: "text" };
|
||||
import refFeeType from "../../skills/hose-use/references/feetype.md" with { type: "text" };
|
||||
import refStore from "../../skills/hose-use/references/store.md" with { type: "text" };
|
||||
import refAssistPlatform from "../../skills/hose-use/references/assist-platform.md" with { type: "text" };
|
||||
@@ -22,11 +22,17 @@ import multiMvelAgent from "../../skills/hose-use/multi/ekuaibao-mvel/agents/ope
|
||||
import multiNodes from "../../skills/hose-use/multi/ekuaibao-nodes/SKILL.md" with { type: "text" };
|
||||
import multiNodesGray from "../../skills/hose-use/multi/ekuaibao-nodes/references/gray-nodes.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
// ── hose-aipro Skill 文件 ──────────────────────────────────────────────────────
|
||||
import aiproSkillMain from "../../skills/hose-aipro/SKILL.md" with { type: "text" };
|
||||
import aiproAgentOpenAi from "../../skills/hose-aipro/agents/openai.yaml" with { type: "text" };
|
||||
import aiproRefApproval from "../../skills/hose-aipro/references/approval.md" with { type: "text" };
|
||||
import aiproRefService from "../../skills/hose-aipro/references/service.md" with { type: "text" };
|
||||
import aiproRefReadme from "../../skills/hose-aipro/references/README.references.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_HOSE_USE_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": skillMain,
|
||||
"agents/openai.yaml": agentOpenAi,
|
||||
"references/auth.md": refAuth,
|
||||
"references/approval.md": refApproval,
|
||||
"references/bill.md": refBill,
|
||||
"references/feetype.md": refFeeType,
|
||||
"references/contact.md": refContact,
|
||||
@@ -44,36 +50,92 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"multi/ekuaibao-nodes/references/gray-nodes.md": multiNodesGray,
|
||||
};
|
||||
|
||||
export const EMBEDDED_AIPRO_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": aiproSkillMain,
|
||||
"agents/openai.yaml": aiproAgentOpenAi,
|
||||
"references/approval.md": aiproRefApproval,
|
||||
"references/service.md": aiproRefService,
|
||||
"references/README.references.md": aiproRefReadme,
|
||||
};
|
||||
|
||||
// 保持模块级向后兼容
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = EMBEDDED_HOSE_USE_SKILL_FILES;
|
||||
|
||||
export function getSkillContent(): string {
|
||||
return EMBEDDED_SKILL_FILES["SKILL.md"] || "";
|
||||
return EMBEDDED_HOSE_USE_SKILL_FILES["SKILL.md"] || "";
|
||||
}
|
||||
|
||||
export function getAiProSkillContent(): string {
|
||||
return EMBEDDED_AIPRO_SKILL_FILES["SKILL.md"] || "";
|
||||
}
|
||||
|
||||
export function getDefaultGlobalSkillDir(): string {
|
||||
return join(homedir(), ".agents", "skills", "hose-use");
|
||||
}
|
||||
|
||||
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
export function getDefaultAiProGlobalSkillDir(): string {
|
||||
return join(homedir(), ".agents", "skills", "hose-aipro");
|
||||
}
|
||||
|
||||
export function installHoseUseSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
} {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
const installed: string[] = [];
|
||||
|
||||
for (const [relPath, content] of Object.entries(EMBEDDED_SKILL_FILES)) {
|
||||
for (const [relPath, content] of Object.entries(EMBEDDED_HOSE_USE_SKILL_FILES)) {
|
||||
const fullPath = join(targetDir, relPath);
|
||||
mkdirSync(dirname(fullPath), { recursive: true });
|
||||
writeFileSync(fullPath, content, "utf8");
|
||||
installed.push(relPath);
|
||||
}
|
||||
|
||||
return {
|
||||
targetDir,
|
||||
files: installed,
|
||||
};
|
||||
return { targetDir, files: installed };
|
||||
}
|
||||
|
||||
export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: string } {
|
||||
const globalDir = getDefaultGlobalSkillDir();
|
||||
installSkillFiles(globalDir);
|
||||
return { synced: true, targetDir: globalDir };
|
||||
export function installAiProSkillFiles(targetDir: string = getDefaultAiProGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
} {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
const installed: string[] = [];
|
||||
|
||||
for (const [relPath, content] of Object.entries(EMBEDDED_AIPRO_SKILL_FILES)) {
|
||||
const fullPath = join(targetDir, relPath);
|
||||
mkdirSync(dirname(fullPath), { recursive: true });
|
||||
writeFileSync(fullPath, content, "utf8");
|
||||
installed.push(relPath);
|
||||
}
|
||||
|
||||
return { targetDir, files: installed };
|
||||
}
|
||||
|
||||
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
skills?: string[];
|
||||
} {
|
||||
const defaultGlobalDir = getDefaultGlobalSkillDir();
|
||||
// 当为全局默认目录时,自动同时安装两个 Skill
|
||||
if (targetDir === defaultGlobalDir) {
|
||||
const hoseRes = installHoseUseSkillFiles(defaultGlobalDir);
|
||||
const aiproRes = installAiProSkillFiles(getDefaultAiProGlobalSkillDir());
|
||||
return {
|
||||
targetDir,
|
||||
files: [...hoseRes.files, ...aiproRes.files.map((f) => `hose-aipro/${f}`)],
|
||||
skills: ["hose-use", "hose-aipro"],
|
||||
};
|
||||
}
|
||||
|
||||
// 显式指定自定义目录时,在该目录下安装 hose-use 文件
|
||||
return installHoseUseSkillFiles(targetDir);
|
||||
}
|
||||
|
||||
export function syncGlobalSkillIfPresent(): { synced: boolean; targetDir?: string; targetDirs: string[] } {
|
||||
const hoseDir = getDefaultGlobalSkillDir();
|
||||
const aiproDir = getDefaultAiProGlobalSkillDir();
|
||||
installHoseUseSkillFiles(hoseDir);
|
||||
installAiProSkillFiles(aiproDir);
|
||||
return { synced: true, targetDir: hoseDir, targetDirs: [hoseDir, aiproDir] };
|
||||
}
|
||||
Reference in new issue
Block a user