Files
hose-use/src/aipro-cli.ts
T

627 lines
26 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bun
import { parseArgs, stringOption, booleanOption, numberOption } from "./cli/parser.js";
import { printJson, printTable, redactSensitiveText } from "./cli/printer.js";
import { initCorpRuntime } from "./cli/helpers.js";
import { createEkbClient } from "./core/auth/ekb.js";
import {
ApprovalService,
ApprovalRepository,
ApprovalGatewayBlockedError,
FindingCheckStatus,
} from "./domains/approval/index.js";
import { VERSION } from "./version.js";
export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
const parsed = parseArgs(rawArgs);
const runtime = initCorpRuntime({
corpId: stringOption(parsed.options, ["corp", "c"]),
jsonMode: booleanOption(parsed.options, ["json"]),
});
const corp = runtime.selectedCorp;
const repo = new ApprovalRepository();
const service = new ApprovalService(repo);
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
const positional: string[] = [];
for (let i = 0; i < rawArgs.length; i++) {
const arg = rawArgs[i];
if (arg === "--") {
positional.push(...rawArgs.slice(i + 1));
break;
}
if (arg.startsWith("-")) {
const eqIdx = arg.indexOf("=");
if (eqIdx === -1) {
const flagName = arg.replace(/^--?/, "").toLowerCase();
const isBool = ["raw", "json", "j", "help", "h", "version", "v", "yes", "y", "confirm", "apply", "execute", "run", "do"].includes(flagName);
if (!isBool && i + 1 < rawArgs.length && !rawArgs[i + 1].startsWith("-")) {
i++; // skip option value
}
}
continue;
}
positional.push(arg);
}
const command = (positional[0] || "help").toLowerCase();
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
const args = positional.slice(1);
const corpId = corp?.corpId || corp?.id;
const operator = corp?.staffId || corp?.name || "AI-Agent";
const requireCorpId = () => {
if (!corpId) {
throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。");
}
return corpId;
};
const getClient = async () => {
const activeCorpId = requireCorpId();
if (!corp) throw new Error("未找到当前企业配置");
client ??= await createEkbClient(corp);
return { client, corpId: activeCorpId };
};
try {
switch (command) {
// ── 1. 规约场景索引列表查看 ─────────────────────────────────────────
case "scopes":
case "scope":
case "rules":
case "rule":
case "index":
case "indexes": {
const scopes = repo.listScopes();
if (runtime.jsonMode) {
return {
stdout: printJson({ count: scopes.length, scopes }),
stderr: "",
exitCode: 0,
};
}
const headers = ["索引号", "适用场景 (Scope)", "有效规则数", "包含规则编号"];
const rows = scopes.map((s) => [
s.index,
s.scope,
s.ruleCount,
s.ruleCodes.map((c) => `#${c}`).join(", "),
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO] 规约场景索引列表 (共 ${scopes.length} 个适用场景) ======\n`;
const tip =
`\n提示:\n` +
` • 查看场景审核要点 (纯规则元数据,与单据无关): hose-aipro points <索引号|场景名称> (例如: hose-aipro points 1)\n` +
` • 绑定单据发起审核: hose-aipro bind <单号> <索引号> (例如: hose-aipro bind S26000001 1)\n`;
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
}
// ── 2. 查看审核要点清单(纯规则元数据,与具体单据无关)────────────────
case "points":
case "clauses": {
const arg1 = positional[1] || stringOption(parsed.options, ["scope", "s", "index", "i"]);
const arg2 = positional[2];
// 兼容双参数调用: 如果同时提供了单号和索引号,走单据绑定流
if (arg1 && arg2) {
const billSn = arg1;
const scopeTarget = arg2;
const context = await getClient();
const result = await service.injectAuditPoints(context.client, context.corpId, billSn, {
scope: scopeTarget ? (isNaN(Number(scopeTarget)) ? scopeTarget : Number(scopeTarget)) : undefined,
});
repo.logAiProAction({
action: "bind",
documentSn: result.bill.billCode,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
decision: "PENDING",
summary: `绑定单据并挂载审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`,
});
if (runtime.jsonMode) {
return {
stdout: printJson({
sn: result.bill.billCode,
scope: result.scope,
runId: result.run.id,
count: result.findings.length,
findings: result.findings,
}),
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 = `====== [AI PRO] 单据 ${result.bill.billCode} 已挂载场景 [${result.scope}] 审核要点 (共 ${result.findings.length} 条) ======\n`;
const tip =
`\n✅ [已安全登记] 审核要点已固化至数据库审批实例,全流程监控已激活。\n` +
`下一步: 运行 "hose-aipro review ${result.bill.billCode} --eval '...' " 进行事实核验打标。\n` +
`最终决断: 运行 "hose-aipro decide ${result.bill.billCode} --apply --yes" 由确定性网关仲裁审批。\n`;
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
}
// 纯规则审查要点输出(与具体单据没有任何关系!)
const targetScope = arg1;
if (!targetScope) {
const allScopes = repo.listScopes("active");
if (allScopes.length === 0) {
return { stdout: "规约库中暂无生效规则。可使用 hose-use rule add <场景> <正文> 新增规则。\n", stderr: "", exitCode: 0 };
}
const lines: string[] = [
`====== [AI PRO] 规约审核要点总览 (共 ${allScopes.length} 个适用场景) ======\n`
];
for (const s of allScopes) {
const detail = repo.getScopeDetail(s.index);
if (!detail) continue;
lines.push(`▶ 场景 [${detail.index}] ${detail.scope} (包含 ${detail.ruleCount} 条规则):`);
let count = 0;
detail.rules.forEach((r) => {
r.parsed.clauses.forEach((c) => {
count++;
lines.push(` ${count}. [${c.strictness}] (规则 #${r.code}) ${c.action}`);
});
});
lines.push("");
}
lines.push(`提示: 输入 "hose-aipro points <索引号|场景名称>" 查看指定场景要点明细。\n`);
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
}
const detail = repo.getScopeDetail(targetScope);
if (!detail) {
return {
stdout: "",
stderr: `[NOT FOUND] 未找到索引号或场景为 "${targetScope}" 的规约场景。\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`,
exitCode: 1,
};
}
const points: Array<{ index: number; strictness: string; ruleCode: number; clauseText: string }> = [];
let count = 0;
for (const rule of detail.rules) {
for (const clause of rule.parsed.clauses) {
count++;
points.push({
index: count,
strictness: clause.strictness,
ruleCode: rule.code,
clauseText: clause.action,
});
}
}
if (runtime.jsonMode) {
return {
stdout: printJson({
index: detail.index,
scope: detail.scope,
ruleCount: detail.ruleCount,
pointsCount: points.length,
points,
}),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "归属规则", "审核要点内容 (Clause)"];
const rows = points.map((p) => [
p.index,
`[${p.strictness}]`,
`#${p.ruleCode}`,
p.clauseText,
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO] 适用场景 [${detail.index}] ${detail.scope} - 审核要点清单 (共 ${points.length} 条要点) ======\n`;
const tip =
`\n说明: 审核要点为规约条款提取出的判定标准,纯规则元数据,与具体单据无关。\n` +
`绑定单据: 运行 "hose-aipro bind <单号> ${detail.index}" 将此要点清单挂载到具体单据。\n`;
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
}
// ── 3. 绑定单据与规则场景(激活审批运行实例)─────────────────────────
case "bind":
case "mount":
case "init": {
const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
const scopeTarget = positional[2] || stringOption(parsed.options, ["scope", "s", "index", "i"]);
if (!billSn) {
throw new Error("请提供单号: hose-aipro bind <单号> [索引号|场景名称]");
}
const context = await getClient();
const result = await service.injectAuditPoints(context.client, context.corpId, billSn, {
scope: scopeTarget ? (isNaN(Number(scopeTarget)) ? scopeTarget : Number(scopeTarget)) : undefined,
});
repo.logAiProAction({
action: "bind",
documentSn: result.bill.billCode,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
decision: "PENDING",
summary: `绑定单据并挂载审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`,
});
if (runtime.jsonMode) {
return {
stdout: printJson({
sn: result.bill.billCode,
scope: result.scope,
runId: result.run.id,
count: result.findings.length,
findings: result.findings,
}),
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 = `====== [AI PRO] 单据 ${result.bill.billCode} 已挂载场景 [${result.scope}] 审核要点 (共 ${result.findings.length} 条) ======\n`;
const tip =
`\n✅ [已安全登记] 审核要点已固化至数据库审批实例,全流程监控已激活。\n` +
`下一步: 运行 "hose-aipro review ${result.bill.billCode} --eval '...' " 进行事实核验打标。\n` +
`最终决断: 运行 "hose-aipro decide ${result.bill.billCode} --apply --yes" 由确定性网关仲裁审批。\n`;
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
}
// ── 4. 查看审核要点清单与进度(未绑定则硬阻断)────────────────────────
case "checklist":
case "list":
case "status": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro checklist <单号>");
}
const activeCorpId = requireCorpId();
const { run, findings } = service.getAuditChecklist(targetSn, activeCorpId);
if (!run || findings.length === 0) {
repo.logAiProAction({
action: "checklist",
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "BLOCKED",
summary: "查询审核清单阻断:单据尚未绑定任何审核要点",
});
const errorMsg =
`[审批链路阻断] 单据 [${targetSn}] 尚未绑定任何明细级审核要点(要点列表为空)!\n` +
`网关安全卡点生效:在要点未绑定前,审批链路物理不通!\n` +
`请先执行: hose-aipro bind ${targetSn} <索引号> 挂载明细级审核要点清单。\n`;
return { stdout: "", stderr: errorMsg, exitCode: 1 };
}
if (runtime.jsonMode) {
return {
stdout: printJson({ run, findings }),
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 = `====== [AI PRO] 单据 ${targetSn} 审核清单核验进度 (适用场景: [${run.scope || "未关联"}] | 总数: ${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-aipro review <单号> --eval '...'");
}
const evalStr = stringOption(parsed.options, ["eval", "findings", "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) {
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-aipro review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
` 或: hose-aipro review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
);
}
const activeCorpId = requireCorpId();
const updatedFindings = service.evaluateAuditPoints(targetSn, updates, activeCorpId);
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
repo.logAiProAction({
action: "review",
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: `已录入 ${updates.length} 处要点核验事实(待核验剩余: ${pendingCount} 项)`,
});
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 msg =
`====== [AI PRO] 单据 ${targetSn} 事实核验已登记入库 (待核验剩余: ${pendingCount} 项) ======\n` +
table +
(pendingCount === 0
? `\n🎉 [事实全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-aipro decide ${targetSn} --apply --yes\n`
: `\n⏳ [待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
return { stdout: msg, stderr: "", exitCode: 0 };
}
// ── 4. 确定性网关仲裁决断与执行 ───────────────────────────────────────
case "decide":
case "approve":
case "reject": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro 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("./cli/helpers.js");
const ans = await prompt("[AI PRO] 即将向合思系统真实执行审批流转/意见留痕,确认执行?输入 yes: ");
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
}
}
const requestedAction = command === "approve" ? "approve" : command === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
const context = await getClient();
const decisionResult = await service.decideAudit(context.client, context.corpId, targetSn, {
requestedAction,
apply,
comment: userComment,
});
repo.logAiProAction({
action: "decide",
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
decision: decisionResult.decision,
summary: `网关仲裁完成: ${decisionResult.decision} (硬性违规: ${decisionResult.hardFailedCount}, 弹性违规: ${decisionResult.elasticFailedCount})`,
});
if (runtime.jsonMode) {
return {
stdout: printJson(decisionResult),
stderr: "",
exitCode: 0,
};
}
const outLines: string[] = [];
outLines.push(`\n====== [AI PRO] 合思确定性网关仲裁决断书 (单号: ${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 };
}
// ── 5. 全流程监控流水查看 (Audit Logs) ────────────────────────────────
case "logs":
case "log":
case "history":
case "trail": {
const limit = numberOption(parsed.options, ["limit", "n"], 50) ?? 50;
const logs = repo.listAiProLogs(targetSn || undefined, limit);
if (runtime.jsonMode) {
return {
stdout: printJson({ total: logs.length, logs }),
stderr: "",
exitCode: 0,
};
}
if (logs.length === 0) {
return {
stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetSn ? ` (单号: ${targetSn})` : ""}。\n`,
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "发生时间", "动作 (Action)", "单号", "操作人", "状态", "网关决策", "摘要说明"];
const rows = logs.map((l, i) => [
i + 1,
new Date(l.createdAt).toLocaleString("zh-CN"),
l.action,
l.documentSn || "-",
l.operator || "-",
l.status === "SUCCESS" ? "✅ SUCCESS" : l.status === "BLOCKED" ? "🚫 BLOCKED" : "❌ ERROR",
l.decision || "-",
l.summary || "-",
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO 全流程监控流水账本] (共登记 ${logs.length} 条记录) ======\n`;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
// ── 6. 规约快捷查看 ───────────────────────────────────────────────────
case "rules":
case "rule":
case "scopes": {
const scopes = repo.listScopes();
const headers = ["索引号", "适用场景 (Scope)", "有效规则数", "包含规则编号"];
const rows = scopes.map((s) => [
s.index,
s.scope,
s.ruleCount,
s.ruleCodes.map((c) => `#${c}`).join(", "),
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO] 规约场景索引库 (共 ${scopes.length} 个场景) ======\n`;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
// ── 7. 帮助 ───────────────────────────────────────────────────────────
case "help":
default: {
const helpText = `
合思 AI PRO 确定性审批仲裁网关 CLI (hose-aipro) v${VERSION}
一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。
核心工作流:
1. 查看规约场景索引库 (获取规则索引号):
hose-aipro scopes # 列出所有场景索引 (Index / Scope / 规则数)
2. 查看场景审核要点清单 (纯规则元数据,与单据无关):
hose-aipro points <索引号|场景名称> # 例如: hose-aipro points 1
3. 显式绑定单据并挂载审核要点:
hose-aipro bind <单号> <索引号> # 例如: hose-aipro bind S26000001 1
4. 查看单据审核清单与核验进度:
hose-aipro checklist <单号> # 查看当前单据要点核验进度与挂载场景
5. 逐项录入事实核验打标:
hose-aipro review <单号> --eval "1=PASS; 2=FAIL:证据说明; 3=SKIP"
hose-aipro review <单号> --point 1 --status FAIL --reason "缺少发票"
6. 确定性网关仲裁与流转执行 (硬性条款物理切断同意分支):
hose-aipro decide <单号> # 预审仿真 (Dry Run)
hose-aipro decide <单号> --apply --yes # 真实驱动下游审批/驳回/评论
7. 全流程监控日志流水查看:
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
`;
return { stdout: helpText.trim() + "\n", stderr: "", exitCode: 0 };
}
}
} catch (err: any) {
// 将阻断或异常统一记录至审计日志
if (err instanceof ApprovalGatewayBlockedError) {
repo.logAiProAction({
action: command,
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "BLOCKED",
summary: err.message.replace(/\n+/g, " "),
});
return {
stdout: "",
stderr: `\n${err.message}\n`,
exitCode: 1,
};
}
repo.logAiProAction({
action: command,
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "ERROR",
summary: String(err?.message || err),
});
return {
stdout: "",
stderr: `[AI PRO 错误] ${err?.message || err}\n`,
exitCode: 1,
};
}
}
// 直接作为可执行脚本运行时
if (import.meta.main) {
const rawArgs = process.argv.slice(2);
const result = await runAiProCli(rawArgs);
if (result.stdout) process.stdout.write(redactSensitiveText(result.stdout));
if (result.stderr) process.stderr.write(redactSensitiveText(result.stderr));
process.exit(result.exitCode);
}