@autocodeflow/cli 1.7.0 → 1.9.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.
@@ -6,7 +6,44 @@ import axios from 'axios';
6
6
  import { spawnSync } from 'child_process';
7
7
  import * as fs from 'fs';
8
8
  import * as path from 'path';
9
- import { get, post, patch, del, formatApiError, ANALYZE_TIMEOUT_MS } from '../client.js';
9
+ import { get, post, put, patch, del, ANALYZE_TIMEOUT_MS } from '../client.js';
10
+ import { emitError, emitUsageError, UsageError, interruptExit } from '../ui.js';
11
+ // P3 glue:执行器侧运行时白名单(executor-node execute.ts 的 glueLanguage 分支
12
+ // —— javascript/python/shell,另有 glue_node 等旧别名)。注意 node 脚本的合法
13
+ // 值是 `javascript`:发 `node` 执行器会在运行时抛 "Unsupported glue language",
14
+ // 与 acf task lint 的本地推断值(node|python|shell)刻意不同——lint 只做本地
15
+ // new Function 编译,glue 的 language 要落库给执行器消费。
16
+ const GLUE_LANGUAGES = ['python', 'javascript', 'shell'];
17
+ const GLUE_EXT_LANG = {
18
+ '.py': 'python',
19
+ '.js': 'javascript',
20
+ '.mjs': 'javascript',
21
+ '.cjs': 'javascript',
22
+ '.sh': 'shell',
23
+ '.bash': 'shell',
24
+ };
25
+ /**
26
+ * E-1:`acf task import -` 的 stdin 读取。"-" 是 CI/管道惯例;stdin 是 TTY
27
+ * 时(用户忘了给文件、手敲 `-`)拒绝而不是挂死等待 EOF。流参数可注入——
28
+ * 单测用 PassThrough 驱动,不碰真实 stdin。
29
+ */
30
+ export function readStdin(stream = process.stdin) {
31
+ return new Promise((resolve, reject) => {
32
+ if (stream.isTTY) {
33
+ reject(new UsageError('stdin is a TTY — pipe the payload (cat payload.json | acf task import -) or pass a file path'));
34
+ return;
35
+ }
36
+ let data = '';
37
+ stream.setEncoding('utf-8');
38
+ stream.on('data', (chunk) => {
39
+ data += chunk;
40
+ });
41
+ stream.on('end', () => resolve(data));
42
+ stream.on('error', (err) => {
43
+ reject(new UsageError(`Cannot read stdin: ${err instanceof Error ? err.message : String(err)}`));
44
+ });
45
+ });
46
+ }
10
47
  function statusColor(s) {
11
48
  if (s === 'success')
12
49
  return chalk.green(s);
@@ -58,9 +95,7 @@ export function tasksCommand() {
58
95
  console.log(chalk.gray(`Total: ${data.total} page ${data.page}/${Math.ceil(data.total / data.pageSize)}`));
59
96
  }
60
97
  catch (e) {
61
- spinner.fail('Failed to list tasks');
62
- console.error(chalk.red(formatApiError(e)));
63
- process.exit(1);
98
+ emitError('Failed to list tasks', e, { spinner });
64
99
  }
65
100
  });
66
101
  // acf task get <id>
@@ -86,9 +121,7 @@ export function tasksCommand() {
86
121
  console.log(' Cron :', t.cronExpression ?? '-');
87
122
  }
88
123
  catch (e) {
89
- spinner.fail('Failed');
90
- console.error(chalk.red(formatApiError(e)));
91
- process.exit(1);
124
+ emitError('Failed', e, { spinner });
92
125
  }
93
126
  });
94
127
  // acf task trigger <id>
@@ -131,15 +164,15 @@ export function tasksCommand() {
131
164
  }
132
165
  }
133
166
  catch (e) {
134
- spinner.fail('Failed to trigger');
135
- console.error(chalk.red(formatApiError(e)));
136
- process.exit(1);
167
+ emitError('Failed to trigger', e, { spinner });
137
168
  }
138
169
  });
139
170
  // acf task executions <id>
140
171
  cmd.command('executions <id>')
141
172
  .description('List recent executions for a task')
142
173
  .option('-n, --limit <n>', 'Number of results', '10')
174
+ // --json 补面(本轮 UX 统一):对齐 task list 的 ECO-02 CI 消费面
175
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
143
176
  .action(async (id, opts) => {
144
177
  const spinner = ora('Fetching executions…').start();
145
178
  try {
@@ -150,6 +183,11 @@ export function tasksCommand() {
150
183
  page: 1,
151
184
  });
152
185
  spinner.stop();
186
+ if (opts.json) {
187
+ // ECO-02 同款:列表/信封形态 → 单行紧凑 JSON(与 task list --json 一致)
188
+ console.log(JSON.stringify(data));
189
+ return;
190
+ }
153
191
  const table = new Table({
154
192
  // U11: exitCode column — distinguishes "failed by callback
155
193
  // report" (exit 0 / null) from "process died" (non-zero).
@@ -169,9 +207,7 @@ export function tasksCommand() {
169
207
  console.log(table.toString());
170
208
  }
171
209
  catch (e) {
172
- spinner.fail('Failed');
173
- console.error(chalk.red(formatApiError(e)));
174
- process.exit(1);
210
+ emitError('Failed', e, { spinner });
175
211
  }
176
212
  });
177
213
  // acf task logs <execId>
@@ -222,9 +258,7 @@ export function tasksCommand() {
222
258
  }
223
259
  }
224
260
  catch (e) {
225
- spinner.fail('Failed to fetch logs');
226
- console.error(chalk.red(formatApiError(e)));
227
- process.exit(1);
261
+ emitError('Failed to fetch logs', e, { spinner });
228
262
  }
229
263
  });
230
264
  // acf task analyze <taskId> <execId>
@@ -241,9 +275,7 @@ export function tasksCommand() {
241
275
  console.log(result.aiAnalysis || 'No analysis available (AI not configured).');
242
276
  }
243
277
  catch (e) {
244
- spinner.fail('Analysis failed');
245
- console.error(chalk.red(formatApiError(e)));
246
- process.exit(1);
278
+ emitError('Analysis failed', e, { spinner });
247
279
  }
248
280
  });
249
281
  // acf task suggest-schedule <id>
@@ -262,38 +294,46 @@ export function tasksCommand() {
262
294
  console.log(result.reasoning);
263
295
  }
264
296
  catch (e) {
265
- spinner.fail('Failed');
266
- console.error(chalk.red(formatApiError(e)));
267
- process.exit(1);
297
+ emitError('Failed', e, { spinner });
268
298
  }
269
299
  });
270
300
  // acf task stats <id>
271
301
  cmd.command('stats <id>')
272
302
  .description('Show execution statistics for a task')
273
- .action(async (id) => {
303
+ // --json 补面(本轮 UX 统一):单对象形态 → pretty JSON(与 task get --json 一致)
304
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
305
+ .action(async (id, opts) => {
274
306
  const spinner = ora('Fetching stats…').start();
275
307
  try {
276
308
  const s = await get(`/tasks/${id}/stats`);
277
309
  spinner.stop();
310
+ if (opts.json) {
311
+ console.log(JSON.stringify(s, null, 2));
312
+ return;
313
+ }
278
314
  console.log(chalk.bold('Execution Stats'));
279
315
  console.log(` Success rate : ${chalk.green(s.successRate + '%')}`);
280
316
  console.log(` Avg duration : ${s.avgDuration}ms`);
281
317
  console.log(` Total runs : ${s.totalRuns}`);
282
318
  }
283
319
  catch (e) {
284
- spinner.fail('Failed');
285
- console.error(chalk.red(formatApiError(e)));
286
- process.exit(1);
320
+ emitError('Failed', e, { spinner });
287
321
  }
288
322
  });
289
323
  // acf task versions <id>
290
324
  cmd.command('versions <id>')
291
325
  .description('List historical versions of a task')
292
- .action(async (id) => {
326
+ // --json 补面(本轮 UX 统一):rollback/compare 前先拿 versionId 的脚本消费面
327
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
328
+ .action(async (id, opts) => {
293
329
  const spinner = ora('Fetching task versions…').start();
294
330
  try {
295
331
  const versions = await get(`/tasks/${id}/versions`);
296
332
  spinner.stop();
333
+ if (opts.json) {
334
+ console.log(JSON.stringify(versions, null, 2));
335
+ return;
336
+ }
297
337
  const table = new Table({
298
338
  head: ['Version', 'Commit', 'Created By', 'Created', 'Description'],
299
339
  colWidths: [12, 14, 16, 25, 30],
@@ -311,9 +351,7 @@ export function tasksCommand() {
311
351
  console.log(table.toString());
312
352
  }
313
353
  catch (e) {
314
- spinner.fail('Failed to list versions');
315
- console.error(chalk.red(formatApiError(e)));
316
- process.exit(1);
354
+ emitError('Failed to list versions', e, { spinner });
317
355
  }
318
356
  });
319
357
  // acf task rollback <id>
@@ -328,19 +366,23 @@ export function tasksCommand() {
328
366
  console.log(chalk.gray(` name: ${t.name} status: ${statusColor(t.status)}`));
329
367
  }
330
368
  catch (e) {
331
- spinner.fail('Failed to roll back');
332
- console.error(chalk.red(formatApiError(e)));
333
- process.exit(1);
369
+ emitError('Failed to roll back', e, { spinner });
334
370
  }
335
371
  });
336
372
  // acf task compare <id> <versionId1> <versionId2>
337
373
  cmd.command('compare <id> <versionId1> <versionId2>')
338
374
  .description('Diff two task versions (shows fields whose values differ)')
339
- .action(async (id, versionId1, versionId2) => {
375
+ // --json 补面(本轮 UX 统一):diff 记录直出,脚本可断言具体字段
376
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
377
+ .action(async (id, versionId1, versionId2, opts) => {
340
378
  const spinner = ora('Comparing versions…').start();
341
379
  try {
342
380
  const diff = await get(`/tasks/${id}/versions/${versionId1}/compare/${versionId2}`);
343
381
  spinner.stop();
382
+ if (opts.json) {
383
+ console.log(JSON.stringify(diff ?? {}, null, 2));
384
+ return;
385
+ }
344
386
  const keys = Object.keys(diff ?? {});
345
387
  if (keys.length === 0) {
346
388
  console.log(chalk.green('No differences between the two versions.'));
@@ -362,25 +404,50 @@ export function tasksCommand() {
362
404
  console.log(table.toString());
363
405
  }
364
406
  catch (e) {
365
- spinner.fail('Failed to compare versions');
366
- console.error(chalk.red(formatApiError(e)));
367
- process.exit(1);
407
+ emitError('Failed to compare versions', e, { spinner });
368
408
  }
369
409
  });
370
410
  // acf task create
371
411
  cmd.command('create')
372
- .description('Create a new task (JSON payload via --json or --file)')
373
- .requiredOption('--json <body>', 'Task body as JSON string')
374
- .option('--file <path>', 'Read task body from a JSON file (overrides --json)')
412
+ .description('Create a new task (JSON payload via --body or --file)')
413
+ // 2026-10-07 deprecation:载荷旗标由 --json 更名 --body——--json 将在下一个
414
+ // 大版本收敛为纯布尔「输出 JSON」旗标(与 task list/show/trigger 等命令的
415
+ // 既有语义统一)。旧名本版本仍可用(与 --body 互斥),stderr 打警告。
416
+ // 二者都声明为可选(requiredOption 会让 --json 过渡路径在 commander 层就
417
+ // 被"缺必填"拒绝),缺一校验在 action 里做。
418
+ .option('--body <json>', 'Task body as JSON string (required unless --file is given)')
419
+ .option('--json <body>', 'DEPRECATED (renamed to --body): Task body as JSON string. In the next major version --json becomes a boolean output flag')
420
+ .option('--file <path>', 'Read task body from a JSON file (overrides --body/--json)')
375
421
  .option('--executor <id>', 'Pin the task to a specific executor ID (uuid); mutually exclusive with executeMode=broadcast')
376
422
  .action(async (opts) => {
423
+ if (opts.body !== undefined && opts.json !== undefined) {
424
+ emitUsageError('--body and --json (deprecated alias) are mutually exclusive — pass only --body');
425
+ }
426
+ if (opts.body === undefined && opts.json === undefined && !opts.file) {
427
+ emitUsageError('Missing required task body — pass --body <json> (or --file <path>)');
428
+ }
377
429
  const spinner = ora('Creating task…').start();
378
430
  try {
431
+ if (opts.json !== undefined) {
432
+ process.stderr.write(chalk.yellow('⚠ --json <body> is deprecated and will be removed in the next major version (it will become a boolean output flag). Use --body <json> instead.\n'));
433
+ }
379
434
  const fs = await import('fs/promises');
380
- const raw = opts.file
381
- ? await fs.readFile(opts.file, 'utf-8')
382
- : opts.json;
383
- const body = JSON.parse(raw);
435
+ // 本地 payload 层错误(文件读不了/JSON 坏)= 用法错误(退出码 2),
436
+ // 与服务端拒绝(1)区分;口径与 apps.ts 的 loadJsonBody 一致。
437
+ let raw;
438
+ try {
439
+ raw = opts.file ? await fs.readFile(opts.file, 'utf-8') : (opts.body ?? opts.json);
440
+ }
441
+ catch (err) {
442
+ throw new UsageError(`Cannot read payload file: ${opts.file} (${err instanceof Error ? err.message : String(err)})`);
443
+ }
444
+ let body;
445
+ try {
446
+ body = JSON.parse(raw);
447
+ }
448
+ catch (err) {
449
+ throw new UsageError(`Invalid JSON payload: ${err instanceof Error ? err.message : String(err)}`);
450
+ }
384
451
  // R7 (N20): 显式 --executor 覆盖/补写 body.executorId(pinning)。
385
452
  if (opts.executor)
386
453
  body.executorId = opts.executor;
@@ -389,25 +456,46 @@ export function tasksCommand() {
389
456
  console.log(chalk.gray(` name: ${t.name} status: ${statusColor(t.status)}`));
390
457
  }
391
458
  catch (e) {
392
- spinner.fail('Failed to create task');
393
- console.error(chalk.red(formatApiError(e)));
394
- process.exit(1);
459
+ emitError('Failed to create task', e, { spinner });
395
460
  }
396
461
  });
397
462
  // acf task update <id>
398
463
  cmd.command('update <id>')
399
- .description('Update a task (JSON payload via --json or --file)')
400
- .requiredOption('--json <body>', 'Task patch body as JSON string')
401
- .option('--file <path>', 'Read task patch body from a JSON file (overrides --json)')
402
- .option('--executor <id>', 'Pin the task to a specific executor ID (uuid); pass --json {"executorId":null} to clear. Mutually exclusive with executeMode=broadcast')
464
+ .description('Update a task (JSON payload via --body or --file)')
465
+ // 2026-10-07 deprecation:同 task create——载荷更名 --body,旧名过渡一版。
466
+ .option('--body <json>', 'Task patch body as JSON string (required unless --file is given)')
467
+ .option('--json <body>', 'DEPRECATED (renamed to --body): Task patch body as JSON string. In the next major version --json becomes a boolean output flag')
468
+ .option('--file <path>', 'Read task patch body from a JSON file (overrides --body/--json)')
469
+ .option('--executor <id>', 'Pin the task to a specific executor ID (uuid); pass --body {"executorId":null} to clear. Mutually exclusive with executeMode=broadcast')
403
470
  .action(async (id, opts) => {
471
+ if (opts.body !== undefined && opts.json !== undefined) {
472
+ emitUsageError('--body and --json (deprecated alias) are mutually exclusive — pass only --body');
473
+ }
474
+ if (opts.body === undefined && opts.json === undefined && !opts.file) {
475
+ emitUsageError('Missing required task patch body — pass --body <json> (or --file <path>)');
476
+ }
404
477
  const spinner = ora('Updating task…').start();
405
478
  try {
479
+ if (opts.json !== undefined) {
480
+ process.stderr.write(chalk.yellow('⚠ --json <body> is deprecated and will be removed in the next major version (it will become a boolean output flag). Use --body <json> instead.\n'));
481
+ }
406
482
  const fs = await import('fs/promises');
407
- const raw = opts.file
408
- ? await fs.readFile(opts.file, 'utf-8')
409
- : opts.json;
410
- const body = JSON.parse(raw);
483
+ // 本地 payload 层错误(文件读不了/JSON 坏)= 用法错误(退出码 2),
484
+ // 与服务端拒绝(1)区分;口径与 apps.ts 的 loadJsonBody 一致。
485
+ let raw;
486
+ try {
487
+ raw = opts.file ? await fs.readFile(opts.file, 'utf-8') : (opts.body ?? opts.json);
488
+ }
489
+ catch (err) {
490
+ throw new UsageError(`Cannot read payload file: ${opts.file} (${err instanceof Error ? err.message : String(err)})`);
491
+ }
492
+ let body;
493
+ try {
494
+ body = JSON.parse(raw);
495
+ }
496
+ catch (err) {
497
+ throw new UsageError(`Invalid JSON payload: ${err instanceof Error ? err.message : String(err)}`);
498
+ }
411
499
  // R7 (N20): 显式 --executor 覆盖/补写 body.executorId(pinning)。
412
500
  if (opts.executor)
413
501
  body.executorId = opts.executor;
@@ -416,9 +504,7 @@ export function tasksCommand() {
416
504
  console.log(chalk.gray(` name: ${t.name} status: ${statusColor(t.status)}`));
417
505
  }
418
506
  catch (e) {
419
- spinner.fail('Failed to update task');
420
- console.error(chalk.red(formatApiError(e)));
421
- process.exit(1);
507
+ emitError('Failed to update task', e, { spinner });
422
508
  }
423
509
  });
424
510
  // acf task delete <id>
@@ -429,6 +515,9 @@ export function tasksCommand() {
429
515
  if (!opts.yes) {
430
516
  const readline = await import('readline/promises');
431
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());
432
521
  const answer = await rl.question(`Delete task ${id}? Running executions will be force-terminated. [y/N] `);
433
522
  rl.close();
434
523
  if (!/^y(es)?$/i.test(answer)) {
@@ -442,9 +531,7 @@ export function tasksCommand() {
442
531
  spinner.succeed(`Task ${id} deleted`);
443
532
  }
444
533
  catch (e) {
445
- spinner.fail('Failed to delete task');
446
- console.error(chalk.red(formatApiError(e)));
447
- process.exit(1);
534
+ emitError('Failed to delete task', e, { spinner });
448
535
  }
449
536
  });
450
537
  // acf task pause <id>
@@ -458,9 +545,7 @@ export function tasksCommand() {
458
545
  console.log(chalk.gray(` status: ${statusColor(t.status)}`));
459
546
  }
460
547
  catch (e) {
461
- spinner.fail('Failed to pause task');
462
- console.error(chalk.red(formatApiError(e)));
463
- process.exit(1);
548
+ emitError('Failed to pause task', e, { spinner });
464
549
  }
465
550
  });
466
551
  // acf task resume <id>
@@ -474,9 +559,129 @@ export function tasksCommand() {
474
559
  console.log(chalk.gray(` status: ${statusColor(t.status)}`));
475
560
  }
476
561
  catch (e) {
477
- spinner.fail('Failed to resume task');
478
- console.error(chalk.red(formatApiError(e)));
479
- process.exit(1);
562
+ emitError('Failed to resume task', e, { spinner });
563
+ }
564
+ });
565
+ // E-1: acf task export <id> [-o file] —— 导出任务定义为 JSON(导出物即
566
+ // POST /tasks/import 的请求体,两端口径完全对称,CLI 不做任何本地变换)。
567
+ // 服务端不经统一 envelope 包裹(@Res() 直写 attachment),client 的 unwrap
568
+ // 判据(数值 code)不会命中,这里拿到的就是原始 { schemaVersion, exportedAt, task }。
569
+ cmd.command('export <id>')
570
+ .description('Export a task definition as JSON (the payload is accepted verbatim by `acf task import`; secrets are never part of it)')
571
+ .option('-o, --output <file>', 'Write the JSON payload to a file instead of stdout')
572
+ .action(async (id, opts) => {
573
+ const spinner = ora('Exporting task…').start();
574
+ try {
575
+ const payload = await get(`/tasks/${id}/export`);
576
+ if (opts.output) {
577
+ try {
578
+ await fs.promises.writeFile(opts.output, JSON.stringify(payload, null, 2) + '\n', 'utf-8');
579
+ }
580
+ catch (err) {
581
+ // 本地文件层错误 = 用法错误(退出码 2),与服务端拒绝(1)区分。
582
+ throw new UsageError(`Cannot write export file: ${opts.output} (${err instanceof Error ? err.message : String(err)})`);
583
+ }
584
+ spinner.succeed(`Task exported to ${opts.output}`);
585
+ }
586
+ else {
587
+ spinner.stop();
588
+ console.log(JSON.stringify(payload, null, 2));
589
+ }
590
+ }
591
+ catch (e) {
592
+ emitError('Failed to export task', e, { spinner });
593
+ }
594
+ });
595
+ // E-1: acf task import <file> —— 从导出物创建任务("-" 读 stdin)。
596
+ // 请求体 = 导出物原样回放(JSON.parse 后交由 axios 序列化,键序/键值不变);
597
+ // 重名自动加后缀不覆盖、secrets 键整体忽略(warnings 常驻重配提示)均为服务端语义。
598
+ cmd.command('import <file>')
599
+ .description('Create a task from an export payload ("-" reads stdin). The new task starts paused; reconfigure secrets afterwards (SEC-02: they are never transferred)')
600
+ .action(async (file) => {
601
+ const spinner = ora('Importing task…').start();
602
+ try {
603
+ let raw;
604
+ try {
605
+ raw = file === '-' ? await readStdin() : await fs.promises.readFile(file, 'utf-8');
606
+ }
607
+ catch (err) {
608
+ // 本地 payload 层错误(文件读不了/stdin 不可用)= 用法错误(退出码 2)。
609
+ throw new UsageError(`Cannot read payload ${file === '-' ? 'from stdin' : `file: ${file}`} (${err instanceof Error ? err.message : String(err)})`);
610
+ }
611
+ let body;
612
+ try {
613
+ body = JSON.parse(raw);
614
+ }
615
+ catch (err) {
616
+ throw new UsageError(`Invalid JSON payload: ${err instanceof Error ? err.message : String(err)}`);
617
+ }
618
+ const result = await post('/tasks/import', body);
619
+ spinner.stop();
620
+ spinner.succeed(`Task imported: ${result.taskId}`);
621
+ console.log(chalk.gray(` name: ${result.name} status: paused`));
622
+ for (const w of result.warnings ?? []) {
623
+ console.log(chalk.yellow(` ⚠ ${w}`));
624
+ }
625
+ }
626
+ catch (e) {
627
+ emitError('Failed to import task', e, { spinner });
628
+ }
629
+ });
630
+ // 批量面:POST /tasks/batch/{trigger|pause|resume|delete},body = { taskIds }。
631
+ // 服务端逐个执行、部分失败不影响其他任务(失败项以 { id, error } 回传,恒 200)。
632
+ cmd.command('batch <action> [ids...]')
633
+ .description('Batch trigger/pause/resume/delete tasks (partial failures do not affect the other tasks)')
634
+ .option('--ids <ids>', 'Comma-separated task IDs (merged with any positional ids, deduplicated)')
635
+ .option('--json', 'Emit raw JSON (CI-consumable: the raw per-task result array)')
636
+ .action(async (action, ids, opts) => {
637
+ const ACTIONS = ['trigger', 'pause', 'resume', 'delete'];
638
+ if (!ACTIONS.includes(action)) {
639
+ emitUsageError(`Unknown batch action "${action}" — expected one of: ${ACTIONS.join(' | ')}`);
640
+ }
641
+ const fromFlag = (opts.ids ?? '')
642
+ .split(',')
643
+ .map((s) => s.trim())
644
+ .filter(Boolean);
645
+ // 服务端硬契约(BatchTaskIdsDto):1..500 个 uuid,单请求上限 500。
646
+ const taskIds = [...new Set([...(ids ?? []), ...fromFlag])];
647
+ if (taskIds.length === 0) {
648
+ emitUsageError('No task IDs given — pass them as arguments or via --ids id1,id2,id3');
649
+ }
650
+ if (taskIds.length > 500) {
651
+ emitUsageError(`Batch is limited to 500 task IDs per request (got ${taskIds.length})`);
652
+ }
653
+ const spinner = ora(`Batch ${action} (${taskIds.length} task(s))…`).start();
654
+ try {
655
+ // Promise.all 保序:results[i] 对应 taskIds[i](失败项为 { id, error })。
656
+ const results = await post(`/tasks/batch/${action}`, { taskIds });
657
+ spinner.stop();
658
+ if (opts.json) {
659
+ console.log(JSON.stringify(results ?? []));
660
+ return;
661
+ }
662
+ let failed = 0;
663
+ (results ?? []).forEach((r, i) => {
664
+ const tid = taskIds[i] ?? String(i);
665
+ if (r && typeof r === 'object' && 'error' in r) {
666
+ failed++;
667
+ console.log(chalk.red(`✗ ${tid}: ${String(r.error)}`));
668
+ }
669
+ else {
670
+ console.log(chalk.green(`✔ ${tid}`));
671
+ }
672
+ });
673
+ if (failed > 0) {
674
+ // 部分失败:服务端仍是 200,但 CLI 要让 CI 看得见(对齐 CLI-EXIT-01
675
+ // 的「--wait 失败终态 → 非零退出码」语义)。退出码 1 = 服务端拒绝类。
676
+ console.error(chalk.red(`Batch ${action} finished with ${failed} failure(s) out of ${taskIds.length} task(s).`));
677
+ process.exitCode = 1;
678
+ }
679
+ else {
680
+ console.log(chalk.green(`Batch ${action}: ${taskIds.length}/${taskIds.length} succeeded`));
681
+ }
682
+ }
683
+ catch (e) {
684
+ emitError(`Failed to batch ${action}`, e, { spinner });
480
685
  }
481
686
  });
482
687
  // acf task kill <taskId> <execId>
@@ -489,9 +694,126 @@ export function tasksCommand() {
489
694
  spinner.succeed(r.message || 'Execution cancelled');
490
695
  }
491
696
  catch (e) {
492
- spinner.fail('Failed to cancel execution');
493
- console.error(chalk.red(formatApiError(e)));
494
- process.exit(1);
697
+ emitError('Failed to cancel execution', e, { spinner });
698
+ }
699
+ });
700
+ // P3: acf task webhook <enable|rotate|disable|status> <taskId>(FEAT-21 任务级
701
+ // 入站 webhook)。契约:enable/rotate 响应 { url, secret }——secret 明文仅在
702
+ // 该响应出现一次,服务端只存加密信封,输出必须带一次性提示(口径同 apikey
703
+ // create 的 plaintext);enable 对已启用任务等价轮换;disable 清空密钥、签名
704
+ // 请求即刻 401;status(GET)只回 { enabled, url },secret 永不回传——查看
705
+ // URL 而不必轮换密钥的通路。
706
+ cmd.command('webhook <action> <taskId>')
707
+ .description('Manage the task inbound webhook (HMAC-signed). enable/rotate print the secret exactly once; status shows the URL without touching the secret; disable makes signed calls answer 401 immediately')
708
+ .option('--json', 'Emit raw JSON (CI-consumable; includes the one-time secret for enable/rotate)')
709
+ .action(async (action, taskId, opts) => {
710
+ const ACTIONS = ['enable', 'rotate', 'disable', 'status'];
711
+ if (!ACTIONS.includes(action)) {
712
+ emitUsageError(`Unknown webhook action "${action}" — expected one of: ${ACTIONS.join(' | ')}`);
713
+ }
714
+ const spinner = ora(`Task webhook ${action}…`).start();
715
+ try {
716
+ if (action === 'status') {
717
+ const s = await get(`/tasks/${taskId}/webhook`);
718
+ spinner.stop();
719
+ if (opts.json) {
720
+ console.log(JSON.stringify(s));
721
+ return;
722
+ }
723
+ console.log(chalk.bold('Task Webhook'));
724
+ console.log(' Enabled:', s.enabled ? chalk.green('yes') : chalk.red('no'));
725
+ console.log(' URL :', s.url);
726
+ console.log(chalk.gray(' (the secret is never returned by status — run rotate to reissue one)'));
727
+ return;
728
+ }
729
+ if (action === 'disable') {
730
+ const r = await post(`/tasks/${taskId}/webhook/disable`);
731
+ spinner.stop();
732
+ if (opts.json) {
733
+ console.log(JSON.stringify(r));
734
+ return;
735
+ }
736
+ spinner.succeed('Task webhook disabled — signed calls now answer 401');
737
+ return;
738
+ }
739
+ // enable | rotate:{ url, secret } 一次性回显。路径必须显式——服务端
740
+ // 是三条字面量路由(enable/rotate/disable),动态模板虽运行时可达,
741
+ // 但 consumer-routes 守卫的静态对账无法把两段参数模板对上 openapi。
742
+ const actionPath = action === 'enable'
743
+ ? `/tasks/${taskId}/webhook/enable`
744
+ : `/tasks/${taskId}/webhook/rotate`;
745
+ const r = await post(actionPath);
746
+ spinner.stop();
747
+ if (opts.json) {
748
+ console.log(JSON.stringify(r));
749
+ return;
750
+ }
751
+ spinner.succeed(action === 'enable'
752
+ ? 'Task webhook enabled'
753
+ : 'Task webhook secret rotated — the old secret stopped working immediately');
754
+ console.log(' URL :', r.url);
755
+ console.log(' Secret :', chalk.bold(r.secret));
756
+ console.log(chalk.yellow(' ⚠ The secret is shown only once — store it now (CI secret store / env file). It cannot be retrieved again; rotate to reissue.'));
757
+ console.log(chalk.gray(' Trigger: POST the URL with X-AutoCodeFlow-Timestamp and X-Hub-Signature-256: sha256=<hex of HMAC_SHA256(secret, "<timestamp>.<rawBody>")>'));
758
+ }
759
+ catch (e) {
760
+ emitError(`Failed to ${action} task webhook`, e, { spinner });
761
+ }
762
+ });
763
+ // P3: acf task glue <taskId> -f <file> | --stdin —— PUT /tasks/:id/glue
764
+ //({ source, language? })。语言按扩展名推断或 --language 显式指定(白名单
765
+ // 见 GLUE_LANGUAGES);空/纯空白脚本服务端 400(会让任务静默改跑 entrypoint
766
+ // 的自相矛盾态),CLI 本地同判提前拒绝。语法可先用 acf task lint 本地预检。
767
+ cmd.command('glue <taskId>')
768
+ .description('Update the GLUE script inline (online code edit). Language is inferred from the file extension (.js/.mjs/.cjs → javascript, .py → python, .sh/.bash → shell) or forced with --language python|javascript|shell')
769
+ .option('-f, --file <path>', 'Read the script from a file; "-" reads stdin (same convention as acf task import)')
770
+ .option('--stdin', 'Read the script from stdin (equivalent to -f -)')
771
+ .option('--language <lang>', 'Language: python | javascript | shell (the executor rejects anything else at run time)')
772
+ .action(async (taskId, opts) => {
773
+ if (opts.stdin && opts.file) {
774
+ emitUsageError('--stdin and -f/--file are mutually exclusive');
775
+ }
776
+ if (!opts.stdin && !opts.file) {
777
+ emitUsageError('Nothing to upload — pass -f <file> (or --stdin). Preview syntax locally first with: acf task lint <file>');
778
+ }
779
+ const fromStdin = opts.stdin || opts.file === '-';
780
+ const spinner = ora('Updating glue script…').start();
781
+ try {
782
+ let source;
783
+ try {
784
+ source = fromStdin ? await readStdin() : await fs.promises.readFile(opts.file, 'utf-8');
785
+ }
786
+ catch (err) {
787
+ // 本地 payload 层错误(文件读不了/stdin 不可用)= 用法错误(退出码 2)。
788
+ throw new UsageError(`Cannot read script ${fromStdin ? 'from stdin' : `file: ${opts.file}`} (${err instanceof Error ? err.message : String(err)})`);
789
+ }
790
+ if (!source.trim()) {
791
+ // 与服务端 P0 防线同判(service 层拒绝空脚本,语义同一条消息)。
792
+ throw new UsageError('Refusing to upload an empty glue script — the server would reject it (the task would silently fall back to its entrypoint)');
793
+ }
794
+ let language;
795
+ if (opts.language) {
796
+ if (!GLUE_LANGUAGES.includes(opts.language)) {
797
+ throw new UsageError(`Unknown glue language "${opts.language}" — expected one of: ${GLUE_LANGUAGES.join(' | ')} (the executor rejects other values at run time)`);
798
+ }
799
+ language = opts.language;
800
+ }
801
+ else if (fromStdin) {
802
+ throw new UsageError('Cannot infer the glue language from stdin — pass --language python|javascript|shell');
803
+ }
804
+ else {
805
+ const ext = path.extname(opts.file).toLowerCase();
806
+ language = GLUE_EXT_LANG[ext];
807
+ if (!language) {
808
+ throw new UsageError(`Cannot infer the glue language from extension "${ext}" (${opts.file}) — pass --language python|javascript|shell`);
809
+ }
810
+ }
811
+ const t = await put(`/tasks/${taskId}/glue`, { source, language });
812
+ spinner.succeed(`Glue script updated: ${t.id}`);
813
+ console.log(chalk.gray(` name: ${t.name} language: ${language} bytes: ${Buffer.byteLength(source, 'utf-8')}`));
814
+ }
815
+ catch (e) {
816
+ emitError('Failed to update glue script', e, { spinner });
495
817
  }
496
818
  });
497
819
  // ECO-02: acf task lint <file> —— 本地语法检查(node: 语法编译不执行;
@@ -506,8 +828,8 @@ export function tasksCommand() {
506
828
  source = fs.readFileSync(file, 'utf-8');
507
829
  }
508
830
  catch {
509
- console.error(chalk.red(`Cannot read file: ${file}`));
510
- process.exit(1);
831
+ // 本地参数/文件层错误 → 用法错误(退出码 2),与服务端拒绝(1)区分。
832
+ emitUsageError(`Cannot read file: ${file}`);
511
833
  }
512
834
  const ext = path.extname(file).toLowerCase();
513
835
  const lang = opts.language ??
@@ -519,8 +841,7 @@ export function tasksCommand() {
519
841
  ? 'shell'
520
842
  : undefined);
521
843
  if (!lang) {
522
- console.error(chalk.red(`Cannot infer language from extension "${ext}" — pass --language node|python|shell`));
523
- process.exit(1);
844
+ emitUsageError(`Cannot infer language from extension "${ext}" — pass --language node|python|shell`);
524
845
  }
525
846
  const ok = (msg) => {
526
847
  console.log(chalk.green(`✔ ${file}: ${msg}`));
@@ -623,9 +944,9 @@ async function pollExecution(execId, waitTimeoutSeconds = 600) {
623
944
  // 空转到 MAX_WAIT 并误报超时,掩盖真实错误;立即退出并透出后端消息。
624
945
  const status = axios.isAxiosError(e) ? e.response?.status : undefined;
625
946
  if (status && status >= 400 && status < 500 && status !== 429) {
626
- spinner.fail('Waiting for execution failed');
627
- console.error(chalk.red(formatApiError(e)));
628
- process.exit(1);
947
+ // 统一错误出口:4xx 按类别映射退出码(401→3、其余→1),网络/5xx 继续
948
+ // 轮询(下方 transient 分支)。
949
+ emitError('Waiting for execution failed', e, { spinner });
629
950
  }
630
951
  // transient (network / 429 / 5xx), keep polling
631
952
  }