@autocodeflow/cli 1.9.0 → 1.10.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.
@@ -7,7 +7,23 @@ import { spawnSync } from 'child_process';
7
7
  import * as fs from 'fs';
8
8
  import * as path from 'path';
9
9
  import { get, post, put, patch, del, ANALYZE_TIMEOUT_MS } from '../client.js';
10
- import { emitError, emitUsageError, UsageError, interruptExit } from '../ui.js';
10
+ import { emitError, emitUsageError, UsageError, confirmDestructive } from '../ui.js';
11
+ /**
12
+ * 结构化失败原因(failureReason,执行器回调上报)→ 可直接照做的建议。
13
+ *
14
+ * 2026-10 开发人员实测:任务声明 runtimeVersion=3.12 派到无该解释器的执行器
15
+ * 秒失败且执行日志 0 行——failureReason=interpreter_unavailable 只有 --json
16
+ * 里能看到,中文详情还得再查一次文档。把最常见的几个失败原因翻译成"下一步
17
+ * 怎么做",随 `--wait` 的失败终态直接打出来(键集对齐 executor-node
18
+ * protocol.schemas.ts 的 CallbackFailureReason 枚举)。
19
+ */
20
+ export const FAILURE_REASON_HINTS = {
21
+ interpreter_unavailable: 'the interpreter requested by runtimeVersion is not available on this executor — remove runtimeVersion to use the host default interpreter',
22
+ runtime_missing: 'the task runtime is not available on this executor — check the task runtime field or the executor interpreter pool',
23
+ script_error: 'the entry script exited with a non-zero code — inspect the log with: acf task logs <execId>',
24
+ timeout: 'the execution exceeded its time budget — raise the task timeout or split the work',
25
+ sandbox_unavailable: 'the executor sandbox is not available — contact the executor operator or relax the sandbox configuration',
26
+ };
11
27
  // P3 glue:执行器侧运行时白名单(executor-node execute.ts 的 glueLanguage 分支
12
28
  // —— javascript/python/shell,另有 glue_node 等旧别名)。注意 node 脚本的合法
13
29
  // 值是 `javascript`:发 `node` 执行器会在运行时抛 "Unsupported glue language",
@@ -63,19 +79,21 @@ export function tasksCommand() {
63
79
  cmd.command('list')
64
80
  .description('List all tasks')
65
81
  .option('-s, --status <status>', 'Filter by status (active|paused)')
66
- .option('-k, --keyword <keyword>', 'Search by name (sent as the `name` query param)')
82
+ .option('-k, --keyword <keyword>', 'Search by NAME only (sent as the `name` query param; backward-compatible channel)')
83
+ .option('--search <keyword>', 'Search across name AND description (sent as the `q` query param — what the console search box sends; combined with --keyword both must match)')
67
84
  .option('-p, --page <n>', 'Page number', '1')
68
85
  .option('-n, --page-size <n>', 'Items per page', '20')
69
86
  .option('--json', 'Emit raw JSON (CI-consumable, no table)')
70
87
  .action(async (opts) => {
71
88
  const spinner = ora('Fetching tasks…').start();
72
89
  try {
73
- // ListTasksQueryDto has `name` (no `keyword`)
90
+ // ListTasksQueryDto: `name`(按名,向后兼容)+ `q`(name OR description)
74
91
  const data = await get('/tasks', {
75
92
  page: opts.page,
76
93
  pageSize: opts.pageSize,
77
94
  status: opts.status,
78
95
  name: opts.keyword,
96
+ q: opts.search,
79
97
  });
80
98
  spinner.stop();
81
99
  if (opts.json) {
@@ -114,11 +132,17 @@ export function tasksCommand() {
114
132
  return;
115
133
  }
116
134
  console.log(chalk.bold('Task Details'));
117
- console.log(' ID :', t.id);
118
- console.log(' Name :', t.name);
119
- console.log(' Runtime :', t.runtime);
120
- console.log(' Status :', statusColor(t.status));
121
- console.log(' Cron :', t.cronExpression ?? '-');
135
+ console.log(' ID :', t.id);
136
+ console.log(' Name :', t.name);
137
+ console.log(' Runtime :', t.runtime);
138
+ console.log(' Status :', statusColor(t.status));
139
+ console.log(' Trigger :', t.triggerType ?? '-');
140
+ console.log(' Cron :', t.cronExpression ?? '-');
141
+ console.log(' Description :', t.description ?? '-');
142
+ console.log(' App :', t.applicationId ?? '-');
143
+ console.log(' Timeout :', t.timeout !== undefined && t.timeout !== null ? `${t.timeout}s` : '-');
144
+ console.log(' Max retry :', t.maxRetry ?? '-');
145
+ console.log(' Enabled :', t.enabled === undefined ? '-' : (t.enabled ? chalk.green('yes') : chalk.gray('no')));
122
146
  }
123
147
  catch (e) {
124
148
  emitError('Failed', e, { spinner });
@@ -126,7 +150,7 @@ export function tasksCommand() {
126
150
  });
127
151
  // acf task trigger <id>
128
152
  cmd.command('trigger <id>')
129
- .description('Manually trigger a task and wait for completion')
153
+ .description('Manually trigger a task. Returns the execution id immediately; add --wait to poll until the terminal state and get its exit code')
130
154
  .option('--wait', 'Poll until execution finishes', false)
131
155
  // NETOPT-2①: --wait 的轮询上限可调(秒)。默认 600 保持既有行为;
132
156
  // 非正值直接报参数错误而不是静默回落默认值——CI 里写错单位(毫秒当秒)
@@ -143,24 +167,49 @@ export function tasksCommand() {
143
167
  // per-trigger pin would be rejected with 400. Executor pinning IS
144
168
  // supported by the backend as a task-level field (tasks.executorId) — set
145
169
  // it via `acf task create/update --executor <id>`, not per run.
170
+ // --params 补面(本轮):TriggerTaskDto 收 params(覆盖任务默认参数,与
171
+ // webhook 面同形),block-strategy 闸(N-14)按生效参数判重——CLI 此前
172
+ // 永远发空 body,无法按 run 覆盖参数。
173
+ .option('--params <json>', 'Per-run param overrides as JSON, e.g. \'{"KEY":"value"}\' (replaces the task\'s default params for this run)')
146
174
  // 第四轮审计(--json 补面):trigger 响应(execution 对象)直出 JSON,
147
175
  // CI 拿 executionId 做后续断言无需解析人读文本。
148
176
  .option('--json', 'Emit raw JSON (CI-consumable, no table)')
149
177
  .action(async (id, opts) => {
150
178
  const spinner = ora('Triggering task…').start();
151
179
  try {
152
- const exec = await post(`/tasks/${id}/trigger`);
180
+ // 本地 JSON 预检:坏 params 是用法错误(退出码 2),请求不发出。
181
+ let params;
182
+ if (opts.params !== undefined) {
183
+ try {
184
+ params = JSON.parse(opts.params);
185
+ }
186
+ catch (e) {
187
+ throw new UsageError(`Invalid --params JSON: ${e instanceof Error ? e.message : String(e)}`);
188
+ }
189
+ }
190
+ // 只有显式 --params 才带 body(缺省时 post 单参调用,既有语义逐字节保持)。
191
+ const exec = params !== undefined
192
+ ? await post(`/tasks/${id}/trigger`, { params })
193
+ : await post(`/tasks/${id}/trigger`);
153
194
  if (opts.json) {
154
- // ECO-02 同款:--json —— ora 默认写 stderr,stdout 仍是干净 JSON;
155
- // --wait 语义不变(等终态 + 非零退出码逻辑照旧生效)。
195
+ // ECO-02 同款:--json —— ora 默认写 stderr,stdout 仍是干净 JSON。
196
+ // P2(CLI-AGENT-UX-AUDIT):--json **且** --wait 时不在这里输出中间态,
197
+ // 改由 pollExecution 在最末尾一次性输出**最终** execution 对象——
198
+ // 否则 stdout 会先来一段 execution JSON,再接死亡终态的人类可读行
199
+ // (Exit code / Failure reason),单行 JSON 解析器必崩。
156
200
  spinner.stop();
157
- console.log(JSON.stringify(exec, null, 2));
201
+ if (!opts.wait) {
202
+ console.log(JSON.stringify(exec, null, 2));
203
+ }
158
204
  }
159
205
  else {
160
206
  spinner.succeed(`Execution started: ${exec.id}`);
207
+ if (!opts.wait) {
208
+ process.stderr.write(chalk.gray(' (add --wait to poll until completion and get the exit code)\n'));
209
+ }
161
210
  }
162
211
  if (opts.wait) {
163
- await pollExecution(exec.id, opts.waitTimeout);
212
+ await pollExecution(exec.id, opts.waitTimeout, { json: !!opts.json });
164
213
  }
165
214
  }
166
215
  catch (e) {
@@ -191,8 +240,11 @@ export function tasksCommand() {
191
240
  const table = new Table({
192
241
  // U11: exitCode column — distinguishes "failed by callback
193
242
  // report" (exit 0 / null) from "process died" (non-zero).
194
- head: ['Exec ID', 'Status', 'Duration', 'Exit', 'Started'],
195
- colWidths: [14, 12, 12, 6, 25],
243
+ // 2026-10 补 failureReason 列:interpreter_unavailable 这类结构化
244
+ // 失败此前只在 --json 可见(executions 表格无原因),值班扫一眼
245
+ // 即可分流。
246
+ head: ['Exec ID', 'Status', 'Duration', 'Exit', 'Reason', 'Started'],
247
+ colWidths: [14, 12, 12, 6, 30, 25],
196
248
  style: { head: ['cyan'] },
197
249
  });
198
250
  for (const e of data.list ?? []) {
@@ -201,6 +253,7 @@ export function tasksCommand() {
201
253
  statusColor(e.status),
202
254
  e.duration ? `${e.duration}ms` : '-',
203
255
  e.exitCode ?? '-',
256
+ e.failureReason ?? '-',
204
257
  new Date(e.createdAt).toLocaleString(),
205
258
  ]);
206
259
  }
@@ -512,18 +565,9 @@ export function tasksCommand() {
512
565
  .description('Delete a task (force-terminates running executions)')
513
566
  .option('-y, --yes', 'Skip confirmation prompt', false)
514
567
  .action(async (id, opts) => {
515
- if (!opts.yes) {
516
- const readline = await import('readline/promises');
517
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
518
- // raw 模式下 Ctrl+C 触发 rl 'SIGINT' 而非进程信号;无监听只会 pause,
519
- // 确认提示处会假死。接住并走统一中断出口(130)。
520
- rl.on('SIGINT', () => interruptExit());
521
- const answer = await rl.question(`Delete task ${id}? Running executions will be force-terminated. [y/N] `);
522
- rl.close();
523
- if (!/^y(es)?$/i.test(answer)) {
524
- console.log(chalk.yellow('Aborted.'));
525
- return;
526
- }
568
+ // P0(CLI-AGENT-UX-AUDIT):非交互 stdin 下必须显式拒绝,不能静默假绿。
569
+ if (!(await confirmDestructive(`Delete task ${id}? Running executions will be force-terminated.`, { yes: opts.yes }))) {
570
+ return;
527
571
  }
528
572
  const spinner = ora('Deleting task…').start();
529
573
  try {
@@ -633,6 +677,7 @@ export function tasksCommand() {
633
677
  .description('Batch trigger/pause/resume/delete tasks (partial failures do not affect the other tasks)')
634
678
  .option('--ids <ids>', 'Comma-separated task IDs (merged with any positional ids, deduplicated)')
635
679
  .option('--json', 'Emit raw JSON (CI-consumable: the raw per-task result array)')
680
+ .option('-y, --yes', 'Skip the confirmation prompt for batch delete', false)
636
681
  .action(async (action, ids, opts) => {
637
682
  const ACTIONS = ['trigger', 'pause', 'resume', 'delete'];
638
683
  if (!ACTIONS.includes(action)) {
@@ -650,6 +695,15 @@ export function tasksCommand() {
650
695
  if (taskIds.length > 500) {
651
696
  emitUsageError(`Batch is limited to 500 task IDs per request (got ${taskIds.length})`);
652
697
  }
698
+ // P1(CLI-AGENT-UX-AUDIT):`batch delete` 此前**零确认**——单个
699
+ // `task delete` 要确认,而 `--ids a,b,c`(上限 500 个)却能无提示抹掉
700
+ // 一整批任务。按「不可逆 × 影响面」补确认,且与三处 delete 共用同一个
701
+ // 非交互语义(缺 --yes 时以退出码 2 拒绝,不静默假绿)。
702
+ if (action === 'delete') {
703
+ if (!(await confirmDestructive(`Delete ${taskIds.length} task(s)? Running executions will be force-terminated.`, { yes: opts.yes }))) {
704
+ return;
705
+ }
706
+ }
653
707
  const spinner = ora(`Batch ${action} (${taskIds.length} task(s))…`).start();
654
708
  try {
655
709
  // Promise.all 保序:results[i] 对应 taskIds[i](失败项为 { id, error })。
@@ -867,10 +921,14 @@ export function tasksCommand() {
867
921
  return r.status === 0;
868
922
  });
869
923
  if (!py) {
870
- console.error(chalk.red('python not found on PATH — install Python 3 to lint python glue'));
871
- process.exit(1);
924
+ // 环境不满足 ≠ 脚本有语法错:给退出码 2(用法/环境),让 CI 能区分
925
+ // 「我的脚本坏了」与「这台机器没装 Python」。
926
+ emitUsageError('python not found on PATH — install Python 3 to lint python glue (or pass --language to check another runtime)');
872
927
  }
873
- const r = spawnSync(py, ['-c', `import ast,sys; ast.parse(open(sys.argv[1],encoding='utf-8').read())`, file], {
928
+ // 走 stdin 传源码而非把路径当 argv:Windows 路径的反斜杠会被 bash/python
929
+ // 的解析层吃掉(`C:\Users\...` → `C:Users...`),实测必假报。
930
+ const r = spawnSync(py, ['-c', `import ast,sys; ast.parse(sys.stdin.read())`], {
931
+ input: source,
874
932
  stdio: 'pipe',
875
933
  });
876
934
  if (r.status !== 0) {
@@ -881,7 +939,18 @@ export function tasksCommand() {
881
939
  ok('syntax OK (python, ast.parse)');
882
940
  }
883
941
  else {
884
- const r = spawnSync('bash', ['-n', file], { stdio: 'pipe' });
942
+ // P1(CLI-AGENT-UX-AUDIT):此前是 spawnSync('bash', ['-n', file])——
943
+ // Windows 上 bash 把 `C:\Users\...` 的反斜杠当转义符吃掉,报
944
+ // `/bin/bash: C:Users... No such file or directory`,**任何合法脚本
945
+ // 都被判 syntax error**(实测 Git Bash 在场同样复现)。改成把源码经
946
+ // stdin 喂给 `bash -n`(等价的纯语法检查,且跨平台不依赖路径形态)。
947
+ //
948
+ // bash 不存在时(纯 Windows 无 Git Bash)改为可操作的用法错误(码 2),
949
+ // 而不是把 spawn 失败混同成「脚本有语法错」。
950
+ if (!hasCommand('bash')) {
951
+ emitUsageError('bash not found on PATH — install Git Bash (or WSL) to lint shell glue, or pass --language to check another runtime');
952
+ }
953
+ const r = spawnSync('bash', ['-n'], { input: source, stdio: 'pipe' });
885
954
  if (r.status !== 0) {
886
955
  console.error(chalk.red(`✗ ${file}: syntax error`));
887
956
  process.stderr.write(r.stderr?.toString() ?? '');
@@ -892,7 +961,7 @@ export function tasksCommand() {
892
961
  });
893
962
  return cmd;
894
963
  }
895
- async function pollExecution(execId, waitTimeoutSeconds = 600) {
964
+ async function pollExecution(execId, waitTimeoutSeconds = 600, opts = {}) {
896
965
  const INTERVAL = 2000;
897
966
  const MAX_WAIT = waitTimeoutSeconds * 1000;
898
967
  const spinner = ora('Waiting for execution…').start();
@@ -904,6 +973,21 @@ async function pollExecution(execId, waitTimeoutSeconds = 600) {
904
973
  // killed 是后端 ExecutionStatus 的合法终态(acf task kill / Web 端),
905
974
  // 遗漏会让 --wait 在被 kill 后空转到 MAX_WAIT 并误报超时(N10)。
906
975
  if (['success', 'failed', 'timeout', 'cancelled', 'killed'].includes(exec.status)) {
976
+ if (opts.json) {
977
+ // P2(CLI-AGENT-UX-AUDIT):--json --wait 的唯一 stdout 出口 ——
978
+ // 最终 execution 对象(含 status/exitCode/failureReason/errorMessage/
979
+ // aiAnalysis),不再混入人类可读行。细节走 stderr 便于人眼旁读。
980
+ spinner.stop();
981
+ console.log(JSON.stringify(exec, null, 2));
982
+ if (exec.status !== 'success') {
983
+ process.stderr.write(chalk.yellow(`Execution ${exec.status}` +
984
+ (exec.failureReason ? ` (${exec.failureReason})` : '') +
985
+ '\n'));
986
+ }
987
+ if (exec.status !== 'success')
988
+ process.exitCode = 1;
989
+ return;
990
+ }
907
991
  if (exec.status === 'success') {
908
992
  spinner.succeed(`Execution ${exec.status} in ${exec.duration ?? '?'}ms`);
909
993
  }
@@ -927,6 +1011,10 @@ async function pollExecution(execId, waitTimeoutSeconds = 600) {
927
1011
  }
928
1012
  if (exec.failureReason) {
929
1013
  console.log(chalk.yellow(' Failure reason :'), exec.failureReason);
1014
+ // 可操作建议:failureReason 是机器枚举,直接给"下一步怎么做"。
1015
+ const hint = FAILURE_REASON_HINTS[exec.failureReason];
1016
+ if (hint)
1017
+ console.log(chalk.yellow(' Suggestion :'), hint);
930
1018
  }
931
1019
  if (exec.errorMessage) {
932
1020
  console.log(chalk.yellow(' Error :'), exec.errorMessage);
@@ -957,6 +1045,14 @@ async function pollExecution(execId, waitTimeoutSeconds = 600) {
957
1045
  // 与上方失败终态的 CLI-EXIT-01 语义对齐:置 exitCode=1,并明示执行仍在
958
1046
  // 运行、如何继续观察(exec tail)或放宽等待上限(--wait-timeout)。
959
1047
  spinner.fail(`Timed out waiting for execution after ${waitTimeoutSeconds}s`);
1048
+ if (opts.json) {
1049
+ // --json 下超时也只留 stderr:stdout 要么是干净的最终 JSON,要么什么都没有
1050
+ // (此处确实没有终态可输出——超时意味着没有终态)。
1051
+ process.stderr.write(chalk.red(`The execution is still running — no terminal status within ${waitTimeoutSeconds}s. ` +
1052
+ `Follow it later with 'acf exec tail ${execId}' or raise --wait-timeout.\n`));
1053
+ process.exitCode = 1;
1054
+ return;
1055
+ }
960
1056
  console.error(chalk.red(`The execution is still running — no terminal status within ${waitTimeoutSeconds}s. ` +
961
1057
  `Follow it later with 'acf exec tail ${execId}' or raise --wait-timeout.`));
962
1058
  process.exitCode = 1;
@@ -964,3 +1060,16 @@ async function pollExecution(execId, waitTimeoutSeconds = 600) {
964
1060
  function sleep(ms) {
965
1061
  return new Promise((r) => setTimeout(r, ms));
966
1062
  }
1063
+ /**
1064
+ * 探测可执行文件是否在 PATH 上(`task lint` 的 shell 分支用)。
1065
+ * 用 `--version` 的成功退出码判定,`stdio: 'ignore'` 避免污染 lint 的输出;
1066
+ * 探测本身的失败(ENOENT)也统一归为「不可用」。
1067
+ */
1068
+ function hasCommand(bin) {
1069
+ try {
1070
+ return spawnSync(bin, ['--version'], { stdio: 'ignore' }).status === 0;
1071
+ }
1072
+ catch {
1073
+ return false;
1074
+ }
1075
+ }
package/dist/config.d.ts CHANGED
@@ -24,4 +24,13 @@ export declare function setRefreshToken(token: string): void;
24
24
  * apiUrl 保留(用户环境不丢)。
25
25
  */
26
26
  export declare function clearAuth(): void;
27
- export declare function showConfig(): void;
27
+ /**
28
+ * 打印当前配置。
29
+ *
30
+ * `--json`(P2,CLI-AGENT-UX-AUDIT):agent 排障第一步就是读当前配置,
31
+ * 而此前只能 grep 人读文本。**token 永不明文输出**——只给 set/not set,
32
+ * 与既有 `[set]` 口径一致(凭据本身在文件里,不该顺带打到日志/终端)。
33
+ */
34
+ export declare function showConfig(opts?: {
35
+ json?: boolean;
36
+ }): void;
package/dist/config.js CHANGED
@@ -176,9 +176,26 @@ export function clearAuth() {
176
176
  store.set('token', '');
177
177
  store.set('refreshToken', '');
178
178
  }
179
- export function showConfig() {
180
- console.log('API URL :', getApiUrl());
181
- console.log('Token :', getToken() ? '[set]' : '[not set]');
182
- console.log('Refresh :', getRefreshToken() ? '[set]' : '[not set]');
183
- console.log('Config file:', store.path);
179
+ /**
180
+ * 打印当前配置。
181
+ *
182
+ * `--json`(P2,CLI-AGENT-UX-AUDIT):agent 排障第一步就是读当前配置,
183
+ * 而此前只能 grep 人读文本。**token 永不明文输出**——只给 set/not set,
184
+ * 与既有 `[set]` 口径一致(凭据本身在文件里,不该顺带打到日志/终端)。
185
+ */
186
+ export function showConfig(opts = {}) {
187
+ const snapshot = {
188
+ apiUrl: getApiUrl(),
189
+ token: getToken() ? '[set]' : '[not set]',
190
+ refreshToken: getRefreshToken() ? '[set]' : '[not set]',
191
+ configFile: store.path,
192
+ };
193
+ if (opts.json) {
194
+ console.log(JSON.stringify(snapshot));
195
+ return;
196
+ }
197
+ console.log('API URL :', snapshot.apiUrl);
198
+ console.log('Token :', snapshot.token);
199
+ console.log('Refresh :', snapshot.refreshToken);
200
+ console.log('Config file:', snapshot.configFile);
184
201
  }
package/dist/help.js CHANGED
@@ -4,6 +4,13 @@ export const EXAMPLES = {
4
4
  'acf task trigger <taskId> --wait',
5
5
  'acf exec tail <execId>',
6
6
  ],
7
+ whoami: [
8
+ 'acf whoami # preflight: role + API URL behind the current credential',
9
+ 'acf whoami --json',
10
+ ],
11
+ logout: [
12
+ 'acf logout # revoke server-side + clear the local credential file',
13
+ ],
7
14
  login: [
8
15
  'acf login',
9
16
  'acf login --url https://acf.example.com --user admin',
@@ -13,10 +20,12 @@ export const EXAMPLES = {
13
20
  'task list': [
14
21
  'acf task list --status active --page 1',
15
22
  'acf task list --json',
23
+ 'acf task list --search nightly # matches name OR description (q param)',
16
24
  ],
17
25
  'task get': ['acf task get <taskId>', 'acf task get <taskId> --json'],
18
26
  'task trigger': [
19
27
  'acf task trigger <taskId> --wait --wait-timeout 900',
28
+ 'acf task trigger <taskId> --params \'{"KEY":"value"}\' # per-run param overrides (replaces task defaults)',
20
29
  ],
21
30
  'task executions': [
22
31
  'acf task executions <taskId> -n 5',
@@ -35,8 +44,9 @@ export const EXAMPLES = {
35
44
  ],
36
45
  'task compare': ['acf task compare <taskId> <versionId1> <versionId2>'],
37
46
  'task create': [
38
- 'acf task create --file task.json # required: name, version, runtime, triggerType',
39
- "acf task create --json '{\"name\":\"nightly\",\"version\":\"1.0.0\",\"runtime\":\"node\",\"triggerType\":\"cron\",\"cronExpression\":\"0 2 * * *\"}'",
47
+ 'acf task create --file task.json # required: name, triggerType (runtime is optional server-side)',
48
+ "acf task create --body '{\"name\":\"nightly\",\"runtime\":\"node\",\"triggerType\":\"cron\",\"cronExpression\":\"0 2 * * *\"}' # note: there is NO `version` field on the task body — use `currentVersion` if you need one",
49
+ "acf task create --body '{\"name\":\"sync\",\"runtime\":\"python\",\"triggerType\":\"cron\",\"cronExpression\":\"0 8 * * *\",\"params\":{\"REPLACE_EXISTING\":true,\"retries\":3,\"target\":\"nightly\"}}' # params inject as AUTOFLOW_<KEY> env vars, JSON-stringified: booleans/numbers bare ('true','3'), strings quoted ('\"nightly\"')",
40
50
  ],
41
51
  'task update': ['acf task update <taskId> --file patch.json'],
42
52
  'task delete': ['acf task delete <taskId> -y'],
@@ -72,15 +82,21 @@ export const EXAMPLES = {
72
82
  'app list': ['acf app list', 'acf app list --json'],
73
83
  'app get': ['acf app get <appId> --json'],
74
84
  'app create': [
75
- 'acf app create --file app.json # required: name, version, runtime',
85
+ 'acf app create --body \'{"name":"my-app","version":"1.0.0","runtime":"python"}\' # required: name, version, runtime',
76
86
  ],
77
87
  'app update': [
78
- 'acf app update <appId> --json \'{"version":"2.0.0"}\' # renaming is not supported by the backend',
88
+ 'acf app update <appId> --body \'{"version":"2.0.0"}\' # renaming is not supported by the backend',
79
89
  ],
80
90
  'app delete': ['acf app delete <appId> -y'],
81
91
  'app analyze': ['acf app analyze <appId>'],
92
+ 'app releases': [
93
+ 'acf app releases <appId> # DEP-01 unified view: version × latest deployment (modern; `app versions` is the legacy alias)',
94
+ 'acf app releases <appId> -n 200 --json',
95
+ ],
82
96
  'app deploy': [
83
- "acf app deploy <appId> -e <executorId> -m daemon --env '{\"KEY\":\"value\"}'",
97
+ "acf app deploy <appId> -m scheduled # deploy-only — middleware/cron triggers it later (default; entry script does NOT start at deploy)",
98
+ "acf app deploy <appId> -m daemon --env '{\"KEY\":\"value\"}' # resident process — entry script STARTS at deploy, auto-restarts on crash (CLI warns)",
99
+ "acf app deploy <appId> -m deploy-only # alias of scheduled — self-documenting 'deploy, don't run'",
84
100
  ],
85
101
  'app deployments': ['acf app deployments <appId> -n 50 --json'],
86
102
  'app versions': ['acf app versions <appId> --json'],
@@ -100,6 +116,13 @@ export const EXAMPLES = {
100
116
  'executor offline': ['acf executor offline executor-node'],
101
117
  'deploy upgrade': ['acf deploy upgrade <deploymentId>'],
102
118
  'deploy stop': ['acf deploy stop <deploymentId>'],
119
+ 'deploy list': [
120
+ 'acf deploy list # same data as: acf app deployments (deployments live under app in the command tree)',
121
+ 'acf deploy list <appId> -n 50 --json',
122
+ ],
123
+ 'deploy remove': [
124
+ 'acf deploy remove <deploymentId> -y # delete a FINISHED record (failed/stopped only); running/in-flight rows are refused with 409',
125
+ ],
103
126
  'audit list': [
104
127
  'acf audit list --action task.trigger --start-time 2026-01-01T00:00:00Z',
105
128
  'acf audit list --json',
@@ -128,9 +151,31 @@ export const EXAMPLES = {
128
151
  ],
129
152
  'approval reject': ['acf approval reject <deploymentId> --note "wrong version"'],
130
153
  'approval cancel': ['acf approval cancel <deploymentId> # withdraw your own pending request'],
131
- 'config show': ['acf config show'],
154
+ 'mutex list': [
155
+ 'acf mutex list # the same options the console shows in the app-form dropdown (id + attached app count)',
156
+ 'acf mutex list --json',
157
+ ],
158
+ 'mutex create': [
159
+ 'acf mutex create --name ziniao-browser # default: 1 concurrent per device (serial on one device)',
160
+ 'acf mutex create --name sso-account --scope global # platform-wide serial (single-sign-on takeover)',
161
+ 'acf mutex create --name browser --max-concurrent 2 --description "2 browser slots per device"',
162
+ ],
163
+ 'mutex update': [
164
+ 'acf mutex update <groupId> --max-concurrent 3',
165
+ 'acf mutex update <groupId> --scope global # tighten immediately; waiting executions are re-dispatched',
166
+ ],
167
+ 'mutex delete': [
168
+ 'acf mutex delete <groupId> # refuses (409) while apps are attached — lists how many',
169
+ 'acf mutex delete <groupId> --force -y # attached apps silently lose the constraint',
170
+ ],
171
+ 'config show': ['acf config show', 'acf config show --json'],
132
172
  'config set-url': ['acf config set-url http://localhost:3105'],
133
- 'config set-token': ['acf config set-token <token> # prefer: acf login'],
173
+ // 刻意**不**演示 `set-token <明文>`:命令行 token 会进 shell history 与进程列表。
174
+ // 帮助里的示例是 agent 最常照抄的东西,所以这里只给安全通路。
175
+ 'config set-token': [
176
+ 'ACF_TOKEN=<jwt> acf task list # preferred: env var, never touches argv/history',
177
+ 'acf login # or: interactive hidden prompt, stored 0600',
178
+ ],
134
179
  };
135
180
  /**
136
181
  * Walk the whole command tree and attach the matching Examples block to every
package/dist/index.js CHANGED
@@ -35,7 +35,7 @@
35
35
  import { Command, CommanderError } from 'commander';
36
36
  import { pathToFileURL } from 'node:url';
37
37
  import chalk from 'chalk';
38
- import { loginCommand } from './commands/login.js';
38
+ import { loginCommand, whoamiCommand, logoutCommand } from './commands/login.js';
39
39
  import { tasksCommand } from './commands/tasks.js';
40
40
  import { appsCommand } from './commands/apps.js';
41
41
  import { executorsCommand } from './commands/executors.js';
@@ -47,6 +47,7 @@ import { sopCommand } from './commands/sop.js';
47
47
  import { agentCommand } from './commands/agent.js';
48
48
  import { apikeysCommand } from './commands/apikeys.js';
49
49
  import { approvalCommand } from './commands/approval.js';
50
+ import { mutexCommand } from './commands/mutex.js';
50
51
  import { showConfig, setApiUrl, setToken } from './config.js';
51
52
  import { applyExamples } from './help.js';
52
53
  import { EXIT_CODES, interruptExit } from './ui.js';
@@ -60,14 +61,46 @@ import { EXIT_CODES, interruptExit } from './ui.js';
60
61
  // `resolveJsonModule` 已在 tsconfig 打开;tsc 的 rootDir=src 会把 package.json
61
62
  // 视为 src 之外的输入,故走运行时解析(发布物里 package.json 与 dist/ 同级,
62
63
  // 路径稳定)。本包为 ESM(type: module),JSON 导入须带 import attribute。
64
+ // 2026-10 起不再经 Commander .version() 注册(详见下方 VERSION-HIJACK 注释),
65
+ // 但 pkg.version 仍是版本输出的唯一事实源——行为层守卫跑真实构建产物钉死。
63
66
  import pkg from '../package.json' with { type: 'json' };
64
67
  // 导出命令树供测试复用(结构守卫:每个叶子命令都必须有 Examples)。配合底部
65
68
  // 的 main-guard,import 本文件不会触发 parseAsync。
66
69
  export const program = new Command();
67
70
  program
68
71
  .name('acf')
69
- .description('AutoCodeFlow CLI — manage tasks, executions, applications and projects')
70
- .version(pkg.version);
72
+ .description('AutoCodeFlow CLI — manage tasks, executions, applications and projects');
73
+ // ---------------------------------------------------------------------------
74
+ // 版本号处理(VERSION-HIJACK,P1 修复)
75
+ // ---------------------------------------------------------------------------
76
+ // 根命令**不**注册 --version 选项:commander 的根层 parseOptions 会在派发子
77
+ // 命令之前扫描**全部**参数,一旦经 .version() 注册,`acf app upload --version
78
+ // 1.2.0` / `acf app upgrade-all --version 1.9.0` / `acf task rollback --version
79
+ // v9` 里的 --version 会在根层被匹配并 exit 0 打印 CLI 版本——上传/升级/回滚
80
+ // 根本没发生却不报错(2026-10 开发人员实测,三个子命令全部中招)。
81
+ //
82
+ // 修法:版本输出改由根命令的 unknownOption 覆盖接管——只有到达根层仍未被
83
+ // 任何子命令消费的 --version / -V(即 `acf --version` / `acf -V` 这类根级
84
+ // 请求)才打印 pkg.version 并以 0 退出;子命令自己的 --version 选项由各自的
85
+ // parseOptions 消费,互不干扰。pkg.version 仍是唯一事实源(行为层守卫
86
+ // release-metadata.test.ts 跑真实构建产物钉死,改回硬编码会转红)。
87
+ // 'before' 只挂在根命令的帮助上(子命令 help 不显示版本横幅——原 .version()
88
+ // 的版本 banner 同样是根级专属;'beforeAll' 会传播到所有子命令,太吵)。
89
+ program.addHelpText('before', `acf v${pkg.version}\n`);
90
+ // 根级 unknownOption 覆盖:`acf --version` / `acf -V` 会在根 _parseCommand 的
91
+ // checkForUnknownOptions 里走到这里(无子命令可派发),此时按 CLI 版本处理;
92
+ // 其余未知选项(含"某子命令树里没有 --version 选项"的情形)走 commander
93
+ // 原逻辑(报错 + 完整 help + 退出码 2)。
94
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
95
+ const programAny = program;
96
+ const rootUnknownOption = programAny.unknownOption.bind(program);
97
+ programAny.unknownOption = (flag) => {
98
+ if (flag === '--version' || flag === '-V') {
99
+ console.log(pkg.version);
100
+ process.exit(0);
101
+ }
102
+ return rootUnknownOption(flag);
103
+ };
71
104
  // ---------------------------------------------------------------------------
72
105
  // 解析期行为统一(全树,见下方 applyParseErrorBehavior 的说明)
73
106
  // ---------------------------------------------------------------------------
@@ -84,6 +117,8 @@ program.hook('preAction', (thisCommand) => {
84
117
  });
85
118
  // ---- sub-commands ----
86
119
  program.addCommand(loginCommand());
120
+ program.addCommand(whoamiCommand());
121
+ program.addCommand(logoutCommand());
87
122
  program.addCommand(tasksCommand());
88
123
  program.addCommand(appsCommand());
89
124
  program.addCommand(executorsCommand());
@@ -95,9 +130,15 @@ program.addCommand(sopCommand());
95
130
  program.addCommand(agentCommand());
96
131
  program.addCommand(apikeysCommand());
97
132
  program.addCommand(approvalCommand());
133
+ program.addCommand(mutexCommand());
98
134
  // acf config show / set
99
135
  const configCmd = new Command('config').description('View or update CLI configuration');
100
- configCmd.command('show').description('Show current config').action(() => showConfig());
136
+ configCmd
137
+ .command('show')
138
+ .description('Show current config (token is always masked — [set] / [not set])')
139
+ // P2(CLI-AGENT-UX-AUDIT):--json 让 agent 能解析当前配置(不改 [set]/[not set] 口径)
140
+ .option('--json', 'Emit raw JSON (CI-consumable)')
141
+ .action((opts) => showConfig({ json: opts.json }));
101
142
  configCmd.command('set-url <url>').description('Set API base URL').action((url) => {
102
143
  setApiUrl(url);
103
144
  console.log(chalk.green(`✔ API URL set to ${url}`));
package/dist/ui.d.ts CHANGED
@@ -52,4 +52,29 @@ export declare function emitUsageError(message: string): never;
52
52
  * `rl.on('SIGINT')` 共用这一个出口。
53
53
  */
54
54
  export declare function interruptExit(): never;
55
+ /**
56
+ * 破坏性操作的交互确认 —— 三处 delete 此前各自内联 readline.question,
57
+ * 在 stdin 非交互(agent / CI / `< NUL`)时会**静默假绿**:
58
+ *
59
+ * $ acf app delete <id> < NUL
60
+ * Delete application <id>? [y/N] <- 提示打出后立刻 EOF
61
+ * $ echo $? -> 0,且既无 "Aborted." 也无错误行
62
+ *
63
+ * 后果是自动化面最危险的一类失败:agent 把「什么都没删」读成「删除成功」,
64
+ * 继续跑下游步骤。根因是 readline 在 EOF 时以空串 resolve(不是 reject),
65
+ * 调用方的 `/^y(es)?$/` 判否后走 "Aborted." 分支——而该分支在 Windows 上
66
+ * 连输出都会丢,进程以 0 收场。
67
+ *
68
+ * 语义(与 login 的 TOTP 非交互分支同一思路,收敛到一处):
69
+ * - `--yes` 给定 → 直接放行,不碰 stdin(脚本显式表态的唯一通路);
70
+ * - stdin 非 TTY → **拒绝**并给可操作错误(UsageError → 退出码 2)。既不
71
+ * 静默通过(会误删)也不静默取消(会假绿);
72
+ * - stdin 是 TTY → 交互提问;除 y/yes 外一律视为主动放弃,返回 false,
73
+ * 由调用方原样 return(退出码 0 —— README 已把「主动放弃确认」归入成功)。
74
+ *
75
+ * @returns true = 继续执行;false = 用户主动放弃(调用方应直接 return)。
76
+ */
77
+ export declare function confirmDestructive(question: string, opts?: {
78
+ yes?: boolean;
79
+ }): Promise<boolean>;
55
80
  export {};