@autocodeflow/cli 1.5.2 → 1.6.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/dist/client.js CHANGED
@@ -1,14 +1,8 @@
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.formatApiError = exports.del = exports.patch = exports.put = exports.post = exports.get = exports.unwrap = exports.resetClient = exports.ANALYZE_TIMEOUT_MS = void 0;
7
1
  /**
8
2
  * Thin HTTP client wrapper for the AutoCodeFlow Admin API.
9
3
  */
10
- const axios_1 = __importDefault(require("axios"));
11
- const config_1 = require("./config");
4
+ import axios from "axios";
5
+ import { getApiUrl, getToken, getRefreshToken, setToken, setRefreshToken, clearAuth, } from "./config.js";
12
6
  let _client = null;
13
7
  /**
14
8
  * NETOPT-6④:analyze/suggest 类调用的 per-call 超时预算。
@@ -18,16 +12,15 @@ let _client = null;
18
12
  * suggest-schedule / app analyze 用 120s 覆盖(axios per-request timeout
19
13
  * 覆盖实例默认),其余端点维持 30s。
20
14
  */
21
- exports.ANALYZE_TIMEOUT_MS = 120000;
15
+ export const ANALYZE_TIMEOUT_MS = 120_000;
22
16
  /** base URL without trailing slashes(/auth/refresh 直连拼接用) */
23
17
  function baseUrl() {
24
- return (0, config_1.getApiUrl)().replace(/\/+$/, "");
18
+ return getApiUrl().replace(/\/+$/, "");
25
19
  }
26
20
  /** Reset client (needed after config changes in same process). */
27
- function resetClient() {
21
+ export function resetClient() {
28
22
  _client = null;
29
23
  }
30
- exports.resetClient = resetClient;
31
24
  // The admin-api applies a global ResponseInterceptor that wraps every
32
25
  // successful response in `{ code, message, data }`. Mirror admin-web's
33
26
  // client and strip that envelope so callers can keep using `data.list`,
@@ -39,7 +32,7 @@ exports.resetClient = resetClient;
39
32
  // 「数值 code」即可精确识别信封,`message` 的存在不再作为判据——旧的
40
33
  // data+(code|message) 宽松启发式会把自带 data+message 字段(无 code)的
41
34
  // 业务实体误解包,整个实体被截断成它的 data 值;收紧后这类实体原样透传。
42
- function unwrap(raw) {
35
+ export function unwrap(raw) {
43
36
  if (raw &&
44
37
  typeof raw === "object" &&
45
38
  "data" in raw) {
@@ -50,7 +43,6 @@ function unwrap(raw) {
50
43
  }
51
44
  return raw;
52
45
  }
53
- exports.unwrap = unwrap;
54
46
  // ---------------------------------------------------------------------------
55
47
  // BUG-13 (SEC-01 CLI 复审): 401 单飞自愈
56
48
  // ---------------------------------------------------------------------------
@@ -65,18 +57,18 @@ exports.unwrap = unwrap;
65
57
  // 被拒」的认证态,不是业务副作用重试,单次重放安全。
66
58
  let refreshInFlight = null;
67
59
  async function refreshAccessToken() {
68
- const refreshToken = (0, config_1.getRefreshToken)();
60
+ const refreshToken = getRefreshToken();
69
61
  if (!refreshToken)
70
62
  return null;
71
63
  try {
72
- const r = await axios_1.default.post(`${baseUrl()}/auth/refresh`, { refreshToken }, { timeout: 10000 });
64
+ const r = await axios.post(`${baseUrl()}/auth/refresh`, { refreshToken }, { timeout: 10_000 });
73
65
  const data = unwrap(r.data);
74
66
  if (typeof data?.accessToken === "string" && data.accessToken.length > 0) {
75
- (0, config_1.setToken)(data.accessToken);
67
+ setToken(data.accessToken);
76
68
  // DR-07 修复后的 refresh 是原子轮换:响应携带新 refreshToken 必须跟进
77
69
  if (typeof data.refreshToken === "string" &&
78
70
  data.refreshToken.length > 0) {
79
- (0, config_1.setRefreshToken)(data.refreshToken);
71
+ setRefreshToken(data.refreshToken);
80
72
  }
81
73
  return data.accessToken;
82
74
  }
@@ -91,14 +83,14 @@ function isAuthPath(url) {
91
83
  }
92
84
  function getClient() {
93
85
  if (!_client) {
94
- _client = axios_1.default.create({
95
- baseURL: (0, config_1.getApiUrl)(),
96
- timeout: 30000,
86
+ _client = axios.create({
87
+ baseURL: getApiUrl(),
88
+ timeout: 30_000,
97
89
  });
98
90
  // Token 逐请求读取(不再在实例创建时烘焙):同进程内 login / 刷新轮换
99
91
  // 后无需 resetClient 也能带上最新凭据(resetClient 保留仅为兼容)。
100
92
  _client.interceptors.request.use((cfg) => {
101
- const token = (0, config_1.getToken)();
93
+ const token = getToken();
102
94
  if (token) {
103
95
  cfg.headers = Object.assign({}, cfg.headers, {
104
96
  Authorization: `Bearer ${token}`,
@@ -116,47 +108,42 @@ function getClient() {
116
108
  throw err;
117
109
  }
118
110
  cfg._acfAuthRetried = true;
119
- refreshInFlight ?? (refreshInFlight = refreshAccessToken().finally(() => {
111
+ refreshInFlight ??= refreshAccessToken().finally(() => {
120
112
  refreshInFlight = null;
121
- }));
113
+ });
122
114
  const token = await refreshInFlight;
123
115
  if (token) {
124
116
  // 重放走 getClient():request 拦截器会用刚换发的新 token 重写
125
117
  // Authorization 头,无需手工改 cfg.headers。
126
118
  return getClient().request(cfg);
127
119
  }
128
- (0, config_1.clearAuth)();
120
+ clearAuth();
129
121
  throw err;
130
122
  });
131
123
  }
132
124
  return _client;
133
125
  }
134
- async function get(path, params) {
126
+ export async function get(path, params) {
135
127
  const r = await getClient().get(path, { params });
136
128
  return unwrap(r.data);
137
129
  }
138
- exports.get = get;
139
- async function post(path, body, timeoutMs) {
130
+ export async function post(path, body, timeoutMs) {
140
131
  // per-request timeout 覆盖实例默认(undefined 时 axios 回落实例默认 30s)。
141
132
  const r = await getClient().post(path, body, { timeout: timeoutMs });
142
133
  return unwrap(r.data);
143
134
  }
144
- exports.post = post;
145
- async function put(path, body) {
135
+ export async function put(path, body) {
146
136
  const r = await getClient().put(path, body);
147
137
  return unwrap(r.data);
148
138
  }
149
- exports.put = put;
150
- async function patch(path, body) {
139
+ export async function patch(path, body) {
151
140
  const r = await getClient().patch(path, body);
152
141
  return unwrap(r.data);
153
142
  }
154
- exports.patch = patch;
155
- async function del(path) {
143
+ export async function del(path) {
156
144
  const r = await getClient().delete(path);
157
145
  return unwrap(r.data);
158
146
  }
159
- exports.del = del;
160
147
  // ---------------------------------------------------------------------------
161
148
  // Error formatting
162
149
  // ---------------------------------------------------------------------------
@@ -184,8 +171,8 @@ function detailFromData(data) {
184
171
  * 401 (not authenticated) from 403 (authenticated but not allowed) and
185
172
  * surfacing the backend message instead of axios' generic text.
186
173
  */
187
- function formatApiError(e) {
188
- if (axios_1.default.isAxiosError(e)) {
174
+ export function formatApiError(e) {
175
+ if (axios.isAxiosError(e)) {
189
176
  const err = e;
190
177
  const status = err.response?.status;
191
178
  const detail = detailFromData(err.response?.data);
@@ -204,9 +191,8 @@ function formatApiError(e) {
204
191
  if (status) {
205
192
  return `API error (${status}): ${detail || err.message}`;
206
193
  }
207
- return `Network error: ${err.message} (is the API reachable at ${(0, config_1.getApiUrl)()}?)`;
194
+ return `Network error: ${err.message} (is the API reachable at ${getApiUrl()}?)`;
208
195
  }
209
196
  }
210
197
  return e instanceof Error ? e.message : String(e);
211
198
  }
212
- exports.formatApiError = formatApiError;
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare function agentCommand(): Command;
@@ -0,0 +1,59 @@
1
+ import { Command } from 'commander';
2
+ import Table from 'cli-table3';
3
+ import chalk from 'chalk';
4
+ import ora from 'ora';
5
+ import { get, formatApiError } from '../client.js';
6
+ export function agentCommand() {
7
+ const cmd = new Command('agent').description('Inspect agent sessions');
8
+ // acf agent sessions
9
+ cmd.command('sessions')
10
+ .description('List agent sessions (newest first; waiting_input = paused on a human decision)')
11
+ .option('--kind <kind>', 'Filter by kind (ops_watch | incident | sop_authoring)')
12
+ .option('--status <status>', 'Filter by status (pending | running | waiting_input | succeeded | failed | aborted)')
13
+ .option('-p, --page <n>', 'Page number', '1')
14
+ .option('-n, --page-size <n>', 'Page size (max 100)', '20')
15
+ .action(async (opts) => {
16
+ const spinner = ora('Fetching agent sessions…').start();
17
+ try {
18
+ const data = await get('/agent/sessions', {
19
+ page: opts.page,
20
+ pageSize: opts.pageSize,
21
+ kind: opts.kind,
22
+ status: opts.status,
23
+ });
24
+ spinner.stop();
25
+ const items = data.items ?? data.data ?? [];
26
+ const table = new Table({
27
+ head: ['Time', 'Kind', 'Status', 'Title', 'ID'],
28
+ colWidths: [22, 14, 14, 36, 20],
29
+ style: { head: ['cyan'] },
30
+ });
31
+ for (const s of items) {
32
+ table.push([
33
+ s.createdAt ? new Date(s.createdAt).toLocaleString() : '-',
34
+ s.kind,
35
+ statusColor(s.status),
36
+ s.title ?? '-',
37
+ s.id,
38
+ ]);
39
+ }
40
+ console.log(table.toString());
41
+ console.log(chalk.gray(`Total: ${data.total ?? items.length} page ${opts.page}`));
42
+ }
43
+ catch (e) {
44
+ spinner.fail('Failed to list agent sessions');
45
+ console.error(chalk.red(formatApiError(e)));
46
+ process.exit(1);
47
+ }
48
+ });
49
+ return cmd;
50
+ }
51
+ function statusColor(s) {
52
+ if (s === 'succeeded')
53
+ return chalk.green(s);
54
+ if (s === 'failed' || s === 'aborted')
55
+ return chalk.red(s);
56
+ if (s === 'waiting_input')
57
+ return chalk.yellow(s);
58
+ return s;
59
+ }
@@ -1,51 +1,22 @@
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.appsCommand = void 0;
30
- const commander_1 = require("commander");
31
- const cli_table3_1 = __importDefault(require("cli-table3"));
32
- const chalk_1 = __importDefault(require("chalk"));
33
- const ora_1 = __importDefault(require("ora"));
34
- const client_1 = require("../client");
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, put, del, formatApiError, ANALYZE_TIMEOUT_MS } from '../client.js';
35
6
  function statusColor(s) {
36
7
  if (s === 'running')
37
- return chalk_1.default.green(s);
8
+ return chalk.green(s);
38
9
  if (s === 'stopped')
39
- return chalk_1.default.gray(s);
10
+ return chalk.gray(s);
40
11
  if (s === 'error' || s === 'failed')
41
- return chalk_1.default.red(s);
12
+ return chalk.red(s);
42
13
  if (s === 'deploying')
43
- return chalk_1.default.cyan(s);
44
- return chalk_1.default.yellow(s);
14
+ return chalk.cyan(s);
15
+ return chalk.yellow(s);
45
16
  }
46
17
  /** Load a JSON payload from --file (preferred) or --json. */
47
18
  async function loadJsonBody(json, file) {
48
- const fs = await Promise.resolve().then(() => __importStar(require('fs/promises')));
19
+ const fs = await import('fs/promises');
49
20
  const raw = file ? await fs.readFile(file, 'utf-8') : json;
50
21
  if (raw === undefined) {
51
22
  throw new Error('Missing JSON payload (provide --json or --file)');
@@ -57,16 +28,16 @@ async function loadJsonBody(json, file) {
57
28
  throw new Error(`Invalid JSON payload: ${e instanceof Error ? e.message : String(e)}`);
58
29
  }
59
30
  }
60
- function appsCommand() {
61
- const cmd = new commander_1.Command('app').description('Manage applications');
31
+ export function appsCommand() {
32
+ const cmd = new Command('app').description('Manage applications');
62
33
  // acf app list
63
34
  cmd.command('list')
64
35
  .description('List all applications')
65
36
  .option('--json', 'Emit raw JSON (CI-consumable, no table)')
66
37
  .action(async (opts) => {
67
- const spinner = (0, ora_1.default)('Fetching applications…').start();
38
+ const spinner = ora('Fetching applications…').start();
68
39
  try {
69
- const data = await (0, client_1.get)('/applications');
40
+ const data = await get('/applications');
70
41
  spinner.stop();
71
42
  const apps = Array.isArray(data) ? data : (data.list ?? []);
72
43
  if (opts.json) {
@@ -74,7 +45,7 @@ function appsCommand() {
74
45
  console.log(JSON.stringify(apps));
75
46
  return;
76
47
  }
77
- const table = new cli_table3_1.default({
48
+ const table = new Table({
78
49
  head: ['ID', 'Name', 'Status', 'Version', 'Git Repo', 'Branch'],
79
50
  colWidths: [14, 26, 12, 10, 28, 14],
80
51
  style: { head: ['cyan'] },
@@ -93,7 +64,7 @@ function appsCommand() {
93
64
  }
94
65
  catch (e) {
95
66
  spinner.fail('Failed to list applications');
96
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
67
+ console.error(chalk.red(formatApiError(e)));
97
68
  process.exit(1);
98
69
  }
99
70
  });
@@ -101,11 +72,11 @@ function appsCommand() {
101
72
  cmd.command('get <id>')
102
73
  .description('Show application details')
103
74
  .action(async (id) => {
104
- const spinner = (0, ora_1.default)('Fetching application…').start();
75
+ const spinner = ora('Fetching application…').start();
105
76
  try {
106
- const a = await (0, client_1.get)(`/applications/${id}`);
77
+ const a = await get(`/applications/${id}`);
107
78
  spinner.stop();
108
- console.log(chalk_1.default.bold('Application Details'));
79
+ console.log(chalk.bold('Application Details'));
109
80
  console.log(' ID :', a.id);
110
81
  console.log(' Name :', a.name);
111
82
  console.log(' Status :', statusColor(a.status));
@@ -120,7 +91,7 @@ function appsCommand() {
120
91
  }
121
92
  catch (e) {
122
93
  spinner.fail('Failed');
123
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
94
+ console.error(chalk.red(formatApiError(e)));
124
95
  process.exit(1);
125
96
  }
126
97
  });
@@ -130,16 +101,16 @@ function appsCommand() {
130
101
  .requiredOption('--json <body>', 'Application body as JSON string')
131
102
  .option('--file <path>', 'Read application body from a JSON file (overrides --json)')
132
103
  .action(async (opts) => {
133
- const spinner = (0, ora_1.default)('Creating application…').start();
104
+ const spinner = ora('Creating application…').start();
134
105
  try {
135
106
  const body = await loadJsonBody(opts.json, opts.file);
136
- const a = await (0, client_1.post)('/applications', body);
107
+ const a = await post('/applications', body);
137
108
  spinner.succeed(`Application created: ${a.id}`);
138
- console.log(chalk_1.default.gray(` name: ${a.name} version: ${a.version ?? '-'} status: ${statusColor(a.status)}`));
109
+ console.log(chalk.gray(` name: ${a.name} version: ${a.version ?? '-'} status: ${statusColor(a.status)}`));
139
110
  }
140
111
  catch (e) {
141
112
  spinner.fail('Failed to create application');
142
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
113
+ console.error(chalk.red(formatApiError(e)));
143
114
  process.exit(1);
144
115
  }
145
116
  });
@@ -151,7 +122,7 @@ function appsCommand() {
151
122
  .requiredOption('--json <body>', 'Application patch body as JSON string')
152
123
  .option('--file <path>', 'Read application patch body from a JSON file (overrides --json)')
153
124
  .action(async (id, opts) => {
154
- const spinner = (0, ora_1.default)('Updating application…').start();
125
+ const spinner = ora('Updating application…').start();
155
126
  try {
156
127
  const body = (await loadJsonBody(opts.json, opts.file));
157
128
  // UpdateApplicationDto has no `name` — with forbidNonWhitelisted the
@@ -161,13 +132,13 @@ function appsCommand() {
161
132
  throw new Error('Application update does not support renaming: the backend UpdateApplicationDto has no `name` field. ' +
162
133
  'Remove "name" from the payload.');
163
134
  }
164
- const a = await (0, client_1.put)(`/applications/${id}`, body);
135
+ const a = await put(`/applications/${id}`, body);
165
136
  spinner.succeed(`Application updated: ${a.id}`);
166
- console.log(chalk_1.default.gray(` name: ${a.name} version: ${a.version ?? '-'} status: ${statusColor(a.status)}`));
137
+ console.log(chalk.gray(` name: ${a.name} version: ${a.version ?? '-'} status: ${statusColor(a.status)}`));
167
138
  }
168
139
  catch (e) {
169
140
  spinner.fail('Failed to update application');
170
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
141
+ console.error(chalk.red(formatApiError(e)));
171
142
  process.exit(1);
172
143
  }
173
144
  });
@@ -177,23 +148,23 @@ function appsCommand() {
177
148
  .option('-y, --yes', 'Skip confirmation prompt', false)
178
149
  .action(async (id, opts) => {
179
150
  if (!opts.yes) {
180
- const readline = await Promise.resolve().then(() => __importStar(require('readline/promises')));
151
+ const readline = await import('readline/promises');
181
152
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
182
153
  const answer = await rl.question(`Delete application ${id}? [y/N] `);
183
154
  rl.close();
184
155
  if (!/^y(es)?$/i.test(answer)) {
185
- console.log(chalk_1.default.yellow('Aborted.'));
156
+ console.log(chalk.yellow('Aborted.'));
186
157
  return;
187
158
  }
188
159
  }
189
- const spinner = (0, ora_1.default)('Deleting application…').start();
160
+ const spinner = ora('Deleting application…').start();
190
161
  try {
191
- await (0, client_1.del)(`/applications/${id}`);
162
+ await del(`/applications/${id}`);
192
163
  spinner.succeed(`Application ${id} deleted`);
193
164
  }
194
165
  catch (e) {
195
166
  spinner.fail('Failed to delete application');
196
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
167
+ console.error(chalk.red(formatApiError(e)));
197
168
  process.exit(1);
198
169
  }
199
170
  });
@@ -201,26 +172,26 @@ function appsCommand() {
201
172
  cmd.command('analyze <id>')
202
173
  .description('Run AI health analysis on an application')
203
174
  .action(async (id) => {
204
- const spinner = (0, ora_1.default)('Running AI health analysis…').start();
175
+ const spinner = ora('Running AI health analysis…').start();
205
176
  try {
206
177
  // NETOPT-6④:同步 AI 端点(服务端预算 60s×2)用 120s per-call 覆盖,
207
178
  // 否则默认 30s 结构性小于服务端预算,AI 跑满预算成功返回时 CLI 已超时。
208
- const result = await (0, client_1.post)(`/applications/${id}/analyze`, undefined, client_1.ANALYZE_TIMEOUT_MS);
179
+ const result = await post(`/applications/${id}/analyze`, undefined, ANALYZE_TIMEOUT_MS);
209
180
  spinner.stop();
210
- console.log(chalk_1.default.bold(`\nAI Health Analysis — ${result.appName}`));
211
- console.log(chalk_1.default.gray('─'.repeat(60)));
181
+ console.log(chalk.bold(`\nAI Health Analysis — ${result.appName}`));
182
+ console.log(chalk.gray('─'.repeat(60)));
212
183
  console.log(` Total tasks : ${result.stats.totalTasks}`);
213
- console.log(` Avg success rate: ${chalk_1.default.green(result.stats.avgSuccessRate + '%')}`);
184
+ console.log(` Avg success rate: ${chalk.green(result.stats.avgSuccessRate + '%')}`);
214
185
  console.log(` Avg duration : ${result.stats.avgDuration}ms`);
215
186
  if (result.stats.criticalTasks.length > 0) {
216
- console.log(` Critical tasks : ${chalk_1.default.red(result.stats.criticalTasks.join(', '))}`);
187
+ console.log(` Critical tasks : ${chalk.red(result.stats.criticalTasks.join(', '))}`);
217
188
  }
218
189
  console.log();
219
190
  console.log(result.analysis);
220
191
  }
221
192
  catch (e) {
222
193
  spinner.fail('Analysis failed');
223
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
194
+ console.error(chalk.red(formatApiError(e)));
224
195
  process.exit(1);
225
196
  }
226
197
  });
@@ -232,7 +203,7 @@ function appsCommand() {
232
203
  .option('--env <json>', 'Env var overrides as JSON, e.g. \'{"KEY":"value"}\'')
233
204
  .option('--start-command <cmd>', 'Startup command override (defaults to manifest entrypoint)')
234
205
  .action(async (id, opts) => {
235
- const spinner = (0, ora_1.default)('Triggering deployment…').start();
206
+ const spinner = ora('Triggering deployment…').start();
236
207
  try {
237
208
  const body = { runMode: opts.runMode };
238
209
  if (opts.executor)
@@ -241,13 +212,13 @@ function appsCommand() {
241
212
  body.env = JSON.parse(opts.env);
242
213
  if (opts.startCommand)
243
214
  body.startCommand = opts.startCommand;
244
- const dep = await (0, client_1.post)(`/app-deployments/applications/${id}/deploy`, body);
215
+ const dep = await post(`/app-deployments/applications/${id}/deploy`, body);
245
216
  spinner.succeed('Deployment triggered');
246
- console.log(chalk_1.default.gray(` deployment: ${dep?.id ?? '-'} status: ${dep?.status ?? '-'} executor: ${dep?.executorId ?? 'auto'}`));
217
+ console.log(chalk.gray(` deployment: ${dep?.id ?? '-'} status: ${dep?.status ?? '-'} executor: ${dep?.executorId ?? 'auto'}`));
247
218
  }
248
219
  catch (e) {
249
220
  spinner.fail('Deployment failed');
250
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
221
+ console.error(chalk.red(formatApiError(e)));
251
222
  process.exit(1);
252
223
  }
253
224
  });
@@ -257,17 +228,17 @@ function appsCommand() {
257
228
  .option('-p, --page <n>', 'Page number', '1')
258
229
  .option('-n, --page-size <n>', 'Page size', '20')
259
230
  .action(async (appId, opts) => {
260
- const spinner = (0, ora_1.default)('Fetching deployments…').start();
231
+ const spinner = ora('Fetching deployments…').start();
261
232
  try {
262
233
  // app-deployment.service.findAll returns `{ data, total }`
263
- const data = await (0, client_1.get)('/app-deployments', {
234
+ const data = await get('/app-deployments', {
264
235
  ...(appId ? { applicationId: appId } : {}),
265
236
  page: opts.page,
266
237
  pageSize: opts.pageSize,
267
238
  });
268
239
  spinner.stop();
269
240
  const list = Array.isArray(data) ? data : (data.data ?? data.list ?? []);
270
- const table = new cli_table3_1.default({
241
+ const table = new Table({
271
242
  head: ['Deployment', 'App', 'Executor', 'Status', 'RunMode'],
272
243
  colWidths: [14, 14, 14, 12, 11],
273
244
  style: { head: ['cyan'] },
@@ -285,7 +256,7 @@ function appsCommand() {
285
256
  }
286
257
  catch (e) {
287
258
  spinner.fail('Failed to list deployments');
288
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
259
+ console.error(chalk.red(formatApiError(e)));
289
260
  process.exit(1);
290
261
  }
291
262
  });
@@ -293,12 +264,12 @@ function appsCommand() {
293
264
  cmd.command('versions <id>')
294
265
  .description('Show application version history')
295
266
  .action(async (id) => {
296
- const spinner = (0, ora_1.default)('Fetching version history…').start();
267
+ const spinner = ora('Fetching version history…').start();
297
268
  try {
298
269
  // getVersionHistory returns `commit` / `deployedAt` (no gitCommit / changeNote)
299
- const versions = await (0, client_1.get)(`/applications/${id}/versions`);
270
+ const versions = await get(`/applications/${id}/versions`);
300
271
  spinner.stop();
301
- const table = new cli_table3_1.default({
272
+ const table = new Table({
302
273
  head: ['Version', 'Commit', 'Deployed', 'Status'],
303
274
  colWidths: [12, 14, 25, 12],
304
275
  style: { head: ['cyan'] },
@@ -315,10 +286,9 @@ function appsCommand() {
315
286
  }
316
287
  catch (e) {
317
288
  spinner.fail('Failed to list versions');
318
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
289
+ console.error(chalk.red(formatApiError(e)));
319
290
  process.exit(1);
320
291
  }
321
292
  });
322
293
  return cmd;
323
294
  }
324
- exports.appsCommand = appsCommand;
@@ -1,23 +1,17 @@
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.auditCommand = 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");
1
+ import { Command } from 'commander';
2
+ import Table from 'cli-table3';
3
+ import chalk from 'chalk';
4
+ import ora from 'ora';
5
+ import { get, formatApiError } from '../client.js';
12
6
  function resultColor(r) {
13
7
  if (r === 'success')
14
- return chalk_1.default.green(r);
8
+ return chalk.green(r);
15
9
  if (r === 'failure')
16
- return chalk_1.default.red(r);
10
+ return chalk.red(r);
17
11
  return r ?? '-';
18
12
  }
19
- function auditCommand() {
20
- const cmd = new commander_1.Command('audit').description('Query the audit log');
13
+ export function auditCommand() {
14
+ const cmd = new Command('audit').description('Query the audit log');
21
15
  // acf audit list
22
16
  cmd.command('list')
23
17
  .description('List audit log entries (newest first)')
@@ -29,13 +23,15 @@ function auditCommand() {
29
23
  .option('--end-time <iso>', 'Only entries created at/before this time (ISO 8601)')
30
24
  .option('-p, --page <n>', 'Page number', '1')
31
25
  .option('-n, --page-size <n>', 'Page size (max 100)', '20')
26
+ // 第四轮审计(--json 补面):对齐 task list 的 ECO-02 CI 消费面
27
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
32
28
  .action(async (opts) => {
33
- const spinner = (0, ora_1.default)('Fetching audit logs…').start();
29
+ const spinner = ora('Fetching audit logs…').start();
34
30
  try {
35
31
  // AuditQueryDto whitelist: action / resource / userId / username /
36
32
  // startTime / endTime (+ page / pageSize from PaginationDto). Any
37
33
  // other query field is rejected with 400 by forbidNonWhitelisted.
38
- const data = await (0, client_1.get)('/audit', {
34
+ const data = await get('/audit', {
39
35
  page: opts.page,
40
36
  pageSize: opts.pageSize,
41
37
  action: opts.action,
@@ -46,9 +42,15 @@ function auditCommand() {
46
42
  endTime: opts.endTime,
47
43
  });
48
44
  spinner.stop();
45
+ if (opts.json) {
46
+ // ECO-02 同款:--json —— 后端返回的信封({ data, total },旧后端可
47
+ // 能是裸数组)原样直出,不做任何字段裁剪。
48
+ console.log(JSON.stringify(data, null, 2));
49
+ return;
50
+ }
49
51
  const rows = Array.isArray(data) ? data : (data.data ?? []);
50
52
  const total = Array.isArray(data) ? rows.length : (data.total ?? rows.length);
51
- const table = new cli_table3_1.default({
53
+ const table = new Table({
52
54
  head: ['Time', 'User', 'Action', 'Resource', 'Resource ID', 'Result'],
53
55
  colWidths: [25, 16, 24, 14, 18, 10],
54
56
  style: { head: ['cyan'] },
@@ -64,14 +66,13 @@ function auditCommand() {
64
66
  ]);
65
67
  }
66
68
  console.log(table.toString());
67
- console.log(chalk_1.default.gray(`Total: ${total} page ${opts.page}`));
69
+ console.log(chalk.gray(`Total: ${total} page ${opts.page}`));
68
70
  }
69
71
  catch (e) {
70
72
  spinner.fail('Failed to list audit logs');
71
- console.error(chalk_1.default.red((0, client_1.formatApiError)(e)));
73
+ console.error(chalk.red(formatApiError(e)));
72
74
  process.exit(1);
73
75
  }
74
76
  });
75
77
  return cmd;
76
78
  }
77
- exports.auditCommand = auditCommand;