- skill: 补充终止节点物理断点与样本固化 (Stop Barrier & Sample Pinning) 最佳实践 - config: 修复 switchCorp / enter --switch 持久化写入 defaultCorpId 与激活 stateful 模式 - workflow node: 新增 inspect (探针透视配置/样本/执行) 与 sample-save (一键固化出参至 sampleData 并刷新选择树) - workflow test: 新增 --save-sample 选项,调测通过后自动将产生出参的节点固化为 sampleData - parser/metadata: 注册 save-sample 选项词汇表,补充单测 workflow-node-sample-inspect.test.ts
944 lines
34 KiB
TypeScript
944 lines
34 KiB
TypeScript
import {
|
||
getWorkflowDetail,
|
||
updateWorkflow,
|
||
flattenWorkflowTaskTree,
|
||
findWorkflowTask,
|
||
addWorkflowTask,
|
||
editWorkflowTask,
|
||
removeWorkflowTask,
|
||
applyNodeMapping,
|
||
getJobExecutionTree,
|
||
listWorkflowLogs,
|
||
refreshWorkflowChooses,
|
||
} from "../../../domains/platform/workflow/services.js";
|
||
import { isServerManagedDescType } from "../../../domains/platform/workflow/nodes/mutations.js";
|
||
import { ValidationError } from "../../../core/errors.js";
|
||
import type { WorkflowDetail } from "../../../domains/platform/workflow/types.js";
|
||
import { stringOption, numberOption } from "../../parser.js";
|
||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||
import { createWorkflowDetailClient, formatWorkflowVersion, resolveChooseSerialization, normalizeNodeExpressionFields, preflightNodeAppRequirements, renderAppRequirementAlerts } from "./shared.js";
|
||
import { handleGrantNodes, handleListAvailableNodes } from "./node-catalog.js";
|
||
|
||
async function saveNodeChanges(client: Parameters<typeof getWorkflowDetail>[0], original: WorkflowDetail, updated: WorkflowDetail, platformId?: string) {
|
||
// 并发保护由 SDK 出口统一负责,避免每个调用点各写一份、或干脆忘写。
|
||
return updateWorkflow(client, updated, {
|
||
platformId,
|
||
expectedVersion: { version: original.version, tasksVersion: original.tasksVersion },
|
||
});
|
||
}
|
||
|
||
const SUB_ACTIONS = new Set([
|
||
"list", "ls", "get", "show", "info", "add", "append", "insert",
|
||
"edit", "update", "set", "map", "rm", "remove", "delete", "del",
|
||
"inspect", "probe", "examine", "sample-save", "save-sample",
|
||
]);
|
||
|
||
export async function handleNodeCommand(
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
const isPluralNodes = parsed.action === "nodes";
|
||
const firstArg = parsed.args[0]?.toLowerCase();
|
||
|
||
// 1. 企业级节点字典与灰度开通快捷分支
|
||
if (firstArg === "grant" || firstArg === "open") {
|
||
return handleGrantNodes(parsed, runtime);
|
||
}
|
||
if (
|
||
firstArg === "available" ||
|
||
firstArg === "list-available" ||
|
||
firstArg === "catalog" ||
|
||
firstArg === "probe"
|
||
) {
|
||
return handleListAvailableNodes(parsed, runtime);
|
||
}
|
||
|
||
// 2. 如果是 `hose-use workflow nodes`(复数)且没有指定具体的 pipelineId
|
||
const secondArg = parsed.args[1];
|
||
const isSecondArgPipelineId = secondArg && /^\d{10,}$/.test(secondArg.trim());
|
||
if (isPluralNodes && (!firstArg || ((firstArg === "list" || firstArg === "ls") && !isSecondArgPipelineId && !parsed.options.id && !parsed.options.pipelineId))) {
|
||
return handleListAvailableNodes(parsed, runtime);
|
||
}
|
||
|
||
let subAction = "list";
|
||
let pipelineId = "";
|
||
let nodeTarget = "";
|
||
|
||
if (firstArg && SUB_ACTIONS.has(firstArg)) {
|
||
subAction = firstArg;
|
||
pipelineId = parsed.args[1] || stringOption(parsed.options, ["id", "pipelineId", "workflowId"]) || "";
|
||
nodeTarget = parsed.args[2] || stringOption(parsed.options, ["node", "target", "name"]) || "";
|
||
} else if (firstArg) {
|
||
// 允许缩写直接跟 pipelineId: hose-use workflow node <pipelineId>
|
||
pipelineId = firstArg;
|
||
nodeTarget = parsed.args[1] || stringOption(parsed.options, ["node", "target", "name"]) || "";
|
||
} else {
|
||
pipelineId = stringOption(parsed.options, ["id", "pipelineId", "workflowId"]) || "";
|
||
nodeTarget = stringOption(parsed.options, ["node", "target", "name"]) || "";
|
||
}
|
||
|
||
if (!pipelineId) {
|
||
return {
|
||
stdout: "",
|
||
stderr: [
|
||
"用法: hose-use workflow node <子命令> <pipelineId> [选项]",
|
||
"",
|
||
"子命令 (工作流级别):",
|
||
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
|
||
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
|
||
" inspect <pipelineId> <节点标识> 透视节点契约、样本与最近调试出参 (别名: probe)",
|
||
" sample-save <pipelineId> <节点标识> 固化指定 Job 或最新调测出参为 sampleData",
|
||
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
|
||
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
|
||
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
|
||
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
|
||
"",
|
||
"子命令 (企业灰度节点级别):",
|
||
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
|
||
" nodes grant <type...> [--is-test] [--allow-prod] 为当前企业开通灰度节点(生产企业执行需显式 --allow-prod)",
|
||
"",
|
||
"示例:",
|
||
" hose-use workflow nodes",
|
||
" hose-use workflow nodes --all",
|
||
" hose-use workflow nodes grant code-js2",
|
||
" hose-use workflow nodes grant code-js2 --is-test # 仅用于工作流位于测试 Piper 的企业",
|
||
" hose-use workflow nodes grant code-js2 --dry-run # 生产企业:预览(无需覆盖参数)",
|
||
" hose-use workflow nodes grant code-js2 --allow-prod --yes # 生产企业:确认执行(--force 兼容)",
|
||
" hose-use workflow node list 896398895352487950",
|
||
].join("\n") + "\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
switch (subAction) {
|
||
case "list":
|
||
case "ls":
|
||
return handleListNodes(pipelineId, parsed, runtime);
|
||
case "inspect":
|
||
case "probe":
|
||
case "examine":
|
||
return handleInspectNode(pipelineId, nodeTarget, parsed, runtime);
|
||
case "sample-save":
|
||
case "save-sample":
|
||
return handleSaveNodeSample(pipelineId, nodeTarget, parsed, runtime);
|
||
case "get":
|
||
case "show":
|
||
case "info":
|
||
return handleGetNode(pipelineId, nodeTarget, parsed, runtime);
|
||
case "add":
|
||
case "append":
|
||
case "insert":
|
||
return handleAddNode(pipelineId, parsed, runtime);
|
||
case "edit":
|
||
case "update":
|
||
case "set":
|
||
return handleEditNode(pipelineId, nodeTarget, parsed, runtime);
|
||
case "map":
|
||
return handleMapNode(pipelineId, nodeTarget, parsed, runtime);
|
||
case "rm":
|
||
case "remove":
|
||
case "delete":
|
||
case "del":
|
||
return handleRemoveNode(pipelineId, nodeTarget, parsed, runtime);
|
||
default:
|
||
return {
|
||
stdout: "",
|
||
stderr: `未知 workflow node 子命令: ${subAction}。支持: list, get, add, edit, rm\n`,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
}
|
||
|
||
async function handleListNodes(
|
||
pipelineId: string,
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||
const detail = await getWorkflowDetail(client, pipelineId);
|
||
const tasks = detail.tasks || [];
|
||
const flattened = flattenWorkflowTaskTree(tasks);
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson({ pipelineId, label: detail.label, totalNodes: flattened.length, nodes: flattened }, runtime.outputOptions),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
if (flattened.length === 0) {
|
||
return {
|
||
stdout: `工作流 [${detail.label || pipelineId}] 暂无任何任务节点。\n`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
const rows = flattened.map((item) => [
|
||
item.hierarchicalIndex,
|
||
item.task.name,
|
||
item.task.type,
|
||
item.task.displayName || item.task.label || "-",
|
||
item.task.groupName || "-",
|
||
item.summary,
|
||
]);
|
||
|
||
const table = printTable(
|
||
["#", "节点标识 (name)", "类型 (type)", "标题", "分组", "配置摘要"],
|
||
rows
|
||
);
|
||
|
||
const out = [
|
||
`====== 工作流 [${detail.label || pipelineId}] 任务节点树 (共 ${flattened.length} 个节点) ======`,
|
||
table,
|
||
].join("\n");
|
||
|
||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||
}
|
||
|
||
async function handleGetNode(
|
||
pipelineId: string,
|
||
nodeTarget: string,
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
if (!nodeTarget) {
|
||
return {
|
||
stdout: "",
|
||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node get <pipelineId> <nodeNameOrIndex>\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||
const detail = await getWorkflowDetail(client, pipelineId);
|
||
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
|
||
|
||
if (!located) {
|
||
return {
|
||
stdout: "",
|
||
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson({ pipelineId, ...located }, runtime.outputOptions),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
const { task, hierarchicalIndex, path, parentName } = located;
|
||
const kv: Record<string, string> = {
|
||
"工作流 ID": pipelineId,
|
||
"节点标识 (name)": task.name,
|
||
"层级编号 (#)": hierarchicalIndex,
|
||
"JSON 路径": path,
|
||
"父容器节点": parentName || "顶级节点 (root)",
|
||
"节点类型 (type)": task.type,
|
||
"节点标题 (label)": task.label || "-",
|
||
"节点显示名 (displayName)": (task as any).displayName || "-",
|
||
"节点分组 (group)": task.groupName || "-",
|
||
"状态 (status)": task.status || "active",
|
||
};
|
||
|
||
if ((task as any).code !== undefined) {
|
||
kv["代码行数"] = String((task as any).code.split("\n").length);
|
||
}
|
||
|
||
const outLines = [
|
||
`====== 节点详情 [${task.name}] (${(task as any).displayName || task.label || task.type}) ======`,
|
||
printKeyValue(kv),
|
||
];
|
||
|
||
if ((task as any).code) {
|
||
outLines.push("\n--- 脚本内容 ---");
|
||
outLines.push((task as any).code);
|
||
}
|
||
|
||
return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 };
|
||
}
|
||
|
||
async function handleAddNode(
|
||
pipelineId: string,
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
const type = stringOption(parsed.options, ["type", "t"]);
|
||
if (!type) {
|
||
return {
|
||
stdout: "",
|
||
stderr: [
|
||
"请指定新增节点类型: --type=<类型>",
|
||
"常见类型: task-dynamic-delay (延迟等待), code-js2 (JS脚本), code (MVEL代码), http (HTTP请求), stop (终止流程), every (循环遍历), condition (分支条件)",
|
||
"",
|
||
"常用选项:",
|
||
" --type=<type> 节点类型 (如 task-dynamic-delay / code-js2 / http)",
|
||
" --sleep-time=<秒数> 延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||
" --set='key=value' 自定义节点属性注入",
|
||
" --label=<标题> 节点类型标题",
|
||
" --display-name=<名称> 设计器节点标题(displayName,最多 20 字符)",
|
||
" --code-file=<脚本路径> (推荐) 从本地文件导入代码,避免终端转义与 Token 浪费",
|
||
" --code=<代码片段> 传入代码字符串(仅限简短代码)",
|
||
" --parent=<容器节点name> 插入指定容器节点内部 (如 every 循环)",
|
||
" --after=<前置节点name> 插入指定节点之后",
|
||
" --yes 确认追加",
|
||
"",
|
||
"示例:",
|
||
" hose-use workflow node add 881196955148578838 --type=task-dynamic-delay --sleep-time=5 --after=action_123 --yes",
|
||
" hose-use workflow node add 896398895352487950 --type=code-js2 --label='数据清洗' --code-file=./clean.js --yes",
|
||
].join("\n") + "\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const label = stringOption(parsed.options, ["label", "name", "l"]);
|
||
const displayName = stringOption(parsed.options, ["display-name", "displayName", "display"]);
|
||
const parent = stringOption(parsed.options, ["parent", "container", "p"]);
|
||
const after = stringOption(parsed.options, ["after", "insert-after"]);
|
||
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
|
||
const codeFile = stringOption(parsed.options, ["code-file", "file"]);
|
||
let code = stringOption(parsed.options, ["code", "c"]);
|
||
|
||
if (codeFile) {
|
||
const fs = await import("fs/promises");
|
||
code = await fs.readFile(codeFile, "utf-8");
|
||
}
|
||
|
||
const rawSleepTime = numberOption(parsed.options, ["sleep-time", "sleepTime", "seconds"]);
|
||
const rawSet = stringOption(parsed.options, ["set", "value"]);
|
||
const extra: Record<string, any> = {};
|
||
if (rawSleepTime !== undefined) {
|
||
extra.sleepTime = rawSleepTime;
|
||
}
|
||
if (rawSet) {
|
||
if (rawSet.startsWith("{") && rawSet.endsWith("}")) {
|
||
try {
|
||
Object.assign(extra, JSON.parse(rawSet));
|
||
} catch {
|
||
// fallback
|
||
}
|
||
} else {
|
||
const eqIdx = rawSet.indexOf("=");
|
||
if (eqIdx !== -1) {
|
||
const k = rawSet.slice(0, eqIdx).trim();
|
||
const v = rawSet.slice(eqIdx + 1).trim();
|
||
try {
|
||
extra[k] = JSON.parse(v);
|
||
} catch {
|
||
extra[k] = v;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// choose 表达式形态归一化:默认与设计器产出一致(多一个右花括号),可切换为配平形态
|
||
const chooseMode = resolveChooseSerialization(parsed);
|
||
normalizeNodeExpressionFields(extra, chooseMode);
|
||
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"追加工作流节点",
|
||
`hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes`
|
||
);
|
||
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "追加工作流节点", pipelineId, {
|
||
pipelineId,
|
||
type,
|
||
label: label || "-",
|
||
displayName: displayName || "-",
|
||
targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾",
|
||
extra: Object.keys(extra).length ? extra : undefined,
|
||
});
|
||
}
|
||
|
||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||
const detail = await getWorkflowDetail(client, pipelineId);
|
||
|
||
const { workflow: updatedWorkflow, newTask } = addWorkflowTask(detail, {
|
||
type,
|
||
label,
|
||
displayName,
|
||
desc,
|
||
code,
|
||
parent,
|
||
after,
|
||
extra: Object.keys(extra).length ? extra : undefined,
|
||
});
|
||
|
||
const appPreflight = await preflightNodeAppRequirements(runtime, [
|
||
newTask as unknown as Record<string, any>,
|
||
]);
|
||
|
||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson({ success: true, pipelineId, newTask, workflow: saveResult, appRequirementAlerts: appPreflight.alerts }, runtime.outputOptions),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
const out = [
|
||
`✨ 节点 [${newTask.name}] (${newTask.displayName || newTask.label}) 已成功添加至工作流 [${pipelineId}]:`,
|
||
printKeyValue({
|
||
"节点标识 (name)": newTask.name,
|
||
"节点类型 (type)": newTask.type,
|
||
"节点标题 (label)": newTask.label || "-",
|
||
"节点显示名 (displayName)": newTask.displayName || "-",
|
||
"所属位置": parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流顶级末尾",
|
||
"节点总数": String(saveResult.tasks?.length || updatedWorkflow.tasks?.length || 0),
|
||
"工作流版本": formatWorkflowVersion(saveResult),
|
||
}),
|
||
renderAppRequirementAlerts(appPreflight.alerts),
|
||
].join("\n");
|
||
|
||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||
}
|
||
|
||
async function handleEditNode(
|
||
pipelineId: string,
|
||
nodeTarget: string,
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
if (!nodeTarget) {
|
||
return {
|
||
stdout: "",
|
||
stderr: [
|
||
"请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]",
|
||
"",
|
||
"常用选项:",
|
||
" --sleep-time=<秒数> 更新延迟等待秒数 (针对 task-dynamic-delay,如 5)",
|
||
" --set='key=value' 定向修改节点自定义属性 (如 --set='sleepTime=5')",
|
||
" --label=<类型标题> 更新节点类型标题(服务端保存时可能重新生成)",
|
||
" --display-name=<新名称> 更新设计器节点标题(displayName,最多 20 字符)",
|
||
" --code-file=<脚本路径> (推荐) 从本地文件导入最新脚本,避免终端转义与 Token 浪费",
|
||
" --code=<行内代码> 直接传入代码片段(短脚本)",
|
||
" --desc=<描述> 更新节点描述",
|
||
" --dry-run 只预览变更",
|
||
" --yes 确认保存修改",
|
||
"",
|
||
"示例:",
|
||
" hose-use workflow node edit 900682164608835609 action_cdd6fv --code-file=./clean.mvel --yes",
|
||
].join("\n") + "\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const label = stringOption(parsed.options, ["label", "l"]);
|
||
const displayName = stringOption(parsed.options, ["display-name", "displayName", "display"]);
|
||
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
|
||
const codeFile = stringOption(parsed.options, ["code-file", "file"]);
|
||
let code = stringOption(parsed.options, ["code", "c"]);
|
||
|
||
if (codeFile) {
|
||
const fs = await import("fs/promises");
|
||
code = await fs.readFile(codeFile, "utf-8");
|
||
}
|
||
|
||
const rawSet = stringOption(parsed.options, ["set", "value"]);
|
||
const customSet: Record<string, any> = {};
|
||
const rawSleepTime = numberOption(parsed.options, ["sleep-time", "sleepTime", "seconds"]);
|
||
if (rawSleepTime !== undefined) {
|
||
customSet.sleepTime = rawSleepTime;
|
||
}
|
||
if (rawSet) {
|
||
if (rawSet.startsWith("{") && rawSet.endsWith("}")) {
|
||
try {
|
||
Object.assign(customSet, JSON.parse(rawSet));
|
||
} catch {
|
||
// fallback to key=value if json parse fails
|
||
}
|
||
} else {
|
||
const eqIdx = rawSet.indexOf("=");
|
||
if (eqIdx !== -1) {
|
||
const k = rawSet.slice(0, eqIdx).trim();
|
||
const v = rawSet.slice(eqIdx + 1).trim();
|
||
try {
|
||
customSet[k] = JSON.parse(v);
|
||
} catch {
|
||
customSet[k] = v;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// choose 表达式形态归一化:默认与设计器产出一致(多一个右花括号),可切换为配平形态
|
||
const chooseMode = resolveChooseSerialization(parsed);
|
||
normalizeNodeExpressionFields(customSet, chooseMode);
|
||
|
||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "json-file"]);
|
||
if (mappingFile) {
|
||
const fs = await import("fs/promises");
|
||
const rawContent = await fs.readFile(mappingFile, "utf-8");
|
||
const mappingData = JSON.parse(rawContent);
|
||
return handleMapNode(pipelineId, nodeTarget, parsed, runtime, mappingData);
|
||
}
|
||
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"修改工作流节点",
|
||
`hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""} --yes`
|
||
);
|
||
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "修改工作流节点", `${pipelineId}:${nodeTarget}`, {
|
||
pipelineId,
|
||
nodeName: nodeTarget,
|
||
label: label || "-",
|
||
displayName: displayName || "-",
|
||
updatedFields: {
|
||
...(label ? { label } : {}),
|
||
...(displayName !== undefined ? { displayName } : {}),
|
||
...(desc ? { desc } : {}),
|
||
...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file=<path> 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}),
|
||
...customSet,
|
||
},
|
||
});
|
||
}
|
||
|
||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||
const detail = await getWorkflowDetail(client, pipelineId);
|
||
|
||
const { workflow: updatedWorkflow, editedTask } = editWorkflowTask(detail, nodeTarget, {
|
||
label,
|
||
displayName,
|
||
desc,
|
||
code,
|
||
set: Object.keys(customSet).length > 0 ? customSet : undefined,
|
||
});
|
||
const descManaged = desc !== undefined && isServerManagedDescType(editedTask.type);
|
||
|
||
const appPreflight = await preflightNodeAppRequirements(runtime, [
|
||
editedTask as unknown as Record<string, any>,
|
||
]);
|
||
|
||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult, descIgnored: descManaged, appRequirementAlerts: appPreflight.alerts }, runtime.outputOptions),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
let codeTip = "";
|
||
if (!codeFile && code && code.length > 300) {
|
||
codeTip = `\n💡 提示: 检测到通过命令行行内传入大段代码 (${code.length} 字符)。建议将脚本落地为本地文件并通过 --code-file=<路径> 传入,避免 Token 浪费与 Shell 转义风险。\n`;
|
||
}
|
||
const labelTip = label
|
||
? "\n💡 提示: --label 是节点类型标题,服务端保存时可能重新生成;要修改设计器标题请使用 --display-name。\n"
|
||
: "";
|
||
const descTip = descManaged
|
||
? "\n💡 提示: 该节点描述由服务端按配置自动生成,--desc 已忽略;如需稳定说明,请使用代码节点或在创建节点上写业务说明。\n"
|
||
: "";
|
||
|
||
return {
|
||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.displayName || editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n📌 ${formatWorkflowVersion(saveResult)}\n${codeTip}${labelTip}${descTip}${renderAppRequirementAlerts(appPreflight.alerts)}`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
async function handleMapNode(
|
||
pipelineId: string,
|
||
nodeTarget: string,
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime,
|
||
injectedMappingData?: any
|
||
): Promise<CliResult> {
|
||
if (!nodeTarget) {
|
||
return {
|
||
stdout: "",
|
||
stderr: [
|
||
"请提供目标节点标识 (name 或层级序号): hose-use workflow node map <pipelineId> <nodeNameOrIndex> --mapping-file=<path> [选项]",
|
||
"",
|
||
"常用选项:",
|
||
" --mapping-file=<路径> 包含字段映射的本地 JSON 文件 (可为字段数组或属性对象)",
|
||
" --dry-run 只预览变更",
|
||
" --yes 确认保存修改",
|
||
"",
|
||
"示例:",
|
||
" hose-use workflow node map 900682164608835609 action_datalink_create --mapping-file=./fields.json --yes",
|
||
].join("\n") + "\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
let mappingData = injectedMappingData;
|
||
if (!mappingData) {
|
||
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "file", "json-file"]);
|
||
if (!mappingFile) {
|
||
return {
|
||
stdout: "",
|
||
stderr: "错误: 请通过 --mapping-file=<路径> 指定本地字段映射 JSON 文件\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
const fs = await import("fs/promises");
|
||
try {
|
||
const content = await fs.readFile(mappingFile, "utf-8");
|
||
mappingData = JSON.parse(content);
|
||
} catch (e: any) {
|
||
return {
|
||
stdout: "",
|
||
stderr: `错误: 读取或解析映射文件失败: ${e.message}\n`,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
}
|
||
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"批量映射工作流节点配置",
|
||
`hose-use workflow node map ${pipelineId} ${nodeTarget} --yes`
|
||
);
|
||
|
||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||
const detail = await getWorkflowDetail(client, pipelineId);
|
||
|
||
const { workflow: updatedWorkflow, editedTask, changedKeys } = applyNodeMapping(detail, nodeTarget, mappingData);
|
||
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "批量映射工作流节点配置", `${pipelineId}:${editedTask.name}`, {
|
||
pipelineId,
|
||
nodeName: editedTask.name,
|
||
label: editedTask.label,
|
||
nodeType: editedTask.type,
|
||
changedKeys,
|
||
mappingSummary: Array.isArray(mappingData)
|
||
? `数组格式更新 (${mappingData.length} 项)`
|
||
: `对象属性更新 (${Object.keys(mappingData).join(", ")})`,
|
||
});
|
||
}
|
||
|
||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson({ success: true, pipelineId, editedTask, changedKeys, workflow: saveResult }, runtime.outputOptions),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
return {
|
||
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 已批量应用映射: ${changedKeys.join(", ")},并已保存至工作流 [${pipelineId}]。\n📌 ${formatWorkflowVersion(saveResult)}\n`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
async function handleRemoveNode(
|
||
pipelineId: string,
|
||
nodeTarget: string,
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
if (!nodeTarget) {
|
||
return {
|
||
stdout: "",
|
||
stderr: "请提供待删除节点标识 (name 或层级序号): hose-use workflow node rm <pipelineId> <nodeNameOrIndex>\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"移除工作流节点",
|
||
`hose-use workflow node rm ${pipelineId} ${nodeTarget} --yes`
|
||
);
|
||
|
||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||
const detail = await getWorkflowDetail(client, pipelineId);
|
||
|
||
const { workflow: updatedWorkflow, removedTask } = removeWorkflowTask(detail, nodeTarget);
|
||
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "移除工作流节点", `${pipelineId}:${removedTask.name}`, {
|
||
pipelineId,
|
||
nodeName: removedTask.name,
|
||
type: removedTask.type,
|
||
label: removedTask.label || "-",
|
||
remainingTasksCount: updatedWorkflow.tasks?.length || 0,
|
||
});
|
||
}
|
||
|
||
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson({ success: true, pipelineId, removedTask, workflow: saveResult }, runtime.outputOptions),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
return {
|
||
stdout: `🗑️ 节点 [${removedTask.name}] (${removedTask.label || removedTask.type}) 已从工作流 [${pipelineId}] 中安全移除。\n📌 ${formatWorkflowVersion(saveResult)}\n`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
async function handleInspectNode(
|
||
pipelineId: string,
|
||
nodeTarget: string,
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
if (!nodeTarget) {
|
||
return {
|
||
stdout: "",
|
||
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node inspect <pipelineId> <nodeNameOrIndex>\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||
const detail = await getWorkflowDetail(client, pipelineId);
|
||
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
|
||
|
||
if (!located) {
|
||
return {
|
||
stdout: "",
|
||
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const { task, hierarchicalIndex, path, parentName } = located;
|
||
const sampleData = (task as any).sampleData ?? null;
|
||
|
||
let executionProbe: {
|
||
jobId: string;
|
||
status: string;
|
||
executionTime?: number;
|
||
output?: any;
|
||
error?: any;
|
||
} | null = null;
|
||
|
||
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
|
||
try {
|
||
let jobIdToProbe = targetJobId;
|
||
if (!jobIdToProbe) {
|
||
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
|
||
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
|
||
if (firstItem && firstItem.id) {
|
||
jobIdToProbe = firstItem.id;
|
||
}
|
||
}
|
||
|
||
if (jobIdToProbe) {
|
||
const tree = await getJobExecutionTree(client, jobIdToProbe);
|
||
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
|
||
if (matchExecution) {
|
||
executionProbe = {
|
||
jobId: jobIdToProbe,
|
||
status: matchExecution.status || "UNKNOWN",
|
||
executionTime: (matchExecution as any).durationTime ?? matchExecution.executionTime,
|
||
output: matchExecution.output,
|
||
error: matchExecution.error,
|
||
};
|
||
}
|
||
}
|
||
} catch {
|
||
// 探针容错
|
||
}
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson(
|
||
{
|
||
pipelineId,
|
||
node: located,
|
||
sampleData,
|
||
executionProbe,
|
||
},
|
||
runtime.outputOptions
|
||
),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
const outLines: string[] = [
|
||
`====== 工作流节点只读探针 [${detail.label || pipelineId}] · ${task.displayName || task.label || task.name} ======`,
|
||
`节点标识 (name) : ${task.name}`,
|
||
`层级编号 (#) : ${hierarchicalIndex}`,
|
||
`节点类型 (type) : ${task.type}`,
|
||
`节点标题 (label) : ${task.label || "-"}`,
|
||
`节点显示名 (display): ${(task as any).displayName || "-"}`,
|
||
`父容器节点 : ${parentName || "顶级节点 (root)"}`,
|
||
`JSON 路径 : ${path}`,
|
||
];
|
||
|
||
if ((task as any).code !== undefined) {
|
||
outLines.push(`脚本代码行数 : ${(task as any).code.split("\n").length} 行`);
|
||
}
|
||
if ((task as any).url) {
|
||
outLines.push(`请求 URL : ${(task as any).url}`);
|
||
}
|
||
if ((task as any).specificationId) {
|
||
outLines.push(`单据模板 ID : ${JSON.stringify((task as any).specificationId)}`);
|
||
}
|
||
|
||
outLines.push("");
|
||
outLines.push("── 📦 节点固化样本数据 (sampleData) ──");
|
||
if (sampleData && typeof sampleData === "object" && Object.keys(sampleData).length > 0) {
|
||
const keys = Object.keys(sampleData);
|
||
outLines.push(`状态: ✅ 已固化样本 (${keys.length} 个字段)`);
|
||
outLines.push(printJson(sampleData, runtime.outputOptions));
|
||
} else {
|
||
outLines.push("状态: ⚪ 暂无样本数据 (设计器下拉菜单将无法自动解析其结构化变量)");
|
||
outLines.push("💡 提示: 可运行 hose-use workflow node sample-save <pipelineId> <nodeName> 固化最近调测出参");
|
||
}
|
||
|
||
outLines.push("");
|
||
outLines.push("── 🧪 最近一次调试执行出参 (Execution Output Probe) ──");
|
||
if (executionProbe) {
|
||
outLines.push(`来源 Job ID : ${executionProbe.jobId}`);
|
||
outLines.push(`执行状态 (status) : ${executionProbe.status}`);
|
||
outLines.push(`执行耗时 (ms) : ${executionProbe.executionTime ?? "-"}`);
|
||
if (executionProbe.output && typeof executionProbe.output === "object") {
|
||
outLines.push(`出参全貌 (output):`);
|
||
outLines.push(printJson(executionProbe.output, runtime.outputOptions));
|
||
} else {
|
||
outLines.push(`出参: ${JSON.stringify(executionProbe.output ?? null)}`);
|
||
}
|
||
} else {
|
||
outLines.push("未找到或无匹配的最近调试执行记录。");
|
||
}
|
||
|
||
return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 };
|
||
}
|
||
|
||
async function handleSaveNodeSample(
|
||
pipelineId: string,
|
||
nodeTarget: string,
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
if (!nodeTarget) {
|
||
return {
|
||
stdout: "",
|
||
stderr: "用法: hose-use workflow node sample-save <pipelineId> <nodeNameOrIndex> [--job=<jobId>]\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||
const detail = await getWorkflowDetail(client, pipelineId);
|
||
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
|
||
|
||
if (!located) {
|
||
return {
|
||
stdout: "",
|
||
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const { task } = located;
|
||
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
|
||
|
||
let jobIdToProbe = targetJobId;
|
||
if (!jobIdToProbe) {
|
||
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
|
||
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
|
||
if (firstItem && firstItem.id) {
|
||
jobIdToProbe = firstItem.id;
|
||
}
|
||
}
|
||
|
||
if (!jobIdToProbe) {
|
||
return {
|
||
stdout: "",
|
||
stderr: `未指定 Job ID 且未查询到工作流 [${pipelineId}] 的历史运行日志,无法提取样本数据。请先执行调试或通过 --job=<id> 指定。\n`,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const tree = await getJobExecutionTree(client, jobIdToProbe);
|
||
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
|
||
|
||
if (!matchExecution || matchExecution.output === undefined) {
|
||
return {
|
||
stdout: "",
|
||
stderr: `在 Job [${jobIdToProbe}] 中未找到节点 [${task.name}] 的有效执行出参 (output)。\n`,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const samplePayload = matchExecution.output;
|
||
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "固化节点样本数据 (sampleData)", `${pipelineId}:${task.name}`, {
|
||
pipelineId,
|
||
nodeName: task.name,
|
||
jobId: jobIdToProbe,
|
||
samplePayload,
|
||
});
|
||
}
|
||
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"固化节点样本数据 (sampleData)",
|
||
`hose-use workflow node sample-save ${pipelineId} ${nodeTarget} --job=${jobIdToProbe} --yes`
|
||
);
|
||
|
||
(task as any).sampleData = samplePayload;
|
||
const saveResult = await saveNodeChanges(client, detail, detail, platformId);
|
||
|
||
try {
|
||
await refreshWorkflowChooses(client, pipelineId);
|
||
} catch {}
|
||
|
||
const fieldCount = typeof samplePayload === "object" && samplePayload !== null ? Object.keys(samplePayload).length : 1;
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson(
|
||
{
|
||
success: true,
|
||
pipelineId,
|
||
nodeName: task.name,
|
||
jobId: jobIdToProbe,
|
||
fieldsSaved: fieldCount,
|
||
sampleData: samplePayload,
|
||
workflow: saveResult,
|
||
},
|
||
runtime.outputOptions
|
||
),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
return {
|
||
stdout: [
|
||
`✨ 节点 [${task.name}] (${task.displayName || task.label || task.type}) 样本数据 (sampleData) 固化成功!`,
|
||
` • 来源 Job ID : ${jobIdToProbe}`,
|
||
` • 固化字段数 : ${fieldCount} 个属性`,
|
||
` • 设计器联动 : 已刷新选择器 (chooses) 树,下游节点现在可在下拉列表中直接点选其输出变量。`,
|
||
`📌 ${formatWorkflowVersion(saveResult)}`,
|
||
].join("\n") + "\n",
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|