@autocodeflow/cli 1.14.0 → 2.0.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/dist/client.js +9 -0
- package/dist/commands/approval.js +77 -6
- package/dist/commands/apps.js +167 -9
- package/dist/commands/deploy.js +47 -2
- package/dist/commands/tasks.js +8 -2
- package/dist/error-code.js +28 -3
- package/dist/help.js +7 -0
- package/dist/ui.d.ts +4 -0
- package/dist/ui.js +70 -2
- package/package.json +1 -1
package/dist/client.js
CHANGED
|
@@ -128,6 +128,15 @@ export function normalizeApiBase(url) {
|
|
|
128
128
|
}
|
|
129
129
|
return out;
|
|
130
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* P2-3 端间 parity 登记注释(2026-10-26,文档-实现漂移修订):
|
|
133
|
+
* 本客户端刻意**无重试、无熔断**——CLI 是一次性交互进程,唯一的自愈面是
|
|
134
|
+
* 上方 401 单飞刷新(BUG-13)。完整的重试 + 熔断契约只存在于管理面客户端
|
|
135
|
+
* `packages/autocodeflow-http`(与 node-sdk 两端对齐,见其模块 docstring 的
|
|
136
|
+
* parity 地图);任务进程通用通道 `autoflow-sdk`(http.py)与 `mcp-server`
|
|
137
|
+
* (api.ts,仅超时 + 401 refresh 自愈)同样无重试/熔断。修订任何一端前先
|
|
138
|
+
* 互读各端注释。
|
|
139
|
+
*/
|
|
131
140
|
function getClient() {
|
|
132
141
|
if (!_client) {
|
|
133
142
|
_client = axios.create({
|
|
@@ -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
|
-
|
|
83
|
-
|
|
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
|
-
|
|
101
|
-
|
|
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
|
-
|
|
115
|
-
|
|
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 });
|
package/dist/commands/apps.js
CHANGED
|
@@ -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
|
}
|
|
@@ -342,9 +360,13 @@ export function appsCommand() {
|
|
|
342
360
|
// 保持;canary 传 { rollout: { strategy: 'canary', percentage? } }。
|
|
343
361
|
// 2026-10-07:UpgradeAllDto 增可选 version(版本定向灰度/渐进回滚)——
|
|
344
362
|
// --version <v> 时 body 带顶层 version;缺省不带(升级目标恒为应用当前版本)。
|
|
363
|
+
// R2(部署模型评审 §4.4,2026-10-24):覆盖面显式化——默认覆盖 = 全部
|
|
364
|
+
// RUNNING 行(scheduled「仅部署」行实证稳态即 RUNNING,同属默认覆盖);
|
|
365
|
+
// --include-stopped 把 stopped 行显式纳入(仅 all 策略);在途行由服务端
|
|
366
|
+
// 跳过并在响应 skipped 明细回显(黄字透出,不当作失败)。
|
|
345
367
|
// 批次由服务端异步推进(心跳确认 → 健康探测 → 提升),受理 ≠ 完成。
|
|
346
368
|
cmd.command('upgrade-all <appId>')
|
|
347
|
-
.description("Trigger a rolling upgrade of
|
|
369
|
+
.description("Trigger a rolling upgrade of the application's deployed devices to its current version (or --version). Default coverage = all RUNNING rows (deploy-only/scheduled rows report running on completion, so they are covered too); --include-stopped additionally dispatches STOPPED rows (all strategy only). Canary batches advance asynchronously on the server — acceptance is not completion")
|
|
348
370
|
.option('--strategy <strategy>', 'Rollout strategy: all (default) | canary (first batch → heartbeat confirm → health probe → auto-promote the rest, DEP-02)')
|
|
349
371
|
.option('--percentage <n>', 'Canary first-batch percentage, int 1-100 (default 50 — first batch = ceil(N × p%), at least 1)', (v) => {
|
|
350
372
|
const n = Number.parseInt(v, 10);
|
|
@@ -353,7 +375,8 @@ export function appsCommand() {
|
|
|
353
375
|
}
|
|
354
376
|
return n;
|
|
355
377
|
})
|
|
356
|
-
.option('--version <version>', 'Target a historical released version (version string, not uuid) — enables gradual rollback. Default: the application\'s current version. The app record is restored from that version snapshot before the rollout starts')
|
|
378
|
+
.option('--version <version>', 'Target a historical released version (version string, not uuid) — enables gradual rollback. Default: the application\'s current version. The app record is restored from that version snapshot before the rollout starts. Equivalent to the R1 set-current-version + deploy-version split endpoints; prefer those')
|
|
379
|
+
.option('--include-stopped', 'Also dispatch STOPPED deployment rows under the all strategy (default: only RUNNING rows — daemon and deploy-only alike). The canary strategy rejects this flag (health probing needs live processes)', false)
|
|
357
380
|
.option('--json', 'Emit raw JSON (CI-consumable)')
|
|
358
381
|
.option('-y, --yes', 'Skip the confirmation prompt for a FULL upgrade (all strategy)', false)
|
|
359
382
|
.action(async (appId, opts) => {
|
|
@@ -364,18 +387,30 @@ export function appsCommand() {
|
|
|
364
387
|
if (opts.percentage !== undefined && strategy !== 'canary') {
|
|
365
388
|
emitUsageError('--percentage only applies to --strategy canary (the full-upgrade path never reads it)');
|
|
366
389
|
}
|
|
390
|
+
// R2 §4.4:includeStopped 只作用于 all——canary 的健康探测需要活进程,
|
|
391
|
+
// 扩覆盖只会造出必失败的灰度首批;客户端先拒(与 --percentage 同口径)。
|
|
392
|
+
if (opts.includeStopped && strategy !== 'all') {
|
|
393
|
+
emitUsageError('--include-stopped only applies to the all strategy (canary batches probe live processes)');
|
|
394
|
+
}
|
|
367
395
|
// P1(CLI-AGENT-UX-AUDIT):全量滚动升级会重启该应用**所有 RUNNING 部署**,
|
|
368
396
|
// 此前零确认。canary 天然是低风险首步(且服务端会自动提升/回滚),不设门;
|
|
369
397
|
// all 是「一次性动全量」,需要显式表态——与三处 delete 共用同一套非交互语义。
|
|
370
398
|
if (strategy === 'all') {
|
|
371
|
-
if (!(await confirmDestructive(`Roll out the upgrade to ALL running deployments of ${appId}?`, { yes: opts.yes }))) {
|
|
399
|
+
if (!(await confirmDestructive(`Roll out the upgrade to ALL running deployments of ${appId}${opts.includeStopped ? ' (including stopped rows)' : ''}?`, { yes: opts.yes }))) {
|
|
372
400
|
return;
|
|
373
401
|
}
|
|
374
402
|
}
|
|
375
403
|
const spinner = ora('Triggering upgrade…').start();
|
|
376
404
|
try {
|
|
377
|
-
// all
|
|
378
|
-
// 白名单体,percentage
|
|
405
|
+
// all:缺省(无 version/include-stopped)不传 body —— 与既有全量升级
|
|
406
|
+
// 语义逐字节一致;canary:rollout 白名单体,percentage 仅在给出时携带
|
|
407
|
+
// (服务端缺省 50)。R2:all + --include-stopped 带 {includeStopped:true}。
|
|
408
|
+
const allExtras = opts.version !== undefined || opts.includeStopped
|
|
409
|
+
? {
|
|
410
|
+
...(opts.version !== undefined ? { version: opts.version } : {}),
|
|
411
|
+
...(opts.includeStopped ? { includeStopped: true } : {}),
|
|
412
|
+
}
|
|
413
|
+
: undefined;
|
|
379
414
|
const body = strategy === 'canary'
|
|
380
415
|
? {
|
|
381
416
|
...(opts.version !== undefined ? { version: opts.version } : {}),
|
|
@@ -384,9 +419,7 @@ export function appsCommand() {
|
|
|
384
419
|
...(opts.percentage !== undefined ? { percentage: opts.percentage } : {}),
|
|
385
420
|
},
|
|
386
421
|
}
|
|
387
|
-
:
|
|
388
|
-
? { version: opts.version }
|
|
389
|
-
: undefined;
|
|
422
|
+
: allExtras;
|
|
390
423
|
const r = await post(`/applications/${appId}/upgrade-all`, body);
|
|
391
424
|
spinner.stop();
|
|
392
425
|
if (opts.json) {
|
|
@@ -405,6 +438,16 @@ export function appsCommand() {
|
|
|
405
438
|
process.exitCode = 1;
|
|
406
439
|
return;
|
|
407
440
|
}
|
|
441
|
+
// R2 §4.4:覆盖面分组如实回显(旧输出只报 succeeded/total,用户无从知道
|
|
442
|
+
// 「仅部署」行也在覆盖内、stopped 有多少台被留下)。
|
|
443
|
+
const cov = r.coverage;
|
|
444
|
+
if (cov) {
|
|
445
|
+
console.log(chalk.gray(` coverage: running ${cov.running}, deploy-only ${cov.scheduled}, stopped ${cov.stopped}${opts.includeStopped ? ' (included)' : ''}, failed ${cov.failed}, in-flight ${cov.inFlight}`));
|
|
446
|
+
}
|
|
447
|
+
// 在途跳过明细:黄字逐行列出(不是失败——exit code 不受影响)。
|
|
448
|
+
for (const s of r.skipped ?? []) {
|
|
449
|
+
console.log(chalk.yellow(` skipped: ${s.deploymentId.slice(0, 12)} executor=${s.executorId ?? '-'} status=${s.status} reason=${s.reason}`));
|
|
450
|
+
}
|
|
408
451
|
if (strategy === 'canary') {
|
|
409
452
|
spinner.succeed(`Canary batch accepted: first batch ${r.succeeded}/${r.total} deployment(s)`);
|
|
410
453
|
console.log(chalk.gray(` batchId: ${r.rollout?.batchId ?? '-'} strategy: ${r.rollout?.strategy ?? strategy}`));
|
|
@@ -422,12 +465,104 @@ export function appsCommand() {
|
|
|
422
465
|
console.error(chalk.red(` ${r.failed} deployment(s) failed to accept the upgrade — inspect with: acf app deployments ${appId}`));
|
|
423
466
|
process.exitCode = 1;
|
|
424
467
|
}
|
|
468
|
+
// 存在 stopped 行且本次未纳入——显式指路(如实提示,不留「以为全升了」的误会)。
|
|
469
|
+
if (!opts.includeStopped && (cov?.stopped ?? 0) > 0) {
|
|
470
|
+
console.log(chalk.yellow(` ⚠ ${cov.stopped} stopped deployment(s) not covered — pass --include-stopped to include them`));
|
|
471
|
+
}
|
|
425
472
|
}
|
|
426
473
|
}
|
|
427
474
|
catch (e) {
|
|
428
475
|
emitError('Failed to trigger upgrade-all', e, { spinner });
|
|
429
476
|
}
|
|
430
477
|
});
|
|
478
|
+
// ── R1(2026-10-24 部署模型评审 §4.2):应用回滚拆出的两个显式动作 ──────
|
|
479
|
+
// 「设为当前版本」只按版本快照恢复应用当前字段(绝不触碰部署行/设备);
|
|
480
|
+
// 「下发到设备」先做同一份字段恢复,再对部署行逐台走 upgrade 链。旧 POST
|
|
481
|
+
// /applications/:id/rollback/:id 已标 deprecated alias(admin-web 已切双动作),
|
|
482
|
+
// CLI 不再暴露旧端点——此前 CLI 本就没有 app rollback 子命令,保持不补。
|
|
483
|
+
// acf app set-current-version <appId> <versionId>
|
|
484
|
+
cmd.command('set-current-version <appId> <versionId>')
|
|
485
|
+
.description("Restore the application's current fields from a released version snapshot (version/commit/packageUrl/entrypoint/env/manifest — same mapping as the deprecated rollback). NEVER touches deployment rows or devices; to dispatch use: acf app deploy-version")
|
|
486
|
+
.option('--json', 'Emit raw JSON (CI-consumable)')
|
|
487
|
+
.action(async (appId, versionId, opts) => {
|
|
488
|
+
// 安全半边(只改记录面)不设确认门——与 upgrade-all 的 canary 首步同口径。
|
|
489
|
+
const spinner = ora('Setting current version…').start();
|
|
490
|
+
try {
|
|
491
|
+
const r = await post(`/applications/${appId}/set-current-version`, { versionId });
|
|
492
|
+
spinner.stop();
|
|
493
|
+
if (opts.json) {
|
|
494
|
+
console.log(JSON.stringify(r, null, 2));
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
spinner.succeed(`Current version set to ${r.version}`);
|
|
498
|
+
console.log(chalk.gray(` versionId: ${r.versionId} dispatched: ${r.dispatched} (no devices touched)`));
|
|
499
|
+
}
|
|
500
|
+
catch (e) {
|
|
501
|
+
emitError('Failed to set current version', e, { spinner });
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
// acf app deploy-version <appId> <versionId> [--executors <id1,id2>]
|
|
505
|
+
cmd.command('deploy-version <appId> <versionId>')
|
|
506
|
+
.description('Restore the app fields from the version snapshot, then dispatch an upgrade to its deployment rows (default: ALL running rows, same as the deprecated rollback). Executors without a dispatchable row are reported as skipped, not errors')
|
|
507
|
+
.option('--executors <ids>', 'Comma-separated executor ids to dispatch to (default: all running deployment rows of the application)')
|
|
508
|
+
.option('--json', 'Emit raw JSON (CI-consumable)')
|
|
509
|
+
.option('-y, --yes', 'Skip the confirmation prompt (the dispatch restarts the selected deployments)', false)
|
|
510
|
+
.action(async (appId, versionId, opts) => {
|
|
511
|
+
let executorIds;
|
|
512
|
+
if (opts.executors !== undefined) {
|
|
513
|
+
executorIds = opts.executors.split(',').map((s) => s.trim()).filter(Boolean);
|
|
514
|
+
if (executorIds.length === 0) {
|
|
515
|
+
emitUsageError('--executors must list at least one executor id (comma-separated)');
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
// 下发半边会重启所选部署——与 upgrade-all 全量路径同款确认门。
|
|
519
|
+
const scope = executorIds
|
|
520
|
+
? `${executorIds.length} named executor(s)`
|
|
521
|
+
: 'ALL running deployments';
|
|
522
|
+
if (!(await confirmDestructive(`Deploy version to ${scope} of ${appId}? (this restarts those deployments)`, { yes: opts.yes }))) {
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
const spinner = ora('Dispatching version…').start();
|
|
526
|
+
try {
|
|
527
|
+
const r = await post(`/applications/${appId}/deploy-version`, {
|
|
528
|
+
versionId,
|
|
529
|
+
...(executorIds ? { executorIds } : {}),
|
|
530
|
+
});
|
|
531
|
+
spinner.stop();
|
|
532
|
+
// upgrade_rejected = 有行在 upgrade 链被拒(真失败);no_deployment /
|
|
533
|
+
// not_running 是显式点名的预期跳过——CI 只对前者红。
|
|
534
|
+
const rejected = r.skipped.filter((s) => s.reason === 'upgrade_rejected');
|
|
535
|
+
if (opts.json) {
|
|
536
|
+
console.log(JSON.stringify(r, null, 2));
|
|
537
|
+
if (r.upgraded.length === 0 || rejected.length > 0)
|
|
538
|
+
process.exitCode = 1;
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
if (r.upgraded.length === 0) {
|
|
542
|
+
spinner.fail('No deployment was dispatched (all targets skipped)');
|
|
543
|
+
for (const s of r.skipped) {
|
|
544
|
+
console.error(chalk.red(` ${s.executorId ?? s.deploymentId ?? '?'}: ${s.reason}${s.detail ? ` (${s.detail})` : ''}`));
|
|
545
|
+
}
|
|
546
|
+
process.exitCode = 1;
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
spinner.succeed(`Version ${r.version} dispatched: ${r.upgraded.length} deployment(s) upgrading`);
|
|
550
|
+
for (const u of r.upgraded) {
|
|
551
|
+
console.log(chalk.gray(` ${u.deploymentId.slice(0, 12)} executor: ${u.executorId ?? '-'} ${u.executorAddress ?? ''}`));
|
|
552
|
+
}
|
|
553
|
+
if (r.skipped.length > 0) {
|
|
554
|
+
console.error(chalk.yellow(` ⚠ ${r.skipped.length} skipped:`));
|
|
555
|
+
for (const s of r.skipped) {
|
|
556
|
+
console.error(chalk.yellow(` ${s.executorId ?? s.deploymentId ?? '?'}: ${s.reason}${s.detail ? ` (${s.detail})` : ''}`));
|
|
557
|
+
}
|
|
558
|
+
if (rejected.length > 0)
|
|
559
|
+
process.exitCode = 1;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
catch (e) {
|
|
563
|
+
emitError('Failed to deploy version', e, { spinner });
|
|
564
|
+
}
|
|
565
|
+
});
|
|
431
566
|
// acf app deployments [appId]
|
|
432
567
|
cmd.command('deployments [appId]')
|
|
433
568
|
.description('List deployments (optionally filtered by application)')
|
|
@@ -504,6 +639,9 @@ export function appsCommand() {
|
|
|
504
639
|
emitError('Failed to list versions', e, { spinner });
|
|
505
640
|
}
|
|
506
641
|
});
|
|
642
|
+
// P8-R:被截版本「仍有设备保留」清单的展示上限——超出折叠为计数,与
|
|
643
|
+
// admin-web ApplicationDetailPage 的 RETAINED_BUT_TRUNCATED_MAX_TAGS(10)同口径。
|
|
644
|
+
const RETAINED_BUT_TRUNCATED_MAX = 10;
|
|
507
645
|
cmd.command('releases <appId>')
|
|
508
646
|
.description('List unified release history (version × latest deployment) for an application — the modern DEP-01 view; `app versions` is the legacy alias')
|
|
509
647
|
.option('-p, --page <n>', 'Page number', '1')
|
|
@@ -513,10 +651,13 @@ export function appsCommand() {
|
|
|
513
651
|
.action(async (appId, opts) => {
|
|
514
652
|
const spinner = ora('Fetching releases…').start();
|
|
515
653
|
try {
|
|
516
|
-
// getReleases returns `{ data, total, page, pageSize }`
|
|
654
|
+
// getReleases returns `{ data, total, page, pageSize, truncated, retainedButTruncated }`
|
|
655
|
+
// (0a278da6:truncated=synthetic 聚合扫描到 5000 行上限被截;
|
|
656
|
+
// retainedButTruncated=被截但仍有设备保留的版本号,字母序。)
|
|
517
657
|
const data = await get(`/applications/${appId}/releases`, { page: opts.page, pageSize: opts.pageSize });
|
|
518
658
|
spinner.stop();
|
|
519
659
|
if (opts.json) {
|
|
660
|
+
// 信封原样透传(truncated / retainedButTruncated 一并直出,CI 自行判断)
|
|
520
661
|
console.log(JSON.stringify(data));
|
|
521
662
|
return;
|
|
522
663
|
}
|
|
@@ -543,6 +684,23 @@ export function appsCommand() {
|
|
|
543
684
|
}
|
|
544
685
|
console.log(table.toString());
|
|
545
686
|
console.log(chalk.gray(`Total: ${data.total ?? list.length} page ${opts.page}`));
|
|
687
|
+
// P8(对齐 admin-web Releases 截断告警条):truncated=true = synthetic
|
|
688
|
+
// 聚合扫描到 5000 行上限被截——表格用户必须看到「被截」事实,否则会把
|
|
689
|
+
// 「看到的」当「全量」。--json 形态已在上方原样透传两字段,不走这里。
|
|
690
|
+
if (data.truncated) {
|
|
691
|
+
console.log(chalk.yellow(`⚠ 版本行数超上限被截断,仅显示前 ${list.length} 条;完整动作史见事件流(acf app releases --json 可拿 truncated/retainedButTruncated 原始字段)`));
|
|
692
|
+
// P8-R:被截版本里「仍有设备保留」的版本号显式列出——徽标行不在
|
|
693
|
+
// 本页,不列出的话「设备还留着这版」的事实就从表格消失。超 10 个
|
|
694
|
+
// 折叠计数,与前端 RETAINED_BUT_TRUNCATED_MAX_TAGS 口径一致。
|
|
695
|
+
const retained = data.retainedButTruncated ?? [];
|
|
696
|
+
if (retained.length > 0) {
|
|
697
|
+
const shown = retained.slice(0, RETAINED_BUT_TRUNCATED_MAX).join(', ');
|
|
698
|
+
const more = retained.length > RETAINED_BUT_TRUNCATED_MAX
|
|
699
|
+
? `(还有 ${retained.length - RETAINED_BUT_TRUNCATED_MAX} 个版本)`
|
|
700
|
+
: '';
|
|
701
|
+
console.log(chalk.yellow(` 被截断但仍有设备保留的版本: ${shown}${more}`));
|
|
702
|
+
}
|
|
703
|
+
}
|
|
546
704
|
}
|
|
547
705
|
catch (e) {
|
|
548
706
|
emitError('Failed to list releases', e, { spinner });
|
package/dist/commands/deploy.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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 });
|
package/dist/commands/tasks.js
CHANGED
|
@@ -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
|
-
|
|
180
|
-
|
|
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;
|
package/dist/error-code.js
CHANGED
|
@@ -51,7 +51,18 @@ const CATEGORY_RULES = [
|
|
|
51
51
|
],
|
|
52
52
|
[
|
|
53
53
|
'permission',
|
|
54
|
-
|
|
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',
|
|
@@ -64,11 +75,25 @@ const CATEGORY_RULES = [
|
|
|
64
75
|
// (validation),而 `TASK_TRIGGER_CONCURRENT` / `_CONCURRENT_MODIFICATION`
|
|
65
76
|
// 才是并发冲突。少了这个环视,前者会被误判成冲突、给出"重新读一次"的
|
|
66
77
|
// 无效建议(实测红过一条)。
|
|
67
|
-
|
|
78
|
+
// 2026-10-23:补两条 SOP 归档语义——
|
|
79
|
+
// · `SOP_ARCHIVE_HAS_ACTIVE_ASSIGNMENTS`:还有未结束的指派(先处理再归档)
|
|
80
|
+
// · `SOP_NOT_DEPRECATED`:不是归档态(无可恢复)
|
|
81
|
+
// 两者都是**状态冲突**("重新读一次再决定"),不是入参错误。不加这两条
|
|
82
|
+
// 时它们会落到「未知」分支:用户拿到码却没有任何下一步。
|
|
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))/,
|
|
68
91
|
],
|
|
69
92
|
[
|
|
70
93
|
'validation',
|
|
71
|
-
|
|
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)/,
|
|
72
97
|
],
|
|
73
98
|
];
|
|
74
99
|
/**
|
package/dist/help.js
CHANGED
|
@@ -108,6 +108,13 @@ export const EXAMPLES = {
|
|
|
108
108
|
'acf app upgrade-all <appId> # full rolling upgrade (default, no body)',
|
|
109
109
|
'acf app upgrade-all <appId> --strategy canary --percentage 20 # canary first, auto-promote after probe',
|
|
110
110
|
],
|
|
111
|
+
'app set-current-version': [
|
|
112
|
+
'acf app set-current-version <appId> <versionId> # R1 §4.2: restore app fields from a released snapshot ONLY — no devices touched (versionId from: acf app releases <appId>)',
|
|
113
|
+
],
|
|
114
|
+
'app deploy-version': [
|
|
115
|
+
'acf app deploy-version <appId> <versionId> # R1 §4.2: restore fields, then upgrade ALL running deployments (same as the deprecated rollback)',
|
|
116
|
+
'acf app deploy-version <appId> <versionId> --executors <id1,id2> -y # targeted dispatch; executors without a dispatchable row are skipped, not errors',
|
|
117
|
+
],
|
|
111
118
|
'executor list': ['acf executor list', 'acf executor list --json'],
|
|
112
119
|
'executor get': ['acf executor get <executorId> --json'],
|
|
113
120
|
'executor rotate': [
|
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
|
-
|
|
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
|
|
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) {
|