Merge pull request #136 from yunyingk/release/v0.8.18

release: v0.8.18 — 工作流在途与延时执行精准透视及节点字典增强
This commit is contained in:
yunyingk authored and GitHub committed 2026-10-21 17:23:15 +08:00
commit d349227b7b
22 files changed
+1138 -600

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.17",
"version": "0.8.18",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+1 -1
View File
@@ -1,4 +1,4 @@
# hose-use (v0.8.17)
# hose-use (v0.8.18)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
+516 -515
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.17",
"version": "0.8.18",
"module": "src/server.ts",
"type": "module",
"exports": {
+2 -2
View File
@@ -2,11 +2,11 @@
name: hose-use
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
metadata:
version: 0.8.17
version: 0.8.18
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
---
# hose-use (v0.8.17)
# hose-use (v0.8.18)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.8.17",
"version": "0.8.18",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.8.17
version: 0.8.18
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+1 -1
View File
@@ -272,7 +272,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"dictionary": "enum",
"dict": "enum"
},
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose", "boolean"), ...flagList("a admin-key adminKey after app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId keyword l label log logs max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform-id platformId pwd query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId keyword l label log logs max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
},
"bill": {
"summary": "单据检索、表单规格诊断与审批动作",
+30
View File
@@ -27,6 +27,7 @@ export async function handleProbeCommand(
env: currentCorp.env,
isTest: currentCorp.isTest,
staffId: currentCorp.credentials.staffId,
staffName: currentCorp.staffName || currentCorp.session?.staffName,
baseUrl: currentCorp.baseUrl,
source: currentCorp.source,
accountId: currentCorp.accountId,
@@ -52,6 +53,35 @@ export async function handleProbeCommand(
loginStaffId: sessionRes.value?.loginStaffId,
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
};
// 自愈补全员工姓名 (Self-Healing Profile Hydration)
if (!currentCorp.staffName && !currentCorp.session?.staffName) {
if (hasOpenApi && currentCorp.credentials.appKey && currentCorp.credentials.appSecurity && currentCorp.credentials.staffId) {
try {
const { fetchHoseOpenApiAccessToken, fetchHoseStaffDetails } = await import("../../core/auth/openapi-v1.js");
const openapiToken = await fetchHoseOpenApiAccessToken({
baseUrl: currentCorp.baseUrl,
appKey: currentCorp.credentials.appKey,
appSecurity: currentCorp.credentials.appSecurity,
});
const details = await fetchHoseStaffDetails(currentCorp.baseUrl || "https://app.ekuaibao.com", openapiToken, [currentCorp.credentials.staffId]);
if (details[0]?.name) {
currentCorp.staffName = details[0].name;
if (!currentCorp.session) {
currentCorp.session = { staffName: details[0].name } as any;
} else {
currentCorp.session.staffName = details[0].name;
}
if (details[0].cellphone && currentCorp.session) {
currentCorp.session.cellphone = details[0].cellphone;
}
(results.enterprise as any).staffName = details[0].name;
const { saveCorpConfig } = await import("../../core/config/loader.js");
saveCorpConfig(currentCorp);
}
} catch {}
}
}
} catch (e) {
results.ekbSession = {
status: "error",
+178
View File
@@ -1989,5 +1989,183 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
expect(wfEvalRes.stdout).toContain("执行成功 ✅");
expect(wfEvalRes.stdout).toContain('"total": 100');
});
it("workflow logs correctly detects and formats running/delayed jobs and in-progress count", async () => {
const mockDetail = {
id: "pipe_delay_test",
pipelineName: "审批延时测试流程",
state: 1,
tasks: [
{ name: "trigger_1", type: "clock", label: "定时触发" },
{ name: "action_delay_1", type: "task-dynamic-delay", label: "延时等待节点", sleepTime: 60 },
{ name: "action_js_1", type: "code-js2", label: "通知节点" },
],
};
const mockLogs = {
executeCount: 3,
successCount: 2,
errorCount: 0,
number: 1,
size: 10,
totalPages: 1,
totalItems: 3,
jobList: [
{
state: 0,
jobName: "审批延时测试流程",
jobId: "job_running_001",
executeTime: "2026-10-21 17:15:00",
status: "STARTED",
runType: "DEBUG",
successTaskCount: 1,
errorTaskCount: 0,
hasError: "不存在",
},
{
state: 0,
jobName: "审批延时测试流程",
jobId: "job_completed_002",
executeTime: "2026-10-21 17:10:00",
status: "COMPLETED",
runType: "DEBUG",
successTaskCount: 3,
errorTaskCount: 0,
hasError: "不存在",
},
],
};
const mockClient = {
get: (url: string) => ({
json: async () => {
if (url.includes("/log")) return { code: 200, data: mockLogs };
return { code: 200, data: mockDetail };
},
}),
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: mockClient as any,
easoClient: mockClient as any,
corp: mockCorp,
} as any)
);
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any));
// 1. All logs view
const allLogsRes = await handleWorkflowCommand(
{
area: "workflow",
action: "logs",
args: ["pipe_delay_test"],
options: {},
raw: ["workflow", "logs", "pipe_delay_test"],
},
mockRuntime
);
expect(allLogsRes.exitCode).toBe(0);
expect(allLogsRes.stdout).toContain("运行中/延时");
expect(allLogsRes.stdout).toContain("1 (正在执行或延时等待中)");
expect(allLogsRes.stdout).toContain("⏳ 运行中");
expect(allLogsRes.stdout).toContain("✅ 已完成");
expect(allLogsRes.stdout).toContain("⏳ 执行中");
// 2. Client-side filtering by --state=RUNNING
const runningOnlyRes = await handleWorkflowCommand(
{
area: "workflow",
action: "logs",
args: ["pipe_delay_test"],
options: { state: "RUNNING" },
raw: ["workflow", "logs", "pipe_delay_test", "--state=RUNNING"],
},
mockRuntime
);
expect(runningOnlyRes.exitCode).toBe(0);
expect(runningOnlyRes.stdout).toContain("job_running_001");
expect(runningOnlyRes.stdout).not.toContain("job_completed_002");
});
it("workflow job correctly displays mid-flight delayed job progress and non-interruptive hints", async () => {
const mockDetail = {
id: "pipe_delay_test",
pipelineName: "审批延时测试流程",
state: 1,
tasks: [
{ name: "trigger_1", type: "clock", label: "定时触发" },
{ name: "action_delay_1", type: "task-dynamic-delay", label: "延时等待节点", sleepTime: 60 },
{ name: "action_js_1", type: "code-js2", label: "通知节点" },
],
};
const mockRunningJob = {
id: "job_running_001",
pipelineId: "pipe_delay_test",
status: "STARTED",
state: 0,
startTime: 1792574000000,
};
const mockExecutionTree = [
{ id: "exec_1", name: "trigger_1", label: "定时触发", type: "clock", status: "COMPLETED", durationTime: 10 },
{ id: "exec_2", name: "action_delay_1", label: "延时等待节点", type: "task-dynamic-delay", status: "STARTED" },
];
const mockClient = {
get: (url: string) => ({
json: async () => {
if (url.includes("/execution")) return { code: 200, data: mockExecutionTree };
if (url.includes("/failed")) return { code: 200, data: { items: [] } };
if (url.includes("/jobs/job_running_001")) return { code: 200, data: mockRunningJob };
return { code: 200, data: mockDetail };
},
}),
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: mockClient as any,
easoClient: mockClient as any,
corp: mockCorp,
} as any)
);
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any));
// 1. Overview view
const jobRes = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_running_001"],
options: {},
raw: ["workflow", "job", "job_running_001"],
},
mockRuntime
);
expect(jobRes.exitCode).toBe(0);
expect(jobRes.stdout).toContain("⏳ 运行中 (STARTED)");
expect(jobRes.stdout).toContain("当前正在执行第 2 步(延时等待中或任务处理中)");
expect(jobRes.stdout).not.toContain("本次调度在第 2 步中断");
expect(jobRes.stdout).toContain("⏳ 延时等待中");
// 2. Timeline view
const timelineRes = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_running_001"],
options: { timeline: true },
raw: ["workflow", "job", "job_running_001", "--timeline"],
},
mockRuntime
);
expect(timelineRes.exitCode).toBe(0);
expect(timelineRes.stdout).toContain("✅ 已完成");
expect(timelineRes.stdout).toContain("⏳ 延时等待中");
expect(timelineRes.stdout).toContain("⏳ 等待前序步骤执行完成");
expect(timelineRes.stdout).not.toContain("因前序步骤中断");
});
});
+83 -12
View File
@@ -1,4 +1,4 @@
import { listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js";
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js";
import { stringOption, numberOption, booleanOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
@@ -37,46 +37,117 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
});
const stateOption = stringOption(parsed.options, ["state"]);
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
const isJobError = (job: any): boolean => {
const s = (job.status || "").toUpperCase();
if (s === "STARTED" || s === "RUNNING") return false;
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
if (job.state === "FAILED" || job.status === "FAILED") return true;
return false;
};
const filteredJobList = hasErrorFilter
? rawResult.jobList.filter(isJobError)
: rawResult.jobList;
const result = hasErrorFilter
? { ...rawResult, jobList: filteredJobList }
: rawResult;
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
let filteredJobList = rawResult.jobList;
if (hasErrorFilter) {
filteredJobList = filteredJobList.filter(isJobError);
} else if (stateOption) {
const norm = stateOption.trim().toUpperCase();
if (norm === "FAILED" || norm === "FAIL" || norm === "ERROR") {
filteredJobList = filteredJobList.filter(isJobError);
} else if (norm === "COMPLETED" || norm === "SUCCESS") {
filteredJobList = filteredJobList.filter((j: any) => (j.status || "").toUpperCase() === "COMPLETED" && !isJobError(j));
} else if (norm === "RUNNING" || norm === "STARTED" || norm === "IN_PROGRESS") {
filteredJobList = filteredJobList.filter((j: any) => {
const s = (j.status || "").toUpperCase();
return s === "STARTED" || s === "RUNNING";
});
}
}
const inProgressCount = Math.max(
0,
(rawResult.executeCount ?? 0) - (rawResult.successCount ?? 0) - (rawResult.errorCount ?? 0)
);
const result = {
...rawResult,
jobList: filteredJobList,
inProgressCount,
};
let workflowName = rawResult.jobList[0]?.jobName;
let workflowState: string | undefined;
try {
const detail = await getWorkflowDetail(client, pipelineId);
if (detail) {
workflowName = detail.pipelineName || detail.label || workflowName;
workflowState = detail.state === 1 ? "🟢 启用中" : "⚪ 已停用";
}
} catch {}
if (runtime.jsonMode) {
return {
stdout: printJson({ ...result, workflowName, workflowState }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const formatRunType = (runType?: string): string => {
if (!runType) return "-";
const upper = runType.toUpperCase();
if (upper === "DEBUG") return "🧪 调试";
if (upper === "RUN") return "🏃 运行";
return runType;
};
const formatJobStatus = (status?: string, state?: unknown): string => {
const s = (status || "").toUpperCase();
if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中";
if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成";
if (s === "FAILED" || s === "ERROR") return "❌ 失败";
if (s === "STOP" || s === "STOPPED") return "🛑 终止";
if (s === "CANCELLED" || s === "CANCELED") return "🚫 取消";
if (!s && (state === 0 || state === "0")) return "COMPLETED";
return s || String(state ?? "-");
};
const formatErrorColumn = (job: any): string => {
const s = (job.status || "").toUpperCase();
if (s === "STARTED" || s === "RUNNING") return "⏳ 执行中";
if (isJobError(job)) return "⚠️ 包含错误";
return "正常";
};
const rows = result.jobList.map((job: any, idx) => [
idx + 1,
job.jobId || job.id || "-",
job.status || (job.state === 0 ? "COMPLETED" : String(job.state ?? "-")),
formatRunType(job.runType),
formatJobStatus(job.status, job.state),
job.successTaskCount ?? 0,
job.errorTaskCount ?? 0,
isJobError(job) ? "⚠️ 包含错误" : "正常",
formatErrorColumn(job),
job.durationTime ?? "-",
job.executeTime || job.startTime || "-",
]);
const tableStr = rows.length
? printTable(
["#", "Job ID", "状态 (state)", "成功节点 (successTaskCount)", "失败节点 (errorTaskCount)", "有错误 (hasError)", "耗时(ms)", "开始时间"],
["#", "Job ID", "类型 (runType)", "状态 (state)", "成功节点", "失败节点", "有错误", "耗时(ms)", "开始时间"],
rows
)
: "暂无匹配的运行记录";
return {
stdout: [
`====== 工作流运行日志 [${pipelineId}] ======`,
`====== 工作流运行日志 [${pipelineId}]${workflowName ? ` · ${workflowName}` : ""}${workflowState ? ` (${workflowState})` : ""} ======`,
printKeyValue({
...(workflowName ? { "工作流名称": workflowName } : {}),
...(workflowState ? { "当前状态": workflowState } : {}),
"执行次数": result.executeCount,
"成功次数": result.successCount,
"错误次数": result.errorCount,
...(result.inProgressCount > 0 ? { "运行中/延时": `${result.inProgressCount} (正在执行或延时等待中)` } : {}),
"日志条数": result.totalItems,
"当前返回记录": result.jobList.length,
}),
+146 -13
View File
@@ -7,6 +7,7 @@ import {
getJobExecutionLevel,
getJobExecutionTree,
getJobFailedExecutions,
getWorkflowDetail,
isTaskExecutionFailed,
listPlatforms,
explainConditionBranches,
@@ -119,6 +120,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
const nodeQuery = stringOption(parsed.options, ["node", "task", "node-id", "nodeId"]);
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
const verbose = booleanOption(parsed.options, ["verbose", "v"]);
const isTimeline = booleanOption(parsed.options, ["timeline", "progress", "steps"]);
// 1. --logs=<executionId>
if (logsExecutionId) {
@@ -389,7 +391,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
};
}
// 4. Default mode: Job overview + top-level tree + failed executions
// 4. Default mode: Job overview + top-level tree + failed executions + timeline
const [job, tree, failedPage] = await Promise.all([
getJob(client, jobId),
getJobExecutionTree(client, jobId),
@@ -401,19 +403,120 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
items: [] as WorkflowTaskExecution[],
})),
]);
const workflowDetail = await getWorkflowDetail(client, job.pipelineId).catch(() => undefined);
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
const conditionDiagnoses = explainConditionBranches(tree);
const timeline = workflowDetail?.tasks?.map((t: any, idx: number) => {
const executed = tree.find((node) => node.name === t.name);
let statusText = "⏳ 未执行";
let errorDetail = "-";
if (executed) {
if (executed.status === "COMPLETED") statusText = "✅ 已完成";
else if (executed.status === "FAILED") {
statusText = "❌ 失败中断";
const msg = (executed.error?.message || "执行失败").replace(/\s+/g, " ");
errorDetail = msg.length > 100 ? `${msg.slice(0, 97)}...` : msg;
} else if (executed.status === "STARTED" || executed.status === "RUNNING") {
statusText = t.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 正在执行中";
} else {
statusText = executed.status;
}
} else {
const runningPrior = tree.find((node) => node.status === "STARTED" || node.status === "RUNNING");
const failedPrior = tree.find((node) => node.status === "FAILED");
if (runningPrior) {
statusText = "⏳ 等待前序步骤执行完成";
} else if (failedPrior) {
statusText = "⏳ 未执行 (因前序步骤中断)";
}
}
return {
index: idx + 1,
name: t.name,
displayName: t.displayName || t.label || t.name,
type: t.type,
status: statusText,
duration: executed ? String((executed as any).durationTime ?? executed.executionTime ?? "-") : "-",
detail: errorDetail,
};
});
if (isTimeline && timeline && timeline.length > 0) {
if (runtime.jsonMode) {
return {
stdout: printJson(
{
jobId,
pipelineId: job.pipelineId,
workflowName: workflowDetail?.pipelineName || workflowDetail?.label,
workflowState: workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
jobStatus: job.state ?? job.status,
totalTasks: timeline.length,
executedTasks: tree.length,
unexecutedTasks: timeline.length - tree.length,
timeline,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const timelineRows = timeline.map((it: any) => [
it.index,
it.name,
it.displayName,
it.type,
it.status,
it.duration,
it.detail,
]);
return {
stdout: [
`====== 工作流全链路步骤进度 [${job.id}] ======`,
printKeyValue({
"Job ID": job.id,
"工作流 ID": job.pipelineId,
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
"Job 状态": job.state ?? job.status,
"定义总步骤数": timeline.length,
"已调度步骤数": tree.length,
"未执行步骤数": timeline.length - tree.length,
}),
"",
printTable(
["#", "节点标识", "步骤名称", "类型", "执行状态", "耗时(ms)", "详细说明"],
timelineRows
),
"",
].join("\n"),
stderr: "",
exitCode: 0,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
jobId,
job,
workflow: workflowDetail
? {
id: workflowDetail.id,
name: workflowDetail.pipelineName || workflowDetail.label,
state: workflowDetail.state,
stateLabel: workflowDetail.state === 1 ? "🟢 启用中" : "⚪ 已停用",
totalTasks: workflowDetail.tasks?.length ?? tree.length,
}
: undefined,
executionTree: tree,
failedExecutions,
conditionDiagnoses,
timeline,
},
runtime.outputOptions
),
@@ -422,16 +525,32 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
};
}
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 formatJobStatusLabel = (status?: string, state?: unknown): string => {
const s = (status || "").toUpperCase();
if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中 (STARTED)";
if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成 (COMPLETED)";
if (s === "FAILED" || s === "ERROR") return "❌ 失败 (FAILED)";
if (s === "STOP" || s === "STOPPED") return "🛑 终止 (STOPPED)";
if (s === "CANCELLED" || s === "CANCELED") return "🚫 已取消";
return s || String(state ?? "-");
};
const treeRows = tree.map((node, idx) => {
const isRunning = node.status === "STARTED" || node.status === "RUNNING";
const statusLabel = isRunning
? (node.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 运行中")
: node.status || "-";
return [
idx + 1,
node.id,
node.name || "-",
node.label || node.displayName || "-",
node.type || "-",
statusLabel,
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
node.error?.message || "-",
];
});
const failedRows = failedExecutions.map((item, idx) => [
idx + 1,
@@ -444,18 +563,32 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
item.error?.message || "-",
]);
const hasUnexecuted = workflowDetail && workflowDetail.tasks && workflowDetail.tasks.length > tree.length;
const isJobRunning = (job.status || "").toUpperCase() === "STARTED" || (job.status || "").toUpperCase() === "RUNNING";
const outLines = [
`====== 工作流 Job 执行详情 [${job.id}] ======`,
printKeyValue({
"Job ID": job.id,
"工作流 ID (pipelineId)": job.pipelineId,
"Job 状态 (state)": job.state ?? job.status,
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
"Job 状态 (state)": formatJobStatusLabel(job.status, job.state),
"开始时间": job.startTime || "-",
"结束时间": job.endTime || "-",
"耗时(ms)": String(job.durationTime ?? "-"),
"顶层节点数": tree.length,
"定义总步骤数": workflowDetail?.tasks?.length ?? tree.length,
"已调度节点数": tree.length,
...(hasUnexecuted ? { "未执行步骤数": workflowDetail.tasks.length - tree.length } : {}),
"异常/跳过节点数": failedExecutions.length,
}),
...(hasUnexecuted
? [
"",
isJobRunning
? `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,当前正在执行第 ${tree.length} 步(延时等待中或任务处理中),后续 ${workflowDetail.tasks.length - tree.length} 个步骤尚未调度。运行 'hose-use workflow job ${job.id} --timeline' 可查看实时节点进度。`
: `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,本次调度在第 ${tree.length} 步中断,后续 ${workflowDetail.tasks.length - tree.length} 个步骤未执行。运行 'hose-use workflow job ${job.id} --timeline' 查看全链路步骤时间线。`,
]
: []),
"",
"── 顶层节点执行树 ──",
treeRows.length
+1 -1
View File
@@ -3,7 +3,7 @@ import { stringOption } from "../../parser.js";
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
import type { CliParsedArgs, CliRuntime } from "../../types.js";
export const PLATFORM_ID_OPTION_KEYS = ["platform-id", "platformId", "app-id", "appId"];
export const PLATFORM_ID_OPTION_KEYS = ["platform", "platform-id", "platformId", "app", "app-id", "appId"];
export async function createWorkflowDetailClient(
parsed: CliParsedArgs,
+32 -2
View File
@@ -88,9 +88,39 @@ export async function handleWorkflowTest(
}
case "WEBHOOK": {
// 分支 B: Webhook / 外部事件触发器 ── 支持 sample / body / file / empty
// 分支 B: Webhook / 外部事件触发器 ── 支持 flow/bill / sample / body / file / empty
targetId = "";
if (rawBody) {
if (flowCodeOrId && !rawBody && !filePath) {
try {
const { getBillByCodeOrId } = await import("../../../domains/bill/tools.js");
const { createSessionClient } = await import("../../../core/http/index.js");
const sessionClient = await createSessionClient(runtime.selectedCorp!);
const corpId = runtime.selectedCorp?.corpId || runtime.selectedCorp?.id || "";
const bills = await getBillByCodeOrId(sessionClient, corpId, flowCodeOrId);
const bill = bills[0];
if (bill) {
customPayload = {
code: bill.billCode,
flowId: bill.billId,
title: bill.title,
data: bill,
corporationId: corpId,
};
} else {
customPayload = {
code: flowCodeOrId,
flowId: flowCodeOrId,
corporationId: corpId,
};
}
} catch {
customPayload = {
code: flowCodeOrId,
flowId: flowCodeOrId,
corporationId: runtime.selectedCorp?.corpId || runtime.selectedCorp?.id,
};
}
} else if (rawBody) {
try {
customPayload = JSON.parse(rawBody);
} catch (e: any) {
+33 -15
View File
@@ -118,11 +118,17 @@ export async function getScriptEngineClient(
const cachedHoseToken = mem.hoseToken;
return createAuthClient({
prefixUrl: SCRIPT_ENGINE_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
platformid: platformId,
hoseaccesstoken: scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken,
}),
getHeaders: () => {
const headers: Record<string, string> = {
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`,
platformid: platformId,
};
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
if (currentHoseToken) {
headers.hoseaccesstoken = currentHoseToken;
}
return headers;
},
onUnauthorized: async () => {
invalidateScriptEngineCache(corp.id, cacheKey);
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
@@ -144,11 +150,17 @@ export async function getScriptEngineClient(
const baseUrl = corp.baseUrl || EKB_BASE_URL;
// 重新换取
const hoseToken = await fetchHoseToken(
corp.credentials.accessToken,
corpId,
environment
);
let hoseToken = "";
try {
hoseToken = await fetchHoseToken(
corp.credentials.accessToken,
corpId,
environment
);
} catch {
// 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限,
// 此处优雅降级避免阻塞 Piper / ScriptEngine 客户端构建
}
const easoJwt = await fetchEasoJwt(
corp.credentials.accessToken,
corpId,
@@ -179,11 +191,17 @@ export async function getScriptEngineClient(
return createAuthClient({
prefixUrl: SCRIPT_ENGINE_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
platformid: platformId,
hoseaccesstoken: scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken,
}),
getHeaders: () => {
const headers: Record<string, string> = {
Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`,
platformid: platformId,
};
const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
if (currentHoseToken) {
headers.hoseaccesstoken = currentHoseToken;
}
return headers;
},
onUnauthorized: async () => {
invalidateScriptEngineCache(corp.id, cacheKey);
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
+44 -23
View File
@@ -107,15 +107,18 @@ export async function fetchUnityJwt(
export async function fetchEasoRealmToken(
corpId: string,
unityJwt: string,
hoseToken: string
hoseToken?: string
): Promise<string> {
const headers: Record<string, string> = {
Authorization: `Bearer ${unityJwt}`,
};
if (hoseToken) {
headers.hoseaccesstoken = hoseToken;
}
const response = await ky
.get(`${EASO_BASE_URL}/api/realms/EASO`, {
searchParams: { corpId },
headers: {
Authorization: `Bearer ${unityJwt}`,
hoseaccesstoken: hoseToken,
},
headers,
})
.json<{ value?: { accessToken?: string } }>();
const token = response.value?.accessToken;
@@ -185,12 +188,18 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
return {
client: createAuthClient({
prefixUrl: EASO_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? cachedToken}`,
accesstoken: corp.credentials.accessToken,
corporationid: corpId,
hoseaccesstoken: easoMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken,
}),
getHeaders: () => {
const headers: Record<string, string> = {
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? cachedToken}`,
accesstoken: corp.credentials.accessToken,
corporationid: corpId,
};
const currentHoseToken = easoMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken;
if (currentHoseToken) {
headers.hoseaccesstoken = currentHoseToken;
}
return headers;
},
onUnauthorized: async () => {
invalidateEasoCache(corp.id);
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
@@ -212,11 +221,17 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
const baseUrl = corp.baseUrl || EKB_BASE_URL;
// 重新换取
const hoseToken = await fetchHoseToken(
corp.credentials.accessToken,
corpId,
environment
);
let hoseToken = "";
try {
hoseToken = await fetchHoseToken(
corp.credentials.accessToken,
corpId,
environment
);
} catch {
// 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限,
// 但 EASO Realm 换票仅依赖 Unity JWT 即可完成鉴权,此处降级兼容以避免阻断
}
const unityJwt = await fetchUnityJwt(
corp.credentials.accessToken,
corpId,
@@ -226,7 +241,7 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
const easoToken = await fetchEasoRealmToken(
corpId,
unityJwt,
hoseToken
hoseToken || undefined
);
const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时
@@ -265,12 +280,18 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
return {
client: createAuthClient({
prefixUrl: EASO_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? easoToken}`,
accesstoken: corp.credentials.accessToken,
corporationid: corpId,
hoseaccesstoken: easoMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken,
}),
getHeaders: () => {
const headers: Record<string, string> = {
Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? easoToken}`,
accesstoken: corp.credentials.accessToken,
corporationid: corpId,
};
const currentHoseToken = easoMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken;
if (currentHoseToken) {
headers.hoseaccesstoken = currentHoseToken;
}
return headers;
},
onUnauthorized: async () => {
invalidateEasoCache(corp.id);
if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp);
+10 -1
View File
@@ -240,7 +240,16 @@ export async function listRunningJobs(
const response = await client.get("api/easo/jobs/running", {
searchParams: { pipelineId, runType },
});
return unwrap(response, z.array(WorkflowJobSchema));
const json = (await response.json()) as { code?: number; data?: unknown };
const rawData = json?.data;
if (!rawData) return [];
if (Array.isArray(rawData)) {
return z.array(WorkflowJobSchema).parse(rawData);
}
if (typeof rawData === "object") {
return [WorkflowJobSchema.parse(rawData)];
}
return [];
}
export async function getJob(
+33 -8
View File
@@ -188,6 +188,11 @@ export const FlowCreateTaskSchema = BaseTaskSchema.extend({
onError: OnErrorSchema.optional(),
});
export const DynamicDelayTaskSchema = BaseTaskSchema.extend({
type: z.literal("task-dynamic-delay"),
sleepTime: z.union([z.number(), z.string()]).optional(),
});
// 兜底节点:遇到未收录类型时仍保留全部字段
export const UnknownTaskSchema = z
.object({
@@ -217,6 +222,7 @@ export const WorkflowTaskSchema: z.ZodType<WorkflowTask> = z.union([
EkuaibaoDatalinkCreateTaskSchema,
DataConvertTaskSchema,
FlowCreateTaskSchema,
DynamicDelayTaskSchema,
UnknownTaskSchema,
]);
@@ -351,14 +357,33 @@ export const WorkflowChargeSchema = z.object({
// ── 运行中的任务与单次 Job 执行详情 ──────────────────────────────────────────
export const WorkflowJobSchema = z.object({
id: z.string(),
pipelineId: z.string(),
status: z.string().default(""),
startTime: z.union([z.string(), z.number()]).optional(),
endTime: z.union([z.string(), z.number()]).optional(),
triggerType: z.string().default(""),
});
export const WorkflowJobSchema = z
.object({
id: z.string().optional(),
jobId: z.string().optional(),
pipelineId: z.string().nullish().default(""),
jobName: z.string().nullish(),
status: z.string().default(""),
runType: z.string().default(""),
executeTime: z.union([z.string(), z.number()]).nullish(),
startTime: z.union([z.string(), z.number()]).nullish(),
endTime: z.union([z.string(), z.number()]).nullish(),
triggerType: z.string().default(""),
successTaskCount: z.number().nullish().default(0),
errorTaskCount: z.number().nullish().default(0),
hasError: z.union([z.string(), z.boolean()]).nullish(),
state: z.union([z.number(), z.string()]).nullish(),
autoPublish: z.boolean().nullish(),
version: z.string().nullish(),
snapshotId: z.string().nullish(),
})
.passthrough()
.transform((val) => ({
...val,
id: val.id || val.jobId || "",
jobId: val.jobId || val.id || "",
pipelineId: val.pipelineId || "",
}));
export const WorkflowJobDetailSchema = z
.object({
@@ -50,6 +50,7 @@ const KNOWN_TYPES = new Set([
"ekuaibao-datalink-delete-trigger",
"data-convert",
"flow-create-task",
"task-dynamic-delay",
]);
function referencesFromTask(task: WorkflowTask): string[] {
@@ -175,6 +175,21 @@ export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions>
...options.extra,
};
case "task-dynamic-delay":
case "delay":
return {
name,
type: "task-dynamic-delay",
label: options.label || "延迟执行节点",
desc: options.desc || "在工作流中暂停等待指定秒数",
groupName: "action",
orderIndex: 0,
levelIndex: [0],
status: "active",
sleepTime: options.extra?.sleepTime ?? 60,
...options.extra,
};
default:
return {
name,
@@ -30,6 +30,10 @@ export function summarizeTask(task: WorkflowTask): string {
if (task.type === "stop") {
return "阻断终止流程";
}
if (task.type === "task-dynamic-delay") {
const sleep = (task as any).sleepTime;
return sleep !== undefined && sleep !== null ? `延迟等待: ${sleep} 秒` : "延迟等待节点";
}
if (task.type === "ekuaibao-datalink-create-trigger") {
return "业务对象台账新增触发";
}
@@ -7,11 +7,13 @@ export function normalizeJobStatus(job?: Partial<WorkflowJobDetail> | Record<str
const rawStatus = (job as any).status;
const rawState = (job as any).state;
if (typeof rawStatus === "string" && rawStatus.trim()) {
return rawStatus.trim().toUpperCase();
const s = rawStatus.trim().toUpperCase();
if (s === "STARTED") return "RUNNING";
return s;
}
if (rawState === 0 || rawState === "0") return "COMPLETED";
if (rawState === 1 || rawState === "1") return "RUNNING";
if (rawState === 2 || rawState === "2") return "FAILED";
if (rawState === 0 || rawState === "0") return "COMPLETED";
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
return "UNKNOWN";
}