feat: add workflow lifecycle controls and monitoring

This commit is contained in:
gitea committed 2026-09-09 18:41:36 +08:00
1 parent 9f9f3abe22
commit 0cdd62161f
16 files changed
+778 -20

No files matched your search

+263 -8
View File
@@ -4,10 +4,25 @@ import {
} from "../../domains/platform/services.js";
import * as api from "../../domains/platform/api.js";
import { stringOption, numberOption, booleanOption } from "../parser.js";
import { createClientsForCorp } from "../helpers.js";
import { createClientsForCorp, createPiperClientForCorp } from "../helpers.js";
import { printJson, printTable, printKeyValue } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { analyzeWorkflow } from "../../domains/platform/analysis.js";
import { readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { WorkflowDetailSchema } from "../../domains/platform/types.js";
import {
createWorkflowDraft,
beginWorkflowSave,
commitWorkflowSave,
failWorkflowSave,
hasWorkflowVersionConflict,
applyWorkflowPathPatch,
} from "../../domains/platform/workflow-state.js";
import { WorkflowAlertStore } from "../../domains/platform/workflow-alert-store.js";
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
export async function handleWorkflowCommand(
parsed: CliParsedArgs,
@@ -38,23 +53,165 @@ export async function handleWorkflowCommand(
return handleFind(parsed, runtime);
case "toggle":
return handleToggle(parsed, runtime);
case "publish":
case "enable":
return handlePublish(parsed, runtime);
case "save":
case "update":
return handleSave(parsed, runtime);
case "patch":
return handlePatch(parsed, runtime);
case "history":
case "snapshots":
return handleHistory(parsed, runtime);
case "logs":
case "log":
return handleLogs(parsed, runtime);
case "check":
case "health":
return handleCheck(parsed, runtime);
case "analyze":
case "analyse":
return handleAnalyze(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, toggle\n`,
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, check\n`,
exitCode: 1,
};
}
}
async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
const file = stringOption(parsed.options, ["file", "input", "from"]);
const path = stringOption(parsed.options, ["path", "field"]);
const rawValue = parsed.options.value;
const output = stringOption(parsed.options, ["output", "output-file", "outputFile"]);
const inPlace = booleanOption(parsed.options, ["in-place", "inPlace"]);
if (!pipelineId || !file || !path || typeof rawValue !== "string" || (!output && !inPlace)) {
return {
stdout: "",
stderr: "用法: hose-use workflow patch <pipelineId> --file=<workflow.json> --path=<tasks.0.code> --value=<值> (--output=<patched.json>|--in-place) [--value-json]\n",
exitCode: 1,
};
}
let source: unknown;
try {
source = JSON.parse(readFileSync(file, "utf8"));
} catch (error) {
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
}
const sourceWorkflow = WorkflowDetailSchema.parse(source);
if (sourceWorkflow.id !== pipelineId) {
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${sourceWorkflow.id}]`);
}
let value: unknown = rawValue;
if (booleanOption(parsed.options, ["value-json", "valueJson"])) {
try {
value = JSON.parse(rawValue);
} catch (error) {
throw new Error(`--value-json 不是合法 JSON: ${error instanceof Error ? error.message : String(error)}`);
}
}
const patched = applyWorkflowPathPatch(sourceWorkflow, path, value);
const target = inPlace ? file : output!;
writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8");
const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion };
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `✅ 已生成工作流草稿 [${target}],修改路径: ${path}\n`, stderr: "", exitCode: 0 };
}
async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
const file = stringOption(parsed.options, ["file", "input", "from"]);
if (!pipelineId || !file) {
return {
stdout: "",
stderr: "用法: hose-use workflow save <pipelineId> --file=<workflow.json> [--force-write]\n",
exitCode: 1,
};
}
let draftWorkflow: unknown;
try {
draftWorkflow = JSON.parse(readFileSync(file, "utf8"));
} catch (error) {
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
}
const parsedWorkflow = WorkflowDetailSchema.parse(draftWorkflow);
if (parsedWorkflow.id !== pipelineId) {
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`);
}
const clients = await createClientsForCorp(runtime.selectedCorp!);
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
const remote = await api.getWorkflowDetail(piperClient, pipelineId);
let state = createWorkflowDraft(parsedWorkflow);
state = {
...state,
revision: 1,
status: "dirty",
dirtyPaths: ["*"],
};
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
if (!forceWrite && hasWorkflowVersionConflict(state, remote)) {
throw new Error(
`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。`
);
}
state = beginWorkflowSave(state);
try {
const payload = state.workflow.inputs?.length
? state.workflow
: { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] };
const saved = await api.updateWorkflow(piperClient, payload);
state = commitWorkflowSave(state, saved);
const result = {
success: true,
pipelineId,
status: state.status,
tasksVersion: saved.tasksVersion,
updateTime: saved.updateTime,
};
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return {
stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功,tasksVersion=${saved.tasksVersion}。\n`,
stderr: "",
exitCode: 0,
};
} catch (error) {
state = failWorkflowSave(state, error);
throw new Error(`工作流保存失败(${state.status}): ${state.error}`);
}
}
async function resolveWorkflowPlatformId(
parsed: CliParsedArgs,
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
pipelineId: string
): Promise<string> {
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
if (explicit) return explicit;
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
const match = all.workflows.find((workflow) => workflow.id === pipelineId);
if (!match?.platformId) {
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId>`);
}
return match.platformId;
}
async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
const clients = await createClientsForCorp(runtime.selectedCorp!);
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await api.getWorkflowDetail(client, pipelineId);
const result = analyzeWorkflow(detail);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const diagnosticRows = result.diagnostics.map((item) => [item.severity, item.code, item.path, item.message]);
@@ -67,6 +224,89 @@ async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promis
].join("\n"), stderr: "", exitCode: 0 };
}
async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow history <pipelineId> [--page=1] [--page-size=10]\n", exitCode: 1 };
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const page = numberOption(parsed.options, ["page"]) || 1;
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 10;
const result = await api.listWorkflowSnapshots(client, pipelineId, page, pageSize);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const rows = result.items.map((snapshot, index) => [
(page - 1) * pageSize + index + 1,
snapshot.version,
snapshot.id,
snapshot.updateTime,
snapshot.staffName || snapshot.staffId || "-",
]);
return {
stdout: `====== 工作流版本历史 [${pipelineId}](共 ${result.totalItems} 个) ======\n${printTable(["#", "版本", "快照 ID", "更新时间", "操作者"], rows)}\n`,
stderr: "",
exitCode: 0,
};
}
async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const result = await api.listWorkflowLogs(client, pipelineId, {
state: stringOption(parsed.options, ["state"]),
page: numberOption(parsed.options, ["page"]),
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
});
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `====== 工作流运行日志 [${pipelineId}] ======\n${printKeyValue({ "执行次数": result.executeCount, "成功次数": result.successCount, "错误次数": result.errorCount, "日志条数": result.totalItems, "运行记录": result.jobList.length })}\n${printJson(result, runtime.outputOptions)}\n`, stderr: "", exitCode: 0 };
}
async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const clients = await createClientsForCorp(runtime.selectedCorp!);
const result = await listAllWorkflows(clients, { page: 1, pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100 });
const observedAt = Date.now();
const logResults = await Promise.all(result.workflows.map(async (workflow) => {
try {
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, workflow.platformId);
const log = await api.listWorkflowLogs(piperClient, workflow.id, { page: 1, pageSize: 1 });
return { workflow, errorCount: log.errorCount };
} catch (error) {
return { workflow, errorCount: workflow.errorCount, error: error instanceof Error ? error.message : String(error) };
}
}));
const logErrors = logResults.filter((item): item is typeof item & { error: string } => Boolean(item.error)).map((item) => ({ platformId: item.workflow.platformId, platformName: item.workflow.platformName, error: item.error }));
const activeAlerts = logResults
.filter(({ errorCount }) => errorCount > 0)
.map(({ workflow, errorCount }) => ({
id: `${runtime.selectedCorp!.id}:${workflow.platformId}:${workflow.id}`,
pipelineId: workflow.id,
platformId: workflow.platformId,
pipelineName: workflow.pipelineName,
errorCount,
state: workflow.state,
observedAt,
}));
const stateFile = stringOption(parsed.options, ["state-file", "stateFile"]) || join(WORKFLOW_STATE_DIR, `workflow-alerts-${runtime.selectedCorp!.id}.json`);
const check = new WorkflowAlertStore(stateFile).observe(activeAlerts);
const output = { corpId: runtime.selectedCorp!.id, observedAt, stateFile, activeAlerts: check.activeAlerts, newAlerts: check.newAlerts, scanErrors: [...result.errors, ...logErrors] };
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
const rows = check.activeAlerts.map((alert) => [alert.pipelineId, alert.pipelineName || "-", alert.errorCount, alert.state === 1 ? "启用" : "停用", check.newAlerts.some((item) => item.id === alert.id) ? "🔔 新提醒" : "已记录"]);
const warning = check.newAlerts.length ? `\n🔔 新错误管道提醒 ${check.newAlerts.length} 条` : "\n暂无新的错误管道提醒";
const scanErrorCount = result.errors.length + logErrors.length;
const scanWarning = scanErrorCount ? `\n⚠️ 工作流扫描失败 ${scanErrorCount} 个` : "";
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态文件: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
}
async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow publish <pipelineId>\n", exitCode: 1 };
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const result = await api.toggleWorkflow(client, pipelineId, 1);
const output = { success: result.success, pipelineId, published: result.success, state: 1 };
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: result.success ? 0 : 1 };
return { stdout: result.success ? `✅ 工作流 [${pipelineId}] 已发布并启用。\n` : `❌ 工作流 [${pipelineId}] 发布失败。\n`, stderr: "", exitCode: result.success ? 0 : 1 };
}
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const clients = await createClientsForCorp(runtime.selectedCorp!);
const page = numberOption(parsed.options, ["page"]) || 1;
@@ -113,8 +353,8 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
return { stdout: "", stderr: "用法: hose-use workflow get <pipelineId>\n", exitCode: 1 };
}
const clients = await createClientsForCorp(runtime.selectedCorp!);
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await api.getWorkflowDetail(client, pipelineId);
if (runtime.jsonMode) {
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
@@ -147,6 +387,21 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
};
}
async function createWorkflowDetailClient(
parsed: CliParsedArgs,
runtime: CliRuntime,
pipelineId: string,
): Promise<{ client: Awaited<ReturnType<typeof createPiperClientForCorp>> }> {
const clients = await createClientsForCorp(runtime.selectedCorp!);
const explicit = stringOption(parsed.options, ["platform-id", "platformId"]);
let platformId = explicit;
if (!platformId) {
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
}
return { client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient };
}
async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const taskType = stringOption(parsed.options, ["task", "taskType", "type"]) || parsed.args[0];
if (!taskType) {
@@ -213,8 +468,8 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
}
const state = (stateArg === "1" || stateArg === "true" ? 1 : 0) as 0 | 1;
const clients = await createClientsForCorp(runtime.selectedCorp!);
const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state);
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const result = await api.toggleWorkflow(client, pipelineId, state);
if (runtime.jsonMode) {
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
+5
View File
@@ -4,6 +4,7 @@ import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
import { CorpConfig } from "../core/config/types.js";
import { createEkbClient } from "../core/auth/ekb.js";
import { getEasoClient } from "../core/auth/easo.js";
import { getPiperClient } from "../core/auth/piper.js";
import { CliRuntime, OutputOptions } from "./types.js";
export function initCorpRuntime(
@@ -64,6 +65,10 @@ export async function createClientsForCorp(corp: CorpConfig) {
};
}
export async function createPiperClientForCorp(corp: CorpConfig, platformId: string) {
return getPiperClient(corp, platformId);
}
export function prompt(question: string): Promise<string> {
const rl = readline.createInterface({
input: process.stdin,
+1 -1
View File
@@ -122,7 +122,7 @@ export function printHelp(): string {
corps 多企业租户管理 (list, search <关键词>, switch, current, add-link)
aipro 合思 AI PRO 确定性审批仲裁网关入口 (status, scopes, bind, checklist, review, decide, logs)
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
workflow 工作流管理 (list, get, find, analyze, toggle)
workflow 工作流管理 (list, get, find, analyze, toggle, publish, patch, save, history, logs, check)
bill 单据检索与审批动作 (list, get <单号|ID> [--risk], approve|reject|transfer|add-node|comment <单号|ID> [选项], refs, relations, attachments, download, flow, risk, budget, schema, link)
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
task 待办中心与审批任务 (todo, approved, records, submitted, cc)