@autocodeflow/cli 1.12.1 → 1.14.0

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/README.md CHANGED
@@ -48,9 +48,16 @@ CLI 的非零退出码按失败类别区分,脚本/CI 可以只按码分支处
48
48
 
49
49
  ### 破坏性操作的 `--yes`(非交互必读)
50
50
 
51
- `app delete` / `task delete` / `deploy remove` 有交互确认。**stdin 非 TTY 时
52
- (CI、agent、`< NUL`、管道)它们不会静默放行也不会静默取消,而是以退出码 2
53
- 拒绝**,要求显式传 `-y/--yes`:
51
+ 破坏性动作有交互确认。**stdin 非 TTY 时(CI、agent、`< NUL`、管道)它们不会
52
+ 静默放行也不会静默取消,而是以退出码 2 拒绝**,要求显式传 `-y/--yes`:
53
+
54
+ | 类别 | 命令 |
55
+ | --- | --- |
56
+ | 删除 | `app delete` / `task delete` / `task batch delete` / `deploy remove` / `mutex delete` |
57
+ | 一次性密钥轮换(旧值立即失效) | `executor rotate` / `task webhook enable` / `task webhook rotate` / `task webhook disable` |
58
+ | 强制终止(KILLED 是终态,无法恢复) | `task kill` |
59
+ | 全量滚动升级(`--strategy canary` 不加门) | `app upgrade-all` |
60
+ | 撤销凭据(影响仍在用它的外部系统) | `apikey revoke` |
54
61
 
55
62
  ```bash
56
63
  acf task delete <id> -y # 非交互下唯一被接受的确认方式
@@ -82,6 +89,23 @@ acf task delete <id> -y # 非交互下唯一被接受的确认方式
82
89
  `--json` 不裁剪字段:后端返回什么就输出什么,消费方按 `--help` 示例里的
83
90
  形状断言即可。
84
91
 
92
+ ### 失败时的结构化错误(stderr)
93
+
94
+ `--json` 调用的失败输出同样是机器可读的**一行 JSON**(写 stderr,stdout 保持
95
+ 纯净,`| jq` 不被污染):
96
+
97
+ ```json
98
+ {"ok":false,"scope":"Failed to fetch task","code":404,"errorCode":"TASK_NOT_FOUND","category":"not_found","params":{"taskId":"t1"},"message":"任务不存在","exitCode":1}
99
+ ```
100
+
101
+ - `code` = HTTP 状态,`errorCode` = admin-api 的稳定码,`params` = 文案插值参数;
102
+ - `errorCode` / `category` / `params` **只在有值时出现**(未知码或无码时该键缺失,
103
+ 用 `'errorCode' in payload` 判断最可靠);
104
+ - `category` ∈ `auth | permission | not_found | conflict | capacity | validation`
105
+ —— 人类可读输出同样按这 6 类在原文案后追加一句话处置建议(`[CODE] — 建议`);
106
+ 未知码与无码**逐字节保持原输出**(透传后端文案);
107
+ - 退出码不因 JSON 化改变(仍见上面的 Exit codes 表)。
108
+
85
109
  ## 认证与配置
86
110
 
87
111
  凭据保存在用户配置目录(`acf config show` 查看实际路径),文件权限 0600;
@@ -97,7 +121,8 @@ acf task delete <id> -y # 非交互下唯一被接受的确认方式
97
121
  且缺 `--code` 时会报可操作的用法错误,退出码 2)。
98
122
  - `acf apikey`(AUTH-03):为 CI/CD 创建限权 API Key(`readonly` / `trigger` /
99
123
  `manage`)。明文(`acf_<64 hex>`)仅在 `acf apikey create` 时回显**一次**,
100
- 此后只能 `acf apikey list`(脱敏)/ `acf apikey revoke <id>`。
124
+ 此后只能 `acf apikey list`(脱敏)/ `acf apikey revoke <id>`(撤销不可逆,
125
+ 非交互场景加 `-y`)。
101
126
  - Access token 过期时自动用 refresh token 换发并重放一次;刷新失败才要求
102
127
  重新登录(此时退出码为 3)。
103
128
 
@@ -135,7 +160,8 @@ acf task delete <id> -y # 非交互下唯一被接受的确认方式
135
160
  撤回自己的请求用 `cancel`;`--note`(≤200 字符)映射契约字段 `reason`。
136
161
  - `acf task webhook enable|rotate|disable|status <taskId>`:任务级入站 webhook
137
162
  (HMAC)。secret 仅在 enable/rotate 响应中回显**一次**;`status` 查看 URL
138
- 不动密钥;`disable` 后签名请求即刻 401。
163
+ 不动密钥;`disable` 后签名请求即刻 401。三个写面都会让**旧 secret 不可逆失效**
164
+ (enable 对已启用任务等价轮换),非交互场景需 `-y`;`status` 是只读面,不加门。
139
165
  - `acf task glue <taskId> -f glue.js`(或 `--stdin`):在线更新 GLUE 脚本。
140
166
  语言按扩展名推断(`.js/.mjs/.cjs` → `javascript`),或 `--language
141
167
  python|javascript|shell` 显式指定(执行器运行时白名单);空脚本本地即拒。
package/dist/client.js CHANGED
@@ -2,6 +2,7 @@
2
2
  * Thin HTTP client wrapper for the AutoCodeFlow Admin API.
3
3
  */
4
4
  import axios from "axios";
5
+ import { appendErrorCodeHint, messageFromData } from "./error-code.js";
5
6
  import { getApiUrl, getToken, getRefreshToken, setToken, setRefreshToken, clearAuth, } from "./config.js";
6
7
  let _client = null;
7
8
  /**
@@ -207,20 +208,15 @@ export async function del(path, params) {
207
208
  // `{ code, message, data }` envelope. class-validator may send `message` as a
208
209
  // string[]. Axios itself only surfaces "Request failed with status code 400",
209
210
  // so without this helper the actual cause never reaches the terminal.
211
+ /**
212
+ * 错误体的人读文案(message / message[] / error 兜底)。
213
+ *
214
+ * R31-E1: 实现挪到 `error-code.ts` 的 `messageFromData`(与 `--json` 结构化
215
+ * 错误输出共用同一份抽取逻辑,避免两处漂移);这里保留原函数名,调用点与
216
+ * 既有语义(含 QA-07 的空串 message 契约)逐字节不变。
217
+ */
210
218
  function detailFromData(data) {
211
- if (!data || typeof data !== "object")
212
- return "";
213
- const d = data;
214
- const m = d.message;
215
- // QA-07 契约:空串 message 视为「未提供」,继续走 message[]/error 兜底
216
- //(与 mcp-server extractDetail 对齐;此前空串 message 会遮蔽 error 字段)。
217
- if (typeof m === "string" && m)
218
- return m;
219
- if (Array.isArray(m) && m.length)
220
- return m.map(String).join("; ");
221
- if (typeof d.error === "string" && d.error)
222
- return d.error;
223
- return "";
219
+ return messageFromData(data);
224
220
  }
225
221
  /**
226
222
  * Classify any thrown error for exit-code mapping:
@@ -250,6 +246,12 @@ export function classifyApiError(e) {
250
246
  * surfacing the backend message instead of axios' generic text.
251
247
  */
252
248
  export function formatApiError(e) {
249
+ // R31-E1: 有稳定码且归类得出来时,在既有文案后追加「[码] — 一句话处置」;
250
+ // 未知码 / 无码逐字节保持原输出(appendErrorCodeHint 原样返回 base)。
251
+ return appendErrorCodeHint(formatApiErrorBase(e), e);
252
+ }
253
+ /** 既有的人读文案(按 HTTP 状态分派)。错误码提示由 formatApiError 追加。 */
254
+ function formatApiErrorBase(e) {
253
255
  if (axios.isAxiosError(e)) {
254
256
  const err = e;
255
257
  const status = err.response?.status;
@@ -3,7 +3,7 @@ import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
5
  import { get, post, del } from '../client.js';
6
- import { emitError, emitUsageError } from '../ui.js';
6
+ import { emitError, emitUsageError, confirmDestructive } from '../ui.js';
7
7
  // scope 三级矩阵(api-reference.md「API Keys」节):readonly 读 / trigger
8
8
  // 读+触发 / manage 全量。本地预检只为报错快一点,服务端 IsIn 仍是权威。
9
9
  const SCOPES = ['readonly', 'trigger', 'manage'];
@@ -85,11 +85,18 @@ export function apikeysCommand() {
85
85
  });
86
86
  cmd.command('revoke <id>')
87
87
  .description('Revoke an API key (soft-delete — takes effect on its next request, cannot be undone)')
88
- .action(async (id) => {
88
+ .option('-y, --yes', 'Skip confirmation prompt', false)
89
+ .action(async (id, opts) => {
89
90
  // 服务端 ParseIntPipe:id 是数字主键(acf apikey list 查看)。
90
91
  if (!/^\d+$/.test(id)) {
91
92
  emitUsageError(`API key id must be a number (got "${id}") — find ids with: acf apikey list`);
92
93
  }
94
+ // R192-A1:撤销不可逆(服务端只做 revokedAt 软删,没有「取消撤销」面),
95
+ // 且影响面是**外部系统**——仍用这把 key 的 CI/SDK 会在下一次请求起 401。
96
+ // 与三处 delete 同一套确认语义:非 TTY 且缺 --yes → 退出码 2,请求不发出。
97
+ if (!(await confirmDestructive(`Revoke API key ${id}? This cannot be undone — any workload still using it starts failing on its next request.`, { yes: opts.yes }))) {
98
+ return;
99
+ }
93
100
  const spinner = ora('Revoking API key…').start();
94
101
  try {
95
102
  // DELETE /api-keys/:id(REST 主语义;POST /:id/revoke 是幂等别名端点)。
@@ -73,6 +73,26 @@ function statusColor(s) {
73
73
  return chalk.yellow(s);
74
74
  return chalk.gray(s);
75
75
  }
76
+ /**
77
+ * R192-A1:数值旗标的**严格**解析器。
78
+ *
79
+ * 旧实现用 `parseInt(v, 10) || 默认值`(--tail/--from-line)与裸字符串直传
80
+ * (--limit):写错单位/打错字(`--tail 5o`、`--from-line 1O0`)会被静默吞成
81
+ * 默认值或 NaN,请求照发、用户拿到**另一页日志**却以为是自己要的那页。与本文件
82
+ * `trigger --wait-timeout` 的既有纪律一致:非法值在 commander 层报用法错误
83
+ * (退出码 2),请求不发出。
84
+ */
85
+ function intOption(flag, min, max) {
86
+ return (v) => {
87
+ const raw = String(v).trim();
88
+ const n = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
89
+ if (!Number.isInteger(n) || n < min || (max !== undefined && n > max)) {
90
+ const range = max === undefined ? `>= ${min}` : `between ${min} and ${max}`;
91
+ throw new InvalidArgumentError(`${flag} must be an integer ${range} (got "${v}")`);
92
+ }
93
+ return n;
94
+ };
95
+ }
76
96
  export function tasksCommand() {
77
97
  const cmd = new Command('task').description('Manage tasks');
78
98
  // acf task list
@@ -266,16 +286,18 @@ export function tasksCommand() {
266
286
  // acf task logs <execId>
267
287
  cmd.command('logs <execId>')
268
288
  .description('Fetch execution logs (line-paginated)')
269
- .option('-f, --from-line <n>', 'Start line (0-based)', '0')
270
- .option('-n, --limit <n>', 'Max lines to fetch (max 2000)', '200')
271
- .option('--tail <n>', 'Show last N lines (overrides --from-line)')
289
+ .option('-f, --from-line <n>', 'Start line (0-based)', intOption('--from-line', 0), 0)
290
+ .option('-n, --limit <n>', 'Max lines to fetch (max 2000)', intOption('--limit', 1, 2000), 200)
291
+ .option('--tail <n>', 'Show last N lines (overrides --from-line)', intOption('--tail', 1))
272
292
  // 第四轮审计(--json 补面):行页对象(lines/totalLines/hasMore)直出 JSON
273
293
  .option('--json', 'Emit raw JSON (CI-consumable, no table)')
274
294
  .action(async (execId, opts) => {
275
295
  const spinner = ora('Fetching logs…').start();
276
296
  try {
277
- if (opts.tail) {
278
- const tail = Math.max(1, parseInt(opts.tail, 10) || 50);
297
+ if (opts.tail !== undefined) {
298
+ // 数值已在 commander 层校验(intOption):这里不再做 parseInt 兜底——
299
+ // 曾经的 `Math.max(1, parseInt(x) || 50)` 会把 --tail 5o 静默变成 50。
300
+ const tail = opts.tail;
279
301
  const head = await get(`/tasks/executions/${execId}/logs`, {
280
302
  fromLine: 0,
281
303
  limit: 1,
@@ -293,7 +315,7 @@ export function tasksCommand() {
293
315
  console.log(chalk.gray(`\n(${data.lines?.length ?? 0}/${data.totalLines} lines — last ${tail})`));
294
316
  }
295
317
  else {
296
- const fromLine = parseInt(opts.fromLine, 10) || 0;
318
+ const fromLine = opts.fromLine;
297
319
  const data = await get(`/tasks/executions/${execId}/logs`, { fromLine, limit: opts.limit });
298
320
  spinner.stop();
299
321
  if (opts.json) {
@@ -750,8 +772,15 @@ export function tasksCommand() {
750
772
  });
751
773
  // acf task kill <taskId> <execId>
752
774
  cmd.command('kill <taskId> <execId>')
753
- .description('Force-cancel a running or pending execution')
754
- .action(async (taskId, execId) => {
775
+ .description('Force-cancel a running or pending execution (irreversible: the executor terminates the process)')
776
+ .option('-y, --yes', 'Skip confirmation prompt', false)
777
+ .action(async (taskId, execId, opts) => {
778
+ // R192-A1:KILLED 是终态,没有「反 kill」——被杀掉的执行无法恢复。与
779
+ // delete / rotate 同属不可逆动作,必须共用同一套确认语义(非 TTY 且缺
780
+ // --yes 时以退出码 2 拒绝,既不静默执行也不静默取消)。
781
+ if (!(await confirmDestructive(`Force-cancel execution ${execId} of task ${taskId}? The running process is terminated and cannot be resumed.`, { yes: opts.yes }))) {
782
+ return;
783
+ }
755
784
  const spinner = ora('Cancelling execution…').start();
756
785
  try {
757
786
  const r = await post(`/tasks/${taskId}/executions/${execId}/kill`);
@@ -770,11 +799,27 @@ export function tasksCommand() {
770
799
  cmd.command('webhook <action> <taskId>')
771
800
  .description('Manage the task inbound webhook (HMAC-signed). enable/rotate print the secret exactly once; status shows the URL without touching the secret; disable makes signed calls answer 401 immediately')
772
801
  .option('--json', 'Emit raw JSON (CI-consumable; includes the one-time secret for enable/rotate)')
802
+ .option('-y, --yes', 'Skip the confirmation prompt for enable / rotate / disable', false)
773
803
  .action(async (action, taskId, opts) => {
774
804
  const ACTIONS = ['enable', 'rotate', 'disable', 'status'];
775
805
  if (!ACTIONS.includes(action)) {
776
806
  emitUsageError(`Unknown webhook action "${action}" — expected one of: ${ACTIONS.join(' | ')}`);
777
807
  }
808
+ // R192-A1:三个写面都会**不可逆地让旧 secret 失效**——
809
+ // · enable 对已启用任务等价轮换(服务端同一把密钥,旧 secret 立即失效);
810
+ // · rotate 更直接,且新 secret 只在本命令输出里出现一次;
811
+ // · disable 清空密钥,重新 enable 发的是**另一把**(旧值永不回传)。
812
+ // 与 executor rotate 同类(同一轮审计里给它补了确认门),此前这三个却零确认:
813
+ // agent / CI 里一次手滑就把线上 webhook 打断且拿不回旧密钥。status 只读,不加门。
814
+ if (action !== 'status') {
815
+ const question = action === 'disable'
816
+ ? `Disable the task webhook for ${taskId}? Signed calls answer 401 immediately and the current secret is destroyed (re-enable issues a NEW one).`
817
+ : action === 'rotate'
818
+ ? `Rotate the webhook secret for ${taskId}? The old secret stops working immediately and the new one is shown only once.`
819
+ : `Enable the task webhook for ${taskId}? If a secret already exists this rotates it — the old one stops working immediately and the new one is shown only once.`;
820
+ if (!(await confirmDestructive(question, { yes: opts.yes })))
821
+ return;
822
+ }
778
823
  const spinner = ora(`Task webhook ${action}…`).start();
779
824
  try {
780
825
  if (action === 'status') {
@@ -0,0 +1,66 @@
1
+ /**
2
+ * R31-E1: admin-api **稳定错误码**的消费侧(CLI)。
3
+ *
4
+ * 背景:admin-api 已全量错误码化,HTTP 错误响应体形如
5
+ * { code: <数字 HTTP 状态>, message: <中文兜底>, errorCode: '<稳定码>', params: {...} }
6
+ * 浏览器端按码做 i18n;CLI 此前只透传 `message`——用户看到的是中文兜底文案,
7
+ * 脚本也拿不到稳定码(只能匹配文案,文案一改就断)。
8
+ *
9
+ * 本模块只做三件事,且**不依赖 axios 实例**(纯函数,便于单测与复用):
10
+ * 1. `extractApiErrorInfo` —— 从任意抛出的值里抽出 { status, errorCode,
11
+ * params, message }(axios 形状 / SDK 形状 / 普通对象都吃);
12
+ * 2. `classifyErrorCode` —— 把稳定码归到 **6 类**之一(不枚举几百个码,
13
+ * 用命名约定的前缀/后缀模式;顺序即优先级);
14
+ * 3. `appendErrorCodeHint` —— 在既有的人读文案后追加「[码] — 一句话处置」。
15
+ *
16
+ * ⚠️ 未知码与无码必须**逐字节保持现状**:这两个分支不追加任何文本
17
+ * (`appendErrorCodeHint` 直接返回入参),因为历史输出被大量测试与用户
18
+ * 习惯钉住,且「猜一个类别」比「不说」更容易误导。
19
+ */
20
+ /** 6 个处置类别(认证 / 权限 / 不存在 / 冲突 / 容量或限流 / 校验失败)。 */
21
+ export type ApiErrorCategory = 'auth' | 'permission' | 'not_found' | 'conflict' | 'capacity' | 'validation';
22
+ /**
23
+ * 每类的**一句话**处置建议。刻意按类给而不是按码给:三百多个码逐条写建议
24
+ * 必然腐化,而「你是谁不对 / 你没权限 / 东西没了 / 状态冲突 / 服务撑不住 /
25
+ * 入参不合法」这六类的下一步动作是稳定的。
26
+ */
27
+ export declare const CATEGORY_HINTS: Readonly<Record<ApiErrorCategory, string>>;
28
+ /**
29
+ * 稳定码 → 类别;未知码 / 非字符串 / 空串 → `null`(调用方据此保持现状)。
30
+ *
31
+ * 只做命名约定匹配,**不维护码表清单**:新增码只要沿用约定就自动归类,
32
+ * 不沿用则安全地落到「未知」分支(不猜、不误导)。
33
+ */
34
+ export declare function classifyErrorCode(errorCode: unknown): ApiErrorCategory | null;
35
+ /** 稳定码 → 一句话处置建议;未知码 / 无码 → `null`。 */
36
+ export declare function hintForErrorCode(errorCode: unknown): string | null;
37
+ /** 从错误响应体里抽人读文案(`message` / class-validator 的 `message[]` / `error`)。 */
38
+ export declare function messageFromData(data: unknown): string;
39
+ /** 错误的可机读面(缺什么就没有对应键,不写 undefined)。 */
40
+ export interface ApiErrorInfo {
41
+ /** HTTP 状态(优先 `response.status`,回落响应体里的数值 `code`)。 */
42
+ status?: number;
43
+ /** 管理员侧稳定码(如 `TASK_NOT_FOUND`)。 */
44
+ errorCode?: string;
45
+ /** 码的插值参数。 */
46
+ params?: Record<string, unknown>;
47
+ /** 服务端人读文案(已含 message[] / error 兜底)。 */
48
+ message?: string;
49
+ }
50
+ /**
51
+ * 从任意抛出的值里抽出可机读的错误面。
52
+ *
53
+ * 三种来源都要吃(CLI 一条链路上都会出现):
54
+ * - axios 错误:`err.response.data` 是 admin-api 的错误体;
55
+ * - node SDK 标记过的错误:`errorCode` / `params` 直接挂在 Error 上
56
+ * (packages/autocodeflow-node-sdk 的 attachErrorCode),没有 response;
57
+ * - 直接抛的普通对象(本地派生错误 / 测试桩)。
58
+ */
59
+ export declare function extractApiErrorInfo(e: unknown): ApiErrorInfo;
60
+ /**
61
+ * 在既有的人读文案后追加「[码] — 一句话处置」;**未知码 / 无码原样返回**。
62
+ *
63
+ * 之所以把码本身也打出来:用户报障时贴一行就够定位(不必再开 --json),
64
+ * 而这个码正是 README/文档里能搜到的稳定标识。
65
+ */
66
+ export declare function appendErrorCodeHint(base: string, e: unknown): string;
@@ -0,0 +1,177 @@
1
+ /**
2
+ * R31-E1: admin-api **稳定错误码**的消费侧(CLI)。
3
+ *
4
+ * 背景:admin-api 已全量错误码化,HTTP 错误响应体形如
5
+ * { code: <数字 HTTP 状态>, message: <中文兜底>, errorCode: '<稳定码>', params: {...} }
6
+ * 浏览器端按码做 i18n;CLI 此前只透传 `message`——用户看到的是中文兜底文案,
7
+ * 脚本也拿不到稳定码(只能匹配文案,文案一改就断)。
8
+ *
9
+ * 本模块只做三件事,且**不依赖 axios 实例**(纯函数,便于单测与复用):
10
+ * 1. `extractApiErrorInfo` —— 从任意抛出的值里抽出 { status, errorCode,
11
+ * params, message }(axios 形状 / SDK 形状 / 普通对象都吃);
12
+ * 2. `classifyErrorCode` —— 把稳定码归到 **6 类**之一(不枚举几百个码,
13
+ * 用命名约定的前缀/后缀模式;顺序即优先级);
14
+ * 3. `appendErrorCodeHint` —— 在既有的人读文案后追加「[码] — 一句话处置」。
15
+ *
16
+ * ⚠️ 未知码与无码必须**逐字节保持现状**:这两个分支不追加任何文本
17
+ * (`appendErrorCodeHint` 直接返回入参),因为历史输出被大量测试与用户
18
+ * 习惯钉住,且「猜一个类别」比「不说」更容易误导。
19
+ */
20
+ /**
21
+ * 每类的**一句话**处置建议。刻意按类给而不是按码给:三百多个码逐条写建议
22
+ * 必然腐化,而「你是谁不对 / 你没权限 / 东西没了 / 状态冲突 / 服务撑不住 /
23
+ * 入参不合法」这六类的下一步动作是稳定的。
24
+ */
25
+ export const CATEGORY_HINTS = {
26
+ auth: 'run "acf login" (or pass --token / set ACF_TOKEN) to refresh your credentials.',
27
+ permission: 'your account or role is not allowed to do this — ask an admin for the required role/ownership (some endpoints require ADMIN).',
28
+ not_found: 'the resource does not exist (or was deleted) — re-check the ID with the matching "acf ... list" command.',
29
+ conflict: 'the resource already exists or is in a conflicting state — re-read it with "acf ... get" before retrying.',
30
+ capacity: 'the service is at capacity or throttling — retry later with backoff (for executors: free a slot or raise maxConcurrentTasks).',
31
+ validation: 'the input was rejected by validation — fix the field(s) named in the message; retrying unchanged fails the same way.',
32
+ };
33
+ /**
34
+ * 码 → 类别的判定表。**顺序即优先级**:先命中先归类。
35
+ *
36
+ * 优先级刻意如此:
37
+ * - `capacity` 最先:`API_KEY_QUOTA_REACHED`(429)、`NO_AVAILABLE_EXECUTOR`
38
+ * (409)、`EXECUTOR_OFFLINE`(409)这些状态码本身不表达"容量",而
39
+ * "稍后重试/腾容量"才是正确的下一步;
40
+ * - `permission` 早于 `auth`:`API_KEY_SCOPE_DENIED`(403)以 `API_KEY_`
41
+ * 开头,若 auth 先命中就会误给"去 acf login"这种无效建议;
42
+ * - `auth` 早于 `validation`:`INVALID_CREDENTIALS` 含 `INVALID`,但正确
43
+ * 的动作是重新登录,不是"改入参";
44
+ * - `conflict` 早于 `validation`:`TASK_ALREADY_PAUSED` / `TASK_UPDATE_STALE`
45
+ * 是状态冲突(重新读一次再决定),不是入参写错。
46
+ */
47
+ const CATEGORY_RULES = [
48
+ [
49
+ 'capacity',
50
+ /(QUOTA|RATE_?LIMIT|TOO_MANY|CAPACITY|THROTTL|TIMEOUT|_STREAM_LIMIT|LIMIT_GLOBAL|LIMIT_PER_EXECUTION|NO_[A-Z_]*EXECUTOR|_OFFLINE)/,
51
+ ],
52
+ [
53
+ 'permission',
54
+ /(FORBIDDEN|_DENIED|NOT_AUTHORIZED|_NOT_OWNER|NO_OWNER|NOT_MEMBER|NOT_VISIBLE|_SELF_ONLY|ADMIN_ONLY|_READONLY|PERMISSION|ROLE_)/,
55
+ ],
56
+ [
57
+ 'auth',
58
+ /(UNAUTHORIZED|INVALID_CREDENTIALS|CREDENTIAL|LOGIN_|SESSION_|TOKEN|API_KEY_|ACCOUNT_|OIDC_|TOTP|AUTH_FAILED|USERNAME_OR_PASSWORD)/,
59
+ ],
60
+ ['not_found', /(_NOT_FOUND)/],
61
+ [
62
+ 'conflict',
63
+ // `(?<!MAX_)CONCURRENT`:`EXECUTOR_MAX_CONCURRENT_INVALID` 说的是"参数非法"
64
+ // (validation),而 `TASK_TRIGGER_CONCURRENT` / `_CONCURRENT_MODIFICATION`
65
+ // 才是并发冲突。少了这个环视,前者会被误判成冲突、给出"重新读一次"的
66
+ // 无效建议(实测红过一条)。
67
+ /(EXISTS|_TAKEN|ALREADY_|CONFLICT|STILL_|IN_FLIGHT|(?<!MAX_)CONCURRENT|STALE|IMMUTABLE|_TERMINAL|_PAUSED|LAST_ADMIN|SELF_DELETE|AWAITING_|_NOT_PENDING)/,
68
+ ],
69
+ [
70
+ 'validation',
71
+ /(INVALID|VALIDATION|_REQUIRED|_MISSING|_EMPTY|_UNCHANGED|UNSUPPORTED|OUT_OF_RANGE|_TOO_|_MALFORMED|_EXCLUSIVE|_MISMATCH|_INCORRECT|_NOT_OBJECT|_NOT_ZIP|_NOT_ARCHIVE|_BLOCKED|SSRF|PASSWORD|NOT_SEMVER|DEPENDENCY)/,
72
+ ],
73
+ ];
74
+ /**
75
+ * 稳定码 → 类别;未知码 / 非字符串 / 空串 → `null`(调用方据此保持现状)。
76
+ *
77
+ * 只做命名约定匹配,**不维护码表清单**:新增码只要沿用约定就自动归类,
78
+ * 不沿用则安全地落到「未知」分支(不猜、不误导)。
79
+ */
80
+ export function classifyErrorCode(errorCode) {
81
+ if (typeof errorCode !== 'string' || errorCode.length === 0)
82
+ return null;
83
+ const code = errorCode.toUpperCase();
84
+ for (const [category, pattern] of CATEGORY_RULES) {
85
+ if (pattern.test(code))
86
+ return category;
87
+ }
88
+ return null;
89
+ }
90
+ /** 稳定码 → 一句话处置建议;未知码 / 无码 → `null`。 */
91
+ export function hintForErrorCode(errorCode) {
92
+ const category = classifyErrorCode(errorCode);
93
+ return category === null ? null : CATEGORY_HINTS[category];
94
+ }
95
+ /** 从错误响应体里抽人读文案(`message` / class-validator 的 `message[]` / `error`)。 */
96
+ export function messageFromData(data) {
97
+ if (!data || typeof data !== 'object')
98
+ return '';
99
+ const d = data;
100
+ const m = d.message;
101
+ // QA-07 契约:空串 message 视为「未提供」,继续走 message[]/error 兜底
102
+ //(与 mcp-server extractDetail 对齐;此前空串 message 会遮蔽 error 字段)。
103
+ if (typeof m === 'string' && m)
104
+ return m;
105
+ if (Array.isArray(m) && m.length)
106
+ return m.map(String).join('; ');
107
+ if (typeof d.error === 'string' && d.error)
108
+ return d.error;
109
+ return '';
110
+ }
111
+ function isPlainObject(value) {
112
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
113
+ }
114
+ /**
115
+ * 从任意抛出的值里抽出可机读的错误面。
116
+ *
117
+ * 三种来源都要吃(CLI 一条链路上都会出现):
118
+ * - axios 错误:`err.response.data` 是 admin-api 的错误体;
119
+ * - node SDK 标记过的错误:`errorCode` / `params` 直接挂在 Error 上
120
+ * (packages/autocodeflow-node-sdk 的 attachErrorCode),没有 response;
121
+ * - 直接抛的普通对象(本地派生错误 / 测试桩)。
122
+ */
123
+ export function extractApiErrorInfo(e) {
124
+ if (e === null || typeof e !== 'object')
125
+ return {};
126
+ const err = e;
127
+ const data = err.response?.data;
128
+ const body = isPlainObject(data) ? data : undefined;
129
+ const info = {};
130
+ const responseStatus = err.response?.status;
131
+ if (typeof responseStatus === 'number') {
132
+ info.status = responseStatus;
133
+ }
134
+ else if (body && typeof body.code === 'number') {
135
+ // 响应体里的数值 code 就是 HTTP 状态(admin-api 的过滤器如此写)
136
+ info.status = body.code;
137
+ }
138
+ // 稳定码:先看响应体(管理员侧真值源),再看错误对象自身(SDK 透传 / 直接抛出)
139
+ const bodyCode = body?.errorCode;
140
+ const ownCode = err.errorCode;
141
+ const errorCode = typeof bodyCode === 'string' && bodyCode
142
+ ? bodyCode
143
+ : typeof ownCode === 'string' && ownCode
144
+ ? ownCode
145
+ : undefined;
146
+ if (errorCode !== undefined)
147
+ info.errorCode = errorCode;
148
+ // 插值参数:同上优先级(响应体优先),非普通对象一律丢弃
149
+ const params = isPlainObject(body?.params)
150
+ ? body?.params
151
+ : isPlainObject(err.params)
152
+ ? err.params
153
+ : undefined;
154
+ if (params !== undefined)
155
+ info.params = params;
156
+ const message = messageFromData(body);
157
+ if (message) {
158
+ info.message = message;
159
+ }
160
+ else if (typeof err.message === 'string' && err.message) {
161
+ info.message = err.message;
162
+ }
163
+ return info;
164
+ }
165
+ /**
166
+ * 在既有的人读文案后追加「[码] — 一句话处置」;**未知码 / 无码原样返回**。
167
+ *
168
+ * 之所以把码本身也打出来:用户报障时贴一行就够定位(不必再开 --json),
169
+ * 而这个码正是 README/文档里能搜到的稳定标识。
170
+ */
171
+ export function appendErrorCodeHint(base, e) {
172
+ const { errorCode } = extractApiErrorInfo(e);
173
+ const hint = hintForErrorCode(errorCode);
174
+ if (errorCode === undefined || hint === null)
175
+ return base;
176
+ return `${base} [${errorCode}] — ${hint}`;
177
+ }
package/dist/ui.d.ts CHANGED
@@ -26,20 +26,45 @@ export declare class UsageError extends Error {
26
26
  }
27
27
  /** spinner 的最小结构面(ora 实例天然满足),避免 ui 层反向依赖 ora。 */
28
28
  interface Failable {
29
- fail(message?: string): unknown;
29
+ fail?(message?: string): unknown;
30
+ /** `--json` 失败时用它收尾:不能把 "✗ scope" 这行人读文本写进 JSON stderr。 */
31
+ stop?(): unknown;
30
32
  }
31
33
  /**
32
34
  * Map a thrown error to its exit code. `UsageError`(本地用法错误)优先——
33
35
  * 它不是 axios 错误,若先走 classifyApiError 会被误归为 GENERIC。
34
36
  */
35
37
  export declare function exitCodeFor(e: unknown): number;
38
+ /**
39
+ * 当前进程是不是 `--json` 调用(决定失败时给人读文案还是结构化 JSON)。
40
+ *
41
+ * 为什么读 argv 而不是让 70 多个 `emitError` 调用点各自传 opts.json:那些
42
+ * 调用点分布在 10 个命令文件里、且多数 catch 块拿不到 opts(action 形参各不
43
+ * 相同),逐个补参既是一次大 diff,也必然漏掉几处(漏一处就是"某个命令的
44
+ * --json 错误不是 JSON")。argv 是**唯一**能覆盖全部出口的位置。
45
+ */
46
+ export declare function isJsonInvocation(argv?: readonly string[]): boolean;
47
+ /**
48
+ * `--json` 失败时的结构化错误体(字段名与 admin-api 错误响应体对齐:
49
+ * `code` = HTTP 状态、`errorCode` = 稳定码、`params` = 插值参数)。
50
+ *
51
+ * 只写入**存在**的键(无码时不出现 `errorCode`),脚本用 `!== undefined`
52
+ * 或 `in` 都能可靠判断;`exitCode` 与进程真实退出码同源(exitCodeFor)。
53
+ */
54
+ export declare function apiErrorToJson(scope: string, e: unknown): Record<string, unknown>;
36
55
  /**
37
56
  * 统一错误出口。有 spinner 时 `spinner.fail(scope)`(失败行与进行中的转圈
38
57
  * 原位收尾);无 spinner 时打 `✗ scope`。错误详情一律走 formatApiError,
39
58
  * 保证 401/网络/后端 message 的呈现全 CLI 一致。
59
+ *
60
+ * R31-E1: `--json` 调用(或显式 `opts.json`)改为往 **stderr** 打一行结构化
61
+ * JSON(含 `errorCode` / `params` / `code` / `exitCode`),stdout 仍只留
62
+ * 成功载荷(CI 的 `| jq` 不被污染);无码时该键不出现,其余语义(退出码、
63
+ * 人类可读输出的文案)完全不变。
40
64
  */
41
65
  export declare function emitError(scope: string, e: unknown, opts?: {
42
66
  spinner?: Failable;
67
+ json?: boolean;
43
68
  }): never;
44
69
  /**
45
70
  * 本地用法错误出口(不涉及 API 调用)。第二条提示固定指向 `--help`——
package/dist/ui.js CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import chalk from 'chalk';
12
12
  import { classifyApiError, formatApiError } from './client.js';
13
+ import { classifyErrorCode, extractApiErrorInfo } from './error-code.js';
13
14
  /**
14
15
  * CLI 退出码表(README.md「Exit codes」为同一张表的人读版,两处必须同步改):
15
16
  * 0 成功(含 --help / --version)
@@ -52,19 +53,68 @@ export function exitCodeFor(e) {
52
53
  return EXIT_CODES.GENERIC;
53
54
  }
54
55
  }
56
+ /**
57
+ * 当前进程是不是 `--json` 调用(决定失败时给人读文案还是结构化 JSON)。
58
+ *
59
+ * 为什么读 argv 而不是让 70 多个 `emitError` 调用点各自传 opts.json:那些
60
+ * 调用点分布在 10 个命令文件里、且多数 catch 块拿不到 opts(action 形参各不
61
+ * 相同),逐个补参既是一次大 diff,也必然漏掉几处(漏一处就是"某个命令的
62
+ * --json 错误不是 JSON")。argv 是**唯一**能覆盖全部出口的位置。
63
+ */
64
+ export function isJsonInvocation(argv = process.argv) {
65
+ return argv.slice(2).includes('--json');
66
+ }
67
+ /**
68
+ * `--json` 失败时的结构化错误体(字段名与 admin-api 错误响应体对齐:
69
+ * `code` = HTTP 状态、`errorCode` = 稳定码、`params` = 插值参数)。
70
+ *
71
+ * 只写入**存在**的键(无码时不出现 `errorCode`),脚本用 `!== undefined`
72
+ * 或 `in` 都能可靠判断;`exitCode` 与进程真实退出码同源(exitCodeFor)。
73
+ */
74
+ export function apiErrorToJson(scope, e) {
75
+ const info = extractApiErrorInfo(e);
76
+ const category = classifyErrorCode(info.errorCode);
77
+ const payload = { ok: false, scope };
78
+ if (info.status !== undefined)
79
+ payload['code'] = info.status;
80
+ if (info.errorCode !== undefined)
81
+ payload['errorCode'] = info.errorCode;
82
+ if (category !== null)
83
+ payload['category'] = category;
84
+ if (info.params !== undefined)
85
+ payload['params'] = info.params;
86
+ payload['message'] =
87
+ info.message ?? (e instanceof Error ? e.message : String(e));
88
+ payload['exitCode'] = exitCodeFor(e);
89
+ return payload;
90
+ }
55
91
  /**
56
92
  * 统一错误出口。有 spinner 时 `spinner.fail(scope)`(失败行与进行中的转圈
57
93
  * 原位收尾);无 spinner 时打 `✗ scope`。错误详情一律走 formatApiError,
58
94
  * 保证 401/网络/后端 message 的呈现全 CLI 一致。
95
+ *
96
+ * R31-E1: `--json` 调用(或显式 `opts.json`)改为往 **stderr** 打一行结构化
97
+ * JSON(含 `errorCode` / `params` / `code` / `exitCode`),stdout 仍只留
98
+ * 成功载荷(CI 的 `| jq` 不被污染);无码时该键不出现,其余语义(退出码、
99
+ * 人类可读输出的文案)完全不变。
59
100
  */
60
101
  export function emitError(scope, e, opts = {}) {
61
- if (opts.spinner) {
62
- opts.spinner.fail(scope);
102
+ const json = opts.json ?? isJsonInvocation();
103
+ if (json) {
104
+ // 不调 fail(scope):那会把 "✗ scope" 这人读行混进 JSON stderr。
105
+ if (opts.spinner)
106
+ opts.spinner.stop?.();
107
+ console.error(JSON.stringify(apiErrorToJson(scope, e)));
63
108
  }
64
109
  else {
65
- console.error(chalk.red(`✗ ${scope}`));
110
+ if (opts.spinner) {
111
+ opts.spinner.fail?.(scope);
112
+ }
113
+ else {
114
+ console.error(chalk.red(`✗ ${scope}`));
115
+ }
116
+ console.error(chalk.red(formatApiError(e)));
66
117
  }
67
- console.error(chalk.red(formatApiError(e)));
68
118
  process.exit(exitCodeFor(e));
69
119
  }
70
120
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autocodeflow/cli",
3
- "version": "1.12.1",
3
+ "version": "1.14.0",
4
4
  "description": "AutoCodeFlow CLI — manage tasks, executions and applications from the terminal",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",