@stalfh233/omc-cli 0.8.2 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/read.js CHANGED
@@ -2,6 +2,72 @@ import { assertWithinCoverage } from "./coverage.js";
2
2
  import { wireErrorKind, isUncertainWireError, jsonBytes, refusalFromCoverage, sha256, summarizeValue, writeArtifact } from "./support.js";
3
3
  import { plannableArgsRaw } from "./plan.js";
4
4
  import { WireError } from "./wire.js";
5
+ import { describeWireFailure, isRetryableTransportKind } from "./wire-failure.js";
6
+ /**
7
+ * B3(0.8.4,2026-11-25 真机):幂等读的有界重试。
8
+ *
9
+ * 真机 `app.list` 连续 8 次同错(含 `--out`)却只回 `fetch failed`——其中至少
10
+ * 一部分是网关/连接层的瞬时抖动(B1 的同类:同一载荷下一次即 200)。读面没有
11
+ * 副作用,重试成本远低于让 agent 自己再发一轮;写面**绝不**重试(结果未知)。
12
+ *
13
+ * 只重试网络类(network/dns/tls)与「网关 HTML 404」(B1 已改写为 transport):
14
+ * 401/403/业务码/超时都是确定性结论,重试只会拖长一轮。
15
+ * 退避 200ms → 400ms(≤1s),最多 2 次(总 3 次尝试)。
16
+ */
17
+ const READ_RETRY_MAX = 2;
18
+ const READ_RETRY_BACKOFF_MS = [200, 400];
19
+ function sleep(ms) {
20
+ return new Promise((resolve) => setTimeout(resolve, ms));
21
+ }
22
+ function isRetryableReadFailure(error) {
23
+ if (!isUncertainWireError(error))
24
+ return false;
25
+ if (error instanceof WireError && error.kind !== "transport")
26
+ return false;
27
+ const facts = describeWireFailure(error);
28
+ if (isRetryableTransportKind(facts.failureKind))
29
+ return true;
30
+ // B1:网关 HTML 404 被改写成 transport,诊断面是 http/404;它确实值得再试一次。
31
+ return error instanceof Error && /网关返回了 HTML 404/.test(error.message);
32
+ }
33
+ /** Copyable fallback for a read whose transport face is unusable (B3: app.list). */
34
+ function readFallback(toolName, environment) {
35
+ if (toolName !== "app.list")
36
+ return undefined;
37
+ const env = environment !== undefined && environment !== "" ? environment : "<env>";
38
+ return {
39
+ tool: "model.list",
40
+ command: `omc call model.list --env ${env} --args '{"allApplications":true}' --jq models[].applicationCode`,
41
+ filteredCommand: `omc call model.list --env ${env} --args '{"allApplications":true,"filter":"<kw>"}'`,
42
+ why: "app.list = apppackage/list + 每个应用的 trees(并发 13 次);model.list --allApplications 走同一个 list 端点,但 trees 并发限 4 且单应用失败不拖垮整体——同一事实的可执行回退。",
43
+ };
44
+ }
45
+ /**
46
+ * B3:把传输失败归类成 agent 能据此决策的形状。
47
+ * `lastFailureKind` 的五个主类:network / dns / tls / http / auth(另有
48
+ * timeout / business / unknown 作为细分)。app.list 的两跳在后端都没有管理员
49
+ * 注解,所以 auth 只可能来自会话/网关,不是工具权限面——这条以 evidence 说明。
50
+ */
51
+ function transportDiagnostics(toolName, error, environment, retried, facts = describeWireFailure(error)) {
52
+ const fallback = readFallback(toolName, environment);
53
+ const auth = facts.failureKind === "auth";
54
+ const appListEvidence = toolName === "app.list"
55
+ ? "app.list 两跳均无管理员注解:AppPackageController.list(launcher-2.1.5 …AppPackageController.java:780-786 / launcher-8.6.26 …:725-731)与 /trees(2.1.5:802-845 / 8.6.26:761-804);401/403 来自会话/网关鉴权,不是该工具的权限面"
56
+ : undefined;
57
+ return {
58
+ ...(facts.endpoint !== undefined ? { endpoint: facts.endpoint } : {}),
59
+ lastFailureKind: facts.failureKind,
60
+ ...(facts.causeCode !== undefined ? { lastFailureCause: facts.causeCode } : {}),
61
+ ...(facts.httpStatus !== undefined ? { lastFailureHttpStatus: facts.httpStatus } : {}),
62
+ ...(facts.errcode !== undefined ? { lastFailureErrcode: facts.errcode } : {}),
63
+ ...(retried > 0 ? { retried, retryNote: `已按网络类失败重试 ${retried} 次(200/400ms 退避)仍失败——不是单次抖动` } : {}),
64
+ ...(auth
65
+ ? { diagnosis: `该端点在此会话权限面不可用(HTTP ${facts.httpStatus ?? 401}/业务鉴权码);不要重试同一载荷,改权限或走 fallback。` }
66
+ : {}),
67
+ ...(appListEvidence !== undefined ? { evidence: appListEvidence } : {}),
68
+ ...(fallback !== undefined ? { fallback } : {}),
69
+ };
70
+ }
5
71
  /**
6
72
  * `full:true` used to bypass every diet gate and inline the raw platform body.
7
73
  * For `workflow.get_draft` that is a 30–75 KB native blob (btnConfigList,
@@ -46,11 +112,30 @@ export async function governedRead(ctx, tool, args, execute, options = {}) {
46
112
  }
47
113
  // issue 2026-11 F5:catch 里也要说清「打的是哪台」,所以把 session 提到 try 外。
48
114
  let sessionRef;
115
+ // B3:attempts 必须活到 catch 里(重试耗尽的回执要带 attempts/retried)。
116
+ let attempts = 0;
49
117
  try {
50
118
  const session = await ctx.sessions.session(args.environment);
51
119
  sessionRef = session;
52
120
  const environmentFingerprint = safeFingerprint(session);
53
- const result = await execute(session);
121
+ let raw;
122
+ for (;;) {
123
+ attempts += 1;
124
+ try {
125
+ raw = await execute(session);
126
+ break;
127
+ }
128
+ catch (error) {
129
+ if (attempts <= READ_RETRY_MAX && isRetryableReadFailure(error)) {
130
+ await sleep(READ_RETRY_BACKOFF_MS[attempts - 1] ?? 400);
131
+ continue;
132
+ }
133
+ throw error;
134
+ }
135
+ }
136
+ const retried = attempts - 1;
137
+ // 只在真的重试过时加键:零重试的回执形状与黄金样本保持不变。
138
+ const result = retried > 0 ? { ...raw, retried, attempts } : raw;
54
139
  if (result.status === "refused" || result.status === "uncertain")
55
140
  return { ...result, environmentFingerprint };
56
141
  const target = options.target ?? `${tool.name}:${JSON.stringify(plannableArgsRaw(args))}`;
@@ -113,18 +198,26 @@ export async function governedRead(ctx, tool, args, execute, options = {}) {
113
198
  return { status: "ok", ...passthroughScalars(result, omittedScalarKeys(compact)), ...compact, ...placeholders, environmentFingerprint, detailFile: artifactRef.detailFile, detailSha256: artifactRef.detailSha256 };
114
199
  }
115
200
  catch (error) {
116
- if (isUncertainWireError(error))
201
+ if (isUncertainWireError(error)) {
202
+ const facts = describeWireFailure(error);
117
203
  return {
118
204
  status: "uncertain",
119
205
  frozen: true,
120
- reason: `wire-transport:${wireErrorKind(error)}`,
206
+ // B3:reason 也别再笼统落成 auth-transport——用真实分类(network/dns/tls/
207
+ // timeout/http/auth);分类不出来才退回旧的 wireErrorKind。
208
+ reason: `wire-transport:${facts.failureKind === "unknown" ? wireErrorKind(error) : facts.failureKind}`,
121
209
  detail: error.message,
210
+ // B3(2026-11-25 真机):只写 "fetch failed" 无法区分网络/权限/平台缺口。
211
+ // 端点、尝试次数、失败分类、可执行回退都在这里(判定不变)。
212
+ attempts: Math.max(1, attempts),
213
+ ...transportDiagnostics(tool.name, error, sessionRef?.environmentName ?? args.environment, Math.max(0, attempts - 1), facts),
122
214
  // issue 2026-11 F5:传输失败时把「到底打的是哪台」一起回出来——真机会话里
123
215
  // env list 是 cwd 作用域,agent 静默落到全局 default 的另一台主机,只看
124
216
  // detail 无从判断。configRoot/项目根用 `omc env list` 复核。
125
217
  ...(sessionRef !== undefined ? { environment: sessionRef.environmentName, baseUrl: sessionRef.profile.baseUrl } : {}),
126
218
  environmentHint: "env 清单随 cwd 变(项目根 .omc-env/.omc-envs + 配置根);`omc env list` 首行回显 configRoot/projectRoot",
127
219
  };
220
+ }
128
221
  if (error instanceof WireError)
129
222
  return { status: "refused", blocker: `wire-${error.kind}`, errcode: error.errcode, message: error.message, ...(error.diagnostic ? { diagnostic: error.diagnostic } : {}), ...(error.hint ? { hint: error.hint } : {}) };
130
223
  throw error;
@@ -344,6 +437,42 @@ function codeOfEntry(entry) {
344
437
  * exists, published, id, code, schemaCode, note, …).
345
438
  */
346
439
  const BULKY_READ_KEYS = new Set(["data", "nodes", "routes", "items", "rules", "applications", "foldersAndModels", "models"]);
440
+ const CONTAINER_NAME_KEYS = [
441
+ "items",
442
+ "models",
443
+ "rules",
444
+ "logs",
445
+ "triggers",
446
+ "fields",
447
+ "records",
448
+ ...[...BULKY_READ_KEYS, ...CODE_LIST_KEYS, ...CODE_NAME_LIST_KEYS, ...ACTIVITY_LIST_KEYS],
449
+ ];
450
+ /**
451
+ * 回执派生/诊断用数组不是「结果容器」:`failed[]`(部分失败清单)、`truncatedKeys`
452
+ * (被折叠的键名)这类在部分失败时可能比数据本身还长,按长度挑会挑错。
453
+ */
454
+ const NON_CONTAINER_KEYS = new Set(["failed", "failures", "truncatedKeys", "omittedKeys", "changedKeys", "unknownKeys"]);
455
+ export function containerKeyOf(result) {
456
+ if (result === null || typeof result !== "object" || Array.isArray(result))
457
+ return undefined;
458
+ const record = result;
459
+ const arrays = Object.entries(record).filter(([key, value]) => Array.isArray(value) && !NON_CONTAINER_KEYS.has(key));
460
+ const objectArrays = arrays.filter(([, value]) => value.length > 0 && value[0] !== null && typeof value[0] === "object" && !Array.isArray(value[0]));
461
+ if (objectArrays.length > 0) {
462
+ const [key] = objectArrays.reduce((best, entry) => (entry[1].length > best[1].length ? entry : best));
463
+ return { key };
464
+ }
465
+ for (const name of CONTAINER_NAME_KEYS) {
466
+ if (arrays.some(([key]) => key === name))
467
+ return { key: name };
468
+ }
469
+ // 分页壳:`{records:{totalElements,content:[…]}}` —— 容器在下一层,键名仍要给出。
470
+ for (const [key, value] of Object.entries(record)) {
471
+ if (value !== null && typeof value === "object" && !Array.isArray(value) && Array.isArray(value.content))
472
+ return { key, path: `${key}.content` };
473
+ }
474
+ return undefined;
475
+ }
347
476
  /**
348
477
  * Carry the handler's small top-level facets through a compact projection.
349
478
  *
@@ -106,6 +106,20 @@ const SHAPE_GATES = Object.freeze({
106
106
  { name: "目标模型 schemaCode", source: "omc call model.list --args '{}'" },
107
107
  ],
108
108
  },
109
+ // A4(2026-11-25):形状门只证明「OMC 的离线判据不接受」,不是平台能力判决。
110
+ // 两类最高频的「形状不支持」拒绝都补同一句逃生路径:先读回平台原文再判断,
111
+ // 不许绕 CLI 直连私有接口(平台 REST 面只认 Authorization bearer;
112
+ // BaseController.getToken 2.1.5:1086-1088 / AuthUtils 2.1.5:80-95,
113
+ // 手工直连会跳过 OMC 的 writable/生产确认/写租约/审计:
114
+ // governed-execution.ts:111-120、:186-194,write-lease.ts:7、write-audit.ts:44)。
115
+ "field-options-shape": {
116
+ whatWentWrong: "字段 options 没过 CLI 的离线形状判据(如关系映射 source/target 写成 模型.字段)",
117
+ doNot: "若确属平台支持但 OMC 判不了,用 readFirst 的命令盘点一下(把平台原文读回来再决定改哪一处);不要绕平台私有接口手工粘 token——平台 REST 面只认 Authorization bearer,手工直连会跳过 OMC 的 writable/生产确认/写租约/审计",
118
+ },
119
+ "form-layout-invalid": {
120
+ whatWentWrong: "表单布局没过写前形状门(validation[].classification 点名,如 child_column_in_rows:子表列写进了 viewJson)",
121
+ doNot: "若确属平台支持但 OMC 判不了,用 readFirst 的命令盘点一下(把平台原文读回来再决定改哪一处);不要绕平台私有接口手工粘 token——平台 REST 面只认 Authorization bearer,手工直连会跳过 OMC 的 writable/生产确认/写租约/审计",
122
+ },
109
123
  });
110
124
  /**
111
125
  * Platform/permission/environment families: honest "fix this first" with NO
package/dist/session.js CHANGED
@@ -39,6 +39,9 @@ export class CloudPivotSession {
39
39
  */
40
40
  loginNotesValue = [];
41
41
  httpAdapter;
42
+ /** 只对我们自己创建的 adapter 生效(测试注入的 adapter 没有可控 signal)。 */
43
+ adapterOwned = false;
44
+ abortController;
42
45
  fingerprintOf;
43
46
  constructor(environmentName, profile, credential, http, systemConfig = undefined, requestTimeoutMs = defaultRequestTimeoutMs(), tokenCache) {
44
47
  this.environmentName = environmentName;
@@ -53,11 +56,34 @@ export class CloudPivotSession {
53
56
  if (this.httpAdapter)
54
57
  return this.httpAdapter;
55
58
  const core = await omcCore();
56
- this.httpAdapter = core.fetchCloudPivotHttp(this.profile.baseUrl, undefined, fetch, core.cloudPivotTenantHeaders(this.profile.engineCode));
59
+ this.abortController = new AbortController();
60
+ this.httpAdapter = core.fetchCloudPivotHttp(this.profile.baseUrl, this.abortController.signal, fetch, core.cloudPivotTenantHeaders(this.profile.engineCode));
61
+ this.adapterOwned = true;
57
62
  if (!this.fingerprintOf)
58
63
  this.fingerprintOf = core.canonicalCloudPivotEnvironmentFingerprint;
59
64
  return this.httpAdapter;
60
65
  }
66
+ /**
67
+ * B4(0.8.4):中止**当前在途**的全部请求(graph pull 的总超时用)。
68
+ *
69
+ * 没有这一步,`--timeout-ms` 只能靠对 `Promise.race` 计时——pull 的协程被
70
+ * 丢掉,但 undici 的 socket 仍挂在事件循环上,进程继续「活着但没输出」,
71
+ * 正是真机报告的形态。中止后重建 adapter(信号已 abort 不可复用);
72
+ * 注入的测试 adapter(无可控信号)不动,回到协作式 deadline。
73
+ */
74
+ abortInFlight(reason) {
75
+ if (!this.adapterOwned || this.abortController === undefined)
76
+ return;
77
+ try {
78
+ this.abortController.abort(reason);
79
+ }
80
+ catch {
81
+ // 已 abort / 宿主不支持——继续重置,让下一跳拿新信号
82
+ }
83
+ this.abortController = undefined;
84
+ this.httpAdapter = undefined;
85
+ this.adapterOwned = false;
86
+ }
61
87
  /**
62
88
  * O4(0.8.1 决策变更):版本证据按缓存窗口复用——`probeVersionEvidence` 只在
63
89
  * 「没有版本」「非锚定族且过了复检窗口」时走 wire。写路径不再强制重探(见
@@ -260,6 +286,8 @@ export class CloudPivotSession {
260
286
  if (!this.loginResult)
261
287
  await this.login();
262
288
  let timer;
289
+ // B4:本跳预算只收紧(总超时倒计时);缺省沿用会话默认。
290
+ const budget = input.timeoutMs === undefined ? this.requestTimeoutMs : Math.max(1, Math.min(this.requestTimeoutMs, input.timeoutMs));
263
291
  try {
264
292
  return await Promise.race([
265
293
  (await this.http()).request({
@@ -272,7 +300,7 @@ export class CloudPivotSession {
272
300
  headers: { ...this.headers(), ...(input.headers ?? {}) },
273
301
  }),
274
302
  new Promise((_, reject) => {
275
- timer = setTimeout(() => reject(new CloudPivotRequestTimeoutError(input.path, this.requestTimeoutMs)), this.requestTimeoutMs);
303
+ timer = setTimeout(() => reject(new CloudPivotRequestTimeoutError(input.path, budget)), budget);
276
304
  }),
277
305
  ]);
278
306
  }
package/dist/support.js CHANGED
@@ -42,7 +42,9 @@ export function writeArtifact(ctx, name, body) {
42
42
  export function isUncertainWireError(error) {
43
43
  if (error instanceof WireError)
44
44
  return error.kind === "transport" || error.kind === "http-status";
45
- return error instanceof Error && /transport failed|transport outage|fetch failed|ENOTFOUND|ECONNREFUSED|timed? ?out|network/i.test(error.message);
45
+ if (error instanceof Error && error.name === "AbortError")
46
+ return true;
47
+ return error instanceof Error && /transport failed|transport outage|fetch failed|aborted|ENOTFOUND|ECONNRESET|ECONNREFUSED|EPIPE|timed? ?out|network/i.test(error.message);
46
48
  }
47
49
  export function wireErrorKind(error) {
48
50
  return error instanceof WireError ? error.kind : "auth-transport";
@@ -0,0 +1,120 @@
1
+ /**
2
+ * B3(0.8.4,2026-11-25 真机):传输失败的**可诊断面**。
3
+ *
4
+ * 真机:`omc call app.list` 连续 8 次(含 `--out`)回
5
+ * `{"status":"uncertain","frozen":true,"reason":"wire-transport:auth-transport","detail":"fetch failed"}`
6
+ * 同期 `model.list` / `form.get` / `data.list` 全正常。`fetch failed` 是 Node
7
+ * undici 的**外壳消息**,真正的原因(ECONNRESET / ENOTFOUND / 证书 / 401 …)
8
+ * 在 `error.cause`(或 AggregateError 的 `errors[]`)里,被整条丢掉之后调用方
9
+ * 无法区分「网络抖动 / 权限 / 平台缺口」。
10
+ *
11
+ * 这里做两件事,都不改任何判定:
12
+ * 1. `classifyTransportFailure` 顺着 cause 链分类(network/dns/tls/timeout/http/auth);
13
+ * 2. `recordWireFailure` 在 `wireCall` 抛错前把**端点 + 分类**记到一个 WeakMap,
14
+ * 读面在回执里把 `endpoint` / `lastFailureKind` / `lastFailureCause` 带出去。
15
+ *
16
+ * 只做诊断,不做策略:是否重试由读通道(read.ts)显式决定。
17
+ */
18
+ const DNS_CODES = new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_FAIL", "EAI_NODATA", "ENODATA"]);
19
+ const TLS_CODES = new Set([
20
+ "CERT_HAS_EXPIRED",
21
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
22
+ "SELF_SIGNED_CERT_IN_CHAIN",
23
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
24
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
25
+ "ERR_TLS_CERT_ALTNAME_INVALID",
26
+ ]);
27
+ const NETWORK_CODES = new Set([
28
+ "ECONNRESET",
29
+ "ECONNREFUSED",
30
+ "ECONNABORTED",
31
+ "EPIPE",
32
+ "ETIMEDOUT",
33
+ "EHOSTUNREACH",
34
+ "ENETUNREACH",
35
+ "EADDRNOTAVAIL",
36
+ "UND_ERR_SOCKET",
37
+ "UND_ERR_CLOSED",
38
+ "UND_ERR_CONNECT_TIMEOUT",
39
+ "UND_ERR_HEADERS_TIMEOUT",
40
+ "UND_ERR_BODY_TIMEOUT",
41
+ ]);
42
+ /** Flatten an Error's `cause` / AggregateError `errors[]` chain (bounded). */
43
+ function factsOf(error, depth = 0) {
44
+ if (depth > 6 || error === null || error === undefined)
45
+ return [];
46
+ if (typeof error !== "object")
47
+ return [{ message: String(error) }];
48
+ const record = error;
49
+ const code = typeof record.code === "string" ? record.code : undefined;
50
+ const name = typeof record.name === "string" ? record.name : undefined;
51
+ const message = typeof record.message === "string" ? record.message : String(error);
52
+ const rawStatus = record.status ?? record.statusCode ?? (typeof record.diagnostic === "object" && record.diagnostic !== null ? record.diagnostic.httpStatus : undefined);
53
+ const status = typeof rawStatus === "number" ? rawStatus : undefined;
54
+ const errcode = typeof record.errcode === "number" ? record.errcode : undefined;
55
+ const out = [{ message, ...(code !== undefined ? { code } : {}), ...(name !== undefined ? { name } : {}), ...(status !== undefined ? { status } : {}), ...(errcode !== undefined ? { errcode } : {}) }];
56
+ if (Array.isArray(record.errors))
57
+ for (const inner of record.errors)
58
+ out.push(...factsOf(inner, depth + 1));
59
+ if (record.cause !== undefined)
60
+ out.push(...factsOf(record.cause, depth + 1));
61
+ return out;
62
+ }
63
+ /** Classify a thrown transport/protocol failure from its whole cause chain. */
64
+ export function classifyTransportFailure(error) {
65
+ const chain = factsOf(error);
66
+ const codes = chain.map((entry) => entry.code).filter((code) => typeof code === "string");
67
+ const causeCode = codes.find((code) => DNS_CODES.has(code) || TLS_CODES.has(code) || NETWORK_CODES.has(code)) ?? codes[0];
68
+ const status = chain.map((entry) => entry.status).find((value) => typeof value === "number");
69
+ const errcode = chain.map((entry) => entry.errcode).find((value) => typeof value === "number");
70
+ if (status === 401 || status === 403)
71
+ return { failureKind: "auth", ...(causeCode !== undefined ? { causeCode } : {}), httpStatus: status, ...(errcode !== undefined ? { errcode } : {}) };
72
+ if (codes.some((code) => DNS_CODES.has(code)))
73
+ return { failureKind: "dns", causeCode: causeCode, ...(status !== undefined ? { httpStatus: status } : {}) };
74
+ if (codes.some((code) => TLS_CODES.has(code) || code.startsWith("ERR_SSL") || code.startsWith("ERR_TLS")))
75
+ return { failureKind: "tls", causeCode: causeCode, ...(status !== undefined ? { httpStatus: status } : {}) };
76
+ if (codes.some((code) => NETWORK_CODES.has(code)))
77
+ return { failureKind: "network", causeCode: causeCode, ...(status !== undefined ? { httpStatus: status } : {}) };
78
+ const names = chain.map((entry) => entry.name ?? "").join(" ");
79
+ const messages = chain.map((entry) => entry.message).join(" | ");
80
+ // Abort / timeout wording. A caller-driven abort (graph pull deadline) and a
81
+ // request timeout are both "no answer in time" — never "endpoint absent".
82
+ if (/AbortError/i.test(names) || /aborted|operation was aborted|timed? ?out|timeout/i.test(messages))
83
+ return { failureKind: "timeout", ...(causeCode !== undefined ? { causeCode } : {}), ...(status !== undefined ? { httpStatus: status } : {}) };
84
+ if (status !== undefined && status >= 400)
85
+ return { failureKind: "http", ...(causeCode !== undefined ? { causeCode } : {}), httpStatus: status };
86
+ if (errcode !== undefined)
87
+ return { failureKind: "business", ...(causeCode !== undefined ? { causeCode } : {}), errcode };
88
+ if (/fetch failed|socket hang up|other side closed/i.test(messages))
89
+ return { failureKind: "network", ...(causeCode !== undefined ? { causeCode } : {}) };
90
+ return { failureKind: "unknown", ...(causeCode !== undefined ? { causeCode } : {}), ...(status !== undefined ? { httpStatus: status } : {}) };
91
+ }
92
+ const failureByError = new WeakMap();
93
+ /** Attach endpoint + classification to a thrown error (diagnostic only). */
94
+ export function recordWireFailure(error, facts) {
95
+ if (error === null || (typeof error !== "object" && typeof error !== "function"))
96
+ return;
97
+ failureByError.set(error, facts);
98
+ }
99
+ /** Facts recorded by `wireCall` for this error, if any. */
100
+ export function wireFailureOf(error) {
101
+ if (error === null || typeof error !== "object")
102
+ return undefined;
103
+ return failureByError.get(error);
104
+ }
105
+ /** Facts for a thrown error: recorded wire facts first, then the cause chain. */
106
+ export function describeWireFailure(error) {
107
+ const recorded = wireFailureOf(error);
108
+ if (recorded !== undefined)
109
+ return recorded;
110
+ return classifyTransportFailure(error);
111
+ }
112
+ /** One short human line for stderr diagnostics (never part of the JSON envelope). */
113
+ export function transportFailureLine(info) {
114
+ return `[omc] wire failure kind=${info.failureKind}${info.endpoint !== undefined ? ` endpoint=${info.endpoint}` : ""}${info.causeCode !== undefined ? ` cause=${info.causeCode}` : ""}${info.httpStatus !== undefined ? ` http=${info.httpStatus}` : ""}`;
115
+ }
116
+ /** Network-class failures are worth retrying for idempotent READS; auth/http are not. */
117
+ export function isRetryableTransportKind(kind) {
118
+ return kind === "network" || kind === "dns" || kind === "tls";
119
+ }
120
+ //# sourceMappingURL=wire-failure.js.map
package/dist/wire.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { CloudPivotRequestTimeoutError } from "./session.js";
2
2
  import { ENDPOINTS } from "./endpoints.js";
3
+ import { classifyTransportFailure, recordWireFailure } from "./wire-failure.js";
3
4
  /**
4
5
  * Generic governed wire driver. Decodes the CloudPivot envelope
5
6
  * ({errcode, errmsg, data}) with Void-envelope semantics, and classifies
@@ -37,6 +38,82 @@ export class WireError extends Error {
37
38
  this.payload = payload;
38
39
  }
39
40
  }
41
+ /**
42
+ * B1(2026-11-25 真机 P0):网关 HTML 404 不是「环境能力缺失」。
43
+ *
44
+ * `omc-core` 的 `fetchCloudPivotHttp` 在「非 2xx + 响应体不是 JSON」时抛
45
+ * `CloudPivotAuthenticationError`,message 形如
46
+ * `CloudPivot /api/api/app/bizsheet/get → HTTP 404(text/html):该端点在此环境不可达
47
+ * (模块未部署/网关未路由),属环境能力缺失,非载荷错误——…勿重试同一载荷。`
48
+ * 真机事实(2.1.6,同一载荷):同一条 `form.get` 下一次即 200,随后 10+ 次
49
+ * (含 180KB 全布局)全成功;404 的响应体是**网关的 HTML 页面**,不是平台
50
+ * JSON 信封。
51
+ *
52
+ * 证据(详见本轮交付报告的证据表):
53
+ * - 网关:`raw/ai21/cloudpivot-2.1.5.zip!/cloudpivot/middleware/openresty/
54
+ * conf.d/cloud8.conf.default:10`(root=nginx/html)+ `:225`
55
+ * `error_page 404 /404.html`;8.7.x 同一份配置(raw/v87,:10/:225)。
56
+ * 8.6.26 的网关配置不在源码树 → 标「需真机采样」。
57
+ * - 平台:launcher 捆绑 Spring Boot 2.5.15,`BasicErrorController` 的
58
+ * `errorHtml` 只在 `produces=text/html` 命中,默认分支回 JSON;CLI 恒发
59
+ * `Accept: application/json`(cloudpivot-auth.ts:279)。平台业务异常由
60
+ * `GlobalExceptionHandler` 统一 `@ResponseStatus(HttpStatus.OK)` +
61
+ * `{errcode,errmsg}`(2.1.5/8.6.26 同构),不会用 404/HTML 表达「没有」。
62
+ * 所以「404 + text/html」不能当成平台端点缺席的判决:它更像网关/边缘的错误页。
63
+ * 把网关/边缘瞬时 404 说成「端点不可达 + 勿重试」,会让 agent 向用户下错误结论,
64
+ * 也会把一次可重试的抖动升级成环境事故。
65
+ *
66
+ * 「连续 ≥2 次才下结论」是我们自己的保守策略,没有平台证据支撑——单次响应
67
+ * 无法区分「瞬时抖动」与「真没部署」,所以文案只说「可重试 1–2 次 / 连续复现
68
+ * 再排查」,任何情况下都不输出「端点不可达」。
69
+ *
70
+ * 这里在传输层把它改写成**可重试的传输错**(`WireError("transport")`,读/写
71
+ * governed 通道照既有约定回 `uncertain` + `retryable:true`)。**只有 404 + 非
72
+ * JSON** 走这条;5xx/4xx 其它码与原 message 一概不动。它**不**参与「版本族
73
+ * 端点缺席 → 下探备选路径」:那个契约靠的是 Spring 的 JSON 404(见
74
+ * `throwIfGatewayHtml404`),HTML 404 说明请求没到平台。
75
+ */
76
+ export const GATEWAY_HTML_404_PREFIX = "网关返回了 HTML 404(不是平台 JSON 信封)";
77
+ export function gatewayHtml404Message(input) {
78
+ const method = input.method ?? "GET";
79
+ const contentType = input.contentType && input.contentType !== "unknown" ? input.contentType : "HTML";
80
+ return `${GATEWAY_HTML_404_PREFIX}:${method} ${input.path}(响应体 ${contentType})——通常是路由/网关瞬时抖动,可重试 1–2 次(同一载荷);连续复现(同一端点 ≥2 次)再查 readiness/部署(omc doctor)。`;
81
+ }
82
+ /** Recognise the omc-core non-JSON-HTTP failure that B1 must not read as "unreachable". */
83
+ function gatewayHtmlResponseOf(error) {
84
+ if (!(error instanceof Error))
85
+ return undefined;
86
+ const match = /^CloudPivot (.+?) → HTTP (\d{3})(([^)]*))/u.exec(error.message);
87
+ if (!match)
88
+ return undefined;
89
+ const status = Number(match[2]);
90
+ // Only 404 is reclassified. Other non-JSON statuses keep their existing
91
+ // wording/behaviour (dashboard 502 has its own boundary teaching).
92
+ if (status !== 404)
93
+ return undefined;
94
+ const contentType = match[3] ?? "";
95
+ if (/json/i.test(contentType))
96
+ return undefined;
97
+ return { path: match[1], status, contentType };
98
+ }
99
+ /** Re-throw a gateway HTML 404 as a retryable transport failure; other errors pass through. */
100
+ function throwIfGatewayHtml404(error) {
101
+ const hit = gatewayHtmlResponseOf(error);
102
+ if (hit === undefined)
103
+ return;
104
+ // `transport` (not `http-status`) is deliberate and evidence-backed:
105
+ // version-family endpoint absence is a *Spring* 404, which BasicErrorController
106
+ // answers as JSON under our `Accept: application/json` (launcher bundles
107
+ // Spring Boot 2.5.15; the HTML branch is produces=text/html only). An HTML 404
108
+ // therefore means the request never reached the platform — the gateway/edge
109
+ // failed to route it — so it must NOT be consumed by the "endpoint absent in
110
+ // this version family → try the alternate path" checks
111
+ // (wireCallWith404Fallback / model-record / form.list / rule-lifecycle).
112
+ // Those checks still see real JSON 404s exactly as before.
113
+ const failure = new WireError("transport", gatewayHtml404Message(hit), undefined, { httpStatus: hit.status });
114
+ recordWireFailure(failure, { endpoint: hit.path, failureKind: "http", httpStatus: hit.status });
115
+ throw failure;
116
+ }
40
117
  /**
41
118
  * 从 300004 业务错误的 `data` 里提取「选项设置有误」明细(T20 兜底)。
42
119
  *
@@ -254,18 +331,36 @@ export async function wireCall(session, call) {
254
331
  ...(call.query ? { query: call.query } : {}),
255
332
  ...(call.body === undefined ? {} : { body: call.body }),
256
333
  ...(call.headers === undefined ? {} : { headers: call.headers }),
334
+ ...(call.timeoutMs === undefined ? {} : { timeoutMs: call.timeoutMs }),
257
335
  }).catch((error) => {
336
+ // B3(0.8.4):把「到底哪一跳、哪一类失败」记在错误上再抛——读面回执要带
337
+ // endpoint / lastFailureKind / lastFailureCause。判定不变(仍是未分类原错,
338
+ // 由 isUncertainWireError 的老规则兜住),只是不再把 undici 的 cause 丢掉。
339
+ recordWireFailure(error, { endpoint: call.path, ...classifyTransportFailure(error) });
258
340
  // A timeout leaves the outcome unknown — classify it as a transport
259
341
  // failure so the governance layer freezes instead of assuming success.
260
- if (error instanceof CloudPivotRequestTimeoutError)
261
- throw new WireError("transport", error.message);
342
+ if (error instanceof CloudPivotRequestTimeoutError) {
343
+ const timeout = new WireError("transport", error.message);
344
+ recordWireFailure(timeout, { endpoint: call.path, failureKind: "timeout" });
345
+ throw timeout;
346
+ }
347
+ // B1: a gateway HTML 404 is a retryable transport blip, never "endpoint
348
+ // absent / do not retry". Every other status keeps its original error.
349
+ throwIfGatewayHtml404(error);
262
350
  throw error;
263
351
  });
264
- if (response.status < 200 || response.status >= 300)
265
- throw new WireError("http-status", `HTTP ${response.status} for ${call.path} (${call.method ?? "GET"}); body: ${redactedBodyPreview(response.body)}`, undefined, {
352
+ if (response.status < 200 || response.status >= 300) {
353
+ const failure = new WireError("http-status", `HTTP ${response.status} for ${call.path} (${call.method ?? "GET"}); body: ${redactedBodyPreview(response.body)}`, undefined, {
266
354
  httpStatus: response.status,
267
355
  bodyPreview: redactedBodyPreview(response.body),
268
356
  });
357
+ recordWireFailure(failure, {
358
+ endpoint: call.path,
359
+ failureKind: response.status === 401 || response.status === 403 ? "auth" : "http",
360
+ httpStatus: response.status,
361
+ });
362
+ throw failure;
363
+ }
269
364
  const body = response.body;
270
365
  if (!body || typeof body !== "object")
271
366
  throw new WireError("malformed-envelope", `non-object envelope for ${call.path} (${call.method ?? "GET"}); body: ${redactedBodyPreview(body)}`, undefined, { bodyPreview: redactedBodyPreview(body) });
@@ -277,7 +372,13 @@ export async function wireCall(session, call) {
277
372
  throw new WireError("malformed-envelope", `envelope for ${call.path} (${call.method ?? "GET"}) has no numeric errcode; body: ${redactedBodyPreview(body)}`, undefined, { httpStatus: response.status, bodyPreview: redactedBodyPreview(body) });
278
373
  if (envelope.errcode !== 0) {
279
374
  const message = typeof envelope.errmsg === "string" ? envelope.errmsg : "CloudPivot rejected the request";
280
- throw new WireError("business", `errcode ${envelope.errcode} for ${call.path}: ${message}`, envelope.errcode, undefined, undefined, envelope.data);
375
+ const failure = new WireError("business", `errcode ${envelope.errcode} for ${call.path}: ${message}`, envelope.errcode, undefined, undefined, envelope.data);
376
+ recordWireFailure(failure, {
377
+ endpoint: call.path,
378
+ failureKind: envelope.errcode === 401 || envelope.errcode === 403 ? "auth" : "business",
379
+ errcode: envelope.errcode,
380
+ });
381
+ throw failure;
281
382
  }
282
383
  const result = {
283
384
  path: call.path,
@@ -351,6 +452,7 @@ export async function wireDownloadBuffer(session, call) {
351
452
  .catch((error) => {
352
453
  if (error instanceof CloudPivotRequestTimeoutError)
353
454
  throw new WireError("transport", error.message);
455
+ throwIfGatewayHtml404(error);
354
456
  throw error;
355
457
  });
356
458
  if (response.status < 200 || response.status >= 300)
@@ -378,6 +480,7 @@ export async function wireDownloadPackageStream(session, call) {
378
480
  .catch((error) => {
379
481
  if (error instanceof CloudPivotRequestTimeoutError)
380
482
  throw new WireError("transport", error.message);
483
+ throwIfGatewayHtml404(error);
381
484
  throw error;
382
485
  });
383
486
  if (response.status < 200 || response.status >= 300)
@@ -434,6 +537,7 @@ export async function wireUploadFile(session, path, filename, content, contentTy
434
537
  .catch((error) => {
435
538
  if (error instanceof CloudPivotRequestTimeoutError)
436
539
  throw new WireError("transport", error.message);
540
+ throwIfGatewayHtml404(error);
437
541
  throw error;
438
542
  });
439
543
  if (response.status < 200 || response.status >= 300)
@@ -136,6 +136,47 @@ export async function getReplayToken(session) {
136
136
  const token = await wireCall(session, { path: ENDPOINTS.runtimeFormReplayToken, query: {} });
137
137
  return typeof token.data === "string" && token.data ? token.data : undefined;
138
138
  }
139
+ /**
140
+ * 实例**读面**上「已结束」的状态集合 —— 「是否已结束」的唯一判据(0.8.3)。
141
+ *
142
+ * 平台存两列:`biz_workflow_instance.state`(`WorkflowInstanceStatus`)与
143
+ * `endStatus`(`WorkflowEndStatus`)。`get_instance_baseinfo` / `list_instances`
144
+ * 的 `status` 是**投影值**,不是存储列
145
+ * (`WorkflowInstanceStatusHelper.parseStatusByInstance:459-474`,2.1.5 与 8.6.26
146
+ * 同形;baseinfo 接线见 `WorkflowInstanceRuntimeController:545`,list 面经
147
+ * `WorkflowInstanceVO.getState:82-96` 再投影一层):
148
+ * - 存储非 `COMPLETED` 直通(`DRAFT`/`PROCESSING`/`CANCELED`/`EXCEPTION`/`PAUSE`);
149
+ * - `COMPLETED` + 空/`APPROVAL` → **`APPROVED`**(末级审批通过;
150
+ * `WorkflowInstanceEntityManagerImpl.onWorkflowFinished:295-303`);
151
+ * - `COMPLETED` + 其它 `endStatus`(`ABORT_END`/`TIMEOUT_END`/`OPERATION`/
152
+ * `VOIDED_*`)→ **`TOPPING_OFF`**(手动结束
153
+ * `WorkflowInstanceFacadeImpl.finishWorkflowInstance:1066-1072` 固定写
154
+ * `ABORT_END`;超时写 `TIMEOUT_END`)。
155
+ *
156
+ * `APPROVED`/`TOPPING_OFF` 是**显示态枚举成员,全库没有 setState 写路径**,所以
157
+ * 只比字符串 `"COMPLETED"` 的判据会漏掉每一个正常终结的实例(0.8.3 修的正是
158
+ * 这一类:`workflow.finish` 对 APPROVED/TOPPING_OFF 实例回了伪成功 `ok`)。
159
+ *
160
+ * 要区分「正常结束 vs 被作废」时用 `isCanceledInstanceStatus` 单独判——作废
161
+ * 直通 `CANCELED`,不属于本集合。
162
+ */
163
+ export const FINISHED_INSTANCE_STATES = ["COMPLETED", "APPROVED", "TOPPING_OFF"];
164
+ /** 读面状态是否属于「实例已结束」(见 {@link FINISHED_INSTANCE_STATES})。 */
165
+ export function isFinishedInstanceStatus(status) {
166
+ if (typeof status !== "string")
167
+ return false;
168
+ return FINISHED_INSTANCE_STATES.includes(status.trim().toUpperCase());
169
+ }
170
+ /**
171
+ * 读面状态是否「已作废」。作废走
172
+ * `handleCancelWorkflowInstance(WorkflowEndStatus.VOIDED_APPROVER)`,实例终态
173
+ * 直通 `CANCELED`(`WorkflowInstanceStatus` 里没有 VOIDED——那是 endStatus)。
174
+ * 绝不能把 `COMPLETED` 家族算作废成功:那是 `workflow.finish` 的终态
175
+ * (`WorkflowInstanceStatus.java:15-22`)。
176
+ */
177
+ export function isCanceledInstanceStatus(status) {
178
+ return typeof status === "string" && /CANCEL/i.test(status);
179
+ }
139
180
  /**
140
181
  * Turn (instance status, per-activity status) into the one-line verdict a caller
141
182
  * needs after `data.submit` returned PROCESSING. A finished instance legitimately
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stalfh233/omc-cli",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
4
4
  "description": "CloudPivot 8.6 configuration capability CLI — governed, fail-closed, coverage-manifest bounded.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -58,7 +58,7 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "commander": "14.0.3",
61
- "omc-core": "0.8.2",
61
+ "omc-core": "0.8.3",
62
62
  "proper-lockfile": "4.1.2",
63
63
  "write-file-atomic": "6.0.0",
64
64
  "zod": "^3.23.8",
@@ -76,6 +76,6 @@
76
76
  "directory": "packages/omc-cli"
77
77
  },
78
78
  "optionalDependencies": {
79
- "@stalfh233/omc-fake-platform": "0.8.2"
79
+ "@stalfh233/omc-fake-platform": "0.8.3"
80
80
  }
81
81
  }