Files
hose-use/src/cli/commands/workflow.ts
T

983 lines
37 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.
import {
listAllWorkflows,
findWorkflowsByTaskType,
} from "../../domains/platform/services.js";
import * as api from "../../domains/platform/services.js";
import { stringOption, numberOption, booleanOption } from "../parser.js";
import { createClientsForCorp, createPiperClientForCorp } from "../helpers.js";
import { printJson, printTable, printKeyValue } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import {
analyzeWorkflow,
extractWorkflowSpecificationIds,
type WorkflowFormSpecLike,
} from "../../domains/platform/analysis.js";
import { getFormSpecification } from "../../domains/bill/tools.js";
import { readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { WorkflowDetailSchema, type WorkflowTaskExecution } 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";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
const PLATFORM_ID_OPTION_KEYS = ["platform-id", "platformId", "app-id", "appId"];
export async function handleWorkflowCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const currentCorp = runtime.selectedCorp;
if (!currentCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const action = parsed.action || "list";
switch (action) {
case "list":
case "list-all":
case "ls":
return handleList(parsed, runtime);
case "get":
case "detail":
case "info":
return handleGet(parsed, runtime);
case "find":
case "search":
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 "job":
case "execution":
return handleJob(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, analyze, toggle, publish, patch, save, history, logs, job, 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!;
requireMutationConfirmation(
parsed,
runtime,
"写入工作流草稿文件",
`hose-use workflow patch ${pipelineId} --file=${file} --path=${path} --value='${rawValue}' ${inPlace ? "--in-place" : `--output=${target}`} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "写入工作流草稿文件", target, {
pipelineId,
path,
value,
tasksVersion: patched.tasksVersion,
});
}
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 forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
requireMutationConfirmation(
parsed,
runtime,
"保存工作流草稿到远端",
`hose-use workflow save ${pipelineId} --file=${file} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, {
file,
tasksVersion: parsedWorkflow.tasksVersion,
forceWrite,
});
}
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: ["*"],
};
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_OPTION_KEYS);
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> 或 --app-id=<appId>`);
}
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 { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await api.getWorkflowDetail(client, pipelineId);
const specIds = extractWorkflowSpecificationIds(detail);
const specifications: Record<string, WorkflowFormSpecLike | undefined> = {};
if (specIds.length > 0) {
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
await Promise.all(
specIds.map(async (specId) => {
try {
const spec = await getFormSpecification(clients.ekbClient, corpId, specId);
if (spec) specifications[specId] = spec;
} catch {
// Ignore specification fetch failure in offline or restricted environments
}
})
);
}
const result = analyzeWorkflow(detail, { specifications });
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]);
const dependencyRows = result.dependencies.map((item) => [item.path, item.taskType, item.references.join(", ")]);
return { stdout: [
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
printKeyValue({
"工作流 ID": detail.id,
"状态": detail.state === 1 ? "🟢 启用 (state=1)" : "⚪ 停用/草稿 (state=0)",
"根节点数": result.ast.length,
"依赖节点数": result.dependencies.length,
"诊断数": result.diagnostics.length,
}),
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
`\n诊断:\n${diagnosticRows.length ? printTable(["级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`, "",
].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] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const rawResult = 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"]),
});
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
const filteredJobList = hasErrorFilter
? rawResult.jobList.filter(
(job) => job.hasError === true || job.errorTaskCount > 0 || job.state === "FAILED"
)
: rawResult.jobList;
const result = hasErrorFilter
? { ...rawResult, jobList: filteredJobList }
: rawResult;
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const rows = result.jobList.map((job, idx) => [
idx + 1,
job.id,
job.state,
job.successTaskCount,
job.errorTaskCount,
job.hasError || job.errorTaskCount > 0 ? "⚠️ 是 (true)" : "否 (false)",
job.durationTime ?? "-",
job.startTime || "-",
]);
const tableStr = rows.length
? printTable(
["#", "Job ID", "状态 (state)", "成功节点 (successTaskCount)", "失败节点 (errorTaskCount)", "有错误 (hasError)", "耗时(ms)", "开始时间"],
rows
)
: "暂无匹配的运行记录";
return {
stdout: [
`====== 工作流运行日志 [${pipelineId}] ======`,
printKeyValue({
"执行次数": result.executeCount,
"成功次数": result.successCount,
"错误次数": result.errorCount,
"日志条数": result.totalItems,
"当前返回记录": result.jobList.length,
}),
"",
tableStr,
"\n提示: 运行 hose-use workflow job <jobId> [--failed] 下钻查看单次 Job 节点级报错与入参明细\n",
].join("\n"),
stderr: "",
exitCode: 0,
};
}
async function createJobPiperClient(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<Awaited<ReturnType<typeof createPiperClientForCorp>>> {
const corp = runtime.selectedCorp!;
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
if (explicit) {
return createPiperClientForCorp(corp, explicit);
}
const clients = await createClientsForCorp(corp);
try {
const corpId = corp.corpId || corp.id;
const platforms = await api.listPlatforms(clients.ekbClient, corpId);
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
if (firstActive?.id) {
return await createPiperClientForCorp(corp, firstActive.id);
}
} catch {
// Fall back to default easoClient
}
return clients.easoClient;
}
async function enrichFailedExecutions(
client: Awaited<ReturnType<typeof createPiperClientForCorp>>,
jobId: string,
items: WorkflowTaskExecution[]
): Promise<WorkflowTaskExecution[]> {
const parentCache = new Map<string, WorkflowTaskExecution[]>();
const enriched: WorkflowTaskExecution[] = [];
for (const item of items) {
if (item.parentId && (!item.currentLoopPath || !item.name || !item.form)) {
let siblings = parentCache.get(item.parentId);
if (!siblings) {
try {
const level = await api.getJobExecutionLevel(client, jobId, {
parentId: item.parentId,
page: 1,
pageSize: 100,
});
siblings = level.items;
} catch {
siblings = [];
}
parentCache.set(item.parentId, siblings);
}
const matched = siblings.find((s) => s.id === item.id);
if (matched) {
const itemInputs = item.inputs;
const matchedInputs = matched.inputs;
const hasItemInputs = Array.isArray(itemInputs)
? itemInputs.length > 0
: Boolean(itemInputs && typeof itemInputs === "object" && Object.keys(itemInputs as Record<string, unknown>).length > 0);
const itemOutputs = item.outputs;
const matchedOutputs = matched.outputs;
const hasItemOutputs = Boolean(
itemOutputs && typeof itemOutputs === "object" && Object.keys(itemOutputs as Record<string, unknown>).length > 0
);
enriched.push({
...matched,
...item,
name: item.name || matched.name,
label: item.label || matched.label,
displayName: item.displayName || matched.displayName,
type: item.type || matched.type,
status: item.status || matched.status,
currentLoopPath: item.currentLoopPath || matched.currentLoopPath,
levelIndex: item.levelIndex?.length ? item.levelIndex : matched.levelIndex,
form: item.form ?? matched.form,
details: item.details ?? matched.details,
inputs: hasItemInputs ? itemInputs : matchedInputs,
outputs: hasItemOutputs ? itemOutputs : matchedOutputs,
error: item.error ?? matched.error,
});
continue;
}
}
enriched.push(item);
}
return enriched;
}
async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const jobId = parsed.args[0] || stringOption(parsed.options, ["id", "job-id", "jobId"]);
if (!jobId) {
return {
stdout: "",
stderr: "用法: hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]\n",
exitCode: 1,
};
}
const client = await createJobPiperClient(parsed, runtime);
const page = numberOption(parsed.options, ["page"]) || 1;
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100;
const logsExecutionId = stringOption(parsed.options, ["logs", "log", "execution-logs"]);
const parentExecutionId = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
// 1. --logs=<executionId>
if (logsExecutionId) {
const logs = await api.getExecutionLogs(client, logsExecutionId);
if (runtime.jsonMode) {
return {
stdout: printJson({ jobId, executionId: logsExecutionId, logs }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const rows = logs.map((log, i) => [
i + 1,
String(log.id ?? "-"),
String(log.createAt ?? (log as Record<string, unknown>).createTime ?? (log as Record<string, unknown>).timestamp ?? "-"),
String(log.level || "INFO"),
String(log.message || JSON.stringify(log)),
]);
return {
stdout: [
`====== 节点执行日志 (Job: ${jobId} | Execution: ${logsExecutionId}) ======`,
rows.length ? printTable(["#", "日志 ID", "时间", "级别", "内容"], rows) : "该节点暂无输出日志",
"",
].join("\n"),
stderr: "",
exitCode: 0,
};
}
// 2. --parent=<executionId>
if (parentExecutionId) {
const levelPage = await api.getJobExecutionLevel(client, jobId, {
parentId: parentExecutionId,
page,
pageSize,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
jobId,
parentId: parentExecutionId,
...levelPage,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const rows = levelPage.items.map((item, idx) => [
idx + 1,
item.id,
item.name || "-",
item.label || item.displayName || "-",
item.type || "-",
item.status || "-",
item.currentLoopPath || "-",
item.error?.message || "-",
]);
const extraDetails: string[] = [];
for (const item of levelPage.items) {
if (item.form !== undefined || item.error?.message) {
extraDetails.push(
`\n── 节点明细 [${item.id}] (${item.name || "-"} | loop=${item.currentLoopPath || "-"} | status=${item.status}) ──`
);
if (item.error?.message) {
extraDetails.push(` 错误原因: ${item.error.message}`);
}
if (item.form !== undefined) {
extraDetails.push(` 传入表单 (form): ${JSON.stringify(item.form)}`);
}
if (item.details !== undefined) {
extraDetails.push(` 明细数据 (details): ${JSON.stringify(item.details)}`);
}
}
}
return {
stdout: [
`====== 子节点执行层级明细 (Job: ${jobId} | Parent: ${parentExecutionId} | 共 ${levelPage.totalItems} 项) ======`,
rows.length
? printTable(
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因"],
rows
)
: "暂无子节点执行记录",
...extraDetails,
"",
].join("\n"),
stderr: "",
exitCode: 0,
};
}
// 3. --failed
if (onlyFailed) {
const [job, failedPage] = await Promise.all([
api.getJob(client, jobId).catch(() => undefined),
api.getJobFailedExecutions(client, jobId),
]);
const enrichedItems = await enrichFailedExecutions(client, jobId, failedPage.items);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
jobId,
job: job ?? null,
totalItems: failedPage.totalItems,
items: enrichedItems,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const rows = enrichedItems.map((item, idx) => [
idx + 1,
item.id,
item.parentId || "-",
item.name || "-",
item.type || "-",
item.status || "-",
item.currentLoopPath || "-",
item.error?.message || "-",
]);
const formSummaries: string[] = [];
for (const item of enrichedItems) {
if (item.error?.message || item.form !== undefined) {
formSummaries.push(
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | status=${item.status} | loop=${item.currentLoopPath || "-"}) ──`
);
if (item.error?.message) {
formSummaries.push(` 错误详情: ${item.error.message}`);
}
if (item.form !== undefined) {
formSummaries.push(` 表单入参 (form): ${JSON.stringify(item.form)}`);
}
}
}
return {
stdout: [
`====== Job 异常/跳过执行节点明细 (Job: ${jobId}) ======`,
job
? printKeyValue({
"Job ID": job.id,
"工作流 ID": job.pipelineId,
"Job 状态": job.state ?? job.status,
"开始时间": job.startTime || "-",
"耗时(ms)": String(job.durationTime ?? "-"),
})
: "",
"",
rows.length
? printTable(
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
rows
)
: "未发现异常或报错跳过的执行节点",
...formSummaries,
"",
].filter(Boolean).join("\n"),
stderr: "",
exitCode: 0,
};
}
// 4. Default mode: Job overview + top-level tree + failed executions
const [job, tree, failedPage] = await Promise.all([
api.getJob(client, jobId),
api.getJobExecutionTree(client, jobId),
api.getJobFailedExecutions(client, jobId).catch(() => ({
number: 1,
size: 100,
totalPages: 0,
totalItems: 0,
items: [] as WorkflowTaskExecution[],
})),
]);
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
jobId,
job,
executionTree: tree,
failedExecutions,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const treeRows = tree.map((node, idx) => [
idx + 1,
node.id,
node.name || "-",
node.label || node.displayName || "-",
node.type || "-",
node.status || "-",
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
node.error?.message || "-",
]);
const failedRows = failedExecutions.map((item, idx) => [
idx + 1,
item.id,
item.parentId || "-",
item.name || "-",
item.type || "-",
item.status || "-",
item.currentLoopPath || "-",
item.error?.message || "-",
]);
const outLines = [
`====== 工作流 Job 执行详情 [${job.id}] ======`,
printKeyValue({
"Job ID": job.id,
"工作流 ID (pipelineId)": job.pipelineId,
"Job 状态 (state)": job.state ?? job.status,
"开始时间": job.startTime || "-",
"结束时间": job.endTime || "-",
"耗时(ms)": String(job.durationTime ?? "-"),
"顶层节点数": tree.length,
"异常/跳过节点数": failedExecutions.length,
}),
"",
"── 顶层节点执行树 ──",
treeRows.length
? printTable(
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"],
treeRows
)
: "暂无顶层节点执行记录",
];
if (failedRows.length > 0) {
outLines.push("");
outLines.push("── ⚠️ 失败/报错跳过节点明细 (含循环子项) ──");
outLines.push(
printTable(
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
failedRows
)
);
}
return {
stdout: `${outLines.join("\n")}\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 explicitStateFile = stringOption(parsed.options, ["state-file", "stateFile"]);
const stateFile = explicitStateFile || `sqlite:workflow_error_alerts:${runtime.selectedCorp!.id}`;
const check = new WorkflowAlertStore(explicitStateFile || `corp:${runtime.selectedCorp!.id}`).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 };
requireMutationConfirmation(
parsed,
runtime,
"发布并启用工作流",
`hose-use workflow publish ${pipelineId} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "发布并启用工作流", pipelineId, { state: 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;
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
const filterPlatformId = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
const rawResult = await listAllWorkflows(clients, { page, pageSize });
const workflows = filterPlatformId
? rawResult.workflows.filter(
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
)
: rawResult.workflows;
const result = filterPlatformId
? { ...rawResult, workflows, totalWorkflows: workflows.length }
: rawResult;
if (runtime.jsonMode) {
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (result.workflows.length === 0) {
return {
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`,
stderr: "",
exitCode: 0,
};
}
const rows = result.workflows.map((wf, i) => [
i + 1,
wf.id,
wf.pipelineName,
wf.platformName || wf.platformId || "-",
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
wf.tasks?.length ?? "-",
]);
const table = printTable(
["#", "工作流 ID", "工作流名称", "所属自建应用", "状态", "节点数"],
rows
);
return {
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表 (共 ${result.workflows.length} 条) ======\n${table}\n`,
stderr: "",
exitCode: 0,
};
}
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) {
return { stdout: "", stderr: "用法: hose-use workflow get <pipelineId>\n", exitCode: 1 };
}
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 };
}
const summary = printKeyValue({
"工作流 ID": detail.id,
"工作流名称": detail.label,
"状态": detail.state === 1 ? "🟢 启用" : "⚪ 停用",
"版本号": detail.version || "-",
"节点总数": detail.tasks?.length ?? 0,
});
let taskList = "";
if (detail.tasks && detail.tasks.length > 0) {
const taskRows = detail.tasks.map((t, i) => [
i + 1,
t.name || "-",
t.label || "-",
t.type,
t.groupName || "-",
]);
taskList = `\n 节点结构:\n` + printTable(["#", "节点标识", "节点名称", "类型", "分组"], taskRows);
}
return {
stdout: `====== 工作流详情 ======\n${summary}\n${taskList}\n`,
stderr: "",
exitCode: 0,
};
}
async function createWorkflowDetailClient(
parsed: CliParsedArgs,
runtime: CliRuntime,
pipelineId: string,
): Promise<{
client: Awaited<ReturnType<typeof createPiperClientForCorp>>;
clients: Awaited<ReturnType<typeof createClientsForCorp>>;
}> {
const clients = await createClientsForCorp(runtime.selectedCorp!);
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
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,
clients,
};
}
async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const taskType = stringOption(parsed.options, ["task", "taskType", "type"]) || parsed.args[0];
if (!taskType) {
return {
stdout: "",
stderr: "用法: hose-use workflow find --task=<节点类型> (如 code-js2, http, condition)\n",
exitCode: 1,
};
}
const clients = await createClientsForCorp(runtime.selectedCorp!);
const includeDetail = booleanOption(parsed.options, ["includeDetail", "detail"]);
const page = numberOption(parsed.options, ["page"]) || 1;
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
const result = await findWorkflowsByTaskType(clients, taskType, {
page,
pageSize,
includeDetail,
});
if (runtime.jsonMode) {
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (result.workflows.length === 0) {
return {
stdout: `未找到包含节点类型 [${taskType}] 的工作流\n`,
stderr: "",
exitCode: 0,
};
}
const rows = result.workflows.map((wf, i) => [
i + 1,
wf.id,
wf.pipelineName,
wf.platformName || wf.platformId || "-",
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
]);
const table = printTable(
["#", "工作流 ID", "工作流名称", "所属自建应用", "状态"],
rows
);
return {
stdout: `====== 匹配节点类型 [${taskType}] 的工作流 (共 ${result.workflows.length} 条) ======\n${table}\n`,
stderr: "",
exitCode: 0,
};
}
async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
const stateArg = stringOption(parsed.options, ["state", "s"]);
if (!pipelineId || stateArg === undefined) {
return {
stdout: "",
stderr: "用法: hose-use workflow toggle <pipelineId> --state=<1|0> (1启用, 0停用)\n",
exitCode: 1,
};
}
const state = (stateArg === "1" || stateArg === "true" ? 1 : 0) as 0 | 1;
requireMutationConfirmation(
parsed,
runtime,
"切换工作流状态",
`hose-use workflow toggle ${pipelineId} --state=${state} --yes`
);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换工作流状态", 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 };
}
return {
stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${state === 1 ? "🟢 启用" : "⚪ 停用"}\n`,
stderr: "",
exitCode: 0,
};
}