@autocodeflow/cli 1.15.0 → 2.1.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.
@@ -5,6 +5,56 @@ import ora from 'ora';
5
5
  import { get, post } from '../client.js';
6
6
  import { emitError, emitUsageError } from '../ui.js';
7
7
  const LIST_STATUSES = ['pending', 'approved', 'rejected', 'cancelled'];
8
+ /**
9
+ * P2(本轮):审批回包里的 status 落在这些取值上,才算「已确认下发」。
10
+ *
11
+ * 为什么不能无条件 succeed:approve/reject/cancel 的 HTTP 回包来自审批动作
12
+ * 本身,真正的派发是 app-deployment.service.ts 里的
13
+ * `pushDeployToExecutor(...).catch(err => logger.error(...))` —— fire-and-
14
+ * forget。执行器离线、推送 4xx 时接口照样回 200,只是行停在 pending(没进
15
+ * deploying/upgrading)。旧实现在这里硬打 `✔ Deployment approved —
16
+ * dispatching to the executor` 并 exit 0,CI 的 `acf approval approve … && 验证`
17
+ * 就把「卡在待派发」读成「已部署」。
18
+ *
19
+ * DeploymentStatus 枚举(apps/admin-api …/app-deployment.entity.ts):
20
+ * pending | deploying | running | stopped | failed | upgrading。
21
+ */
22
+ const DISPATCH_CONFIRMED_STATUSES = new Set([
23
+ 'deploying',
24
+ 'running',
25
+ 'upgrading',
26
+ ]);
27
+ /** 回包状态是否证明「审批已生效且派发已被接受」。 */
28
+ function isDispatchConfirmed(dep) {
29
+ if (!dep)
30
+ return false;
31
+ return (dep.approvalStatus === 'approved' &&
32
+ DISPATCH_CONFIRMED_STATUSES.has(String(dep.status ?? '').toLowerCase()));
33
+ }
34
+ /**
35
+ * 审批拒绝/撤回的确认条件:动作生效(approvalStatus)且行确实落到 FAILED
36
+ * 终态(服务端 reject/cancel 都会把行置 FAILED,释放 in-flight 槽位)。
37
+ */
38
+ function isTerminalOutcome(dep, approvalStatus) {
39
+ if (!dep)
40
+ return false;
41
+ return (dep.approvalStatus === approvalStatus &&
42
+ String(dep.status ?? '').toLowerCase() === 'failed');
43
+ }
44
+ /**
45
+ * 「已受理但未确认」的统一收尾:warn(黄)说清现状 + 给出复核命令 + 退出码 1。
46
+ *
47
+ * 为什么退出码要 1:脚本对 `acf approval approve` 的唯一判据就是退出码。回包
48
+ * 没证明派发被接受时给 0,等于替执行器签了一张它没签的收据。
49
+ */
50
+ function warnNotConfirmed(id, dep, detail) {
51
+ const appId = dep?.applicationId ?? '<appId>';
52
+ console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
53
+ console.log(chalk.yellow(` ${detail}`));
54
+ console.log(chalk.yellow(` The request was accepted by the server but its response does not confirm the executor picked it up ` +
55
+ `(the push is fire-and-forget server-side). Verify with: acf app deployments ${appId}`));
56
+ process.exitCode = 1;
57
+ }
8
58
  function statusColor(s) {
9
59
  if (s === 'running')
10
60
  return chalk.green(s);
@@ -79,8 +129,15 @@ export function approvalCommand() {
79
129
  try {
80
130
  // ApprovalActionDto 白名单:{ reason? }(≤200)。未给 note 时不发 body。
81
131
  const dep = await post(`/app-deployments/${id}/approval/approve`, opts.note ? { reason: opts.note } : undefined);
82
- spinner.succeed('Deployment approved — dispatching to the executor');
83
- console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
132
+ if (isDispatchConfirmed(dep)) {
133
+ spinner.succeed('Deployment approved — dispatching to the executor');
134
+ console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
135
+ }
136
+ else {
137
+ // P2:回包只说「审批已受理」,没说「执行器已接单」。
138
+ spinner.warn('Deployment approved — dispatch NOT yet confirmed by the server response');
139
+ warnNotConfirmed(id, dep, 'The approval was recorded, but the response status does not confirm the dispatch started.');
140
+ }
84
141
  }
85
142
  catch (e) {
86
143
  emitError('Failed to approve deployment', e, { spinner });
@@ -97,8 +154,15 @@ export function approvalCommand() {
97
154
  const spinner = ora('Rejecting deployment…').start();
98
155
  try {
99
156
  const dep = await post(`/app-deployments/${id}/approval/reject`, opts.note ? { reason: opts.note } : undefined);
100
- spinner.succeed('Deployment rejected — nothing will be dispatched (row lands FAILED)');
101
- console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
157
+ if (isTerminalOutcome(dep, 'rejected')) {
158
+ spinner.succeed('Deployment rejected — nothing will be dispatched (row lands FAILED)');
159
+ console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
160
+ }
161
+ else {
162
+ // P2:拒绝的价值全在「行确实落 FAILED」。回包没证明这一点时不能谎报。
163
+ spinner.warn('Deployment rejection recorded — row is not confirmed FAILED');
164
+ warnNotConfirmed(id, dep, 'The rejection was recorded, but the row is not in the FAILED state the server normally sets.');
165
+ }
102
166
  }
103
167
  catch (e) {
104
168
  emitError('Failed to reject deployment', e, { spinner });
@@ -111,8 +175,15 @@ export function approvalCommand() {
111
175
  const spinner = ora('Cancelling pending request…').start();
112
176
  try {
113
177
  const dep = await post(`/app-deployments/${id}/approval/cancel`);
114
- spinner.succeed('Pending deployment request cancelled (row lands FAILED)');
115
- console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
178
+ if (isTerminalOutcome(dep, 'cancelled')) {
179
+ spinner.succeed('Pending deployment request cancelled (row lands FAILED)');
180
+ console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
181
+ }
182
+ else {
183
+ // P2:同上——撤回也必须看到行落 FAILED 才算数。
184
+ spinner.warn('Cancellation recorded — row is not confirmed FAILED');
185
+ warnNotConfirmed(id, dep, 'The withdrawal was recorded, but the row is not in the FAILED state the server normally sets.');
186
+ }
116
187
  }
117
188
  catch (e) {
118
189
  emitError('Failed to cancel deployment', e, { spinner });
@@ -330,6 +330,24 @@ export function appsCommand() {
330
330
  }
331
331
  }
332
332
  const dep = await post(`/app-deployments/applications/${id}/deploy`, body);
333
+ // F2(本轮审计):DEP-04 审批门打开时,后端返回 status=pending +
334
+ // approvalStatus=pending_approval 且**不下发**。旧实现无条件打印
335
+ // `✔ Deployment triggered` 并 exit 0 —— `acf app deploy && …` 会把
336
+ // 「冻结待审批、设备上什么都没跑」读成部署成功;该行还占着 in-flight
337
+ // 槽位,后续部署 409,调用方只看到"冲突"却不知道自己是在等审批。
338
+ // MCP 的 deploy_application 早已按此判定,CLI 漏了。
339
+ const awaitingApproval = dep?.approvalStatus === 'pending_approval' || dep?.status === 'pending';
340
+ if (awaitingApproval) {
341
+ spinner.warn('Deployment frozen pending approval — NOT dispatched yet');
342
+ console.log(chalk.gray(` deployment: ${dep?.id ?? '-'} status: ${dep?.status ?? '-'} ` +
343
+ `approval: ${dep?.approvalStatus ?? 'pending'} executor: ${dep?.executorId ?? 'auto'}`));
344
+ console.log(chalk.yellow(' This application requires a second-person approval. The code has NOT been deployed. ' +
345
+ 'Run `acf approval pending` to see it, or `acf approval approve <id> <deploymentId>` to release it.'));
346
+ // 非零退出:脚本里的 `acf app deploy … && 验证部署` 不能再把「等审批」
347
+ // 当成「已部署」。语义是"未完成",不是"参数错"(那是 2)。
348
+ process.exitCode = 1;
349
+ return;
350
+ }
333
351
  spinner.succeed('Deployment triggered');
334
352
  console.log(chalk.gray(` deployment: ${dep?.id ?? '-'} status: ${dep?.status ?? '-'} executor: ${dep?.executorId ?? 'auto'}`));
335
353
  }
@@ -4,6 +4,28 @@ import chalk from 'chalk';
4
4
  import ora from 'ora';
5
5
  import { get, post, del } from '../client.js';
6
6
  import { emitError, confirmDestructive } from '../ui.js';
7
+ /**
8
+ * 「已确认下发」的 status 取值(DeploymentStatus 枚举:pending | deploying |
9
+ * running | stopped | failed | upgrading)。
10
+ *
11
+ * 为什么需要它:upgrade/stop 的回包只证明**服务端受理了动作**,真正的推送是
12
+ * app-deployment.service.ts 里的 `pushDeployToExecutor(...).catch(logger.error)`
13
+ * —— fire-and-forget。执行器离线、推送 4xx 时回包照样 200,行可能还停在
14
+ * pending。旧实现无条件 `✔ Upgrade triggered` + exit 0,等于替执行器签收。
15
+ */
16
+ const DISPATCH_CONFIRMED_STATUSES = new Set([
17
+ 'deploying',
18
+ 'running',
19
+ 'upgrading',
20
+ ]);
21
+ /** admin-api 的停机送达契约前缀(app-deployment.service.ts STOP_NOT_DELIVERED_PREFIX)。 */
22
+ const STOP_NOT_DELIVERED_PREFIX = '[Stop not delivered] ';
23
+ /** 统一「已受理但未确认」收尾:黄字说现状 + 复核命令 + 退出码 1。 */
24
+ function warnNotConfirmed(detail, hintTarget) {
25
+ console.log(chalk.yellow(` ${detail}`));
26
+ console.log(chalk.yellow(` Verify with: acf app deployments ${hintTarget}`));
27
+ process.exitCode = 1;
28
+ }
7
29
  function statusColor(s) {
8
30
  if (s === 'running')
9
31
  return chalk.green(s);
@@ -75,8 +97,16 @@ export function deployCommand() {
75
97
  try {
76
98
  // POST /app-deployments/:id/upgrade — AppDeploymentController.upgrade
77
99
  const dep = await post(`/app-deployments/${deploymentId}/upgrade`);
78
- spinner.succeed(`Upgrade triggered for deployment ${deploymentId}`);
100
+ const status = String(dep?.status ?? '').toLowerCase();
79
101
  console.log(chalk.gray(` status: ${dep?.status ?? '-'} executor: ${dep?.executorId ?? '-'}`));
102
+ if (DISPATCH_CONFIRMED_STATUSES.has(status)) {
103
+ spinner.succeed(`Upgrade triggered for deployment ${deploymentId}`);
104
+ }
105
+ else {
106
+ // P2:回包没进 upgrading/deploying/running ⇒ 派发未确认。
107
+ spinner.warn(`Upgrade request accepted — dispatch NOT confirmed (status: ${dep?.status ?? '-'})`);
108
+ warnNotConfirmed('The server accepted the upgrade, but the response status does not confirm the executor picked it up.', dep?.applicationId ?? '<appId>');
109
+ }
80
110
  }
81
111
  catch (e) {
82
112
  emitError('Failed to trigger upgrade', e, { spinner });
@@ -90,8 +120,23 @@ export function deployCommand() {
90
120
  try {
91
121
  // POST /app-deployments/:id/stop — AppDeploymentController.stop
92
122
  const dep = await post(`/app-deployments/${deploymentId}/stop`);
93
- spinner.succeed(`Deployment ${deploymentId} stopped`);
123
+ const status = String(dep?.status ?? '').toLowerCase();
124
+ // 停机有两个事实:行转 STOPPED(回包 status)+信号是否送达(statusMessage
125
+ // 前缀,服务端 best-effort 失败时只写前缀、行照样 STOPPED)。两个都要确认
126
+ // 才敢说 "stopped",否则设备上的进程可能还在跑。
127
+ const delivered = !String(dep?.statusMessage ?? '').startsWith(STOP_NOT_DELIVERED_PREFIX);
94
128
  console.log(chalk.gray(` status: ${dep?.status ?? '-'}`));
129
+ if (status === 'stopped' && delivered) {
130
+ spinner.succeed(`Deployment ${deploymentId} stopped`);
131
+ }
132
+ else {
133
+ spinner.warn(status === 'stopped'
134
+ ? `Deployment ${deploymentId} row is STOPPED but the stop signal was NOT delivered`
135
+ : `Stop request accepted — row is not confirmed stopped (status: ${dep?.status ?? '-'})`);
136
+ warnNotConfirmed(status === 'stopped'
137
+ ? 'The row is stopped, but the executor never confirmed the stop signal — the process may still be running on the device.'
138
+ : 'The server accepted the stop, but the response status does not confirm the row reached STOPPED.', dep?.applicationId ?? '<appId>');
139
+ }
95
140
  }
96
141
  catch (e) {
97
142
  emitError('Failed to stop deployment', e, { spinner });
@@ -176,8 +176,14 @@ export function tasksCommand() {
176
176
  // 非正值直接报参数错误而不是静默回落默认值——CI 里写错单位(毫秒当秒)
177
177
  // 若被静默吞掉,长任务又会掉回「假超时假绿」的老坑。
178
178
  .option('--wait-timeout <seconds>', 'Max seconds to keep polling with --wait before giving up (default 600)', (v) => {
179
- const n = Number.parseInt(v, 10);
180
- if (!Number.isFinite(n) || n <= 0) {
179
+ // F5(本轮审计):`parseInt("1m")` = 1 —— 用户写 `1m`(本意 60 秒)
180
+ // 得到 1 秒,长任务立刻"假超时"并 exit 1,提示语还让人以为是任务卡住。
181
+ // 只接受纯数字(与同文件 intOption 同口径)。
182
+ if (!/^\d+$/.test(v.trim())) {
183
+ throw new InvalidArgumentError('must be a positive integer in seconds (e.g. 600); units like "10m" are not supported');
184
+ }
185
+ const n = Number(v.trim());
186
+ if (!Number.isSafeInteger(n) || n <= 0) {
181
187
  throw new InvalidArgumentError('must be a positive integer (seconds)');
182
188
  }
183
189
  return n;
@@ -51,7 +51,18 @@ const CATEGORY_RULES = [
51
51
  ],
52
52
  [
53
53
  'permission',
54
- /(FORBIDDEN|_DENIED|NOT_AUTHORIZED|_NOT_OWNER|NO_OWNER|NOT_MEMBER|NOT_VISIBLE|_SELF_ONLY|ADMIN_ONLY|_READONLY|PERMISSION|ROLE_)/,
54
+ // 2026-10-30(SEC-1 覆盖闸):补 `_REQUIRES_EXECUTOR_TOKEN`——
55
+ // `ARTIFACT_UPLOAD_REQUIRES_EXECUTOR_TOKEN`(403)说的是「你这条凭据不足以
56
+ // 证明你是该执行行的执行器」(共享令牌不携带身份 / 执行行没有地址锚点),
57
+ // 正确动作是**换一枚 per-executor 令牌或让管理员补身份**,不是 `acf login`
58
+ // (那条建议来自下面 auth 规则的裸 `TOKEN`,对机器面凭据完全无效)。
59
+ //
60
+ // 为什么只补这个后缀、而非泛化 `_REQUIRES_`:泛化会把三个**已在基线里的**
61
+ // 码一并改判且给错建议(`TASK_RUNTIME_VERSION_REQUIRES_PYTHON` /
62
+ // `TASK_CODE_SOURCE_ZIP_REQUIRES_APPLICATION` 是「改入参/换运行时」的校验类;
63
+ // `EVENT_SUBSCRIPTION_PRIVATE_NETWORK_REQUIRES_ADMIN` 才是权限类),并把基线
64
+ // 里那两条变成「已能归类」的反向红。故按**语义明确的后缀**归类。
65
+ /(FORBIDDEN|_DENIED|NOT_AUTHORIZED|_NOT_OWNER|NO_OWNER|NOT_MEMBER|NOT_VISIBLE|_SELF_ONLY|ADMIN_ONLY|_READONLY|PERMISSION|ROLE_|_REQUIRES_EXECUTOR_TOKEN)/,
55
66
  ],
56
67
  [
57
68
  'auth',
@@ -69,11 +80,20 @@ const CATEGORY_RULES = [
69
80
  // · `SOP_NOT_DEPRECATED`:不是归档态(无可恢复)
70
81
  // 两者都是**状态冲突**("重新读一次再决定"),不是入参错误。不加这两条
71
82
  // 时它们会落到「未知」分支:用户拿到码却没有任何下一步。
72
- /(EXISTS|_TAKEN|ALREADY_|CONFLICT|STILL_|IN_FLIGHT|(?<!MAX_)CONCURRENT|STALE|IMMUTABLE|_TERMINAL|_PAUSED|LAST_ADMIN|SELF_DELETE|AWAITING_|_NOT_PENDING|_HAS_ACTIVE_|_NOT_DEPRECATED)/,
83
+ // 2026-10-30(R108 覆盖闸):补 AI SOP 会话与幂等触发两组状态冲突——
84
+ // · `AI_SOP_TURN_IN_PROGRESS`(409:同一会话已有轮次在跑)、
85
+ // `AI_SOP_QUESTIONS_EXHAUSTED` / `AI_SOP_VIDEO_LIMIT`(400:会话级状态已到顶,
86
+ // 正确动作是开新会话/补关键信息,不是「改入参重试」);
87
+ // · `TASK_IDEMPOTENCY_REPLAY` / `TASK_IDEMPOTENCY_KEY_REUSED`(409:换新键或
88
+ // 复用原参数)。注意**不能**写成裸 `IDEMPOTENCY`——那会把
89
+ // `TASK_IDEMPOTENCY_KEY_INVALID`(400,入参非法)误判成冲突。
90
+ /(EXISTS|_TAKEN|ALREADY_|CONFLICT|STILL_|IN_FLIGHT|(?<!MAX_)CONCURRENT|STALE|IMMUTABLE|_TERMINAL|_PAUSED|LAST_ADMIN|SELF_DELETE|AWAITING_|_NOT_PENDING|_HAS_ACTIVE_|_NOT_DEPRECATED|_TURN_IN_PROGRESS|_QUESTIONS_EXHAUSTED|_SOP_VIDEO_LIMIT|IDEMPOTENCY_(?:REPLAY|KEY_REUSED))/,
73
91
  ],
74
92
  [
75
93
  'validation',
76
- /(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)/,
94
+ // `_NO_INPUT`(AI_SOP_NO_INPUT:既没文字也没视频)/ `_TYPE_NOT_ALLOWED`
95
+ // (AI_MEDIA_TYPE_NOT_ALLOWED:格式白名单)都是「改入参就能过」,属校验类。
96
+ /(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|_NO_INPUT|_TYPE_NOT_ALLOWED)/,
77
97
  ],
78
98
  ];
79
99
  /**
package/dist/ui.d.ts CHANGED
@@ -42,6 +42,10 @@ export declare function exitCodeFor(e: unknown): number;
42
42
  * 调用点分布在 10 个命令文件里、且多数 catch 块拿不到 opts(action 形参各不
43
43
  * 相同),逐个补参既是一次大 diff,也必然漏掉几处(漏一处就是"某个命令的
44
44
  * --json 错误不是 JSON")。argv 是**唯一**能覆盖全部出口的位置。
45
+ *
46
+ * P3(本轮):只认**独立选项 token**——① `--opt=value` 是单 token 形态(值不
47
+ * 会独立成 token,`--json=false` 也因此保持既有「非 JSON 模式」语义);② 取
48
+ * 值型选项后面的那个 token 是值,跳过。
45
49
  */
46
50
  export declare function isJsonInvocation(argv?: readonly string[]): boolean;
47
51
  /**
package/dist/ui.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * - spinner 的 scope 文案由调用方传入,保持各命令既有的失败措辞。
10
10
  */
11
11
  import chalk from 'chalk';
12
+ import { writeSync } from 'node:fs';
12
13
  import { classifyApiError, formatApiError } from './client.js';
13
14
  import { classifyErrorCode, extractApiErrorInfo } from './error-code.js';
14
15
  /**
@@ -53,6 +54,28 @@ export function exitCodeFor(e) {
53
54
  return EXIT_CODES.GENERIC;
54
55
  }
55
56
  }
57
+ /**
58
+ * 取值型选项(`option('<flag> <placeholder>')` 形态,值是一段任意字符串)。
59
+ *
60
+ * 为什么要这张表:`--json` 只有作为**独立开关 token** 才代表「JSON 输出模
61
+ * 式」。而 `--description <text>` / `--note <text>` / `--body <json>` 的取值
62
+ * 完全可能是字面量 `--json`(`acf task update t1 --description '--json'`),
63
+ * 旧实现 `argv.includes('--json')` 会把这种取值当成开关,整条 CLI 的错误输出
64
+ * 面就从人读文案翻成 JSON。
65
+ *
66
+ * 只列**长**选项与单字母短选项;`--flag=value` 由调用方按 `=` 跳过(见下)。
67
+ * 新增取值型选项时同步补这里(漏补只会回到旧行为,不会破坏既有调用)。
68
+ */
69
+ const VALUE_TAKING_OPTIONS = new Set([
70
+ '-a', '-e', '-f', '-k', '-m', '-n', '-o', '-p', '-s',
71
+ '--action', '--api-url', '--application', '--body', '--code',
72
+ '--description', '--end-time', '--env', '--executor', '--executors',
73
+ '--file', '--from-line', '--ids', '--kind', '--keyword', '--language',
74
+ '--limit', '--name', '--note', '--output', '--page', '--page-size',
75
+ '--params', '--password', '--reason', '--resource', '--runtime', '--scope',
76
+ '--search', '--start-command', '--start-time', '--status', '--strategy',
77
+ '--tail', '--token', '--url', '--user', '--user-id', '--username', '--version',
78
+ ]);
56
79
  /**
57
80
  * 当前进程是不是 `--json` 调用(决定失败时给人读文案还是结构化 JSON)。
58
81
  *
@@ -60,9 +83,52 @@ export function exitCodeFor(e) {
60
83
  * 调用点分布在 10 个命令文件里、且多数 catch 块拿不到 opts(action 形参各不
61
84
  * 相同),逐个补参既是一次大 diff,也必然漏掉几处(漏一处就是"某个命令的
62
85
  * --json 错误不是 JSON")。argv 是**唯一**能覆盖全部出口的位置。
86
+ *
87
+ * P3(本轮):只认**独立选项 token**——① `--opt=value` 是单 token 形态(值不
88
+ * 会独立成 token,`--json=false` 也因此保持既有「非 JSON 模式」语义);② 取
89
+ * 值型选项后面的那个 token 是值,跳过。
63
90
  */
64
91
  export function isJsonInvocation(argv = process.argv) {
65
- return argv.slice(2).includes('--json');
92
+ const args = argv.slice(2);
93
+ for (let i = 0; i < args.length; i += 1) {
94
+ const token = args[i];
95
+ if (token.includes('='))
96
+ continue;
97
+ if (VALUE_TAKING_OPTIONS.has(token)) {
98
+ i += 1; // 跳过该选项的值(即便它字面量是 "--json")
99
+ continue;
100
+ }
101
+ if (token === '--json')
102
+ return true;
103
+ }
104
+ return false;
105
+ }
106
+ /**
107
+ * 把一行文本**同步**写到 stderr(fd 2,短写自动续写)。
108
+ *
109
+ * 为什么不用 `console.error` / `process.stderr.write`:二者是流写入,在管道
110
+ * 或文件(非阻塞/异步队列)下,紧随其后的 `process.exit()` 会丢掉尚未 flush
111
+ * 的尾部——`--json` 的机读契约(stderr 必须是一行可 parse 的 JSON)随之破
112
+ * 裂。`writeSync` 把字节直接交给内核,退出前必定落地。
113
+ *
114
+ * 为什么不干脆只用 `process.exitCode`(exec.ts / tasks.ts 的口径):错误出口
115
+ * 必须**同步终止**调用方的 action —— tasks.ts 的 `--wait` 轮询在 catch 里调
116
+ * emitError 表示「确定性失败,别再轮询」,若它只是返回,401 会被轮询拖成
117
+ * 「超时」。因此保留 exit,但把写操作换成不可丢的同步写。
118
+ */
119
+ function writeStderrSyncLine(line) {
120
+ const fd = typeof process.stderr.fd === 'number' ? process.stderr.fd : 2;
121
+ const buf = Buffer.from(`${line}\n`, 'utf8');
122
+ let offset = 0;
123
+ try {
124
+ while (offset < buf.length) {
125
+ offset += writeSync(fd, buf, offset, buf.length - offset);
126
+ }
127
+ }
128
+ catch {
129
+ // stderr 已关闭(EPIPE/EBADF):还能怎样,按原退出码收场即可——不能让
130
+ // 错误出口自己抛异常,那会把退出码改写成 1。
131
+ }
66
132
  }
67
133
  /**
68
134
  * `--json` 失败时的结构化错误体(字段名与 admin-api 错误响应体对齐:
@@ -104,7 +170,9 @@ export function emitError(scope, e, opts = {}) {
104
170
  // 不调 fail(scope):那会把 "✗ scope" 这人读行混进 JSON stderr。
105
171
  if (opts.spinner)
106
172
  opts.spinner.stop?.();
107
- console.error(JSON.stringify(apiErrorToJson(scope, e)));
173
+ // P3(本轮):同步写 fd 2 而不是 console.error —— 见 writeStderrSyncLine
174
+ // 的注释(管道/文件下未 flush 的尾部会被下面的 exit 丢掉)。
175
+ writeStderrSyncLine(JSON.stringify(apiErrorToJson(scope, e)));
108
176
  }
109
177
  else {
110
178
  if (opts.spinner) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autocodeflow/cli",
3
- "version": "1.15.0",
3
+ "version": "2.1.0",
4
4
  "description": "AutoCodeFlow CLI — manage tasks, executions and applications from the terminal",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -28,7 +28,7 @@
28
28
  "typecheck": "tsc --noEmit"
29
29
  },
30
30
  "dependencies": {
31
- "axios": "1.20.0",
31
+ "axios": "1.21.0",
32
32
  "chalk": "^6.0.0",
33
33
  "cli-table3": "0.6.5",
34
34
  "commander": "15.0.0",
@@ -36,7 +36,7 @@
36
36
  "ora": "^9.4.1"
37
37
  },
38
38
  "devDependencies": {
39
- "@types/node": "26.6.5",
39
+ "@types/node": "26.6.6",
40
40
  "typescript": "^5.9.3",
41
41
  "vitest": "^5.0.1",
42
42
  "tsx": "^4.20.6"
@@ -45,5 +45,8 @@
45
45
  "node": ">=22.12.0"
46
46
  },
47
47
  "_comment_deps": "版本基线(2026-09 依赖审计 + ESM 迁移):本包为 ESM(type: module,NodeNext 产出)。commander 15 / chalk 6 / ora 9 / conf 15 均为 npm 最新;chalk 6 要求 Node >=22,engines 相应抬至 >=22.12.0(commander 15 同要求)。conf 15 保留 configFileMode/defaults/cwd 语义(config.ts 凭据文件 0600 权限与用户目录布局不变)。",
48
- "type": "module"
48
+ "type": "module",
49
+ "overrides": {
50
+ "follow-redirects": "^1.16.2"
51
+ }
49
52
  }