@autocodeflow/cli 1.5.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.
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.deployCommand = void 0;
7
+ const commander_1 = require("commander");
8
+ const chalk_1 = __importDefault(require("chalk"));
9
+ const ora_1 = __importDefault(require("ora"));
10
+ const client_1 = require("../client");
11
+ function deployCommand() {
12
+ const cmd = new commander_1.Command('deploy').description('Manage application deployments (upgrade / stop running instances)');
13
+ // acf deploy upgrade <deploymentId>
14
+ cmd.command('upgrade <deploymentId>')
15
+ .description('Trigger an overlay upgrade for a running deployment (pulls the latest application version)')
16
+ .action(async (deploymentId) => {
17
+ const spinner = (0, ora_1.default)('Triggering upgrade…').start();
18
+ try {
19
+ // POST /app-deployments/:id/upgrade — AppDeploymentController.upgrade
20
+ const dep = await (0, client_1.post)(`/app-deployments/${deploymentId}/upgrade`);
21
+ spinner.succeed(`Upgrade triggered for deployment ${deploymentId}`);
22
+ console.log(chalk_1.default.gray(` status: ${dep?.status ?? '-'} executor: ${dep?.executorId ?? '-'}`));
23
+ }
24
+ catch (e) {
25
+ spinner.fail('Failed to trigger upgrade');
26
+ console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
27
+ process.exit(1);
28
+ }
29
+ });
30
+ // acf deploy stop <deploymentId>
31
+ cmd.command('stop <deploymentId>')
32
+ .description('Stop a running deployment')
33
+ .action(async (deploymentId) => {
34
+ const spinner = (0, ora_1.default)('Stopping deployment…').start();
35
+ try {
36
+ // POST /app-deployments/:id/stop — AppDeploymentController.stop
37
+ const dep = await (0, client_1.post)(`/app-deployments/${deploymentId}/stop`);
38
+ spinner.succeed(`Deployment ${deploymentId} stopped`);
39
+ console.log(chalk_1.default.gray(` status: ${dep?.status ?? '-'}`));
40
+ }
41
+ catch (e) {
42
+ spinner.fail('Failed to stop deployment');
43
+ console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
44
+ process.exit(1);
45
+ }
46
+ });
47
+ return cmd;
48
+ }
49
+ exports.deployCommand = deployCommand;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * ECO-02: acf exec tail <execId> —— 实时跟随执行日志(SSE)。
3
+ *
4
+ * 路由契约:
5
+ * - GET /tasks/executions/:execId(compat alias)解析 taskId 与状态;
6
+ * - 终态执行直接走 GET /tasks/executions/:execId/logs 打全量日志后退出;
7
+ * - 未终态:先 POST /auth/sse-ticket 换短效票据,再走
8
+ * GET /tasks/:taskId/executions/:execId/logs/stream?ticket=
9
+ * (SSE 逐行 data: JSON.stringify(line),event: done 收尾,: ping 保活帧)。
10
+ *
11
+ * SEC-CLI-01(本轮审计):此处此前有两个各自独立、都会让 tail 完全不可用的缺陷:
12
+ * 1) 用 `?access_token=` 建流——该通道已被服务端**整体撤销**
13
+ * (jwt.strategy.ts:SSE_TICKET_PARAM,只认 ?ticket=,且注释明说旧通道
14
+ * "intentionally GONE"),于是任何非终态 tail 立刻 401;
15
+ * 2) 读取 `page.logs`——服务端返回的是 `{ lines, totalLines, hasMore }`
16
+ * (task.service.ts 的 getExecutionLogs),`logs` 恒为 undefined → '',
17
+ * 循环在第一轮就 break,打出**空输出**后静默退出。
18
+ * 两者叠加使 `acf exec tail` 在任何路径上都不工作。
19
+ */
20
+ import { Command } from 'commander';
21
+ export interface SseMessage {
22
+ event: string;
23
+ data: string;
24
+ }
25
+ /**
26
+ * 增量 SSE 解析器:feed(chunk) → 完整消息数组。跨 chunk 半行/半消息安全;
27
+ * 注释行(: ping)忽略;event 行只影响下一条 data 消息的事件名。
28
+ */
29
+ export declare function createSseParser(onMessage: (msg: SseMessage) => void): {
30
+ feed: (chunk: string) => void;
31
+ };
32
+ export declare function execCommand(): Command;
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.execCommand = exports.createSseParser = void 0;
7
+ /**
8
+ * ECO-02: acf exec tail <execId> —— 实时跟随执行日志(SSE)。
9
+ *
10
+ * 路由契约:
11
+ * - GET /tasks/executions/:execId(compat alias)解析 taskId 与状态;
12
+ * - 终态执行直接走 GET /tasks/executions/:execId/logs 打全量日志后退出;
13
+ * - 未终态:先 POST /auth/sse-ticket 换短效票据,再走
14
+ * GET /tasks/:taskId/executions/:execId/logs/stream?ticket=
15
+ * (SSE 逐行 data: JSON.stringify(line),event: done 收尾,: ping 保活帧)。
16
+ *
17
+ * SEC-CLI-01(本轮审计):此处此前有两个各自独立、都会让 tail 完全不可用的缺陷:
18
+ * 1) 用 `?access_token=` 建流——该通道已被服务端**整体撤销**
19
+ * (jwt.strategy.ts:SSE_TICKET_PARAM,只认 ?ticket=,且注释明说旧通道
20
+ * "intentionally GONE"),于是任何非终态 tail 立刻 401;
21
+ * 2) 读取 `page.logs`——服务端返回的是 `{ lines, totalLines, hasMore }`
22
+ * (task.service.ts 的 getExecutionLogs),`logs` 恒为 undefined → '',
23
+ * 循环在第一轮就 break,打出**空输出**后静默退出。
24
+ * 两者叠加使 `acf exec tail` 在任何路径上都不工作。
25
+ */
26
+ const commander_1 = require("commander");
27
+ const axios_1 = __importDefault(require("axios"));
28
+ const chalk_1 = __importDefault(require("chalk"));
29
+ const client_1 = require("../client");
30
+ const config_1 = require("../config");
31
+ const client_2 = require("../client");
32
+ const TERMINAL = new Set(['success', 'failed', 'timeout', 'killed', 'cancelled']);
33
+ /**
34
+ * 增量 SSE 解析器:feed(chunk) → 完整消息数组。跨 chunk 半行/半消息安全;
35
+ * 注释行(: ping)忽略;event 行只影响下一条 data 消息的事件名。
36
+ */
37
+ function createSseParser(onMessage) {
38
+ let buffer = '';
39
+ let eventName = 'message';
40
+ let dataLines = [];
41
+ const dispatch = () => {
42
+ if (dataLines.length > 0) {
43
+ onMessage({ event: eventName, data: dataLines.join('\n') });
44
+ }
45
+ eventName = 'message';
46
+ dataLines = [];
47
+ };
48
+ return {
49
+ feed(chunk) {
50
+ buffer += chunk;
51
+ let idx;
52
+ while ((idx = buffer.indexOf('\n')) !== -1) {
53
+ let line = buffer.slice(0, idx);
54
+ buffer = buffer.slice(idx + 1);
55
+ if (line.endsWith('\r'))
56
+ line = line.slice(0, -1);
57
+ if (line === '') {
58
+ dispatch();
59
+ continue;
60
+ }
61
+ if (line.startsWith(':'))
62
+ continue; // keepalive comment
63
+ if (line.startsWith('event:')) {
64
+ eventName = line.slice(6).trim();
65
+ }
66
+ else if (line.startsWith('data:')) {
67
+ dataLines.push(line.slice(5).trimStart());
68
+ }
69
+ }
70
+ },
71
+ };
72
+ }
73
+ exports.createSseParser = createSseParser;
74
+ /** 把服务端行数组(或旧字符串形态)规整为 string[]。 */
75
+ function toLines(lines) {
76
+ if (Array.isArray(lines))
77
+ return lines.filter((l) => typeof l === 'string');
78
+ if (typeof lines === 'string' && lines.length > 0)
79
+ return lines.split('\n');
80
+ return [];
81
+ }
82
+ function execCommand() {
83
+ const cmd = new commander_1.Command('exec').description('Follow or inspect executions');
84
+ cmd
85
+ .command('tail <execId>')
86
+ .description('Follow execution logs live (SSE); terminal executions print their logs and exit')
87
+ .option('--json', 'Emit raw JSON lines instead of plain text')
88
+ .action(async (execId, opts) => {
89
+ try {
90
+ const exec = await (0, client_1.get)(`/tasks/executions/${execId}`);
91
+ if (!exec?.taskId) {
92
+ throw new Error(`Execution ${execId} not found`);
93
+ }
94
+ if (exec.status && TERMINAL.has(exec.status)) {
95
+ // 终态:全量日志直出(分页拉全,对齐 admin-web U2 兜底语义)
96
+ let fromLine = 0;
97
+ let printed = 0;
98
+ for (;;) {
99
+ const page = await (0, client_1.get)(`/tasks/executions/${execId}/logs?fromLine=${fromLine}&limit=2000`);
100
+ const lines = toLines(page?.lines);
101
+ if (lines.length > 0) {
102
+ for (const line of lines) {
103
+ process.stdout.write((opts.json ? JSON.stringify({ line }) : line) + '\n');
104
+ printed++;
105
+ }
106
+ }
107
+ if (!page?.hasMore || lines.length === 0)
108
+ break;
109
+ fromLine = printed;
110
+ }
111
+ process.exitCode = exec.status === 'success' ? 0 : 1;
112
+ return;
113
+ }
114
+ // 未终态:SSE 跟随。
115
+ // SEC-CLI-01: 先换一枚 30s TTL 的专用 SSE 票据(走常规 Authorization
116
+ // 头的 POST),再以 ?ticket= 建流——`?access_token=` 通道已被服务端撤销,
117
+ // 旧写法会让每次非终态 tail 直接 401。与 admin-web/src/api/sse.ts 同流程。
118
+ const { ticket } = await (0, client_1.post)('/auth/sse-ticket');
119
+ const base = (0, config_1.getApiUrl)().replace(/\/+$/, '');
120
+ const url = `${base}/tasks/${exec.taskId}/executions/${execId}/logs/stream?ticket=${encodeURIComponent(ticket)}`;
121
+ const res = await axios_1.default.get(url, { responseType: 'stream', timeout: 0 });
122
+ process.stderr.write(chalk_1.default.gray(`[tail] following execution ${execId} (status: ${exec.status ?? 'unknown'}) — Ctrl+C to detach\n`));
123
+ const parser = createSseParser((msg) => {
124
+ if (msg.event === 'done') {
125
+ process.stderr.write(chalk_1.default.gray('[tail] done\n'));
126
+ process.exit(0);
127
+ }
128
+ if (msg.event !== 'message')
129
+ return;
130
+ try {
131
+ const line = JSON.parse(msg.data);
132
+ process.stdout.write((opts.json ? JSON.stringify({ line }) : String(line)) + '\n');
133
+ }
134
+ catch {
135
+ // 非 JSON data 帧按原文输出
136
+ process.stdout.write(msg.data + '\n');
137
+ }
138
+ });
139
+ const stream = res.data;
140
+ stream.on('data', (chunk) => {
141
+ parser.feed(chunk.toString('utf-8'));
142
+ });
143
+ stream.on('end', () => process.exit(0));
144
+ stream.on('error', (err) => {
145
+ process.stderr.write(chalk_1.default.red(`[tail] stream error: ${err.message}\n`));
146
+ process.exit(1);
147
+ });
148
+ }
149
+ catch (e) {
150
+ console.error(chalk_1.default.red('✗ tail failed:'), (0, client_2.formatApiError)(e));
151
+ process.exit(1);
152
+ }
153
+ });
154
+ return cmd;
155
+ }
156
+ exports.execCommand = execCommand;
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function executorsCommand(): Command;
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.executorsCommand = void 0;
7
+ const commander_1 = require("commander");
8
+ const cli_table3_1 = __importDefault(require("cli-table3"));
9
+ const chalk_1 = __importDefault(require("chalk"));
10
+ const ora_1 = __importDefault(require("ora"));
11
+ const client_1 = require("../client");
12
+ function statusColor(s) {
13
+ if (s === 'online')
14
+ return chalk_1.default.green(s);
15
+ if (s === 'offline')
16
+ return chalk_1.default.red(s);
17
+ return chalk_1.default.yellow(s);
18
+ }
19
+ function heartbeatAge(ts) {
20
+ if (!ts)
21
+ return '-';
22
+ const diff = Date.now() - new Date(ts).getTime();
23
+ if (diff < 60000)
24
+ return chalk_1.default.green(`${Math.round(diff / 1000)}s ago`);
25
+ if (diff < 300000)
26
+ return chalk_1.default.yellow(`${Math.round(diff / 60000)}m ago`);
27
+ return chalk_1.default.red(`${Math.round(diff / 60000)}m ago`);
28
+ }
29
+ function pct(v) {
30
+ return v === null || v === undefined ? '-' : `${v}%`;
31
+ }
32
+ // CONSISTENCY-02 (U11): tri-state rendering matching admin-web's
33
+ // ExecutorDetailPage semantics for the heartbeat-reported id list.
34
+ function runningExecutionIdsText(ids) {
35
+ if (ids === null || ids === undefined) {
36
+ return chalk_1.default.gray('not reported (older executor)');
37
+ }
38
+ if (ids.length === 0) {
39
+ return chalk_1.default.gray('idle (none running)');
40
+ }
41
+ return `${ids.length} running: ${ids.join(', ')}`;
42
+ }
43
+ function executorsCommand() {
44
+ const cmd = new commander_1.Command('executor').description('View registered executors');
45
+ cmd.command('list')
46
+ .description('List all executors and their status')
47
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
48
+ .action(async (opts) => {
49
+ const spinner = (0, ora_1.default)('Fetching executors…').start();
50
+ try {
51
+ const data = await (0, client_1.get)('/executors');
52
+ spinner.stop();
53
+ if (opts.json) {
54
+ // ECO-02: --json —— CI/脚本消费面
55
+ console.log(JSON.stringify(Array.isArray(data) ? data : data.list ?? []));
56
+ return;
57
+ }
58
+ const executors = Array.isArray(data) ? data : (data.list ?? []);
59
+ const table = new cli_table3_1.default({
60
+ head: ['ID', 'App Name', 'Status', 'Address', 'Last Heartbeat', 'CPU', 'Running'],
61
+ colWidths: [14, 20, 10, 22, 18, 8, 9],
62
+ style: { head: ['cyan'] },
63
+ });
64
+ for (const e of executors) {
65
+ table.push([
66
+ e.id.slice(0, 12),
67
+ e.appName ?? '-',
68
+ statusColor(e.status),
69
+ e.address ?? '-',
70
+ heartbeatAge(e.lastHeartbeat),
71
+ pct(e.cpuUsage),
72
+ e.runningTaskCount !== undefined ? `${e.runningTaskCount}` : '-',
73
+ ]);
74
+ }
75
+ console.log(table.toString());
76
+ }
77
+ catch (e) {
78
+ spinner.fail('Failed');
79
+ console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
80
+ process.exit(1);
81
+ }
82
+ });
83
+ // acf executor get <id>
84
+ cmd.command('get <id>')
85
+ .description('Show details of a single executor (config, status, metrics)')
86
+ .action(async (id) => {
87
+ const spinner = (0, ora_1.default)('Fetching executor…').start();
88
+ try {
89
+ const e = await (0, client_1.get)(`/executors/${id}`);
90
+ spinner.stop();
91
+ console.log(chalk_1.default.bold('Executor Details'));
92
+ console.log(' ID :', e.id);
93
+ console.log(' App Name :', e.appName ?? '-');
94
+ console.log(' Address :', e.address ?? '-');
95
+ console.log(' Status :', statusColor(e.status));
96
+ console.log(' Type :', e.type ?? '-');
97
+ console.log(' Version :', e.executorVersion ?? '-');
98
+ console.log(' Group :', e.groupName ?? '-');
99
+ console.log(' Tags :', e.tags?.length ? e.tags.join(', ') : '-');
100
+ console.log(' Description :', e.description ?? '-');
101
+ console.log(' Running Tasks :', e.runningTaskCount ?? 0);
102
+ console.log(' Running Executions:', runningExecutionIdsText(e.runningExecutionIds));
103
+ console.log(' Max Concurrent :', e.maxConcurrentTasks ?? '-');
104
+ console.log(' Total Tasks :', e.totalTaskCount ?? 0);
105
+ console.log(' Failed Tasks :', e.failedTaskCount ?? 0);
106
+ console.log(' CPU :', pct(e.cpuUsage));
107
+ console.log(' Memory :', pct(e.memUsage));
108
+ console.log(' Last Heartbeat :', e.lastHeartbeat ? `${new Date(e.lastHeartbeat).toLocaleString()} (${heartbeatAge(e.lastHeartbeat)})` : '-');
109
+ }
110
+ catch (e) {
111
+ spinner.fail('Failed');
112
+ console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
113
+ process.exit(1);
114
+ }
115
+ });
116
+ // NF-07: name|id resolution — rotate/offline/set-offline are ADMIN-only
117
+ // id-scoped routes; accepting the appName keeps the UX aligned with
118
+ // `executor list` where the short id is what operators see.
119
+ async function resolveExecutorId(nameOrId) {
120
+ let exec;
121
+ try {
122
+ exec = await (0, client_1.get)(`/executors/${nameOrId}`);
123
+ }
124
+ catch {
125
+ exec = undefined;
126
+ }
127
+ if (exec?.id)
128
+ return exec.id;
129
+ const data = await (0, client_1.get)('/executors');
130
+ const executors = Array.isArray(data) ? data : (data.list ?? []);
131
+ const byName = executors.find((e) => e.appName === nameOrId);
132
+ const byShortId = executors.find((e) => e.id.startsWith(nameOrId));
133
+ const found = byName ?? byShortId;
134
+ if (!found?.id) {
135
+ throw new Error(`Executor "${nameOrId}" not found (no id match, no appName match, no short-id match)`);
136
+ }
137
+ return found.id;
138
+ }
139
+ // acf executor rotate <name|id> [--reason "..."]
140
+ cmd.command('rotate <nameOrId>')
141
+ .description('Rotate an executor token (ADMIN; new token is shown ONCE in this output)')
142
+ .option('--reason <reason>', 'Optional rotation reason (≤200 chars, recorded in the audit log)')
143
+ .action(async (nameOrId, opts) => {
144
+ const spinner = (0, ora_1.default)('Rotating executor token…').start();
145
+ try {
146
+ const id = await resolveExecutorId(nameOrId);
147
+ // POST /executors/:id/rotate-token — ExecutorController.rotateToken
148
+ // (ADMIN-only). Returns { token } — the plaintext is persisted nowhere
149
+ // and never shown again (AUTH-05: optional reason goes to the audit).
150
+ const r = await (0, client_1.post)(`/executors/${id}/rotate-token`, opts.reason ? { reason: opts.reason } : undefined);
151
+ spinner.succeed(`Token rotated for executor ${id}`);
152
+ console.log(chalk_1.default.bold('New token (shown only once — store it now):'));
153
+ console.log(chalk_1.default.green(r?.token ?? ''));
154
+ }
155
+ catch (e) {
156
+ spinner.fail('Failed to rotate token');
157
+ console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
158
+ process.exit(1);
159
+ }
160
+ });
161
+ // acf executor offline <name|id>
162
+ cmd.command('offline <nameOrId>')
163
+ .description('Mark an executor offline (ADMIN; does not interrupt running tasks — for stale records after a crash)')
164
+ .action(async (nameOrId) => {
165
+ const spinner = (0, ora_1.default)('Marking executor offline…').start();
166
+ try {
167
+ const id = await resolveExecutorId(nameOrId);
168
+ // POST /executors/:id/set-offline — ExecutorController.setOffline
169
+ // (ADMIN-only; distinct from the @Public /executors/offline
170
+ // executor-shutdown callback which is not an admin surface).
171
+ const e = await (0, client_1.post)(`/executors/${id}/set-offline`);
172
+ spinner.succeed(`Executor ${id} marked offline`);
173
+ console.log(chalk_1.default.gray(` status: ${e?.status ?? 'offline'} address: ${e?.address ?? '-'}`));
174
+ }
175
+ catch (e) {
176
+ spinner.fail('Failed to mark executor offline');
177
+ console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
178
+ process.exit(1);
179
+ }
180
+ });
181
+ return cmd;
182
+ }
183
+ exports.executorsCommand = executorsCommand;
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function loginCommand(): Command;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.loginCommand = void 0;
30
+ const commander_1 = require("commander");
31
+ const readline = __importStar(require("readline"));
32
+ const client_1 = require("../client");
33
+ const config_1 = require("../config");
34
+ const client_2 = require("../client");
35
+ const chalk_1 = __importDefault(require("chalk"));
36
+ function prompt(question) {
37
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
38
+ return new Promise((resolve) => rl.question(question, (ans) => { rl.close(); resolve(ans); }));
39
+ }
40
+ // PK-27(DEEP_REVIEW 0ef3bbe):交互式密码输入必须隐藏回显(否则旁窥/录屏即泄漏)。
41
+ // 用 readline 的 _writeToOutput 覆盖把回显吞掉——这是 Node 生态隐藏密码的标准做法,
42
+ // 不引入额外依赖。TTY 非交互(CI/管道)时退化为普通 question(无回显需求,因为
43
+ // 此时密码应来自 --password 或 ACF_PASSWORD env,而非人工键入)。
44
+ function hiddenPrompt(question) {
45
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
46
+ if (process.stdin.isTTY) {
47
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
+ const rlAny = rl;
49
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
50
+ const out = rlAny.output;
51
+ rlAny._writeToOutput = (str) => {
52
+ // 只回显提示符的换行,不回显键入字符;退格/回车照常处理。
53
+ if (str === '\n')
54
+ out.write('\n');
55
+ else if (str === '\r')
56
+ out.write('\n');
57
+ else
58
+ out.write('');
59
+ return '';
60
+ };
61
+ }
62
+ return new Promise((resolve) => rl.question(question, (ans) => {
63
+ rl.close();
64
+ resolve(ans);
65
+ }));
66
+ }
67
+ function loginCommand() {
68
+ const cmd = new commander_1.Command('login')
69
+ .description('Authenticate with the AutoCodeFlow API and save credentials')
70
+ .option('--url <url>', 'API base URL (default: http://localhost:3105)')
71
+ .option('--user <username>', 'Username')
72
+ // PK-27(DEEP_REVIEW 0ef3bbe):--password 明文会进 ps/shell history,标记 deprecated。
73
+ // 仍保留以便一次性容器/CI 用(此时 ACF_PASSWORD env 更推荐,不进进程 argv)。
74
+ .option('--password <password>', 'Password (DEPRECATED: visible in process list & shell history; prefer interactive hidden prompt or ACF_PASSWORD env)')
75
+ .action(async (opts) => {
76
+ try {
77
+ const url = opts.url || await prompt('API URL [http://localhost:3105]: ') || 'http://localhost:3105';
78
+ (0, config_1.setApiUrl)(url.trim());
79
+ (0, client_2.resetClient)();
80
+ const username = opts.user || await prompt('Username: ');
81
+ // PK-27 凭据来源优先级:--password(deprecated,告警) > ACF_PASSWORD env > 隐藏交互 prompt。
82
+ let password;
83
+ if (opts.password) {
84
+ process.stderr.write(chalk_1.default.yellow('⚠ --password 会出现在进程列表与 shell 历史中;CI 场景请改用 ACF_PASSWORD 环境变量。\n'));
85
+ password = opts.password;
86
+ }
87
+ else if (process.env.ACF_PASSWORD) {
88
+ password = process.env.ACF_PASSWORD;
89
+ }
90
+ else {
91
+ password = await hiddenPrompt('Password: ');
92
+ }
93
+ // admin-api auth.service.generateTokens returns camelCase { accessToken, refreshToken }
94
+ const data = await (0, client_1.post)('/auth/login', {
95
+ username: username.trim(),
96
+ password,
97
+ });
98
+ if (!data.accessToken) {
99
+ throw new Error('Login response missing accessToken (unexpected auth payload)');
100
+ }
101
+ (0, config_1.setToken)(data.accessToken);
102
+ // BUG-13: refreshToken 一并入库——access token 默认 15m 过期,
103
+ // client 的 401 单飞自愈(/auth/refresh + 重放一次)依赖它,
104
+ // 否则过期后全命令 401 只能重新 login。
105
+ (0, config_1.setRefreshToken)(data.refreshToken ?? '');
106
+ console.log(chalk_1.default.green('✔ Logged in successfully'));
107
+ (0, config_1.showConfig)();
108
+ }
109
+ catch (e) {
110
+ console.error(chalk_1.default.red('✗ Login failed:'), (0, client_1.formatApiError)(e));
111
+ process.exit(1);
112
+ }
113
+ });
114
+ return cmd;
115
+ }
116
+ exports.loginCommand = loginCommand;
@@ -0,0 +1,6 @@
1
+ import { Command } from 'commander';
2
+ /**
3
+ * AUTH-02-B(R18):项目域只读命令。读面与后端一致(列表按主体过滤;
4
+ * 成员列表要求成员身份)。成员写面为 ADMIN-only,不在 CLI 暴露。
5
+ */
6
+ export declare function projectsCommand(): Command;
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.projectsCommand = void 0;
7
+ const commander_1 = require("commander");
8
+ const cli_table3_1 = __importDefault(require("cli-table3"));
9
+ const chalk_1 = __importDefault(require("chalk"));
10
+ const ora_1 = __importDefault(require("ora"));
11
+ const client_1 = require("../client");
12
+ const ROLE_COLOR = {
13
+ admin: chalk_1.default.yellow,
14
+ editor: chalk_1.default.cyan,
15
+ viewer: chalk_1.default.gray,
16
+ };
17
+ function roleText(role) {
18
+ if (!role)
19
+ return '-';
20
+ return (ROLE_COLOR[role] ?? ((x) => x))(role);
21
+ }
22
+ /**
23
+ * AUTH-02-B(R18):项目域只读命令。读面与后端一致(列表按主体过滤;
24
+ * 成员列表要求成员身份)。成员写面为 ADMIN-only,不在 CLI 暴露。
25
+ */
26
+ function projectsCommand() {
27
+ const cmd = new commander_1.Command('project').description('Inspect projects and members (read-only)');
28
+ cmd
29
+ .command('list')
30
+ .description('List projects visible to the current credential (with your role)')
31
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
32
+ .action(async (opts) => {
33
+ const spinner = (0, ora_1.default)('Fetching projects…').start();
34
+ try {
35
+ const rows = (await (0, client_1.get)('/projects'));
36
+ spinner.stop();
37
+ if (opts.json) {
38
+ console.log(JSON.stringify(rows, null, 2));
39
+ return;
40
+ }
41
+ if (!rows.length) {
42
+ console.log(chalk_1.default.gray('No projects visible.'));
43
+ return;
44
+ }
45
+ const table = new cli_table3_1.default({
46
+ head: ['Name', 'My role', 'Description', 'Created'],
47
+ });
48
+ for (const r of rows) {
49
+ table.push([
50
+ r.name,
51
+ roleText(r.myRole),
52
+ r.description ?? '-',
53
+ new Date(r.createdAt).toISOString().slice(0, 10),
54
+ ]);
55
+ }
56
+ console.log(table.toString());
57
+ }
58
+ catch (e) {
59
+ spinner.stop();
60
+ console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
61
+ process.exitCode = 1;
62
+ }
63
+ });
64
+ cmd
65
+ .command('members <projectId>')
66
+ .description('List members (userId + role) of one project')
67
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
68
+ .action(async (projectId, opts) => {
69
+ const spinner = (0, ora_1.default)('Fetching members…').start();
70
+ try {
71
+ const rows = (await (0, client_1.get)(`/projects/${projectId}/members`));
72
+ spinner.stop();
73
+ if (opts.json) {
74
+ console.log(JSON.stringify(rows, null, 2));
75
+ return;
76
+ }
77
+ if (!rows.length) {
78
+ console.log(chalk_1.default.gray('No members.'));
79
+ return;
80
+ }
81
+ const table = new cli_table3_1.default({
82
+ head: ['User ID', 'Role', 'Since'],
83
+ });
84
+ for (const r of rows) {
85
+ table.push([r.userId, roleText(r.role), new Date(r.createdAt).toISOString().slice(0, 10)]);
86
+ }
87
+ console.log(table.toString());
88
+ }
89
+ catch (e) {
90
+ spinner.stop();
91
+ console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
92
+ process.exitCode = 1;
93
+ }
94
+ });
95
+ return cmd;
96
+ }
97
+ exports.projectsCommand = projectsCommand;
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function tasksCommand(): Command;