fix: address Codex PR review findings

This commit is contained in:
gitea committed 2026-10-25 22:32:45 +08:00
1 parent 0f164b6de5
commit a7974abb08
44 files changed
+3317 -667

No files matched your search

+27 -18
View File
@@ -28,8 +28,23 @@ import {
} from "./types.js";
import type { WorkflowState } from "./types.js";
// Helper to unwrap { data: T } / { value: T } response with null/error defense
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
function throwEasoResponseError(response: Response, record?: Record<string, unknown>): never {
const code = record?.code;
const status = typeof code === "number" ? code : response.status || 500;
const urlInfo = response.url ? ` [${response.url}]` : "";
const reason =
(typeof record?.msg === "string" && record.msg.trim()) ||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
(typeof record?.message === "string" && record.message.trim()) ||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
throw new AuthenticationError(fullMsg);
}
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
}
async function readEasoResponse(response: Response) {
const raw = await response.json();
const record =
raw !== null && typeof raw === "object" && !Array.isArray(raw)
@@ -38,23 +53,17 @@ export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promi
const code = record?.code;
const hasCodeError = code !== undefined && code !== null && Number(code) !== 200;
if (hasCodeError) throwEasoResponseError(response, record);
return { raw, record };
}
// Helper to unwrap { data: T } / { value: T } response with null/error defense
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
const { raw, record } = await readEasoResponse(response);
const hasWrapper = Boolean(record && ("data" in record || "value" in record));
const payload = hasWrapper ? (record!.data ?? record!.value) : raw;
if (hasCodeError || payload === null || payload === undefined) {
const status = typeof code === "number" ? code : response.status || 500;
const urlInfo = response.url ? ` [${response.url}]` : "";
const reason =
(typeof record?.msg === "string" && record.msg.trim()) ||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
(typeof record?.message === "string" && record.message.trim()) ||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
throw new AuthenticationError(fullMsg);
}
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
}
if (payload === null || payload === undefined) throwEasoResponseError(response, record);
return schema.parse(payload);
}
@@ -240,8 +249,8 @@ export async function listRunningJobs(
const response = await client.get("api/easo/jobs/running", {
searchParams: { pipelineId, runType },
});
const json = (await response.json()) as { code?: number; data?: unknown };
const rawData = json?.data;
const { record } = await readEasoResponse(response);
const rawData = record?.data;
if (!rawData) return [];
if (Array.isArray(rawData)) {
return z.array(WorkflowJobSchema).parse(rawData);
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it } from "bun:test";
import type { KyInstance } from "ky";
import { z } from "zod";
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
import { classifyCliError } from "../../cli/errors.js";
import { listRunningJobs, unwrap } from "./api.js";
import { watchWorkflowPipeline } from "./workflow/watch/pipeline-watcher.js";
const responding = (body: unknown) => ({ get: async () => Response.json(body) }) as unknown as KyInstance;
describe("running jobs response contract", () => {
for (const code of [401, 403, "401", "403"]) {
it(`rejects business authentication failure ${JSON.stringify(code)} before empty-data normalization`, async () => {
await expect(listRunningJobs(responding({ code, data: null, msg: "session expired" }), "wf"))
.rejects.toBeInstanceOf(AuthenticationError);
await expect(listRunningJobs(responding({ code, data: { id: "job" } }), "wf"))
.rejects.toBeInstanceOf(AuthenticationError);
});
}
it("preserves the API error category and server message for other business failures", async () => {
await expect(listRunningJobs(responding({ code: 500, data: null, errorMessage: "backend failed" }), "wf"))
.rejects.toMatchObject({ name: "EkbApiError", code: "EASO_API_ERROR", status: 500, message: expect.stringContaining("backend failed") });
});
it("preserves successful null, missing, single-job and array responses", async () => {
for (const body of [{ code: 200, data: null }, { code: 200 }, { data: [] }]) {
expect(await listRunningJobs(responding(body), "wf")).toEqual([]);
}
const single = await listRunningJobs(responding({ code: 200, data: { jobId: "job" } }), "wf");
expect(single.map((job) => job.id)).toEqual(["job"]);
const array = await listRunningJobs(responding({ code: "200", data: [{ id: "one" }, { id: "two" }] }), "wf");
expect(array.map((job) => job.id)).toEqual(["one", "two"]);
});
it("does not relax unwrap's nonempty-detail requirement", async () => {
await expect(unwrap(Response.json({ code: 200, data: null }), z.unknown())).rejects.toBeInstanceOf(EkbApiError);
await expect(unwrap(Response.json({ code: "401", data: [] }), z.array(z.unknown()))).rejects.toBeInstanceOf(AuthenticationError);
expect(await unwrap(Response.json({ code: 200, value: { id: "detail" } }), z.object({ id: z.string() })))
.toEqual({ id: "detail" });
});
});
describe("running job watcher error propagation", () => {
function watcherClient(running: unknown, otherFailure = false) {
let logCalls = 0;
const client = { get: async (path: string) => {
if (path === "api/easo/jobs/running") return Response.json(running);
if (path.endsWith("/log")) {
logCalls++;
return Response.json({ code: 200, data: { jobList: logCalls > 1 || otherFailure ? [{ jobId: "job", status: "COMPLETED" }] : [] } });
}
if (path.endsWith("/execution/level/failed")) return Response.json({ data: { items: [] } });
if (path.endsWith("/execution")) return Response.json({ data: [] });
if (path === "api/easo/jobs/job") return Response.json({ data: { id: "job", pipelineId: "wf", status: "COMPLETED" } });
return Response.json({ data: { id: "wf", label: "workflow" } });
} } as unknown as KyInstance;
return { client, logCalls: () => logCalls };
}
for (const once of [true, false]) {
it(`propagates running-job authentication failure in ${once ? "snapshot" : "continuous"} mode`, async () => {
const fixture = watcherClient({ code: 401, data: null });
try {
await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
throw new Error("watcher unexpectedly succeeded");
} catch (error) {
expect(error).toBeInstanceOf(AuthenticationError);
expect(classifyCliError(error).exitCode).toBe(11);
}
expect(fixture.logCalls()).toBe(once ? 0 : 1);
});
it(`retains non-authentication log fallback in ${once ? "snapshot" : "continuous"} mode`, async () => {
const fixture = watcherClient({ code: 500, data: null }, once);
const report = await watchWorkflowPipeline(fixture.client, "wf", { once, timeoutMs: 500 });
expect(report.totalJobsWatched).toBe(1);
expect(report.jobs[0]?.jobId).toBe("job");
});
}
});
@@ -77,6 +77,10 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
- 条件解释支持已声明的比较操作符、嵌套 AND/OR 和循环上下文;缺少证据、不支持的值类型或执行尚未结束时,`evaluation` / `matched` 为 `null`,不据此声称分支判定为 False。
- `diff-job` 按父任务路径、循环路径及重复次数配对实例;JSON 节点包含 `instanceKey` / `currentLoopPath`,输出变化也计入差异。
- `execution-context.ts` 是条件解释和 Job diff 共用的纯执行实例索引,不负责请求或 CLI 输出。
- 代码出参摘要使用同一执行树展开函数,覆盖条件、循环及已有子执行容器;同名节点的多次执行分别保留。
- `logs --has-error` 包括已经产生错误的在途任务,错误标记不被 RUNNING/STARTED 覆盖。`--state` 保留原有终态筛选兼容语义,不能替代“包含错误”筛选;筛选仍针对当前返回页。
- `job` 无法读取工作流详情时,状态显示“未知”,不会把可用 Job 的未知工作流状态显示成“已停用”。
- `tail` 的在途任务接口先校验业务错误码,再兼容成功的空值、单对象和数组;在途任务查询的鉴权错误会终止监听并沿用 CLI 认证错误退出码,其他既有日志回退保留。
## 企业可用节点探针与灰度开通(Nodes Probe & Grant)
@@ -137,6 +141,10 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
`eval-script` 使用内嵌 QuickJS/WASM 独立运行时,输入经过 JSON 复制,脚本无法访问宿主的 `process`、`Bun`、文件或网络。保留同步 JavaScript、日志和结构化执行结果;Promise 返回值明确报错。执行时间默认 3000ms,内存上限 32MiB,输入和结果各不超过 1MiB,日志最多 500 条及 64KiB。WASM 随 MCP bundle 和单文件二进制一起分发,不需要额外运行时文件。
MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `java.util.HashMap` / `java.util.ArrayList` 构造器、Map/List 基本方法,以及可确定的末尾顶层表达式返回;末尾表达式只求值一次,显式 `return` 继续有效。Map.size 按自身键数量计数,List.size 按元素数计数,字符串和注释不参与代码改写。其他 Java 构造器、泛型及无法确定完成值的末项复合语句明确返回 `UnsupportedMvelSyntax`,不把错误仿真结果当作成功。它不模拟 JVM 精确数值、任意 Java 方法或完整原生 MVEL;本地成功不能替代合思真实引擎的兼容性验证。
`node edit --file=<脚本>` 是 `--code-file` 的兼容别名;编辑字段映射使用 `--mapping-file=<JSON>`,或独立的 `node map --file=<JSON>`。不根据文件扩展名猜测用途。
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。管理员密码用于额外授权,不能替代写操作确认。
节点定位约定:CLI 的字符串编号(如 `3`、`2.1`)始终对应列表展示的层级编号;SDK 传入数字 `3` 时表示深度优先遍历的第 3 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。
@@ -157,6 +165,8 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
## 工具链静态门禁与防御性保障 (Toolchain Defense & Linting)
字段引用检查覆盖 `inputs`、`fields`、`mapping`、直接 `form` 及其嵌套对象/数组,不扫描脚本和说明文本。`choose` 支持 JSON 描述符、引号路径和裸路径:明确节点键或标准节点前缀缺失时产生 `BROKEN_CHOOSE_REFERENCE`,旧循环 `$item` 路径产生 `BROKEN_LOOP_ITEM_REFERENCE`;`trigger_1` 也必须实际存在。`body` 等上下文根不按节点处理,来源无法静态确定或无法解析的表达式给出软提示,不据此声称已验证可用。此检查不等同于完整的上游作用域或字段类型校验。
1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`;
2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断;参数包含无效 URL 百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,避免权限探测异常中断其他节点分析;
3. **前端富文本 `$snapshot` 自动清洗**:在 SDK `updateWorkflow` 时,自动递归遍历 `$snapshot` 字典并将陈旧的 `docs.ekuaibao.com` 替换为 `app.ekuaibao.com`,避免 Web 控制台用户重新点开节点保存时产生配置倒退;
@@ -53,20 +53,84 @@ const KNOWN_TYPES = new Set([
"task-dynamic-delay",
]);
function extractChooseTags(val: unknown): Array<{ raw: string; parsed: any }> {
interface ChooseReference {
raw: string;
key?: string;
descriptor?: boolean;
problem?: string;
}
/** 只解析 choose 参数,不执行表达式;引号内的括号不参与标签边界匹配。 */
function extractChooseTags(val: unknown): ChooseReference[] {
if (typeof val !== "string") return [];
const results: Array<{ raw: string; parsed: any }> = [];
const matches = val.matchAll(/@\{choose\('(.*?)'\)\}/g);
for (const m of matches) {
const results: ChooseReference[] = [];
const marker = /@\{\s*choose\s*\(/g;
let match: RegExpExecArray | null;
while ((match = marker.exec(val))) {
const from = marker.lastIndex;
let quote = "";
let escaped = false;
let depth = 1;
let end = from;
for (; end < val.length; end++) {
const ch = val[end];
if (quote) {
if (escaped) escaped = false;
else if (ch === "\\") escaped = true;
else if (ch === quote) quote = "";
} else if (ch === "'" || ch === '"') quote = ch;
else if (ch === "(") depth++;
else if (ch === ")" && --depth === 0) break;
}
const close = /^\s*\}/.exec(val.slice(end + 1));
if (depth !== 0 || !close) {
results.push({ raw: val.slice(match.index), problem: "choose 标签未闭合或缺少结束标记" });
continue;
}
marker.lastIndex = end + 1 + close[0].length;
const raw = val.slice(match.index, marker.lastIndex);
const argument = val.slice(from, end).trim();
try {
results.push({ raw: m[0], parsed: JSON.parse(m[1]) });
let value = argument;
if (argument.startsWith('"')) value = JSON.parse(argument);
else if (argument.startsWith("'")) {
if (!argument.endsWith("'")) throw new Error("未闭合的参数字符串");
// 单引号是模板包裹符;保留 descriptor 内 JSON 自身的转义。
value = argument.slice(1, -1).replace(/\\'/g, "'");
}
if (typeof value !== "string") throw new Error("参数应为节点描述或路径");
if (value.trim().startsWith("{")) {
const descriptor: unknown = JSON.parse(value);
if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor) || typeof (descriptor as Record<string, unknown>).key !== "string" || !(descriptor as { key: string }).key.trim()) throw new Error("节点描述缺少 key");
results.push({ raw, key: (descriptor as { key: string }).key.trim(), descriptor: true });
} else if (/^[$\p{L}_][$\p{L}\p{N}_]*(?:\.[$\p{L}\p{N}_]+)*$/u.test(value.trim())) {
results.push({ raw, key: value.trim(), descriptor: false });
} else throw new Error("参数不是可静态识别的节点路径");
} catch {
// ignore
results.push({ raw, problem: "choose 参数不是可静态识别的节点描述或路径" });
}
}
return results;
}
function collectExpressionValues(value: unknown, path: string, result: Array<{ key: string; value: string }>, allowEntry = false): void {
if (typeof value === "string") result.push({ key: path, value });
else if (Array.isArray(value)) value.forEach((item, index) => {
collectExpressionValues(item, `${path}[${index}]`, result, true);
});
else if (value && typeof value === "object") {
const entry = value as Record<string, unknown>;
if (allowEntry && Object.hasOwn(entry, "key") && typeof entry.key === "string" && Object.hasOwn(entry, "value")) {
// 明确 key/value 条目的 label/type 是元信息;普通映射的 label 字段仍是业务值。
collectExpressionValues(entry.value, `${path}[${entry.key}].value`, result);
} else {
for (const [key, child] of Object.entries(value)) collectExpressionValues(child, `${path}.${key}`, result, true);
}
}
}
const CHOOSE_CONTEXT_ROOTS = new Set(["body", "input", "inputs", "output", "outputs", "context", "ctx"]);
function buildTaskNameMap(tasks: WorkflowTask[]): Map<string, WorkflowTask> {
const map = new Map<string, WorkflowTask>();
const walk = (list: WorkflowTask[]) => {
@@ -687,25 +751,29 @@ export function analyzeWorkflow(
}
// 诊断 5: 字段变量引用失效校验 (BROKEN_CHOOSE_REFERENCE / BROKEN_LOOP_ITEM_REFERENCE)
const inspectFields: Array<{ key?: string; value?: unknown }> = [];
const inspectFields: Array<{ key: string; value: string }> = [];
const rawTask = task as Record<string, unknown>;
if (Array.isArray(task.inputs)) inspectFields.push(...task.inputs);
else if (rawTask.inputs && typeof rawTask.inputs === "object") {
for (const [k, v] of Object.entries(rawTask.inputs)) inspectFields.push({ key: k, value: v });
}
if (Array.isArray(rawTask.fields)) inspectFields.push(...(rawTask.fields as Array<{ key?: string; value?: unknown }>));
if (Array.isArray(rawTask.mapping)) inspectFields.push(...(rawTask.mapping as Array<{ key?: string; value?: unknown }>));
for (const key of ["inputs", "fields", "mapping", "form"]) collectExpressionValues(rawTask[key], key, inspectFields);
for (const field of inspectFields) {
if (typeof field.value === "string") {
const chooseList = extractChooseTags(field.value);
for (const item of chooseList) {
const chooseKey = String(item.parsed?.key || "").trim();
if (!chooseKey) continue;
const chooseKey = item.key;
if (!chooseKey) {
addDiagnostic(diagnostics, {
severity: "warning", category: "soft_advice", code: "UNRESOLVED_CHOOSE_REFERENCE", path,
message: `字段 [${field.key}] 的引用无法静态检查:${item.problem}。请在真实流程设计器中确认。`,
});
continue;
}
const segments = chooseKey.split(".");
const root = segments[0];
const rootTask = taskNameMap.get(root);
// 5.1 循环内使用了旧版已弃用的 control_xxx.$item 语法,前端无法解析
if (chooseKey.endsWith(".$item")) {
const baseNodeKey = chooseKey.replace(/\.\$item$/, "");
if (segments[1] === "$item" && (item.descriptor || rootTask?.type === "every" || root.startsWith("control_"))) {
const baseNodeKey = root;
addDiagnostic(diagnostics, {
severity: "error",
category: "hard_block",
@@ -717,13 +785,20 @@ export function analyzeWorkflow(
}
// 5.2 引用了一个在当前工作流中根本不存在的上游节点
if (chooseKey !== "trigger_1" && !taskNameMap.has(chooseKey)) {
const sourceKey = item.descriptor ? chooseKey : root;
if (taskNameMap.has(sourceKey) || (!item.descriptor && CHOOSE_CONTEXT_ROOTS.has(root))) continue;
if (item.descriptor || /^(?:action|control|trigger)_/.test(root)) {
addDiagnostic(diagnostics, {
severity: "error",
category: "hard_block",
code: "BROKEN_CHOOSE_REFERENCE",
path,
message: `字段 [${field.key || "未知"}] 引用的上游节点 '${chooseKey}' 不存在于当前工作流中,前端设计器将报错【引用变量不存在】并阻断流程保存或运行。`,
message: `字段 [${field.key || "未知"}] 引用的上游节点 '${sourceKey}' 不存在于当前工作流中,前端设计器将报错【引用变量不存在】并阻断流程保存或运行。`,
});
} else {
addDiagnostic(diagnostics, {
severity: "warning", category: "soft_advice", code: "UNRESOLVED_CHOOSE_REFERENCE", path,
message: `字段 [${field.key}] 引用了 '${chooseKey}',无法静态确定根 '${root}' 是节点还是上下文;请在真实流程设计器中确认引用来源。`,
});
}
}
@@ -0,0 +1,110 @@
import { describe, expect, test } from "bun:test";
import { analyzeWorkflow } from "./analyzer.js";
const descriptor = (key: string) => `@{choose('${JSON.stringify({ key, properties: [{ key: "data" }] })}')}`;
function analyze(config: Record<string, unknown>, sources: Array<Record<string, unknown>> = [{ name: "trigger_actual", type: "webhook" }]) {
return analyzeWorkflow({ id: "wf", label: "test", state: 1, version: "1", tasks: [
...sources, { name: "action_write", type: "http", ...config },
] } as any);
}
describe("choose reference containers and source classification", () => {
test("finds missing JSON node references in direct and nested form containers", () => {
const tag = descriptor("missing_node");
for (const config of [
{ fields: [{ key: "title", value: tag }] },
{ mapping: [{ key: "title", value: tag }] },
{ mapping: { title: { nested: [tag] } } },
{ form: [{ key: "title", value: tag }] },
{ form: { title: tag } },
{ inputs: { form: { title: tag } } },
{ inputs: [{ key: "form", value: { title: tag } }] },
{ inputs: [{ key: "form", value: [{ key: "title", value: tag }] }] },
]) {
const result = analyze(config);
expect(result.summary.passed).toBe(false);
expect(result.diagnostics.filter(item => item.code === "BROKEN_CHOOSE_REFERENCE")).toHaveLength(1);
expect(result.diagnostics.find(item => item.code === "BROKEN_CHOOSE_REFERENCE")?.message).toContain("title");
}
});
test("does not inspect script, descriptions or descriptor label/type metadata", () => {
const tag = descriptor("missing_node");
const result = analyze({ code: `return ${JSON.stringify(tag)};`, desc: tag, label: tag, fields: [{ key: "title", label: tag, type: tag, value: "ordinary value" }], inputs: { form: { nested: { key: "title", value: "ordinary value", label: tag, type: tag } } } });
expect(result.diagnostics).toEqual([]);
// A raw form object may legitimately have a business field named label.
expect(analyze({ form: { label: tag } }).summary.passed).toBe(false);
expect(analyze({ form: { key: "ordinary field", value: "ordinary value", label: tag } }).summary.passed).toBe(false);
});
test.each([
"@{choose(action_missing.data)}",
"@{choose('action_missing.data')}",
'@{choose("action_missing.data")}',
descriptor("action_missing"),
])("blocks a clearly identified missing node in %s", tag => {
const result = analyze({ mapping: [{ key: "value", value: tag }] });
expect(result.summary.passed).toBe(false);
expect(result.diagnostics.map(item => item.code)).toContain("BROKEN_CHOOSE_REFERENCE");
});
test("handles multiple descriptors, escaped quotes and parentheses inside labels", () => {
const single = `@{choose('${JSON.stringify({ key: "action_first", label: 'text (with) "quotes"', properties: [] })}')}`;
const double = `@{choose(${JSON.stringify(JSON.stringify({ key: "action_second", properties: [] }))})}`;
const result = analyze({ inputs: { value: `prefix ${single} / ${double} suffix` } });
expect(result.diagnostics.filter(item => item.code === "BROKEN_CHOOSE_REFERENCE")).toHaveLength(2);
});
test("recognizes real custom node names while preserving body and other context roots", () => {
for (const tag of ["@{choose(source.data)}", "@{choose('source.data')}", descriptor("source"), "@{choose('body.invoices')}", "@{choose(input.value)}"]) {
const result = analyze({ inputs: { value: tag } }, [{ name: "source", type: "webhook" }]);
expect(result.summary.passed).toBe(true);
expect(result.diagnostics).toEqual([]);
}
});
test("requires explicit descriptor node keys even when they resemble context roots", () => {
for (const key of ["body", "context"]) {
expect(analyze({ form: { title: descriptor(key) } }).summary.passed).toBe(false);
expect(analyze({ form: { title: descriptor(key) } }, [{ name: key, type: "webhook" }]).summary.passed).toBe(true);
}
});
test("warns for unknown bare roots and unsupported or malformed expressions without blocking", () => {
for (const tag of ["@{choose(missing_node.data)}", "@{choose('missing_node.data')}", "@{choose(action_x.data + 1)}", "@{choose('action_missing.data')", "@{choose('{bad json}')}"]) {
const result = analyze({ form: { title: tag } });
expect(result.summary.passed).toBe(true);
expect(result.diagnostics.map(item => item.code)).toContain("UNRESOLVED_CHOOSE_REFERENCE");
expect(result.diagnostics.every(item => item.category === "soft_advice")).toBe(true);
}
});
test.each(["@{choose(control_loop.$item)}", "@{choose('control_loop.$item.data')}", descriptor("control_loop.$item")])("blocks old loop item paths in %s", tag => {
const result = analyze({ fields: [{ key: "value", value: tag }] });
expect(result.summary.passed).toBe(false);
expect(result.diagnostics.map(item => item.code)).toContain("BROKEN_LOOP_ITEM_REFERENCE");
});
test("accepts the new loop descriptor with $item in properties", () => {
const tag = `@{choose('${JSON.stringify({ key: "control_loop", properties: [{ key: "$item" }, { key: "data" }] })}')}`;
const result = analyze({ fields: [{ key: "value", value: tag }] }, [{ name: "control_loop", type: "every", tasks: [{ name: "inner", type: "http" }] }]);
expect(result.summary.passed).toBe(true);
expect(result.diagnostics).toEqual([]);
});
test("never aliases missing trigger_1 to an actual trigger with another name", () => {
for (const tag of [descriptor("trigger_1"), "@{choose(trigger_1.data)}"]) {
expect(analyze({ inputs: { value: tag } }).summary.passed).toBe(false);
const real = analyze({ inputs: { value: tag } }, [{ name: "trigger_1", type: "webhook" }]);
expect(real.summary.passed).toBe(true);
}
});
test("finds actual nodes in nested task containers", () => {
const result = analyze({ fields: [{ key: "value", value: descriptor("action_nested") }] }, [
{ name: "condition", type: "condition", tasks: [{ name: "action_nested", type: "http" }] },
]);
expect(result.summary.passed).toBe(true);
expect(result.diagnostics).toEqual([]);
});
});
@@ -230,7 +230,7 @@ describe("MVEL lexical boundaries", () => {
it("does not count quoted or commented return as executable code", () => {
const result = lintMvelCode('value = "return"; /* return 1; */ // return 2;');
expect(result.hasReturn).toBe(false);
expect(result.issues.map(i => i.rule)).toEqual(["missing-return"]);
expect(result.issues).toEqual([]); // 赋值本身可作为末尾表达式,仍不算显式 return。
});
it("keeps real references and error coordinates while diagnosing unfinished literals", () => {
@@ -1,5 +1,6 @@
import type { WorkflowTask } from "../../types.js";
import type { ScriptIssue } from "./types.js";
import { hasMvelFinalExpression } from "./mvel-subset.js";
/** Mask literals/comments without moving offsets used by diagnostics. */
function scanMvelCode(code: string, issues: ScriptIssue[]): string {
@@ -84,10 +85,10 @@ export function lintMvelCode(
const executableCode = scanMvelCode(code, issues);
const hasRet = /\breturn\b/.test(executableCode);
if (!hasRet) {
if (!hasRet && !hasMvelFinalExpression(code)) {
issues.push({
level: "warning",
message: "MVEL 代码中未发现 return 语句,合思代码节点通常需要 return 包装后的 Map 或结果对象",
message: "MVEL 代码中未发现显式 return 或可确定的末尾结果表达式;请确认所需结果位于脚本末尾",
rule: "missing-return",
});
}
@@ -0,0 +1,103 @@
import { describe, expect, test } from "bun:test";
import { executeJavaScriptSandbox, executeMvelSandbox } from "./sandbox.js";
import { lintMvelCode } from "./lint-mvel.js";
describe("MVEL collection and completion subset", () => {
test.each(["HashMap", "Map", "java.util.HashMap"])("returns the final Map expression constructed with %s", async kind => {
const result = await executeMvelSandbox(`Map result = new ${kind}(); result.put("value", 7); result;`);
expect(result.success).toBe(true);
expect(result.returnValue).toEqual({ value: 7 });
});
test.each(["ArrayList", "List", "java.util.ArrayList"])("supports List constructor %s", async kind => {
const result = await executeMvelSandbox(`List result = new ${kind}(); result.add(7); result;`);
expect(result.success).toBe(true);
expect(result.returnValue).toEqual([7]);
const direct = await executeMvelSandbox(`new ${kind}().size();`);
expect(direct.success).toBe(true);
expect(direct.returnValue).toBe(0);
});
test("counts Map keys including length and prototype names, without double counting replacements", async () => {
const result = await executeMvelSandbox(`Map m = new HashMap(); List sizes = new ArrayList();
sizes.add(m.size()); m.put("length", 99); sizes.add(m.size());
m.put("length", 100); sizes.add(m.size()); m.put("__proto__", 8); sizes.add(m.size());
sizes.add(m.get("absent")); sizes;`);
expect(result.success).toBe(true);
expect(result.returnValue).toEqual([0, 1, 1, 2, null]);
});
test("supports nested receivers, nested arguments, indexed inputs and collection return values", async () => {
const nested = await executeMvelSandbox(`Map m = new HashMap(); List a = new ArrayList();
a.add(Math.max(2, 3)); m.put("items", a); m.get("items").add(m.get("items").size());
data.get("rows")[0].put("x", 2); a.add((data.get("rows")[0]).size()); m.get("items");`, { data: { rows: [{}] } });
expect(nested.success).toBe(true);
expect(nested.returnValue).toEqual([3, 1, 1]);
});
test("preserves literal contents while ignoring comments during conversion", async () => {
const literal = 'String x = new java.util.HashMap(); .put("x", 1).size() / 2 ? a : b;';
const result = await executeMvelSandbox(`/* new Unsafe(); return 8; */ // new ArrayList(2)
${JSON.stringify(literal)}; // final comment`);
expect(result.success).toBe(true);
expect(result.returnValue).toBe(literal);
});
test.each(["result", "(result);", "result;;; // final comment", "result /* ; return 0; */"])("supports tail expression %s", async tail => {
const result = await executeMvelSandbox(`var result = 7; ${tail}`);
expect(result.success).toBe(true);
expect(result.returnValue).toBe(7);
});
test("evaluates a terminal expression once and preserves put's previous-value return", async () => {
const increment = await executeMvelSandbox("var count = 0; ++count;");
expect(increment.success).toBe(true);
expect(increment.returnValue).toBe(1);
const put = await executeMvelSandbox('Map m = new HashMap(); m.put("x", 1); m.put("x", 2);');
expect(put.success).toBe(true);
expect(put.returnValue).toBe(1);
});
test("preserves division, ternary, classic for and explicit return compatibility", async () => {
const result = await executeMvelSandbox("int total = 0; for (int i = 0; i < 3; i++) { total += i; } if (total == 3) { total += 2; } else { total = 0; } return total > 0 ? total / 2 : 0;");
expect(result.success).toBe(true);
expect(result.returnValue).toBe(2.5);
const assignment = await executeMvelSandbox("var x = 0; x = 9;");
expect(assignment.returnValue).toBe(9);
});
test("does not reject existing JavaScript-compatible blocks before a terminal result", async () => {
const result = await executeMvelSandbox('function value() { return 8; } var result = 0; try { throw "probe"; } catch (error) { result = value(); } finally { result += 1; } result;');
expect(result.success).toBe(true);
expect(result.returnValue).toBe(9);
});
test.each(["new java.util.Date();", "new HashMap(5);", "new java.util.ArrayList(2);", "Map<String, Object> m = new HashMap(); m;", "if (true) { 7; }", "var value = 7;", "for (item : items) { item; } item;"])("rejects unsupported syntax or completion: %s", async code => {
const result = await executeMvelSandbox(code);
expect(result.success).toBe(false);
expect(result.error?.name).toBe("UnsupportedMvelSyntax");
});
test("fails explicitly for invalid receiver types and List bounds", async () => {
for (const code of ['value.size();', 'value.get(1);']) {
const result = await executeMvelSandbox(code, { value: code.includes("get") ? [] : 7 });
expect(result.success).toBe(false);
}
});
test("keeps the execution time budget and JavaScript completion behavior", async () => {
const result = await executeMvelSandbox("while (true) {} 7;", {}, { timeoutMs: 10 });
expect(result.success).toBe(false);
expect(result.error?.message).toContain("timed out");
const js = await executeJavaScriptSandbox("7;");
expect(js.success).toBe(true);
expect(js.returnValue).toBeUndefined();
});
test("lint accepts a final expression without changing explicit hasReturn meaning", () => {
const result = lintMvelCode('Map result = new java.util.HashMap(); result.put("x", 7); result;');
expect(result.hasReturn).toBe(false);
expect(result.issues).toEqual([]);
expect(lintMvelCode("var x = 1;").issues.map(issue => issue.rule)).toContain("missing-return");
});
});
@@ -0,0 +1,203 @@
import { ValidationError } from "../../../../core/errors.js";
function unsupported(message: string): never {
throw new ValidationError(`本地 MVEL 子集不支持 ${message};请使用真实 MVEL 运行时验证`);
}
/** 字符串作为完整 token 保留;注释不参与语法转换。 */
function tokenize(source: string): string[] {
const tokens: string[] = [];
const pattern = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_$][\w$]*|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|>>>=|===|!==|>>>|<<=|>>=|\*\*=|==|!=|<=|>=|&&|\|\||\+\+|--|\+=|-=|\*=|\/=|%=|<<|>>|\*\*|[{}()[\].,;:+*/%=&|^~!<>?-]/y;
let offset = 0;
while (offset < source.length) {
pattern.lastIndex = offset;
const match = pattern.exec(source);
if (!match) unsupported(`字符 ${JSON.stringify(source[offset])}(偏移 ${offset})`);
const token = match[0];
offset = pattern.lastIndex;
if (!/^\s|^\/\//.test(token) && !token.startsWith("/*")) tokens.push(token);
}
return tokens;
}
function closing(tokens: string[], start: number): number {
const stack: string[] = [];
const pairs: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
for (let i = start; i < tokens.length; i++) {
const token = tokens[i];
if (pairs[token]) stack.push(pairs[token]);
else if ([")", "]", "}"].includes(token)) {
if (stack.pop() !== token) unsupported("不匹配的括号");
if (!stack.length) return i;
}
}
return unsupported("未闭合的括号");
}
type Statement = { start: number; end: number; kind: "expression" | "return" | "declaration" | "compound" | "empty" };
/** 只识别语句边界,不模拟复合语句在 MVEL 中的完成值。 */
function statementAt(tokens: string[], start: number): Statement {
const token = tokens[start];
const finish = (end: number, kind: Statement["kind"]): Statement => ({ start, end, kind });
if (token === ";") return finish(start + 1, "empty");
if (token === "{") return finish(closing(tokens, start) + 1, "compound");
if (["if", "for", "while", "switch"].includes(token)) {
if (tokens[start + 1] !== "(") unsupported(`${token} 语句`);
const conditionEnd = closing(tokens, start + 1);
if (token === "for") {
// 三元表达式仍可使用冒号;没有分号的增强 for 不属于本地子集。
const header = tokens.slice(start + 2, conditionEnd);
if (!header.includes(";") && header.includes(":")) unsupported("增强 for 循环");
}
if (conditionEnd + 1 >= tokens.length) unsupported(`${token} 缺少语句体`);
let end = statementAt(tokens, conditionEnd + 1).end;
if (token === "if" && tokens[end] === "else") end = statementAt(tokens, end + 1).end;
return finish(end, "compound");
}
if (token === "do") {
const bodyEnd = statementAt(tokens, start + 1).end;
if (tokens[bodyEnd] !== "while" || tokens[bodyEnd + 1] !== "(") unsupported("do/while 语句");
const end = closing(tokens, bodyEnd + 1) + 1;
return finish(tokens[end] === ";" ? end + 1 : end, "compound");
}
if (token === "try") {
let end = statementAt(tokens, start + 1).end;
if (tokens[end] === "catch") {
end++;
if (tokens[end] === "(") end = closing(tokens, end) + 1;
end = statementAt(tokens, end).end;
}
if (tokens[end] === "finally") end = statementAt(tokens, end + 1).end;
return finish(end, "compound");
}
if (token === "function" || token === "class") {
let body = start + 1;
while (body < tokens.length && tokens[body] !== "{") {
if (tokens[body] === "(") body = closing(tokens, body);
body++;
}
if (body >= tokens.length) unsupported(`${token} 缺少语句体`);
return finish(closing(tokens, body) + 1, "declaration");
}
if (["catch", "finally", "import", "package"].includes(token)) unsupported(`${token} 语句`);
let end = start;
while (end < tokens.length && tokens[end] !== ";") {
if (["(", "[", "{"].includes(tokens[end])) end = closing(tokens, end);
else if ([")", "]", "}"].includes(tokens[end])) unsupported("不匹配的括号");
end++;
}
if (tokens[end] === ";") end++;
const kind = token === "return" || token === "throw" ? "return" : ["var", "let", "const"].includes(token) ? "declaration" : "expression";
return finish(end, kind);
}
function finalStatement(tokens: string[]): Statement | undefined {
let last: Statement | undefined;
for (let i = 0; i < tokens.length;) {
const statement = statementAt(tokens, i);
if (statement.kind !== "empty") last = statement;
i = statement.end;
}
return last;
}
const declarations = new Set(["String", "int", "Integer", "long", "Long", "double", "Double", "float", "Float", "boolean", "Boolean", "List", "Map", "HashMap", "ArrayList", "Object"]);
/** lint 保留 hasReturn 的显式 return 含义,同时识别可确定的末尾表达式。 */
export function hasMvelFinalExpression(source: string): boolean {
try {
const tokens = tokenize(source);
const tail = finalStatement(tokens);
return tail?.kind === "expression" && !declarations.has(tokens[tail.start]);
} catch {
// 原生 MVEL 可能超出本地子集,静态 lint 不因此宣告其语法非法。
return false;
}
}
function receiverStart(tokens: string[], end: number): number {
let start = end;
if (tokens[end] === ")" || tokens[end] === "]") {
const opening = tokens[end] === ")" ? "(" : "[";
let depth = 1;
while (--start >= 0) {
if (tokens[start] === tokens[end]) depth++;
if (tokens[start] === opening && --depth === 0) break;
}
if (start < 0) unsupported("缺少方法接收对象");
const previous = tokens[start - 1];
const previousIsName = /^[A-Za-z_$][\w$]*$/.test(previous ?? "") && !["return", "throw", "if", "while", "for", "switch"].includes(previous);
// 数组字面量不是索引表达式;不能把前面的 return/赋值运算符当作接收对象。
if (previousIsName || (opening === "[" && [")", "]"].includes(previous))) start = receiverStart(tokens, start - 1);
}
if (tokens[start - 1] === ".") start = receiverStart(tokens, start - 2);
if (start < 0) unsupported("缺少方法接收对象");
return start;
}
const arities: Record<string, number> = { put: 2, get: 1, size: 0, add: 1 };
function rewriteMethods(input: string[]): string[] {
const tokens = [...input];
for (let i = 1; i < tokens.length - 2; i++) {
const method = tokens[i + 1];
if (tokens[i] !== "." || tokens[i + 2] !== "(" || !Object.hasOwn(arities, method)) continue;
const end = closing(tokens, i + 2);
const args: string[][] = [];
let from = i + 3;
for (let j = from; j < end; j++) {
if (["(", "[", "{"].includes(tokens[j])) j = closing(tokens, j);
else if (tokens[j] === ",") { args.push(tokens.slice(from, j)); from = j + 1; }
}
if (from < end) args.push(tokens.slice(from, end));
if (args.length !== arities[method] || args.some(arg => !arg.length)) unsupported(`${method} 的该参数数量`);
const start = receiverStart(tokens, i - 1);
const replacement = [`__hose_mvel_${method}`, "(", ...tokens.slice(start, i)];
for (const arg of args) replacement.push(",", ...rewriteMethods(arg));
replacement.push(")");
tokens.splice(start, end - start + 1, ...replacement);
i = start + replacement.length - 1;
}
return tokens;
}
/** 必要的 MVEL 集合与末尾表达式子集;运算仍由隔离 QuickJS 执行。 */
export function transpileMvelSubset(source: string): string {
const tokens = tokenize(source);
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
if (/^__hose_mvel_/.test(token)) unsupported("保留的内部标识符");
if (declarations.has(token) && tokens[i + 1] === "<") unsupported("泛型声明");
// 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l =
if (declarations.has(token) && /^[A-Za-z_$][\w$]*$/.test(tokens[i + 1] ?? "") && ["=", ";"].includes(tokens[i + 2])) tokens[i] = "var";
// 2. 转换 new HashMap() / new ArrayList(),仅精确扩展两个全限定名零参构造器。
if (token === "new") {
let end = i + 1;
while (/^[A-Za-z_$][\w$]*$/.test(tokens[end] ?? "") && tokens[end + 1] === ".") end += 2;
const kind = tokens.slice(i + 1, end + 1).join("");
const map = ["HashMap", "Map", "java.util.HashMap"].includes(kind);
if ((!map && !["ArrayList", "List", "java.util.ArrayList"].includes(kind)) || tokens[end + 1] !== "(" || tokens[end + 2] !== ")") unsupported("该构造器、泛型或构造参数");
tokens.splice(i, end + 3 - i, ...(map ? ["__hose_mvel_map", "(", ")"] : ["[", "]"]));
}
}
// 3. 常见 Map/List 方法调用模拟:
// .put(k, v) -> [k] = v (包装为安全赋值辅助)
// 注入轻量 helper;按 token 边界处理,避免直接正则冲突,并保留方法返回值。
const rewritten = rewriteMethods(tokens);
const tail = finalStatement(rewritten);
if (!tail || !["return", "expression"].includes(tail.kind)) unsupported("末项复合语句或声明的完成值;请添加明确的末尾结果表达式");
if (tail.kind === "expression") {
const end = rewritten[tail.end - 1] === ";" ? tail.end - 1 : tail.end;
rewritten.splice(tail.start, tail.end - tail.start, "return", "(", ...rewritten.slice(tail.start, end), ")", ";");
}
// 恢复并使用 helper,Map 使用自身属性,避免原型键影响集合语义。
const preamble = `
function __hose_mvel_map() { return Object.create(null); }
function __hose_mvel_put(obj, key, val) { if (!obj || Array.isArray(obj) || typeof obj !== 'object') throw new TypeError('put requires Map'); if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); const old = Object.hasOwn(obj, key) ? obj[key] : null; Object.defineProperty(obj, key, {value:val, writable:true, enumerable:true, configurable:true}); return old; }
function __hose_mvel_get(obj, key) { if (!obj || typeof obj !== 'object') throw new TypeError('get requires Map/List'); if (Array.isArray(obj)) { if (!Number.isInteger(key) || key < 0 || key >= obj.length) throw new RangeError('List index out of bounds'); } else if (typeof key !== 'string') throw new TypeError('MVEL subset supports string Map keys only'); return Object.hasOwn(obj, key) ? obj[key] : null; }
function __hose_mvel_size(obj) { if (!obj || typeof obj !== 'object') throw new TypeError('size requires Map/List'); return Array.isArray(obj) ? obj.length : Object.keys(obj).length; }
function __hose_mvel_add(arr, item) { if (!Array.isArray(arr)) throw new TypeError('add requires List'); arr.push(item); return true; }
`;
return preamble + rewritten.join(" ");
}
+10 -35
View File
@@ -1,6 +1,7 @@
import variant from "@jitl/quickjs-singlefile-cjs-release-sync";
import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core";
import type { ScriptEvalResult, ScriptEvalLog } from "./types.js";
import { transpileMvelSubset } from "./mvel-subset.js";
const MAX_MEMORY_BYTES = 32 * 1024 * 1024;
const MAX_VALUE_BYTES = 1024 * 1024;
@@ -127,38 +128,7 @@ export async function executeJavaScriptSandbox(
* 转换 MVEL 常用语法为 QuickJS 可执行的 JavaScript,实现轻量仿真
*/
export function transpileMvelToJs(mvelCode: string): string {
let js = mvelCode;
// 1. 移除 Java 类型声明:如 String x =, int y =, List z =, Map m =, boolean b =, double d =, long l =
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2");
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2");
// 2. 转换 new HashMap() / new ArrayList()
js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})");
js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])");
// 3. 常见 Map/List 方法调用模拟:
// .put(k, v) -> [k] = v (包装为安全赋值辅助)
// 注入轻量 helper
const preamble = [
"function _mvel_put(obj, key, val) { if (obj && typeof obj === 'object') { obj[key] = val; } return val; }",
"function _mvel_get(obj, key) { return obj ? obj[key] : undefined; }",
"function _mvel_size(obj) { if (!obj) return 0; if (Array.isArray(obj)) return obj.length; if (typeof obj === 'object') return Object.keys(obj).length; return 0; }",
"function _mvel_add(arr, item) { if (Array.isArray(arr)) arr.push(item); return arr; }",
"",
].join("\n");
js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, ""); // 避免直接正则冲突,使用下面逐行或更精确替换
// 恢复并使用 helper
js = mvelCode;
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*=)/g, "var $2");
js = js.replace(/\b(String|int|Integer|long|Long|double|Double|float|Float|boolean|Boolean|List|Map|HashMap|ArrayList|Object)\s+([a-zA-Z_$][a-zA-Z0-9_$]*\s*;)/g, "var $2");
js = js.replace(/new\s+(?:HashMap|Map)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "({})");
js = js.replace(/new\s+(?:ArrayList|List)\s*(?:\([^)]*\)|<[^>]*>\s*\([^)]*\))/g, "([])");
js = js.replace(/\.put\s*\(\s*([^,]+)\s*,\s*([^)]+)\s*\)/g, "[$1] = $2");
js = js.replace(/\.size\s*\(\s*\)/g, ".length");
return `${preamble}${js}`;
return transpileMvelSubset(mvelCode);
}
/**
@@ -169,7 +139,12 @@ export async function executeMvelSandbox(
inputs: Record<string, unknown> = {},
options: { timeoutMs?: number } = {}
): Promise<ScriptEvalResult> {
const transpiled = transpileMvelToJs(code);
const result = await executeJavaScriptSandbox(transpiled, inputs, options);
return result;
const start = performance.now();
try {
const transpiled = transpileMvelToJs(code);
return await executeJavaScriptSandbox(transpiled, inputs, options);
} catch (error) {
return { success: false, durationMs: Number((performance.now() - start).toFixed(2)), returnValue: undefined, logs: [],
error: { name: "UnsupportedMvelSyntax", message: (error as Error).message }, inputs };
}
}
@@ -1,4 +1,5 @@
import type { KyInstance } from "ky";
import { AuthenticationError } from "../../../../core/errors.js";
import * as api from "../../api.js";
import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js";
import { normalizeJobStatus, isJobTerminal } from "./helpers.js";
@@ -76,7 +77,8 @@ export async function watchWorkflowPipeline(
try {
const running = await api.listRunningJobs(client, pipelineId, "DEBUG");
if (running.length > 0) targetJobId = running[0].id;
} catch {
} catch (error) {
if (error instanceof AuthenticationError) throw error;
// 忽略
}
@@ -149,7 +151,8 @@ export async function watchWorkflowPipeline(
if (found) {
candidateJob = { id: found.id, status: found.status || "RUNNING", runType: "DEBUG" };
}
} catch {
} catch (error) {
if (error instanceof AuthenticationError) throw error;
// 忽略
}