@autocodeflow/cli 1.8.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LuluDeer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -11,6 +11,12 @@ acf task trigger <taskId> --wait
11
11
  acf exec tail <execId>
12
12
  ```
13
13
 
14
+ > **API 地址口径**(2026-10-07):admin-api 路由带全局 `/api` 前缀。
15
+ > `--api-url`/`ACF_API_URL`/login 的 URL prompt 对**不带** `/api` 尾段的地址
16
+ > 会在请求期自动补上(缺补已有留——修复了默认 `http://localhost:3105` 对
17
+ > 标准部署恒 404 的开箱缺陷);已带 `/api` 的地址逐字节原样。唯一不适用:
18
+ > 「剥 `/api` 前缀」的反代且喂根地址——请传剥前缀后的源站地址。
19
+
14
20
  每个命令(含每个子命令)都支持 `acf <命令> --help`:一行用途、参数表,以及
15
21
  至少一个可直接复制的示例。缺参 / 未知命令 / 未知选项时,报错行之后会紧跟该
16
22
  命令的完整帮助(含示例),不需要去翻文档。
@@ -44,6 +50,9 @@ CLI 的非零退出码按失败类别区分,脚本/CI 可以只按码分支处
44
50
  `task compare`、`task logs`、`task trigger`、`app get`、`app versions`、
45
51
  `executor get`、`sop show`、`project list`、`project members`)→
46
52
  pretty(2) JSON。
53
+ - 部分写面命令同样支持 `--json`(响应对象直出):`app upload`、
54
+ `app upgrade-all`、`task webhook`、`task export`、`task batch`、
55
+ `apikey create`。
47
56
 
48
57
  `--json` 不裁剪字段:后端返回什么就输出什么,消费方按 `--help` 示例里的
49
58
  形状断言即可。
@@ -58,9 +67,34 @@ CLI 的非零退出码按失败类别区分,脚本/CI 可以只按码分支处
58
67
  推荐,不落盘);`--api-url` / `--token` 可单次覆盖。
59
68
  - `acf login` 的密码输入不回显;`--password` 参数已标记 deprecated(会进
60
69
  shell history),CI 请用 `ACF_PASSWORD`。
70
+ - 已启用 TOTP(两步验证)的账号:`acf login` 会在密码后提示输入 6 位动态码;
71
+ CI/非交互场景用 `acf login --user <name> --code <6位码>` 提供(stdin 非交互
72
+ 且缺 `--code` 时会报可操作的用法错误,退出码 2)。
73
+ - `acf apikey`(AUTH-03):为 CI/CD 创建限权 API Key(`readonly` / `trigger` /
74
+ `manage`)。明文(`acf_<64 hex>`)仅在 `acf apikey create` 时回显**一次**,
75
+ 此后只能 `acf apikey list`(脱敏)/ `acf apikey revoke <id>`。
61
76
  - Access token 过期时自动用 refresh token 换发并重放一次;刷新失败才要求
62
77
  重新登录(此时退出码为 3)。
63
78
 
79
+ ## 应用包上传 / 灰度升级 / 审批 / webhook / glue
80
+
81
+ - `acf app upload <pkg.zip> --name <name>`:multipart 上传应用包(按名称
82
+ upsert;`.zip` 扩展名/魔数/zip-bomb 校验在服务端)。`--runtime` / `--version`
83
+ 可选;大包上传走独立 300s 超时预算。
84
+ - `acf app upgrade-all <appId>`:对全部 RUNNING 部署触发滚动升级(缺省 = 全量,
85
+ 既有语义)。`--strategy canary --percentage N`(int 1-100,缺省 50)走灰度:
86
+ 首批心跳确认 → 健康探测 → 自动提升其余台。**批次由服务端异步推进,受理 ≠
87
+ 完成**——进度看 admin 中台(部署行 `rolloutState`)或 `acf app deployments`。
88
+ - `acf approval list | approve <id> --note … | reject <id> | cancel <id>`:
89
+ DEP-04 审批流。第二人规则在服务端强制(审批者 ≠ 提交者,否则 403);
90
+ 撤回自己的请求用 `cancel`;`--note`(≤200 字符)映射契约字段 `reason`。
91
+ - `acf task webhook enable|rotate|disable|status <taskId>`:任务级入站 webhook
92
+ (HMAC)。secret 仅在 enable/rotate 响应中回显**一次**;`status` 查看 URL
93
+ 不动密钥;`disable` 后签名请求即刻 401。
94
+ - `acf task glue <taskId> -f glue.js`(或 `--stdin`):在线更新 GLUE 脚本。
95
+ 语言按扩展名推断(`.js/.mjs/.cjs` → `javascript`),或 `--language
96
+ python|javascript|shell` 显式指定(执行器运行时白名单);空脚本本地即拒。
97
+
64
98
  ## 开发
65
99
 
66
100
  ```bash
package/dist/client.d.ts CHANGED
@@ -7,9 +7,27 @@
7
7
  * 覆盖实例默认),其余端点维持 30s。
8
8
  */
9
9
  export declare const ANALYZE_TIMEOUT_MS = 120000;
10
+ /**
11
+ * P2:`acf app upload` 的 per-call 超时预算。
12
+ *
13
+ * 应用包上限 200 MB(服务端 multer 硬限),实例默认 30s 在普通带宽上结构性
14
+ * 不够——几 MB/s 的链路传 200MB 远超 30s,包还没传完 CLI 已放弃。给 300s
15
+ * (axios per-request timeout 覆盖实例默认,其余端点维持 30s)。
16
+ */
17
+ export declare const UPLOAD_TIMEOUT_MS = 300000;
10
18
  /** Reset client (needed after config changes in same process). */
11
19
  export declare function resetClient(): void;
12
20
  export declare function unwrap<T>(raw: unknown): T;
21
+ /**
22
+ * TOTP-PTY-smoke(2026-10-07)实测抓出的 P1:admin-api 有全局 `api` 前缀
23
+ * (main.ts setGlobalPrefix),而 CLI 的默认 URL 与请求路径都不带 `/api`——
24
+ * 开箱即用形态对标准部署 100% 404。与 node-sdk 的双形态归一(
25
+ * stripTrailingApiSuffix 先例)同思路:baseUrl 缺 `/api` 尾段时请求期补上;
26
+ * 已带 `/api`(按 autoapp-skill 文档约定传公网地址的用户)逐字节原样。
27
+ * 已知边界:经「剥 /api 前缀」反代的部署若把根地址(不带 /api)喂给 CLI,
28
+ * 归一会产生双前缀 404——这类部署请传剥前缀后的源站地址(README 已注明)。
29
+ */
30
+ export declare function normalizeApiBase(url: string): string;
13
31
  export declare function get<T>(path: string, params?: Record<string, string | number | undefined>): Promise<T>;
14
32
  export declare function post<T>(path: string, body?: unknown, timeoutMs?: number): Promise<T>;
15
33
  export declare function put<T>(path: string, body?: unknown): Promise<T>;
package/dist/client.js CHANGED
@@ -13,6 +13,14 @@ let _client = null;
13
13
  * 覆盖实例默认),其余端点维持 30s。
14
14
  */
15
15
  export const ANALYZE_TIMEOUT_MS = 120_000;
16
+ /**
17
+ * P2:`acf app upload` 的 per-call 超时预算。
18
+ *
19
+ * 应用包上限 200 MB(服务端 multer 硬限),实例默认 30s 在普通带宽上结构性
20
+ * 不够——几 MB/s 的链路传 200MB 远超 30s,包还没传完 CLI 已放弃。给 300s
21
+ * (axios per-request timeout 覆盖实例默认,其余端点维持 30s)。
22
+ */
23
+ export const UPLOAD_TIMEOUT_MS = 300_000;
16
24
  /** base URL without trailing slashes(/auth/refresh 直连拼接用) */
17
25
  function baseUrl() {
18
26
  return getApiUrl().replace(/\/+$/, "");
@@ -81,10 +89,35 @@ async function refreshAccessToken() {
81
89
  function isAuthPath(url) {
82
90
  return !!url && url.includes("/auth/");
83
91
  }
92
+ /**
93
+ * TOTP-PTY-smoke(2026-10-07)实测抓出的 P1:admin-api 有全局 `api` 前缀
94
+ * (main.ts setGlobalPrefix),而 CLI 的默认 URL 与请求路径都不带 `/api`——
95
+ * 开箱即用形态对标准部署 100% 404。与 node-sdk 的双形态归一(
96
+ * stripTrailingApiSuffix 先例)同思路:baseUrl 缺 `/api` 尾段时请求期补上;
97
+ * 已带 `/api`(按 autoapp-skill 文档约定传公网地址的用户)逐字节原样。
98
+ * 已知边界:经「剥 /api 前缀」反代的部署若把根地址(不带 /api)喂给 CLI,
99
+ * 归一会产生双前缀 404——这类部署请传剥前缀后的源站地址(README 已注明)。
100
+ */
101
+ export function normalizeApiBase(url) {
102
+ let out = url.replace(/\/+$/, "");
103
+ try {
104
+ const u = new URL(out);
105
+ if (!u.pathname.replace(/\/+$/, "").endsWith("/api")) {
106
+ u.pathname = u.pathname.replace(/\/+$/, "") + "/api";
107
+ }
108
+ out = u.toString().replace(/\/+$/, "");
109
+ }
110
+ catch {
111
+ // 相对/非法 URL(测试桩场景):字符串级兜底
112
+ if (!out.endsWith("/api"))
113
+ out += "/api";
114
+ }
115
+ return out;
116
+ }
84
117
  function getClient() {
85
118
  if (!_client) {
86
119
  _client = axios.create({
87
- baseURL: getApiUrl(),
120
+ baseURL: normalizeApiBase(getApiUrl()),
88
121
  timeout: 30_000,
89
122
  });
90
123
  // Token 逐请求读取(不再在实例创建时烘焙):同进程内 login / 刷新轮换
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function apikeysCommand(): Command;
@@ -0,0 +1,104 @@
1
+ import { Command, InvalidArgumentError } from 'commander';
2
+ import Table from 'cli-table3';
3
+ import chalk from 'chalk';
4
+ import ora from 'ora';
5
+ import { get, post, del } from '../client.js';
6
+ import { emitError, emitUsageError } from '../ui.js';
7
+ // scope 三级矩阵(api-reference.md「API Keys」节):readonly 读 / trigger
8
+ // 读+触发 / manage 全量。本地预检只为报错快一点,服务端 IsIn 仍是权威。
9
+ const SCOPES = ['readonly', 'trigger', 'manage'];
10
+ export function apikeysCommand() {
11
+ const cmd = new Command('apikey')
12
+ .description('Manage API keys (limited-scope machine credentials for CI/CD)');
13
+ cmd.command('create')
14
+ .description('Create an API key — the plaintext (acf_…) is echoed exactly once and can never be retrieved again')
15
+ .requiredOption('--name <name>', 'Key name (1-100 chars)')
16
+ .requiredOption('--scope <scope>', 'Scope: readonly | trigger | manage')
17
+ .option('--expires <days>', 'Expires in N days (1-3650; default: never expires)', (v) => {
18
+ const n = Number.parseInt(v, 10);
19
+ if (!Number.isInteger(n) || n < 1 || n > 3650) {
20
+ throw new InvalidArgumentError('must be an integer between 1 and 3650 (days)');
21
+ }
22
+ return n;
23
+ })
24
+ .option('--json', 'Emit raw JSON (CI-consumable; includes the one-time plaintext)')
25
+ .action(async (opts) => {
26
+ if (!SCOPES.includes(opts.scope)) {
27
+ emitUsageError(`Unknown scope "${opts.scope}" — expected one of: ${SCOPES.join(' | ')}`);
28
+ }
29
+ const spinner = ora('Creating API key…').start();
30
+ try {
31
+ // CreateApiKeyDto 白名单:{ name, scope, expiresInDays? }。不发送
32
+ // undefined 键(forbidNonWhitelisted 下未知/空键没有意义)。
33
+ const body = { name: opts.name, scope: opts.scope };
34
+ if (opts.expires !== undefined)
35
+ body.expiresInDays = opts.expires;
36
+ const key = await post('/api-keys', body);
37
+ spinner.stop();
38
+ if (opts.json) {
39
+ console.log(JSON.stringify(key));
40
+ return;
41
+ }
42
+ console.log(chalk.green(`✔ API key created: ${key.name} (id: ${key.id})`));
43
+ console.log(' Prefix :', key.keyPrefix);
44
+ console.log(' Scope :', key.scope);
45
+ console.log(' Plaintext :', chalk.bold(key.plaintext));
46
+ console.log(chalk.yellow(' ⚠ The plaintext is shown only once — store it now (CI secret store / env file). It cannot be retrieved or re-displayed later.'));
47
+ }
48
+ catch (e) {
49
+ emitError('Failed to create API key', e, { spinner });
50
+ }
51
+ });
52
+ cmd.command('list')
53
+ .description('List your API keys (masked view — plaintext is never returned by the API)')
54
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
55
+ .action(async (opts) => {
56
+ const spinner = ora('Fetching API keys…').start();
57
+ try {
58
+ const keys = await get('/api-keys');
59
+ spinner.stop();
60
+ if (opts.json) {
61
+ console.log(JSON.stringify(keys ?? []));
62
+ return;
63
+ }
64
+ const table = new Table({
65
+ head: ['ID', 'Name', 'Prefix', 'Scope', 'Expires', 'Status', 'Last used'],
66
+ colWidths: [6, 26, 14, 10, 22, 10, 22],
67
+ style: { head: ['cyan'] },
68
+ });
69
+ for (const k of keys ?? []) {
70
+ table.push([
71
+ String(k.id),
72
+ k.name,
73
+ k.keyPrefix,
74
+ k.scope,
75
+ k.expiresAt ? new Date(k.expiresAt).toLocaleString() : 'never',
76
+ k.revokedAt ? chalk.red('revoked') : chalk.green('active'),
77
+ k.lastUsedAt ? new Date(k.lastUsedAt).toLocaleString() : '-',
78
+ ]);
79
+ }
80
+ console.log(table.toString());
81
+ }
82
+ catch (e) {
83
+ emitError('Failed to list API keys', e, { spinner });
84
+ }
85
+ });
86
+ cmd.command('revoke <id>')
87
+ .description('Revoke an API key (soft-delete — takes effect on its next request, cannot be undone)')
88
+ .action(async (id) => {
89
+ // 服务端 ParseIntPipe:id 是数字主键(acf apikey list 查看)。
90
+ if (!/^\d+$/.test(id)) {
91
+ emitUsageError(`API key id must be a number (got "${id}") — find ids with: acf apikey list`);
92
+ }
93
+ const spinner = ora('Revoking API key…').start();
94
+ try {
95
+ // DELETE /api-keys/:id(REST 主语义;POST /:id/revoke 是幂等别名端点)。
96
+ await del(`/api-keys/${id}`);
97
+ spinner.succeed(`API key ${id} revoked`);
98
+ }
99
+ catch (e) {
100
+ emitError('Failed to revoke API key', e, { spinner });
101
+ }
102
+ });
103
+ return cmd;
104
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function approvalCommand(): Command;
@@ -0,0 +1,122 @@
1
+ import { Command } from 'commander';
2
+ import Table from 'cli-table3';
3
+ import chalk from 'chalk';
4
+ import ora from 'ora';
5
+ import { get, post } from '../client.js';
6
+ import { emitError, emitUsageError } from '../ui.js';
7
+ const LIST_STATUSES = ['pending', 'approved', 'rejected', 'cancelled'];
8
+ function statusColor(s) {
9
+ if (s === 'running')
10
+ return chalk.green(s);
11
+ if (s === 'failed' || s === 'stopped')
12
+ return chalk.red(s);
13
+ if (s === 'deploying')
14
+ return chalk.cyan(s);
15
+ return chalk.yellow(s);
16
+ }
17
+ export function approvalCommand() {
18
+ const cmd = new Command('approval')
19
+ .description('DEP-04 deployment approvals (second-person rule enforced server-side; ADMIN only)');
20
+ // acf approval list
21
+ cmd.command('list')
22
+ .description('List deployments in the approval workflow. Default (--status pending) hits the dedicated ADMIN queue; approved/rejected/cancelled filter the generic deployment list')
23
+ .option('-s, --status <status>', 'pending (default) | approved | rejected | cancelled', 'pending')
24
+ .option('-a, --application <appId>', 'Filter by application ID')
25
+ .option('-p, --page <n>', 'Page number', '1')
26
+ .option('-n, --page-size <n>', 'Page size (max 100)', '20')
27
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
28
+ .action(async (opts) => {
29
+ if (!LIST_STATUSES.includes(opts.status)) {
30
+ emitUsageError(`Unknown approval status "${opts.status}" — expected one of: ${LIST_STATUSES.join(' | ')}`);
31
+ }
32
+ const spinner = ora('Fetching approvals…').start();
33
+ try {
34
+ const query = {
35
+ page: opts.page,
36
+ pageSize: opts.pageSize,
37
+ ...(opts.application ? { applicationId: opts.application } : {}),
38
+ };
39
+ // pending 走专用 ADMIN 队列端点;终态走通用列表的 approvalStatus 过滤
40
+ //(契约两端口径,服务端同一 findAll 实现,均返回 { data, total })。
41
+ const data = await get(opts.status === 'pending' ? '/app-deployments/approvals/pending' : '/app-deployments', opts.status === 'pending' ? query : { ...query, approvalStatus: opts.status });
42
+ spinner.stop();
43
+ if (opts.json) {
44
+ // ECO-02:列表/信封形态 → 单行紧凑 JSON
45
+ console.log(JSON.stringify(data));
46
+ return;
47
+ }
48
+ const list = Array.isArray(data) ? data : (data.data ?? []);
49
+ const table = new Table({
50
+ head: ['Deployment', 'App', 'Executor', 'Status', 'Version', 'Requested by'],
51
+ colWidths: [14, 14, 14, 16, 10, 14],
52
+ style: { head: ['cyan'] },
53
+ });
54
+ for (const d of list) {
55
+ table.push([
56
+ d.id.slice(0, 12),
57
+ d.applicationId?.slice(0, 12) ?? '-',
58
+ d.executorId?.slice(0, 12) ?? '-',
59
+ statusColor(d.status),
60
+ d.deployedVersion ?? '-',
61
+ String(d.approvalMeta?.requestedBy ?? '-'),
62
+ ]);
63
+ }
64
+ console.log(table.toString());
65
+ }
66
+ catch (e) {
67
+ emitError('Failed to list approvals', e, { spinner });
68
+ }
69
+ });
70
+ // acf approval approve <id>
71
+ cmd.command('approve <id>')
72
+ .description('Approve a pending deployment (ADMIN). Second-person rule: the approver must differ from the requester (403 otherwise) — to withdraw your own request use: acf approval cancel. On success the deployment is dispatched to the executor')
73
+ .option('--note <text>', 'Decision reason (max 200 chars), recorded in approvalMeta and the audit log')
74
+ .action(async (id, opts) => {
75
+ if (opts.note && opts.note.length > 200) {
76
+ emitUsageError(`--note is limited to 200 characters (got ${opts.note.length}) — the server enforces the same cap on the approval reason`);
77
+ }
78
+ const spinner = ora('Approving deployment…').start();
79
+ try {
80
+ // ApprovalActionDto 白名单:{ reason? }(≤200)。未给 note 时不发 body。
81
+ const dep = await post(`/app-deployments/${id}/approval/approve`, opts.note ? { reason: opts.note } : undefined);
82
+ spinner.succeed('Deployment approved — dispatching to the executor');
83
+ console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
84
+ }
85
+ catch (e) {
86
+ emitError('Failed to approve deployment', e, { spinner });
87
+ }
88
+ });
89
+ // acf approval reject <id>
90
+ cmd.command('reject <id>')
91
+ .description('Reject a pending deployment (ADMIN). Nothing is ever dispatched — the row lands in a FAILED terminal state. Second-person rule applies; the reason lands in approvalMeta/statusMessage and the audit log')
92
+ .option('--note <text>', 'Decision reason (max 200 chars), recorded in approvalMeta and the audit log')
93
+ .action(async (id, opts) => {
94
+ if (opts.note && opts.note.length > 200) {
95
+ emitUsageError(`--note is limited to 200 characters (got ${opts.note.length}) — the server enforces the same cap on the approval reason`);
96
+ }
97
+ const spinner = ora('Rejecting deployment…').start();
98
+ try {
99
+ const dep = await post(`/app-deployments/${id}/approval/reject`, opts.note ? { reason: opts.note } : undefined);
100
+ spinner.succeed('Deployment rejected — nothing will be dispatched (row lands FAILED)');
101
+ console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
102
+ }
103
+ catch (e) {
104
+ emitError('Failed to reject deployment', e, { spinner });
105
+ }
106
+ });
107
+ // acf approval cancel <id>
108
+ cmd.command('cancel <id>')
109
+ .description('Withdraw your own pending deployment request (requester-only — other admins who want to veto should use: acf approval reject)')
110
+ .action(async (id) => {
111
+ const spinner = ora('Cancelling pending request…').start();
112
+ try {
113
+ const dep = await post(`/app-deployments/${id}/approval/cancel`);
114
+ spinner.succeed('Pending deployment request cancelled (row lands FAILED)');
115
+ console.log(chalk.gray(` deployment: ${dep?.id ?? id} status: ${dep?.status ?? '-'} approval: ${dep?.approvalStatus ?? '-'}`));
116
+ }
117
+ catch (e) {
118
+ emitError('Failed to cancel deployment', e, { spinner });
119
+ }
120
+ });
121
+ return cmd;
122
+ }
@@ -1,9 +1,10 @@
1
- import { Command } from 'commander';
1
+ import { Command, InvalidArgumentError } from 'commander';
2
2
  import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
- import { get, post, put, del, ANALYZE_TIMEOUT_MS } from '../client.js';
6
- import { emitError, UsageError, interruptExit } from '../ui.js';
5
+ import * as path from 'path';
6
+ import { get, post, put, del, ANALYZE_TIMEOUT_MS, UPLOAD_TIMEOUT_MS } from '../client.js';
7
+ import { emitError, emitUsageError, UsageError, interruptExit } from '../ui.js';
7
8
  function statusColor(s) {
8
9
  if (s === 'running')
9
10
  return chalk.green(s);
@@ -123,6 +124,61 @@ export function appsCommand() {
123
124
  emitError('Failed to create application', e, { spinner });
124
125
  }
125
126
  });
127
+ // P2: acf app upload <zip> —— POST /applications/upload(multipart/form-data,
128
+ // 按名称 upsert:应用已存在只更新 packageUrl(可选 runtime/version),不存在
129
+ // 则创建)。入参白名单以服务端 UploadApplicationDto 为准:file/name 必填、
130
+ // runtime/version 可选——forbidNonWhitelisted 下多一个字段都 400,故可选字段
131
+ // 只在用户给出时才 append。zip 魔数/大小/zip 炸弹校验是服务端职责(400/503
132
+ // 契约语义),CLI 不复刻,只做廉价的扩展名/可读性预检(退出码 2,请求不发)。
133
+ cmd.command('upload <zip>')
134
+ .description('Upload an application package (.zip, max 200 MB) and upsert it by name: an existing app only gets its packageUrl (and runtime/version) updated, a new one is created. ZIP magic/size/zip-bomb checks are server-side')
135
+ .requiredOption('--name <name>', 'Application name (1-100 chars) — the upsert key')
136
+ .option('--runtime <runtime>', 'Runtime type (max 50 chars; a NEW app defaults to python when omitted)')
137
+ .option('--version <version>', 'Version to record for this upload (e.g. 1.2.0); omit to keep the current version')
138
+ .option('--json', 'Emit raw JSON (CI-consumable)')
139
+ .action(async (zip, opts) => {
140
+ const spinner = ora('Uploading package…').start();
141
+ try {
142
+ if (!/\.zip$/i.test(zip)) {
143
+ throw new UsageError(`Only .zip packages are accepted (got "${zip}") — the server validates both extension and ZIP magic`);
144
+ }
145
+ const fsPromises = await import('fs/promises');
146
+ let buf;
147
+ try {
148
+ buf = await fsPromises.readFile(zip);
149
+ }
150
+ catch (err) {
151
+ // 本地文件层错误 = 用法错误(退出码 2),与服务端拒绝(1)区分;
152
+ // 口径与 loadJsonBody / task import 一致。
153
+ throw new UsageError(`Cannot read package file: ${zip} (${err instanceof Error ? err.message : String(err)})`);
154
+ }
155
+ // Node 内置 FormData/Blob(undici,Node >=18 全局可用):axios 1.x 识别
156
+ // spec FormData 后自动补 multipart boundary 与 Content-Type,无需引入
157
+ // form-data 依赖。字段名 file/name/runtime/version 是服务端 multer +
158
+ // DTO 白名单;不手动设 Content-Type(会把 boundary 写死)。
159
+ const form = new FormData();
160
+ form.append('file', new Blob([buf], { type: 'application/zip' }), path.basename(zip));
161
+ form.append('name', opts.name);
162
+ if (opts.runtime)
163
+ form.append('runtime', opts.runtime);
164
+ if (opts.version)
165
+ form.append('version', opts.version);
166
+ // NETOPT-6④ 同款思路:200MB 上限下实例默认 30s 结构性不够,用
167
+ // UPLOAD_TIMEOUT_MS(300s)per-call 覆盖。
168
+ const a = await post('/applications/upload', form, UPLOAD_TIMEOUT_MS);
169
+ spinner.stop();
170
+ if (opts.json) {
171
+ // ECO-02:单对象形态 → pretty JSON
172
+ console.log(JSON.stringify(a, null, 2));
173
+ return;
174
+ }
175
+ spinner.succeed(`Package uploaded: ${a.name}`);
176
+ console.log(chalk.gray(` id: ${a.id} version: ${a.version ?? '-'} status: ${statusColor(a.status)} packageUrl: ${a.packageUrl ?? '-'}`));
177
+ }
178
+ catch (e) {
179
+ emitError('Failed to upload package', e, { spinner });
180
+ }
181
+ });
126
182
  // acf app update <id>
127
183
  cmd.command('update <id>')
128
184
  .description('Update an application (JSON payload via --json or --file). ' +
@@ -227,6 +283,88 @@ export function appsCommand() {
227
283
  emitError('Deployment failed', e, { spinner });
228
284
  }
229
285
  });
286
+ // P2: acf app upgrade-all <appId> —— POST /applications/:id/upgrade-all(DEP-02
287
+ // 灰度)。契约:请求体全可选,缺省(不传 body)= all 全量升级,既有语义逐字节
288
+ // 保持;canary 传 { rollout: { strategy: 'canary', percentage? } }。注意
289
+ // UpgradeAllDto 只认 rollout —— 没有 per-call 版本覆盖(升级目标恒为应用当前
290
+ // 版本),发送未声明字段会被 forbidNonWhitelisted 400,故本命令不提供
291
+ // --version。批次由服务端异步推进(心跳确认 → 健康探测 → 提升),受理 ≠ 完成。
292
+ cmd.command('upgrade-all <appId>')
293
+ .description("Trigger a rolling upgrade of all RUNNING deployments to the application's current version (or --version). Default = full upgrade (pre-DEP-02 semantics, no body). Canary batches advance asynchronously on the server — acceptance is not completion")
294
+ .option('--strategy <strategy>', 'Rollout strategy: all (default) | canary (first batch → heartbeat confirm → health probe → auto-promote the rest, DEP-02)')
295
+ .option('--percentage <n>', 'Canary first-batch percentage, int 1-100 (default 50 — first batch = ceil(N × p%), at least 1)', (v) => {
296
+ const n = Number.parseInt(v, 10);
297
+ if (!Number.isInteger(n) || n < 1 || n > 100) {
298
+ throw new InvalidArgumentError('must be an integer between 1 and 100');
299
+ }
300
+ return n;
301
+ })
302
+ .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')
303
+ .option('--json', 'Emit raw JSON (CI-consumable)')
304
+ .action(async (appId, opts) => {
305
+ const strategy = opts.strategy ?? 'all';
306
+ if (strategy !== 'all' && strategy !== 'canary') {
307
+ emitUsageError(`Unknown rollout strategy "${strategy}" — expected one of: all | canary`);
308
+ }
309
+ if (opts.percentage !== undefined && strategy !== 'canary') {
310
+ emitUsageError('--percentage only applies to --strategy canary (the full-upgrade path never reads it)');
311
+ }
312
+ const spinner = ora('Triggering upgrade…').start();
313
+ try {
314
+ // all:不传 body —— 与既有全量升级语义逐字节一致;canary:rollout
315
+ // 白名单体,percentage 仅在给出时携带(服务端缺省 50)。
316
+ const body = strategy === 'canary'
317
+ ? {
318
+ ...(opts.version !== undefined ? { version: opts.version } : {}),
319
+ rollout: {
320
+ strategy,
321
+ ...(opts.percentage !== undefined ? { percentage: opts.percentage } : {}),
322
+ },
323
+ }
324
+ : opts.version !== undefined
325
+ ? { version: opts.version }
326
+ : undefined;
327
+ const r = await post(`/applications/${appId}/upgrade-all`, body);
328
+ spinner.stop();
329
+ if (opts.json) {
330
+ // ECO-02:响应对象直出(含 rollout 批次信息),退出码语义与下面的人读
331
+ // 路径一致(受理被拒/批次失败 → 1)。
332
+ console.log(JSON.stringify(r, null, 2));
333
+ if (r.ok === false || (r.failed ?? 0) > 0)
334
+ process.exitCode = 1;
335
+ return;
336
+ }
337
+ if (r.ok === false) {
338
+ // 受理被拒(ARCH-31 在途批次互斥 / canary 首批失败 ok=false,failed=1):
339
+ // HTTP 仍是 2xx,但 CLI 要让 CI 看得见(对齐 task batch 部分失败语义)。
340
+ spinner.fail('Upgrade batch not started');
341
+ console.error(chalk.red(` ${r.rollout?.blockedReason ?? `first canary batch failed (${r.failed}/${r.total}) — see rolloutMeta on the app's deployments for the reason`}`));
342
+ process.exitCode = 1;
343
+ return;
344
+ }
345
+ if (strategy === 'canary') {
346
+ spinner.succeed(`Canary batch accepted: first batch ${r.succeeded}/${r.total} deployment(s)`);
347
+ console.log(chalk.gray(` batchId: ${r.rollout?.batchId ?? '-'} strategy: ${r.rollout?.strategy ?? strategy}`));
348
+ if (r.rollout?.canaryIds?.length) {
349
+ console.log(chalk.gray(` canary: ${r.rollout.canaryIds.map((x) => x.slice(0, 12)).join(', ')}`));
350
+ }
351
+ if (r.rollout?.promotedIds?.length) {
352
+ console.log(chalk.gray(` promoted so far: ${r.rollout.promotedIds.length}`));
353
+ }
354
+ console.log(chalk.yellow(` ⚠ Accepted is not finished — the batch advances asynchronously (heartbeat confirm → health probe → promote). Follow progress in the admin console or: acf app deployments ${appId}`));
355
+ }
356
+ else {
357
+ spinner.succeed(`Upgrade triggered: ${r.succeeded}/${r.total} deployment(s) accepted, ${r.failed} failed`);
358
+ if ((r.failed ?? 0) > 0) {
359
+ console.error(chalk.red(` ${r.failed} deployment(s) failed to accept the upgrade — inspect with: acf app deployments ${appId}`));
360
+ process.exitCode = 1;
361
+ }
362
+ }
363
+ }
364
+ catch (e) {
365
+ emitError('Failed to trigger upgrade-all', e, { spinner });
366
+ }
367
+ });
230
368
  // acf app deployments [appId]
231
369
  cmd.command('deployments [appId]')
232
370
  .description('List deployments (optionally filtered by application)')
@@ -1,4 +1,7 @@
1
1
  import { Command } from 'commander';
2
2
  import * as readline from 'readline';
3
3
  export declare function maskEcho(rl: readline.Interface, isTTY?: boolean): void;
4
+ export declare function resolveTotpCode(opts: {
5
+ code?: string;
6
+ }, promptFn?: (question: string) => Promise<string>): Promise<string>;
4
7
  export declare function loginCommand(): Command;
@@ -2,7 +2,7 @@ import { Command } from 'commander';
2
2
  import * as readline from 'readline';
3
3
  import { post, resetClient } from '../client.js';
4
4
  import { setApiUrl, setToken, setRefreshToken, showConfig } from '../config.js';
5
- import { emitError, interruptExit } from '../ui.js';
5
+ import { emitError, interruptExit, UsageError } from '../ui.js';
6
6
  import chalk from 'chalk';
7
7
  function prompt(question) {
8
8
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
@@ -46,6 +46,39 @@ function hiddenPrompt(question) {
46
46
  resolve(ans);
47
47
  }));
48
48
  }
49
+ // 6 位码形态校验(TOTP 契约:HMAC-SHA1/6 位数字)。本地只判「形态」,
50
+ // 码对不对由服务端 /auth/totp/verify 判(错码 → 401 → 退出码 3)。
51
+ function assertTotpCodeFormat(code, source) {
52
+ if (!/^\d{6}$/.test(code)) {
53
+ const label = source === '--code' ? '--code' : 'Expected';
54
+ throw new UsageError(source === '--code'
55
+ ? `${label} must be a 6-digit TOTP code (got "${code}")`
56
+ : `${label} a 6-digit TOTP code (got "${code}")`);
57
+ }
58
+ }
59
+ // SEC-03:TOTP 登录第二段的 6 位码获取。
60
+ // - --code 提供 → 直接使用(CI/非交互场景,不碰 stdin);
61
+ // - 未提供且 stdin 非交互(TTY 检测,与 maskEcho 同判据)→ 可操作报错
62
+ // (UsageError → 退出码 2),明示如何用 --code 完成;
63
+ // - 其余 → 交互式 prompt(6 位码是一次性短效凭证,不需要像密码那样遮蔽回显)。
64
+ // 本地形态错误一律 throw UsageError(而非 emitUsageError):调用方 login 的
65
+ // action 在 try/catch 里统一走 emitError 出口,UsageError 会被映射到退出码 2
66
+ //(与 task create --file 的本地 payload 错误同一套路)。
67
+ // 导出供单测注入 promptFn(TTY 交互路径无法在测试里驱动真实 stdin)。
68
+ export async function resolveTotpCode(opts, promptFn = prompt) {
69
+ if (opts.code) {
70
+ const code = opts.code.trim();
71
+ assertTotpCodeFormat(code, '--code');
72
+ return code;
73
+ }
74
+ if (process.stdin.isTTY !== true) {
75
+ throw new UsageError('This account has TOTP enabled and stdin is not interactive (no prompt can be shown). ' +
76
+ 'Pass the 6-digit code with --code <code>, e.g. acf login --user admin --code 123456.');
77
+ }
78
+ const code = (await promptFn('TOTP code (6 digits): ')).trim();
79
+ assertTotpCodeFormat(code, 'prompt');
80
+ return code;
81
+ }
49
82
  export function loginCommand() {
50
83
  const cmd = new Command('login')
51
84
  .description('Authenticate with the AutoCodeFlow API and save credentials')
@@ -54,6 +87,9 @@ export function loginCommand() {
54
87
  // PK-27(DEEP_REVIEW 0ef3bbe):--password 明文会进 ps/shell history,标记 deprecated。
55
88
  // 仍保留以便一次性容器/CI 用(此时 ACF_PASSWORD env 更推荐,不进进程 argv)。
56
89
  .option('--password <password>', 'Password (DEPRECATED: visible in process list & shell history; prefer interactive hidden prompt or ACF_PASSWORD env)')
90
+ // SEC-03:TOTP 二段登录的 6 位动态码。交互终端下可省略(会 prompt);
91
+ // CI/非交互场景必须提供(stdin 非 TTY 且无 --code 时直接报用法错误)。
92
+ .option('--code <code>', '6-digit TOTP code (second factor). Required in non-interactive sessions when the account has TOTP enabled')
57
93
  .action(async (opts) => {
58
94
  try {
59
95
  const url = opts.url || await prompt('API URL [http://localhost:3105]: ') || 'http://localhost:3105';
@@ -72,25 +108,46 @@ export function loginCommand() {
72
108
  else {
73
109
  password = await hiddenPrompt('Password: ');
74
110
  }
75
- // admin-api auth.service.generateTokens returns camelCase { accessToken, refreshToken }
111
+ // --code 形态本地预检(在发起任何网络请求之前):坏格式直接报用法错误,
112
+ // 不消耗服务端登录限流(login 20/min、totp/verify 10/min 都是稀缺预算)。
113
+ if (opts.code)
114
+ assertTotpCodeFormat(String(opts.code).trim(), '--code');
115
+ // admin-api auth.service.generateTokens returns camelCase { accessToken, refreshToken }.
116
+ // SEC-03: TOTP 已启用用户返回 200 + { totpRequired: true }(无 token),
117
+ // 进入二段流程:username+password+code 复验后签发双 token。
76
118
  const data = await post('/auth/login', {
77
119
  username: username.trim(),
78
120
  password,
79
121
  });
80
- if (!data.accessToken) {
122
+ let tokens;
123
+ if ('accessToken' in data && data.accessToken) {
124
+ tokens = data;
125
+ }
126
+ else if (data.totpRequired === true) {
127
+ const code = await resolveTotpCode(opts);
128
+ // 契约(api-reference.md / TotpVerifyDto):{ username, password, code },
129
+ // 响应与普通登录同形(双 token)。错码 → 401(计入登录失败锁定),
130
+ // 走下方统一的 Login failed 错误出口(退出码 3)。
131
+ tokens = await post('/auth/totp/verify', {
132
+ username: username.trim(),
133
+ password,
134
+ code,
135
+ });
136
+ }
137
+ else {
81
138
  throw new Error('Login response missing accessToken (unexpected auth payload)');
82
139
  }
83
- setToken(data.accessToken);
140
+ setToken(tokens.accessToken);
84
141
  // BUG-13: refreshToken 一并入库——access token 默认 15m 过期,
85
142
  // client 的 401 单飞自愈(/auth/refresh + 重放一次)依赖它,
86
143
  // 否则过期后全命令 401 只能重新 login。
87
- setRefreshToken(data.refreshToken ?? '');
144
+ setRefreshToken(tokens.refreshToken ?? '');
88
145
  console.log(chalk.green('✔ Logged in successfully'));
89
146
  showConfig();
90
147
  }
91
148
  catch (e) {
92
- // 统一错误出口:401(密码错/token 失效)→ 退出码 3,网络不通 → 4,
93
- // 其余 → 1(见 ui.ts 的 EXIT_CODES 表)。
149
+ // 统一错误出口:401(密码错/TOTP 码错/token 失效)→ 退出码 3,
150
+ // 网络不通 → 4,其余 → 1(见 ui.ts 的 EXIT_CODES 表)。
94
151
  emitError('Login failed', e);
95
152
  }
96
153
  });
@@ -1,2 +1,8 @@
1
1
  import { Command } from 'commander';
2
+ /**
3
+ * E-1:`acf task import -` 的 stdin 读取。"-" 是 CI/管道惯例;stdin 是 TTY
4
+ * 时(用户忘了给文件、手敲 `-`)拒绝而不是挂死等待 EOF。流参数可注入——
5
+ * 单测用 PassThrough 驱动,不碰真实 stdin。
6
+ */
7
+ export declare function readStdin(stream?: NodeJS.ReadableStream): Promise<string>;
2
8
  export declare function tasksCommand(): Command;
@@ -6,8 +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, ANALYZE_TIMEOUT_MS } from '../client.js';
9
+ import { get, post, put, patch, del, ANALYZE_TIMEOUT_MS } from '../client.js';
10
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
+ }
11
47
  function statusColor(s) {
12
48
  if (s === 'success')
13
49
  return chalk.green(s);
@@ -373,19 +409,34 @@ export function tasksCommand() {
373
409
  });
374
410
  // acf task create
375
411
  cmd.command('create')
376
- .description('Create a new task (JSON payload via --json or --file)')
377
- .requiredOption('--json <body>', 'Task body as JSON string')
378
- .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)')
379
421
  .option('--executor <id>', 'Pin the task to a specific executor ID (uuid); mutually exclusive with executeMode=broadcast')
380
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
+ }
381
429
  const spinner = ora('Creating task…').start();
382
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
+ }
383
434
  const fs = await import('fs/promises');
384
435
  // 本地 payload 层错误(文件读不了/JSON 坏)= 用法错误(退出码 2),
385
436
  // 与服务端拒绝(1)区分;口径与 apps.ts 的 loadJsonBody 一致。
386
437
  let raw;
387
438
  try {
388
- raw = opts.file ? await fs.readFile(opts.file, 'utf-8') : opts.json;
439
+ raw = opts.file ? await fs.readFile(opts.file, 'utf-8') : (opts.body ?? opts.json);
389
440
  }
390
441
  catch (err) {
391
442
  throw new UsageError(`Cannot read payload file: ${opts.file} (${err instanceof Error ? err.message : String(err)})`);
@@ -410,19 +461,30 @@ export function tasksCommand() {
410
461
  });
411
462
  // acf task update <id>
412
463
  cmd.command('update <id>')
413
- .description('Update a task (JSON payload via --json or --file)')
414
- .requiredOption('--json <body>', 'Task patch body as JSON string')
415
- .option('--file <path>', 'Read task patch body from a JSON file (overrides --json)')
416
- .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')
417
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
+ }
418
477
  const spinner = ora('Updating task…').start();
419
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
+ }
420
482
  const fs = await import('fs/promises');
421
483
  // 本地 payload 层错误(文件读不了/JSON 坏)= 用法错误(退出码 2),
422
484
  // 与服务端拒绝(1)区分;口径与 apps.ts 的 loadJsonBody 一致。
423
485
  let raw;
424
486
  try {
425
- raw = opts.file ? await fs.readFile(opts.file, 'utf-8') : opts.json;
487
+ raw = opts.file ? await fs.readFile(opts.file, 'utf-8') : (opts.body ?? opts.json);
426
488
  }
427
489
  catch (err) {
428
490
  throw new UsageError(`Cannot read payload file: ${opts.file} (${err instanceof Error ? err.message : String(err)})`);
@@ -500,6 +562,128 @@ export function tasksCommand() {
500
562
  emitError('Failed to resume task', e, { spinner });
501
563
  }
502
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 });
685
+ }
686
+ });
503
687
  // acf task kill <taskId> <execId>
504
688
  cmd.command('kill <taskId> <execId>')
505
689
  .description('Force-cancel a running or pending execution')
@@ -513,6 +697,125 @@ export function tasksCommand() {
513
697
  emitError('Failed to cancel execution', e, { spinner });
514
698
  }
515
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 });
817
+ }
818
+ });
516
819
  // ECO-02: acf task lint <file> —— 本地语法检查(node: 语法编译不执行;
517
820
  // python: ast.parse;shell: bash -n)。上传 glue 前把语法错误挡在本地。
518
821
  cmd
package/dist/help.js CHANGED
@@ -8,6 +8,7 @@ export const EXAMPLES = {
8
8
  'acf login',
9
9
  'acf login --url https://acf.example.com --user admin',
10
10
  'ACF_PASSWORD=... acf login --user admin # CI: password via env, not argv',
11
+ 'acf login --user admin --code 123456 # TOTP-enabled account (second factor)',
11
12
  ],
12
13
  'task list': [
13
14
  'acf task list --status active --page 1',
@@ -41,7 +42,29 @@ export const EXAMPLES = {
41
42
  'task delete': ['acf task delete <taskId> -y'],
42
43
  'task pause': ['acf task pause <taskId>'],
43
44
  'task resume': ['acf task resume <taskId>'],
45
+ 'task export': [
46
+ 'acf task export <taskId>',
47
+ 'acf task export <taskId> -o task.json # payload is accepted verbatim by: acf task import task.json',
48
+ ],
49
+ 'task import': [
50
+ 'acf task import task.json',
51
+ 'cat task.json | acf task import - # "-" reads stdin; the new task starts paused',
52
+ ],
53
+ 'task batch': [
54
+ 'acf task batch trigger --ids id1,id2,id3',
55
+ 'acf task batch pause <id1> <id2>',
56
+ ],
44
57
  'task kill': ['acf task kill <taskId> <execId>'],
58
+ 'task webhook': [
59
+ 'acf task webhook enable <taskId> # prints the webhook URL + secret ONCE',
60
+ 'acf task webhook rotate <taskId> # old secret dies immediately, new one printed once',
61
+ 'acf task webhook status <taskId> # url + enabled, without touching the secret',
62
+ 'acf task webhook disable <taskId>',
63
+ ],
64
+ 'task glue': [
65
+ 'acf task glue <taskId> -f glue.js # language inferred from the extension (.js → javascript)',
66
+ 'cat glue.py | acf task glue <taskId> --stdin --language python',
67
+ ],
45
68
  'task lint': [
46
69
  'acf task lint glue.js',
47
70
  'acf task lint script.py --language python',
@@ -61,6 +84,14 @@ export const EXAMPLES = {
61
84
  ],
62
85
  'app deployments': ['acf app deployments <appId> -n 50 --json'],
63
86
  'app versions': ['acf app versions <appId> --json'],
87
+ 'app upload': [
88
+ 'acf app upload ./dist/app.zip --name my-app',
89
+ 'acf app upload ./dist/app.zip --name my-app --runtime python --version 1.2.0 --json',
90
+ ],
91
+ 'app upgrade-all': [
92
+ 'acf app upgrade-all <appId> # full rolling upgrade (default, no body)',
93
+ 'acf app upgrade-all <appId> --strategy canary --percentage 20 # canary first, auto-promote after probe',
94
+ ],
64
95
  'executor list': ['acf executor list', 'acf executor list --json'],
65
96
  'executor get': ['acf executor get <executorId> --json'],
66
97
  'executor rotate': [
@@ -82,6 +113,21 @@ export const EXAMPLES = {
82
113
  'acf agent sessions --status waiting_input',
83
114
  'acf agent sessions --json',
84
115
  ],
116
+ 'apikey create': [
117
+ 'acf apikey create --name ci-deploy --scope trigger',
118
+ 'acf apikey create --name nightly --scope readonly --expires 90 # plaintext is echoed ONCE',
119
+ ],
120
+ 'apikey list': ['acf apikey list', 'acf apikey list --json'],
121
+ 'apikey revoke': ['acf apikey revoke 3'],
122
+ 'approval list': [
123
+ 'acf approval list # pending queue (default)',
124
+ 'acf approval list --status rejected --json',
125
+ ],
126
+ 'approval approve': [
127
+ 'acf approval approve <deploymentId> --note "change window approved" # second person: approver ≠ requester',
128
+ ],
129
+ 'approval reject': ['acf approval reject <deploymentId> --note "wrong version"'],
130
+ 'approval cancel': ['acf approval cancel <deploymentId> # withdraw your own pending request'],
85
131
  'config show': ['acf config show'],
86
132
  'config set-url': ['acf config set-url http://localhost:3105'],
87
133
  'config set-token': ['acf config set-token <token> # prefer: acf login'],
package/dist/index.d.ts CHANGED
@@ -3,14 +3,20 @@
3
3
  * ACF CLI — AutoCodeFlow command-line interface
4
4
  *
5
5
  * Usage:
6
- * acf login
6
+ * acf login # TOTP accounts: add --code <6 digits> (or prompt)
7
7
  * acf task list
8
8
  * acf task trigger <id> --wait
9
+ * acf task export <id> [-o file] | import <file> | batch <trigger|pause|resume|delete> --ids id1,id2
9
10
  * acf task versions <id> | compare <id> <v1> <v2> | rollback <id> --version <vid>
10
11
  * acf task analyze <taskId> <execId>
11
12
  * acf task suggest-schedule <id>
12
13
  * acf app list | create | update <id> | delete <id>
14
+ * acf app upload <pkg.zip> --name <name>
15
+ * acf app upgrade-all <appId> [--strategy canary --percentage N]
13
16
  * acf app analyze <id>
17
+ * acf task webhook <enable|rotate|disable|status> <taskId>
18
+ * acf task glue <taskId> -f <file>
19
+ * acf approval list | approve <id> --note … | reject <id> | cancel <id>
14
20
  * acf deploy upgrade <deploymentId> | stop <deploymentId>
15
21
  * acf executor list | get <id> | rotate <name|id> | offline <name|id>
16
22
  * acf exec tail <execId>
@@ -18,6 +24,8 @@
18
24
  * acf audit list
19
25
  * acf sop list | show <sopId>
20
26
  * acf agent sessions
27
+ * acf apikey create --name <name> --scope <readonly|trigger|manage> [--expires <days>]
28
+ * acf apikey list | revoke <id>
21
29
  * acf config show
22
30
  *
23
31
  * 退出码表(docs 详见 README.md「Exit codes」,单一事实源在 src/ui.ts 的
package/dist/index.js CHANGED
@@ -3,14 +3,20 @@
3
3
  * ACF CLI — AutoCodeFlow command-line interface
4
4
  *
5
5
  * Usage:
6
- * acf login
6
+ * acf login # TOTP accounts: add --code <6 digits> (or prompt)
7
7
  * acf task list
8
8
  * acf task trigger <id> --wait
9
+ * acf task export <id> [-o file] | import <file> | batch <trigger|pause|resume|delete> --ids id1,id2
9
10
  * acf task versions <id> | compare <id> <v1> <v2> | rollback <id> --version <vid>
10
11
  * acf task analyze <taskId> <execId>
11
12
  * acf task suggest-schedule <id>
12
13
  * acf app list | create | update <id> | delete <id>
14
+ * acf app upload <pkg.zip> --name <name>
15
+ * acf app upgrade-all <appId> [--strategy canary --percentage N]
13
16
  * acf app analyze <id>
17
+ * acf task webhook <enable|rotate|disable|status> <taskId>
18
+ * acf task glue <taskId> -f <file>
19
+ * acf approval list | approve <id> --note … | reject <id> | cancel <id>
14
20
  * acf deploy upgrade <deploymentId> | stop <deploymentId>
15
21
  * acf executor list | get <id> | rotate <name|id> | offline <name|id>
16
22
  * acf exec tail <execId>
@@ -18,6 +24,8 @@
18
24
  * acf audit list
19
25
  * acf sop list | show <sopId>
20
26
  * acf agent sessions
27
+ * acf apikey create --name <name> --scope <readonly|trigger|manage> [--expires <days>]
28
+ * acf apikey list | revoke <id>
21
29
  * acf config show
22
30
  *
23
31
  * 退出码表(docs 详见 README.md「Exit codes」,单一事实源在 src/ui.ts 的
@@ -37,6 +45,8 @@ import { execCommand } from './commands/exec.js';
37
45
  import { projectsCommand } from './commands/projects.js';
38
46
  import { sopCommand } from './commands/sop.js';
39
47
  import { agentCommand } from './commands/agent.js';
48
+ import { apikeysCommand } from './commands/apikeys.js';
49
+ import { approvalCommand } from './commands/approval.js';
40
50
  import { showConfig, setApiUrl, setToken } from './config.js';
41
51
  import { applyExamples } from './help.js';
42
52
  import { EXIT_CODES, interruptExit } from './ui.js';
@@ -83,6 +93,8 @@ program.addCommand(execCommand());
83
93
  program.addCommand(projectsCommand());
84
94
  program.addCommand(sopCommand());
85
95
  program.addCommand(agentCommand());
96
+ program.addCommand(apikeysCommand());
97
+ program.addCommand(approvalCommand());
86
98
  // acf config show / set
87
99
  const configCmd = new Command('config').description('View or update CLI configuration');
88
100
  configCmd.command('show').description('Show current config').action(() => showConfig());
@@ -93,6 +105,10 @@ configCmd.command('set-url <url>').description('Set API base URL').action((url)
93
105
  configCmd.command('set-token <token>').description('Set auth token directly').action((token) => {
94
106
  setToken(token);
95
107
  console.log(chalk.green('✔ Token saved'));
108
+ // 安全提示(与 login 的 --password 告警同风格):命令行明文 token 会留在
109
+ // shell history 与进程列表里;login(交互隐藏输入 + 落 0600 配置文件)或
110
+ // ACF_TOKEN 环境变量(不进 argv)是更安全的通路。
111
+ process.stderr.write(chalk.yellow('⚠ A token passed on the command line can leak into shell history and the process list — prefer `acf login` or the ACF_TOKEN environment variable.\n'));
96
112
  });
97
113
  program.addCommand(configCmd);
98
114
  // 集中式 help:把 help.ts 的 EXAMPLES 表按命令路径走树注入(每个命令至少一个
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autocodeflow/cli",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "AutoCodeFlow CLI — manage tasks, executions and applications from the terminal",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",