@autocodeflow/cli 1.7.0 → 1.8.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 ADDED
@@ -0,0 +1,70 @@
1
+ # @autocodeflow/cli
2
+
3
+ AutoCodeFlow CLI —— 在终端里管理任务、执行、应用、执行器与项目。
4
+
5
+ ```bash
6
+ npm i -g @autocodeflow/cli
7
+
8
+ acf login
9
+ acf task list --status active
10
+ acf task trigger <taskId> --wait
11
+ acf exec tail <execId>
12
+ ```
13
+
14
+ 每个命令(含每个子命令)都支持 `acf <命令> --help`:一行用途、参数表,以及
15
+ 至少一个可直接复制的示例。缺参 / 未知命令 / 未知选项时,报错行之后会紧跟该
16
+ 命令的完整帮助(含示例),不需要去翻文档。
17
+
18
+ ## 退出码
19
+
20
+ CLI 的非零退出码按失败类别区分,脚本/CI 可以只按码分支处理(所有非零码都
21
+ 代表失败,`!= 0` 的既有判断不受影响):
22
+
23
+ | 退出码 | 含义 | 典型场景 / 下一步动作 |
24
+ | --- | --- | --- |
25
+ | `0` | 成功 | 含 `--help` / `--version` / 主动放弃确认(`Aborted.`) |
26
+ | `1` | 运行失败 | 服务端拒绝(400/403/404/409/5xx,错误行透出后端 message);`--wait` 等到失败终态;`acf task lint` 检出语法错误 |
27
+ | `2` | 用法 / 参数错误 | 缺参、未知命令/选项、非法取值(如 `--wait-timeout abc`);本地 payload 问题(JSON 解析失败、`--file` 读不了、`task lint` 无法推断语言) |
28
+ | `3` | 认证失败 | 401:凭据缺失/过期且自动刷新失败 → 运行 `acf login` |
29
+ | `4` | 网络失败 | 连接不通 / 超时 / DNS → 检查 `--api-url`、`ACF_API_URL`;`acf exec tail` 流中断或空闲超时 |
30
+ | `130` | 中断(SIGINT) | Ctrl+C。输出会补一个换行,不留半行 spinner |
31
+
32
+ 单一事实源在 `src/ui.ts` 的 `EXIT_CODES`;错误分类(401/网络/服务端)在
33
+ `src/client.ts` 的 `classifyApiError` 做一次,命令层统一经 `emitError` 出口
34
+ 消费。
35
+
36
+ ## 机器可读输出(`--json`)
37
+
38
+ 所有只读命令都支持 `--json`(CI/脚本消费面,错误仍走 stderr + 非零退出码):
39
+
40
+ - 列表 / 信封形态(`task list`、`task executions`、`app list`、
41
+ `app deployments`、`executor list`、`sop list`、`agent sessions`、
42
+ `audit list`)→ 单行紧凑 JSON,信封(`{list|data|items, total}`)原样直出;
43
+ - 单对象 / 详情形态(`task get`、`task stats`、`task versions`、
44
+ `task compare`、`task logs`、`task trigger`、`app get`、`app versions`、
45
+ `executor get`、`sop show`、`project list`、`project members`)→
46
+ pretty(2) JSON。
47
+
48
+ `--json` 不裁剪字段:后端返回什么就输出什么,消费方按 `--help` 示例里的
49
+ 形状断言即可。
50
+
51
+ ## 认证与配置
52
+
53
+ 凭据保存在用户配置目录(`acf config show` 查看实际路径),文件权限 0600;
54
+ 文件损坏时 CLI 会把坏内容备份到 `<config>.corrupt`、给出 `acf login` 指引,
55
+ 并用默认配置继续运行。
56
+
57
+ - `ACF_TOKEN` / `ACF_REFRESH_TOKEN` / `ACF_API_URL`:环境变量注入(CI/cron
58
+ 推荐,不落盘);`--api-url` / `--token` 可单次覆盖。
59
+ - `acf login` 的密码输入不回显;`--password` 参数已标记 deprecated(会进
60
+ shell history),CI 请用 `ACF_PASSWORD`。
61
+ - Access token 过期时自动用 refresh token 换发并重放一次;刷新失败才要求
62
+ 重新登录(此时退出码为 3)。
63
+
64
+ ## 开发
65
+
66
+ ```bash
67
+ npm run test # vitest run
68
+ npm run typecheck # tsc --noEmit
69
+ npm run build # tsc → dist/
70
+ ```
package/dist/client.d.ts CHANGED
@@ -15,6 +15,25 @@ export declare function post<T>(path: string, body?: unknown, timeoutMs?: number
15
15
  export declare function put<T>(path: string, body?: unknown): Promise<T>;
16
16
  export declare function patch<T>(path: string, body?: unknown): Promise<T>;
17
17
  export declare function del<T>(path: string): Promise<T>;
18
+ /**
19
+ * Error class taxonomy shared by the whole CLI. Classification is done ONCE,
20
+ * here at the HTTP-client layer (the only place that knows axios shapes), so
21
+ * the ten command files never re-implement it. `formatApiError` renders the
22
+ * human line; `classifyApiError` feeds the machine-facing exit code.
23
+ */
24
+ export type ApiErrorClass = "auth" | "network" | "server" | "unknown";
25
+ /**
26
+ * Classify any thrown error for exit-code mapping:
27
+ * - `auth` → 401 (credentials missing/expired/invalid, refresh self-heal
28
+ * already failed) — the user must re-run `acf login`;
29
+ * - `network` → axios error without an HTTP response (connection refused,
30
+ * DNS, timeout) — the server was never reached;
31
+ * - `server` → any other HTTP status (400/403/404/409/5xx) — the request
32
+ * reached the API and was rejected; permission gaps (403) are a server-side
33
+ * decision, not a local credential state, so they stay in this class;
34
+ * - `unknown` → non-axios errors (local file IO, JSON parsing, ...).
35
+ */
36
+ export declare function classifyApiError(e: unknown): ApiErrorClass;
18
37
  /**
19
38
  * Render any thrown error as a single readable line, distinguishing
20
39
  * 401 (not authenticated) from 403 (authenticated but not allowed) and
package/dist/client.js CHANGED
@@ -166,6 +166,28 @@ function detailFromData(data) {
166
166
  return d.error;
167
167
  return "";
168
168
  }
169
+ /**
170
+ * Classify any thrown error for exit-code mapping:
171
+ * - `auth` → 401 (credentials missing/expired/invalid, refresh self-heal
172
+ * already failed) — the user must re-run `acf login`;
173
+ * - `network` → axios error without an HTTP response (connection refused,
174
+ * DNS, timeout) — the server was never reached;
175
+ * - `server` → any other HTTP status (400/403/404/409/5xx) — the request
176
+ * reached the API and was rejected; permission gaps (403) are a server-side
177
+ * decision, not a local credential state, so they stay in this class;
178
+ * - `unknown` → non-axios errors (local file IO, JSON parsing, ...).
179
+ */
180
+ export function classifyApiError(e) {
181
+ if (axios.isAxiosError(e)) {
182
+ const status = e.response?.status;
183
+ if (!status)
184
+ return "network";
185
+ if (status === 401)
186
+ return "auth";
187
+ return "server";
188
+ }
189
+ return "unknown";
190
+ }
169
191
  /**
170
192
  * Render any thrown error as a single readable line, distinguishing
171
193
  * 401 (not authenticated) from 403 (authenticated but not allowed) and
@@ -2,7 +2,8 @@ import { Command } from 'commander';
2
2
  import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
- import { get, formatApiError } from '../client.js';
5
+ import { get } from '../client.js';
6
+ import { emitError } from '../ui.js';
6
7
  export function agentCommand() {
7
8
  const cmd = new Command('agent').description('Inspect agent sessions');
8
9
  // acf agent sessions
@@ -12,6 +13,8 @@ export function agentCommand() {
12
13
  .option('--status <status>', 'Filter by status (pending | running | waiting_input | succeeded | failed | aborted)')
13
14
  .option('-p, --page <n>', 'Page number', '1')
14
15
  .option('-n, --page-size <n>', 'Page size (max 100)', '20')
16
+ // --json 补面(本轮 UX 统一):对齐 audit list 的信封直出口径
17
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
15
18
  .action(async (opts) => {
16
19
  const spinner = ora('Fetching agent sessions…').start();
17
20
  try {
@@ -22,6 +25,10 @@ export function agentCommand() {
22
25
  status: opts.status,
23
26
  });
24
27
  spinner.stop();
28
+ if (opts.json) {
29
+ console.log(JSON.stringify(data));
30
+ return;
31
+ }
25
32
  const items = data.items ?? data.data ?? [];
26
33
  const table = new Table({
27
34
  head: ['Time', 'Kind', 'Status', 'Title', 'ID'],
@@ -41,9 +48,7 @@ export function agentCommand() {
41
48
  console.log(chalk.gray(`Total: ${data.total ?? items.length} page ${opts.page}`));
42
49
  }
43
50
  catch (e) {
44
- spinner.fail('Failed to list agent sessions');
45
- console.error(chalk.red(formatApiError(e)));
46
- process.exit(1);
51
+ emitError('Failed to list agent sessions', e, { spinner });
47
52
  }
48
53
  });
49
54
  return cmd;
@@ -2,7 +2,8 @@ import { Command } from 'commander';
2
2
  import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
- import { get, post, put, del, formatApiError, ANALYZE_TIMEOUT_MS } from '../client.js';
5
+ import { get, post, put, del, ANALYZE_TIMEOUT_MS } from '../client.js';
6
+ import { emitError, UsageError, interruptExit } from '../ui.js';
6
7
  function statusColor(s) {
7
8
  if (s === 'running')
8
9
  return chalk.green(s);
@@ -17,15 +18,23 @@ function statusColor(s) {
17
18
  /** Load a JSON payload from --file (preferred) or --json. */
18
19
  async function loadJsonBody(json, file) {
19
20
  const fs = await import('fs/promises');
20
- const raw = file ? await fs.readFile(file, 'utf-8') : json;
21
+ // 本地 payload 层错误(文件读不了/JSON 坏)= 用法错误(退出码 2),与
22
+ // 服务端拒绝(1)区分;tasks.ts 的 create/update 同口径。
23
+ let raw;
24
+ try {
25
+ raw = file ? await fs.readFile(file, 'utf-8') : json;
26
+ }
27
+ catch (err) {
28
+ throw new UsageError(`Cannot read payload file: ${file} (${err instanceof Error ? err.message : String(err)})`);
29
+ }
21
30
  if (raw === undefined) {
22
- throw new Error('Missing JSON payload (provide --json or --file)');
31
+ throw new UsageError('Missing JSON payload (provide --json or --file)');
23
32
  }
24
33
  try {
25
34
  return JSON.parse(raw);
26
35
  }
27
36
  catch (e) {
28
- throw new Error(`Invalid JSON payload: ${e instanceof Error ? e.message : String(e)}`);
37
+ throw new UsageError(`Invalid JSON payload: ${e instanceof Error ? e.message : String(e)}`);
29
38
  }
30
39
  }
31
40
  export function appsCommand() {
@@ -63,19 +72,23 @@ export function appsCommand() {
63
72
  console.log(table.toString());
64
73
  }
65
74
  catch (e) {
66
- spinner.fail('Failed to list applications');
67
- console.error(chalk.red(formatApiError(e)));
68
- process.exit(1);
75
+ emitError('Failed to list applications', e, { spinner });
69
76
  }
70
77
  });
71
78
  // acf app get <id>
72
79
  cmd.command('get <id>')
73
80
  .description('Show application details')
74
- .action(async (id) => {
81
+ // --json 补面(本轮 UX 统一):单对象形态 → pretty JSON
82
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
83
+ .action(async (id, opts) => {
75
84
  const spinner = ora('Fetching application…').start();
76
85
  try {
77
86
  const a = await get(`/applications/${id}`);
78
87
  spinner.stop();
88
+ if (opts.json) {
89
+ console.log(JSON.stringify(a, null, 2));
90
+ return;
91
+ }
79
92
  console.log(chalk.bold('Application Details'));
80
93
  console.log(' ID :', a.id);
81
94
  console.log(' Name :', a.name);
@@ -90,9 +103,7 @@ export function appsCommand() {
90
103
  console.log(' Description :', a.description ?? '-');
91
104
  }
92
105
  catch (e) {
93
- spinner.fail('Failed');
94
- console.error(chalk.red(formatApiError(e)));
95
- process.exit(1);
106
+ emitError('Failed', e, { spinner });
96
107
  }
97
108
  });
98
109
  // acf app create
@@ -109,9 +120,7 @@ export function appsCommand() {
109
120
  console.log(chalk.gray(` name: ${a.name} version: ${a.version ?? '-'} status: ${statusColor(a.status)}`));
110
121
  }
111
122
  catch (e) {
112
- spinner.fail('Failed to create application');
113
- console.error(chalk.red(formatApiError(e)));
114
- process.exit(1);
123
+ emitError('Failed to create application', e, { spinner });
115
124
  }
116
125
  });
117
126
  // acf app update <id>
@@ -129,7 +138,8 @@ export function appsCommand() {
129
138
  // API would answer 400 "property name should not exist". Fail early
130
139
  // with an actionable message instead.
131
140
  if (body && typeof body === 'object' && 'name' in body) {
132
- throw new Error('Application update does not support renaming: the backend UpdateApplicationDto has no `name` field. ' +
141
+ // 本地 payload 语义错误 = 用法错误(退出码 2),不必等服务端 400。
142
+ throw new UsageError('Application update does not support renaming: the backend UpdateApplicationDto has no `name` field. ' +
133
143
  'Remove "name" from the payload.');
134
144
  }
135
145
  const a = await put(`/applications/${id}`, body);
@@ -137,9 +147,7 @@ export function appsCommand() {
137
147
  console.log(chalk.gray(` name: ${a.name} version: ${a.version ?? '-'} status: ${statusColor(a.status)}`));
138
148
  }
139
149
  catch (e) {
140
- spinner.fail('Failed to update application');
141
- console.error(chalk.red(formatApiError(e)));
142
- process.exit(1);
150
+ emitError('Failed to update application', e, { spinner });
143
151
  }
144
152
  });
145
153
  // acf app delete <id>
@@ -150,6 +158,9 @@ export function appsCommand() {
150
158
  if (!opts.yes) {
151
159
  const readline = await import('readline/promises');
152
160
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
161
+ // raw 模式下 Ctrl+C 触发 rl 'SIGINT' 而非进程信号;无监听只会 pause,
162
+ // 确认提示处会假死。接住并走统一中断出口(130)。
163
+ rl.on('SIGINT', () => interruptExit());
153
164
  const answer = await rl.question(`Delete application ${id}? [y/N] `);
154
165
  rl.close();
155
166
  if (!/^y(es)?$/i.test(answer)) {
@@ -163,9 +174,7 @@ export function appsCommand() {
163
174
  spinner.succeed(`Application ${id} deleted`);
164
175
  }
165
176
  catch (e) {
166
- spinner.fail('Failed to delete application');
167
- console.error(chalk.red(formatApiError(e)));
168
- process.exit(1);
177
+ emitError('Failed to delete application', e, { spinner });
169
178
  }
170
179
  });
171
180
  // acf app analyze <id>
@@ -190,9 +199,7 @@ export function appsCommand() {
190
199
  console.log(result.analysis);
191
200
  }
192
201
  catch (e) {
193
- spinner.fail('Analysis failed');
194
- console.error(chalk.red(formatApiError(e)));
195
- process.exit(1);
202
+ emitError('Analysis failed', e, { spinner });
196
203
  }
197
204
  });
198
205
  // acf app deploy <id>
@@ -217,9 +224,7 @@ export function appsCommand() {
217
224
  console.log(chalk.gray(` deployment: ${dep?.id ?? '-'} status: ${dep?.status ?? '-'} executor: ${dep?.executorId ?? 'auto'}`));
218
225
  }
219
226
  catch (e) {
220
- spinner.fail('Deployment failed');
221
- console.error(chalk.red(formatApiError(e)));
222
- process.exit(1);
227
+ emitError('Deployment failed', e, { spinner });
223
228
  }
224
229
  });
225
230
  // acf app deployments [appId]
@@ -227,6 +232,8 @@ export function appsCommand() {
227
232
  .description('List deployments (optionally filtered by application)')
228
233
  .option('-p, --page <n>', 'Page number', '1')
229
234
  .option('-n, --page-size <n>', 'Page size', '20')
235
+ // --json 补面(本轮 UX 统一):列表/信封形态 → 单行紧凑 JSON
236
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
230
237
  .action(async (appId, opts) => {
231
238
  const spinner = ora('Fetching deployments…').start();
232
239
  try {
@@ -237,6 +244,10 @@ export function appsCommand() {
237
244
  pageSize: opts.pageSize,
238
245
  });
239
246
  spinner.stop();
247
+ if (opts.json) {
248
+ console.log(JSON.stringify(data));
249
+ return;
250
+ }
240
251
  const list = Array.isArray(data) ? data : (data.data ?? data.list ?? []);
241
252
  const table = new Table({
242
253
  head: ['Deployment', 'App', 'Executor', 'Status', 'RunMode'],
@@ -255,20 +266,24 @@ export function appsCommand() {
255
266
  console.log(table.toString());
256
267
  }
257
268
  catch (e) {
258
- spinner.fail('Failed to list deployments');
259
- console.error(chalk.red(formatApiError(e)));
260
- process.exit(1);
269
+ emitError('Failed to list deployments', e, { spinner });
261
270
  }
262
271
  });
263
272
  // acf app versions <id>
264
273
  cmd.command('versions <id>')
265
274
  .description('Show application version history')
266
- .action(async (id) => {
275
+ // --json 补面(本轮 UX 统一):数组形态 → pretty JSON
276
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
277
+ .action(async (id, opts) => {
267
278
  const spinner = ora('Fetching version history…').start();
268
279
  try {
269
280
  // getVersionHistory returns `commit` / `deployedAt` (no gitCommit / changeNote)
270
281
  const versions = await get(`/applications/${id}/versions`);
271
282
  spinner.stop();
283
+ if (opts.json) {
284
+ console.log(JSON.stringify(versions, null, 2));
285
+ return;
286
+ }
272
287
  const table = new Table({
273
288
  head: ['Version', 'Commit', 'Deployed', 'Status'],
274
289
  colWidths: [12, 14, 25, 12],
@@ -285,9 +300,7 @@ export function appsCommand() {
285
300
  console.log(table.toString());
286
301
  }
287
302
  catch (e) {
288
- spinner.fail('Failed to list versions');
289
- console.error(chalk.red(formatApiError(e)));
290
- process.exit(1);
303
+ emitError('Failed to list versions', e, { spinner });
291
304
  }
292
305
  });
293
306
  return cmd;
@@ -2,7 +2,8 @@ import { Command } from 'commander';
2
2
  import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
- import { get, formatApiError } from '../client.js';
5
+ import { get } from '../client.js';
6
+ import { emitError } from '../ui.js';
6
7
  function resultColor(r) {
7
8
  if (r === 'success')
8
9
  return chalk.green(r);
@@ -69,9 +70,7 @@ export function auditCommand() {
69
70
  console.log(chalk.gray(`Total: ${total} page ${opts.page}`));
70
71
  }
71
72
  catch (e) {
72
- spinner.fail('Failed to list audit logs');
73
- console.error(chalk.red(formatApiError(e)));
74
- process.exit(1);
73
+ emitError('Failed to list audit logs', e, { spinner });
75
74
  }
76
75
  });
77
76
  return cmd;
@@ -1,7 +1,8 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import ora from 'ora';
4
- import { post, formatApiError } from '../client.js';
4
+ import { post } from '../client.js';
5
+ import { emitError } from '../ui.js';
5
6
  export function deployCommand() {
6
7
  const cmd = new Command('deploy').description('Manage application deployments (upgrade / stop running instances)');
7
8
  // acf deploy upgrade <deploymentId>
@@ -16,9 +17,7 @@ export function deployCommand() {
16
17
  console.log(chalk.gray(` status: ${dep?.status ?? '-'} executor: ${dep?.executorId ?? '-'}`));
17
18
  }
18
19
  catch (e) {
19
- spinner.fail('Failed to trigger upgrade');
20
- console.error(chalk.red(formatApiError(e)));
21
- process.exit(1);
20
+ emitError('Failed to trigger upgrade', e, { spinner });
22
21
  }
23
22
  });
24
23
  // acf deploy stop <deploymentId>
@@ -33,9 +32,7 @@ export function deployCommand() {
33
32
  console.log(chalk.gray(` status: ${dep?.status ?? '-'}`));
34
33
  }
35
34
  catch (e) {
36
- spinner.fail('Failed to stop deployment');
37
- console.error(chalk.red(formatApiError(e)));
38
- process.exit(1);
35
+ emitError('Failed to stop deployment', e, { spinner });
39
36
  }
40
37
  });
41
38
  return cmd;
@@ -22,7 +22,7 @@ import axios from 'axios';
22
22
  import chalk from 'chalk';
23
23
  import { get, post } from '../client.js';
24
24
  import { getApiUrl } from '../config.js';
25
- import { formatApiError } from '../client.js';
25
+ import { emitError, EXIT_CODES } from '../ui.js';
26
26
  const TERMINAL = new Set(['success', 'failed', 'timeout', 'killed', 'cancelled']);
27
27
  /**
28
28
  * 增量 SSE 解析器:feed(chunk) → 完整消息数组。跨 chunk 半行/半消息安全;
@@ -147,7 +147,7 @@ export function execCommand() {
147
147
  clearTimeout(idleTimer);
148
148
  idleTimer = setTimeout(() => {
149
149
  process.stderr.write(chalk.red(`[tail] no data frame for ${IDLE_TIMEOUT_MS / 1000}s — the stream went silent; retry \`acf exec tail ${execId}\`.\n`));
150
- process.exit(1);
150
+ process.exit(EXIT_CODES.NETWORK);
151
151
  }, IDLE_TIMEOUT_MS);
152
152
  // unref:看门狗不得阻止进程在无其他活动句柄时退出(生产上流挂死
153
153
  // 不绑架退出;测试里不残留挂起定时器拖慢 vitest)。
@@ -179,7 +179,7 @@ export function execCommand() {
179
179
  process.stderr.write(chalk.red('[tail] log stream interrupted before a done frame — the execution may still be running. Retry with `acf exec tail ' +
180
180
  execId +
181
181
  '`.\n'));
182
- process.exitCode = 1;
182
+ process.exitCode = EXIT_CODES.NETWORK;
183
183
  });
184
184
  stream.on('error', (err) => {
185
185
  clearIdleTimer();
@@ -188,8 +188,7 @@ export function execCommand() {
188
188
  });
189
189
  }
190
190
  catch (e) {
191
- console.error(chalk.red('✗ tail failed:'), formatApiError(e));
192
- process.exit(1);
191
+ emitError('tail failed', e);
193
192
  }
194
193
  });
195
194
  return cmd;
@@ -2,7 +2,8 @@ import { Command } from 'commander';
2
2
  import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
- import { get, post, formatApiError } from '../client.js';
5
+ import { get, post } from '../client.js';
6
+ import { emitError } from '../ui.js';
6
7
  function statusColor(s) {
7
8
  if (s === 'online')
8
9
  return chalk.green(s);
@@ -69,19 +70,23 @@ export function executorsCommand() {
69
70
  console.log(table.toString());
70
71
  }
71
72
  catch (e) {
72
- spinner.fail('Failed');
73
- console.error(chalk.red(formatApiError(e)));
74
- process.exit(1);
73
+ emitError('Failed to list executors', e, { spinner });
75
74
  }
76
75
  });
77
76
  // acf executor get <id>
78
77
  cmd.command('get <id>')
79
78
  .description('Show details of a single executor (config, status, metrics)')
80
- .action(async (id) => {
79
+ // --json 补面(本轮 UX 统一):单对象形态 → pretty JSON
80
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
81
+ .action(async (id, opts) => {
81
82
  const spinner = ora('Fetching executor…').start();
82
83
  try {
83
84
  const e = await get(`/executors/${id}`);
84
85
  spinner.stop();
86
+ if (opts.json) {
87
+ console.log(JSON.stringify(e, null, 2));
88
+ return;
89
+ }
85
90
  console.log(chalk.bold('Executor Details'));
86
91
  console.log(' ID :', e.id);
87
92
  console.log(' App Name :', e.appName ?? '-');
@@ -102,9 +107,7 @@ export function executorsCommand() {
102
107
  console.log(' Last Heartbeat :', e.lastHeartbeat ? `${new Date(e.lastHeartbeat).toLocaleString()} (${heartbeatAge(e.lastHeartbeat)})` : '-');
103
108
  }
104
109
  catch (e) {
105
- spinner.fail('Failed');
106
- console.error(chalk.red(formatApiError(e)));
107
- process.exit(1);
110
+ emitError('Failed to fetch executor', e, { spinner });
108
111
  }
109
112
  });
110
113
  // NF-07: name|id resolution — rotate/offline/set-offline are ADMIN-only
@@ -147,9 +150,7 @@ export function executorsCommand() {
147
150
  console.log(chalk.green(r?.token ?? ''));
148
151
  }
149
152
  catch (e) {
150
- spinner.fail('Failed to rotate token');
151
- console.error(chalk.red(formatApiError(e)));
152
- process.exit(1);
153
+ emitError('Failed to rotate token', e, { spinner });
153
154
  }
154
155
  });
155
156
  // acf executor offline <name|id>
@@ -167,9 +168,7 @@ export function executorsCommand() {
167
168
  console.log(chalk.gray(` status: ${e?.status ?? 'offline'} address: ${e?.address ?? '-'}`));
168
169
  }
169
170
  catch (e) {
170
- spinner.fail('Failed to mark executor offline');
171
- console.error(chalk.red(formatApiError(e)));
172
- process.exit(1);
171
+ emitError('Failed to mark executor offline', e, { spinner });
173
172
  }
174
173
  });
175
174
  return cmd;
@@ -1,2 +1,4 @@
1
1
  import { Command } from 'commander';
2
+ import * as readline from 'readline';
3
+ export declare function maskEcho(rl: readline.Interface, isTTY?: boolean): void;
2
4
  export declare function loginCommand(): Command;
@@ -1,35 +1,46 @@
1
1
  import { Command } from 'commander';
2
2
  import * as readline from 'readline';
3
- import { post, formatApiError } from '../client.js';
3
+ import { post, resetClient } from '../client.js';
4
4
  import { setApiUrl, setToken, setRefreshToken, showConfig } from '../config.js';
5
- import { resetClient } from '../client.js';
5
+ import { emitError, interruptExit } from '../ui.js';
6
6
  import chalk from 'chalk';
7
7
  function prompt(question) {
8
8
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
9
+ // readline 终端模式(raw mode)下 Ctrl+C 不产生进程级 SIGINT 信号,而是触发
10
+ // rl 的 'SIGINT' 事件;若无监听,readline 只是 pause,login 会假死不退。
11
+ // 这里显式接住,与全局中断出口同码(130)。
12
+ rl.on('SIGINT', () => interruptExit());
9
13
  return new Promise((resolve) => rl.question(question, (ans) => { rl.close(); resolve(ans); }));
10
14
  }
11
15
  // PK-27(DEEP_REVIEW 0ef3bbe):交互式密码输入必须隐藏回显(否则旁窥/录屏即泄漏)。
12
16
  // 用 readline 的 _writeToOutput 覆盖把回显吞掉——这是 Node 生态隐藏密码的标准做法,
13
17
  // 不引入额外依赖。TTY 非交互(CI/管道)时退化为普通 question(无回显需求,因为
14
18
  // 此时密码应来自 --password 或 ACF_PASSWORD env,而非人工键入)。
19
+ //
20
+ // UX 打磨(本轮):遮蔽逻辑抽成独立函数并导出——「密码不回显」是安全语义,
21
+ // 值得一个函数级不回显断言(ux-uniform.test.ts),内联在闭包里则测不到。
22
+ export function maskEcho(rl, isTTY = process.stdin.isTTY === true) {
23
+ if (!isTTY)
24
+ return;
25
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
26
+ const rlAny = rl;
27
+ const out = rlAny.output;
28
+ rlAny._writeToOutput = (str) => {
29
+ // 只回显提示符的换行,不回显键入字符;退格/回车照常处理。
30
+ if (str === '\n')
31
+ out.write('\n');
32
+ else if (str === '\r')
33
+ out.write('\n');
34
+ else
35
+ out.write('');
36
+ return '';
37
+ };
38
+ }
15
39
  function hiddenPrompt(question) {
16
40
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
17
- if (process.stdin.isTTY) {
18
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
- const rlAny = rl;
20
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
- const out = rlAny.output;
22
- rlAny._writeToOutput = (str) => {
23
- // 只回显提示符的换行,不回显键入字符;退格/回车照常处理。
24
- if (str === '\n')
25
- out.write('\n');
26
- else if (str === '\r')
27
- out.write('\n');
28
- else
29
- out.write('');
30
- return '';
31
- };
32
- }
41
+ // 同上:raw 模式 Ctrl+C 显式接住,避免密码输入中 Ctrl+C 假死。
42
+ rl.on('SIGINT', () => interruptExit());
43
+ maskEcho(rl);
33
44
  return new Promise((resolve) => rl.question(question, (ans) => {
34
45
  rl.close();
35
46
  resolve(ans);
@@ -78,8 +89,9 @@ export function loginCommand() {
78
89
  showConfig();
79
90
  }
80
91
  catch (e) {
81
- console.error(chalk.red('✗ Login failed:'), formatApiError(e));
82
- process.exit(1);
92
+ // 统一错误出口:401(密码错/token 失效)→ 退出码 3,网络不通 → 4,
93
+ // 其余 → 1(见 ui.ts 的 EXIT_CODES 表)。
94
+ emitError('Login failed', e);
83
95
  }
84
96
  });
85
97
  return cmd;
@@ -2,7 +2,8 @@ import { Command } from 'commander';
2
2
  import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
- import { get, formatApiError } from '../client.js';
5
+ import { get } from '../client.js';
6
+ import { emitError } from '../ui.js';
6
7
  const ROLE_COLOR = {
7
8
  admin: chalk.yellow,
8
9
  editor: chalk.cyan,
@@ -50,9 +51,7 @@ export function projectsCommand() {
50
51
  console.log(table.toString());
51
52
  }
52
53
  catch (e) {
53
- spinner.stop();
54
- console.error(chalk.red(formatApiError(e)));
55
- process.exitCode = 1;
54
+ emitError('Failed to list projects', e, { spinner });
56
55
  }
57
56
  });
58
57
  cmd
@@ -81,9 +80,7 @@ export function projectsCommand() {
81
80
  console.log(table.toString());
82
81
  }
83
82
  catch (e) {
84
- spinner.stop();
85
- console.error(chalk.red(formatApiError(e)));
86
- process.exitCode = 1;
83
+ emitError('Failed to list members', e, { spinner });
87
84
  }
88
85
  });
89
86
  return cmd;