@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.
- package/LICENSE +21 -0
- package/README.md +104 -0
- package/dist/client.d.ts +37 -0
- package/dist/client.js +56 -1
- package/dist/commands/agent.js +9 -4
- package/dist/commands/apikeys.d.ts +2 -0
- package/dist/commands/apikeys.js +104 -0
- package/dist/commands/approval.d.ts +2 -0
- package/dist/commands/approval.js +122 -0
- package/dist/commands/apps.js +186 -35
- package/dist/commands/audit.js +3 -4
- package/dist/commands/deploy.js +4 -7
- package/dist/commands/exec.js +4 -5
- package/dist/commands/executors.js +13 -14
- package/dist/commands/login.d.ts +5 -0
- package/dist/commands/login.js +93 -24
- package/dist/commands/projects.js +4 -7
- package/dist/commands/sop.js +17 -8
- package/dist/commands/tasks.d.ts +6 -0
- package/dist/commands/tasks.js +398 -77
- package/dist/config.js +65 -2
- package/dist/help.d.ts +21 -0
- package/dist/help.js +151 -0
- package/dist/index.d.ts +41 -1
- package/dist/index.js +90 -11
- package/dist/ui.d.ts +55 -0
- package/dist/ui.js +87 -0
- package/package.json +1 -1
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
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# @autocodeflow/cli
|
|
2
|
+
|
|
3
|
+
AutoCodeFlow CLI —— 在终端里管理任务、执行、应用、执行器与项目。
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm i -g @autocodeflow/cli
|
|
7
|
+
|
|
8
|
+
acf login
|
|
9
|
+
acf task list --status active
|
|
10
|
+
acf task trigger <taskId> --wait
|
|
11
|
+
acf exec tail <execId>
|
|
12
|
+
```
|
|
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
|
+
|
|
20
|
+
每个命令(含每个子命令)都支持 `acf <命令> --help`:一行用途、参数表,以及
|
|
21
|
+
至少一个可直接复制的示例。缺参 / 未知命令 / 未知选项时,报错行之后会紧跟该
|
|
22
|
+
命令的完整帮助(含示例),不需要去翻文档。
|
|
23
|
+
|
|
24
|
+
## 退出码
|
|
25
|
+
|
|
26
|
+
CLI 的非零退出码按失败类别区分,脚本/CI 可以只按码分支处理(所有非零码都
|
|
27
|
+
代表失败,`!= 0` 的既有判断不受影响):
|
|
28
|
+
|
|
29
|
+
| 退出码 | 含义 | 典型场景 / 下一步动作 |
|
|
30
|
+
| --- | --- | --- |
|
|
31
|
+
| `0` | 成功 | 含 `--help` / `--version` / 主动放弃确认(`Aborted.`) |
|
|
32
|
+
| `1` | 运行失败 | 服务端拒绝(400/403/404/409/5xx,错误行透出后端 message);`--wait` 等到失败终态;`acf task lint` 检出语法错误 |
|
|
33
|
+
| `2` | 用法 / 参数错误 | 缺参、未知命令/选项、非法取值(如 `--wait-timeout abc`);本地 payload 问题(JSON 解析失败、`--file` 读不了、`task lint` 无法推断语言) |
|
|
34
|
+
| `3` | 认证失败 | 401:凭据缺失/过期且自动刷新失败 → 运行 `acf login` |
|
|
35
|
+
| `4` | 网络失败 | 连接不通 / 超时 / DNS → 检查 `--api-url`、`ACF_API_URL`;`acf exec tail` 流中断或空闲超时 |
|
|
36
|
+
| `130` | 中断(SIGINT) | Ctrl+C。输出会补一个换行,不留半行 spinner |
|
|
37
|
+
|
|
38
|
+
单一事实源在 `src/ui.ts` 的 `EXIT_CODES`;错误分类(401/网络/服务端)在
|
|
39
|
+
`src/client.ts` 的 `classifyApiError` 做一次,命令层统一经 `emitError` 出口
|
|
40
|
+
消费。
|
|
41
|
+
|
|
42
|
+
## 机器可读输出(`--json`)
|
|
43
|
+
|
|
44
|
+
所有只读命令都支持 `--json`(CI/脚本消费面,错误仍走 stderr + 非零退出码):
|
|
45
|
+
|
|
46
|
+
- 列表 / 信封形态(`task list`、`task executions`、`app list`、
|
|
47
|
+
`app deployments`、`executor list`、`sop list`、`agent sessions`、
|
|
48
|
+
`audit list`)→ 单行紧凑 JSON,信封(`{list|data|items, total}`)原样直出;
|
|
49
|
+
- 单对象 / 详情形态(`task get`、`task stats`、`task versions`、
|
|
50
|
+
`task compare`、`task logs`、`task trigger`、`app get`、`app versions`、
|
|
51
|
+
`executor get`、`sop show`、`project list`、`project members`)→
|
|
52
|
+
pretty(2) JSON。
|
|
53
|
+
- 部分写面命令同样支持 `--json`(响应对象直出):`app upload`、
|
|
54
|
+
`app upgrade-all`、`task webhook`、`task export`、`task batch`、
|
|
55
|
+
`apikey create`。
|
|
56
|
+
|
|
57
|
+
`--json` 不裁剪字段:后端返回什么就输出什么,消费方按 `--help` 示例里的
|
|
58
|
+
形状断言即可。
|
|
59
|
+
|
|
60
|
+
## 认证与配置
|
|
61
|
+
|
|
62
|
+
凭据保存在用户配置目录(`acf config show` 查看实际路径),文件权限 0600;
|
|
63
|
+
文件损坏时 CLI 会把坏内容备份到 `<config>.corrupt`、给出 `acf login` 指引,
|
|
64
|
+
并用默认配置继续运行。
|
|
65
|
+
|
|
66
|
+
- `ACF_TOKEN` / `ACF_REFRESH_TOKEN` / `ACF_API_URL`:环境变量注入(CI/cron
|
|
67
|
+
推荐,不落盘);`--api-url` / `--token` 可单次覆盖。
|
|
68
|
+
- `acf login` 的密码输入不回显;`--password` 参数已标记 deprecated(会进
|
|
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>`。
|
|
76
|
+
- Access token 过期时自动用 refresh token 换发并重放一次;刷新失败才要求
|
|
77
|
+
重新登录(此时退出码为 3)。
|
|
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
|
+
|
|
98
|
+
## 开发
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
npm run test # vitest run
|
|
102
|
+
npm run typecheck # tsc --noEmit
|
|
103
|
+
npm run build # tsc → dist/
|
|
104
|
+
```
|
package/dist/client.d.ts
CHANGED
|
@@ -7,14 +7,51 @@
|
|
|
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>;
|
|
16
34
|
export declare function patch<T>(path: string, body?: unknown): Promise<T>;
|
|
17
35
|
export declare function del<T>(path: string): Promise<T>;
|
|
36
|
+
/**
|
|
37
|
+
* Error class taxonomy shared by the whole CLI. Classification is done ONCE,
|
|
38
|
+
* here at the HTTP-client layer (the only place that knows axios shapes), so
|
|
39
|
+
* the ten command files never re-implement it. `formatApiError` renders the
|
|
40
|
+
* human line; `classifyApiError` feeds the machine-facing exit code.
|
|
41
|
+
*/
|
|
42
|
+
export type ApiErrorClass = "auth" | "network" | "server" | "unknown";
|
|
43
|
+
/**
|
|
44
|
+
* Classify any thrown error for exit-code mapping:
|
|
45
|
+
* - `auth` → 401 (credentials missing/expired/invalid, refresh self-heal
|
|
46
|
+
* already failed) — the user must re-run `acf login`;
|
|
47
|
+
* - `network` → axios error without an HTTP response (connection refused,
|
|
48
|
+
* DNS, timeout) — the server was never reached;
|
|
49
|
+
* - `server` → any other HTTP status (400/403/404/409/5xx) — the request
|
|
50
|
+
* reached the API and was rejected; permission gaps (403) are a server-side
|
|
51
|
+
* decision, not a local credential state, so they stay in this class;
|
|
52
|
+
* - `unknown` → non-axios errors (local file IO, JSON parsing, ...).
|
|
53
|
+
*/
|
|
54
|
+
export declare function classifyApiError(e: unknown): ApiErrorClass;
|
|
18
55
|
/**
|
|
19
56
|
* Render any thrown error as a single readable line, distinguishing
|
|
20
57
|
* 401 (not authenticated) from 403 (authenticated but not allowed) and
|
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 / 刷新轮换
|
|
@@ -166,6 +199,28 @@ function detailFromData(data) {
|
|
|
166
199
|
return d.error;
|
|
167
200
|
return "";
|
|
168
201
|
}
|
|
202
|
+
/**
|
|
203
|
+
* Classify any thrown error for exit-code mapping:
|
|
204
|
+
* - `auth` → 401 (credentials missing/expired/invalid, refresh self-heal
|
|
205
|
+
* already failed) — the user must re-run `acf login`;
|
|
206
|
+
* - `network` → axios error without an HTTP response (connection refused,
|
|
207
|
+
* DNS, timeout) — the server was never reached;
|
|
208
|
+
* - `server` → any other HTTP status (400/403/404/409/5xx) — the request
|
|
209
|
+
* reached the API and was rejected; permission gaps (403) are a server-side
|
|
210
|
+
* decision, not a local credential state, so they stay in this class;
|
|
211
|
+
* - `unknown` → non-axios errors (local file IO, JSON parsing, ...).
|
|
212
|
+
*/
|
|
213
|
+
export function classifyApiError(e) {
|
|
214
|
+
if (axios.isAxiosError(e)) {
|
|
215
|
+
const status = e.response?.status;
|
|
216
|
+
if (!status)
|
|
217
|
+
return "network";
|
|
218
|
+
if (status === 401)
|
|
219
|
+
return "auth";
|
|
220
|
+
return "server";
|
|
221
|
+
}
|
|
222
|
+
return "unknown";
|
|
223
|
+
}
|
|
169
224
|
/**
|
|
170
225
|
* Render any thrown error as a single readable line, distinguishing
|
|
171
226
|
* 401 (not authenticated) from 403 (authenticated but not allowed) and
|
package/dist/commands/agent.js
CHANGED
|
@@ -2,7 +2,8 @@ import { Command } from 'commander';
|
|
|
2
2
|
import Table from 'cli-table3';
|
|
3
3
|
import chalk from 'chalk';
|
|
4
4
|
import ora from 'ora';
|
|
5
|
-
import { get
|
|
5
|
+
import { get } from '../client.js';
|
|
6
|
+
import { emitError } from '../ui.js';
|
|
6
7
|
export function agentCommand() {
|
|
7
8
|
const cmd = new Command('agent').description('Inspect agent sessions');
|
|
8
9
|
// acf agent sessions
|
|
@@ -12,6 +13,8 @@ export function agentCommand() {
|
|
|
12
13
|
.option('--status <status>', 'Filter by status (pending | running | waiting_input | succeeded | failed | aborted)')
|
|
13
14
|
.option('-p, --page <n>', 'Page number', '1')
|
|
14
15
|
.option('-n, --page-size <n>', 'Page size (max 100)', '20')
|
|
16
|
+
// --json 补面(本轮 UX 统一):对齐 audit list 的信封直出口径
|
|
17
|
+
.option('--json', 'Emit raw JSON (CI-consumable, no table)')
|
|
15
18
|
.action(async (opts) => {
|
|
16
19
|
const spinner = ora('Fetching agent sessions…').start();
|
|
17
20
|
try {
|
|
@@ -22,6 +25,10 @@ export function agentCommand() {
|
|
|
22
25
|
status: opts.status,
|
|
23
26
|
});
|
|
24
27
|
spinner.stop();
|
|
28
|
+
if (opts.json) {
|
|
29
|
+
console.log(JSON.stringify(data));
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
25
32
|
const items = data.items ?? data.data ?? [];
|
|
26
33
|
const table = new Table({
|
|
27
34
|
head: ['Time', 'Kind', 'Status', 'Title', 'ID'],
|
|
@@ -41,9 +48,7 @@ export function agentCommand() {
|
|
|
41
48
|
console.log(chalk.gray(`Total: ${data.total ?? items.length} page ${opts.page}`));
|
|
42
49
|
}
|
|
43
50
|
catch (e) {
|
|
44
|
-
|
|
45
|
-
console.error(chalk.red(formatApiError(e)));
|
|
46
|
-
process.exit(1);
|
|
51
|
+
emitError('Failed to list agent sessions', e, { spinner });
|
|
47
52
|
}
|
|
48
53
|
});
|
|
49
54
|
return cmd;
|
|
@@ -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,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
|
+
}
|