@xfe-repo/cli 2.0.8 → 2.0.9

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @xfe-repo/cli
2
2
 
3
+ ## 2.0.9
4
+
5
+ ### Patch Changes
6
+
7
+ - 修复ai-rules插件的排序问题
8
+ - Updated dependencies
9
+ - @xfe-repo/cli-presets@2.0.5
10
+ - @xfe-repo/cli-core@2.0.5
11
+
3
12
  ## 2.0.8
4
13
 
5
14
  ### Patch Changes
@@ -0,0 +1,45 @@
1
+ /**
2
+ * XFE CLI HTTP Backend Gateway。
3
+ *
4
+ * CLI 通过该适配器连接本地或远端 xfe server。
5
+ */
6
+ export interface BackendGatewayOptions {
7
+ readonly baseUrl: string;
8
+ readonly tenantId?: string;
9
+ }
10
+ export interface CreateRemoteTaskOptions {
11
+ readonly repoUrl: string;
12
+ readonly taskId: string;
13
+ readonly description: string;
14
+ readonly documentUrl?: string;
15
+ readonly baseBranch?: string;
16
+ readonly prepareWorkspace?: boolean;
17
+ }
18
+ export interface StartRemoteTaskOptions {
19
+ readonly taskId: string;
20
+ readonly executor?: string;
21
+ readonly autoApprove?: boolean;
22
+ }
23
+ export interface RespondClientRequestOptions {
24
+ readonly requestId: string;
25
+ readonly action: 'accept' | 'decline' | 'cancel';
26
+ readonly content?: Record<string, unknown>;
27
+ }
28
+ export interface ListClientRequestsOptions {
29
+ readonly status?: string;
30
+ }
31
+ export declare class HttpBackendGateway {
32
+ private baseUrl;
33
+ private tenantId?;
34
+ constructor(options: BackendGatewayOptions);
35
+ health(): Promise<unknown>;
36
+ createTask(options: CreateRemoteTaskOptions): Promise<unknown>;
37
+ startTask(options: StartRemoteTaskOptions): Promise<unknown>;
38
+ listClientRequests(options?: ListClientRequestsOptions): Promise<unknown>;
39
+ respondClientRequest(options: RespondClientRequestOptions): Promise<unknown>;
40
+ private get;
41
+ private post;
42
+ private createUrl;
43
+ private createHeaders;
44
+ }
45
+ //# sourceMappingURL=http-backend.d.ts.map
@@ -0,0 +1,88 @@
1
+ /**
2
+ * XFE CLI HTTP Backend Gateway。
3
+ *
4
+ * CLI 通过该适配器连接本地或远端 xfe server。
5
+ */
6
+ // ─── HttpBackendGateway ─────────────────────────────────────
7
+ export class HttpBackendGateway {
8
+ baseUrl;
9
+ tenantId;
10
+ constructor(options) {
11
+ this.baseUrl = normalizeBaseUrl(options.baseUrl);
12
+ this.tenantId = options.tenantId;
13
+ }
14
+ async health() {
15
+ return this.get('/health');
16
+ }
17
+ async createTask(options) {
18
+ return this.post('/tasks', options);
19
+ }
20
+ async startTask(options) {
21
+ return this.post(`/tasks/${encodeURIComponent(options.taskId)}/start`, {
22
+ executor: options.executor,
23
+ autoApprove: options.autoApprove,
24
+ });
25
+ }
26
+ async listClientRequests(options = {}) {
27
+ return this.get(createPathWithQuery('/client-requests', { status: options.status }));
28
+ }
29
+ async respondClientRequest(options) {
30
+ return this.post(`/client-requests/${encodeURIComponent(options.requestId)}/respond`, {
31
+ action: options.action,
32
+ content: options.content,
33
+ });
34
+ }
35
+ async get(pathname) {
36
+ const response = await fetch(this.createUrl(pathname), { headers: this.createHeaders() });
37
+ return readResponse(response);
38
+ }
39
+ async post(pathname, body) {
40
+ const response = await fetch(this.createUrl(pathname), {
41
+ method: 'POST',
42
+ headers: { ...this.createHeaders(), 'content-type': 'application/json' },
43
+ body: JSON.stringify(body),
44
+ });
45
+ return readResponse(response);
46
+ }
47
+ createUrl(pathname) {
48
+ return `${this.baseUrl}${pathname}`;
49
+ }
50
+ createHeaders() {
51
+ if (!this.tenantId)
52
+ return {};
53
+ return { 'x-xfe-tenant-id': this.tenantId };
54
+ }
55
+ }
56
+ // ─── Helpers ────────────────────────────────────────────────
57
+ async function readResponse(response) {
58
+ const text = await response.text();
59
+ const body = parseJson(text);
60
+ if (!response.ok) {
61
+ const message = typeof body === 'object' && body && 'error' in body ? String(body.error) : text;
62
+ throw new Error(message || `HTTP ${response.status}`);
63
+ }
64
+ return body;
65
+ }
66
+ function parseJson(text) {
67
+ if (!text)
68
+ return undefined;
69
+ try {
70
+ return JSON.parse(text);
71
+ }
72
+ catch {
73
+ return text;
74
+ }
75
+ }
76
+ function normalizeBaseUrl(baseUrl) {
77
+ return baseUrl.replace(/\/$/, '');
78
+ }
79
+ function createPathWithQuery(pathname, query) {
80
+ const searchParams = new URLSearchParams();
81
+ for (const [key, value] of Object.entries(query)) {
82
+ if (value)
83
+ searchParams.set(key, value);
84
+ }
85
+ const queryString = searchParams.toString();
86
+ return queryString ? `${pathname}?${queryString}` : pathname;
87
+ }
88
+ //# sourceMappingURL=http-backend.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * XFE CLI Server/Task 静态命令。
3
+ *
4
+ * 负责本地 server 启动、远端任务创建和 client request 交互循环。
5
+ */
6
+ import { Command } from 'commander';
7
+ export declare function registerServerCommands(program: Command): void;
8
+ export declare function registerTaskCommands(program: Command): void;
9
+ //# sourceMappingURL=server-task-commands.d.ts.map
@@ -0,0 +1,254 @@
1
+ /**
2
+ * XFE CLI Server/Task 静态命令。
3
+ *
4
+ * 负责本地 server 启动、远端任务创建和 client request 交互循环。
5
+ */
6
+ import { createInterface } from 'node:readline/promises';
7
+ import { DEFAULT_SERVER_PORT, startServer } from '@xfe-repo/server';
8
+ import { HttpBackendGateway } from './http-backend.js';
9
+ // ─── Public API ─────────────────────────────────────────────
10
+ export function registerServerCommands(program) {
11
+ const serverCmd = program.command('server').helpCommand(false).description('XFE Server 管理');
12
+ serverCmd
13
+ .command('start')
14
+ .description('启动本地 xfe server')
15
+ .option('-p, --port <port>', `监听端口,默认 ${DEFAULT_SERVER_PORT}`)
16
+ .option('-H, --host <host>', '监听地址')
17
+ .action((options) => {
18
+ const port = resolvePort(options.port);
19
+ const server = startServer({ port, hostname: options.host });
20
+ console.log(`XFE Server listening on ${options.host ?? '0.0.0.0'}:${server.port}`);
21
+ console.log(`HTTP health: http://${options.host ?? 'localhost'}:${server.port}/health`);
22
+ console.log(`MCP endpoint: http://${options.host ?? 'localhost'}:${server.port}/mcp`);
23
+ process.once('SIGINT', () => void stopLocalServer(server.close));
24
+ process.once('SIGTERM', () => void stopLocalServer(server.close));
25
+ });
26
+ }
27
+ export function registerTaskCommands(program) {
28
+ const taskCmd = program.command('task').helpCommand(false).description('远端/本地 XFE Server 任务');
29
+ taskCmd
30
+ .command('create')
31
+ .description('通过 xfe server 创建远端 agent 任务')
32
+ .requiredOption('--repo <repoUrl>', 'Git 仓库地址')
33
+ .requiredOption('--task <taskId>', '任务号,例如 3600')
34
+ .requiredOption('--description <description>', '任务需求描述')
35
+ .option('--server <url>', `server 地址,默认 http://localhost:${DEFAULT_SERVER_PORT}`)
36
+ .option('--tenant <tenantId>', '租户 ID,本地默认 local')
37
+ .option('--document-url <url>', '需求文档链接')
38
+ .option('--base-branch <branch>', '基准分支,默认 main')
39
+ .option('--prepare-workspace', '创建任务后立即 clone 仓库并创建任务分支')
40
+ .option('--start', '创建任务后启动 agent workflow')
41
+ .option('--executor <executor>', 'agent executor,mock | codex | copilot')
42
+ .option('--auto-approve', '启动 agent workflow 后自动通过计划审批')
43
+ .action(async (options) => {
44
+ const gateway = createBackendGateway(options);
45
+ const result = await gateway.createTask({
46
+ repoUrl: options.repo,
47
+ taskId: options.task,
48
+ description: options.description,
49
+ documentUrl: options.documentUrl,
50
+ baseBranch: options.baseBranch,
51
+ prepareWorkspace: options.prepareWorkspace,
52
+ });
53
+ printJson(result);
54
+ if (!options.start)
55
+ return;
56
+ const started = await gateway.startTask({ taskId: options.task, executor: options.executor, autoApprove: options.autoApprove });
57
+ printJson(started);
58
+ });
59
+ taskCmd
60
+ .command('start <taskId>')
61
+ .description('启动已创建的 agent workflow')
62
+ .option('--executor <executor>', 'agent executor,mock | codex | copilot')
63
+ .option('--auto-approve', '自动通过计划审批')
64
+ .option('--server <url>', `server 地址,默认 http://localhost:${DEFAULT_SERVER_PORT}`)
65
+ .option('--tenant <tenantId>', '租户 ID,本地默认 local')
66
+ .action(async (taskId, options) => {
67
+ const gateway = createBackendGateway(options);
68
+ const started = await gateway.startTask({ taskId, executor: options.executor, autoApprove: options.autoApprove });
69
+ printJson(started);
70
+ });
71
+ registerRequestCommands(taskCmd);
72
+ }
73
+ // ─── Command Registration ───────────────────────────────────
74
+ function registerRequestCommands(taskCmd) {
75
+ taskCmd
76
+ .command('requests')
77
+ .description('列出等待用户处理的 ask/approval 请求')
78
+ .option('--status <status>', '请求状态,默认不过滤')
79
+ .option('--server <url>', `server 地址,默认 http://localhost:${DEFAULT_SERVER_PORT}`)
80
+ .option('--tenant <tenantId>', '租户 ID,本地默认 local')
81
+ .action(async (options) => {
82
+ const gateway = createBackendGateway(options);
83
+ const result = await gateway.listClientRequests({ status: options.status });
84
+ printJson(result);
85
+ });
86
+ taskCmd
87
+ .command('watch')
88
+ .description('监听并处理等待用户处理的 ask/approval 请求')
89
+ .option('--server <url>', `server 地址,默认 http://localhost:${DEFAULT_SERVER_PORT}`)
90
+ .option('--tenant <tenantId>', '租户 ID,本地默认 local')
91
+ .option('--interval <ms>', '轮询间隔,默认 1000')
92
+ .option('--once', '只处理当前 pending 请求后退出')
93
+ .action(async (options) => {
94
+ await watchClientRequests({
95
+ gateway: createBackendGateway(options),
96
+ intervalMs: resolvePollInterval(options.interval),
97
+ once: Boolean(options.once),
98
+ });
99
+ });
100
+ taskCmd
101
+ .command('respond <requestId>')
102
+ .description('响应 ask/approval 请求')
103
+ .requiredOption('--action <action>', 'accept | decline | cancel')
104
+ .option('--content <json>', '响应内容 JSON')
105
+ .option('--server <url>', `server 地址,默认 http://localhost:${DEFAULT_SERVER_PORT}`)
106
+ .option('--tenant <tenantId>', '租户 ID,本地默认 local')
107
+ .action(async (requestId, options) => {
108
+ const gateway = createBackendGateway(options);
109
+ const result = await gateway.respondClientRequest({
110
+ requestId,
111
+ action: parseResponseAction(options.action),
112
+ content: parseJsonRecord(options.content),
113
+ });
114
+ printJson(result);
115
+ });
116
+ }
117
+ // ─── Watch Flow ─────────────────────────────────────────────
118
+ async function watchClientRequests(options) {
119
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
120
+ const handledRequestIds = new Set();
121
+ try {
122
+ while (true) {
123
+ const requests = await listPendingClientRequests(options.gateway, handledRequestIds);
124
+ for (const request of requests) {
125
+ handledRequestIds.add(request.id);
126
+ const response = await promptClientRequest(terminal, request);
127
+ await options.gateway.respondClientRequest({ requestId: request.id, action: response.action, content: response.content });
128
+ }
129
+ if (options.once)
130
+ return;
131
+ await wait(options.intervalMs);
132
+ }
133
+ }
134
+ finally {
135
+ terminal.close();
136
+ }
137
+ }
138
+ async function listPendingClientRequests(gateway, handledRequestIds) {
139
+ const response = await gateway.listClientRequests({ status: 'pending' });
140
+ return extractClientRequests(response).filter((request) => !handledRequestIds.has(request.id));
141
+ }
142
+ async function promptClientRequest(terminal, request) {
143
+ console.log(`\n[${request.kind}] ${request.id}`);
144
+ console.log(request.message);
145
+ if (isActionOnlyRequest(request.kind))
146
+ return { action: await promptAction(terminal), content: undefined };
147
+ const content = await promptSchemaContent(terminal, request.schema);
148
+ return { action: 'accept', content };
149
+ }
150
+ async function promptAction(terminal) {
151
+ const answer = await terminal.question('处理方式 accept/decline/cancel,默认 accept: ');
152
+ const normalizedAnswer = answer.trim().toLowerCase();
153
+ if (!normalizedAnswer)
154
+ return 'accept';
155
+ if (normalizedAnswer === 'a' || normalizedAnswer === 'accept')
156
+ return 'accept';
157
+ if (normalizedAnswer === 'd' || normalizedAnswer === 'decline')
158
+ return 'decline';
159
+ if (normalizedAnswer === 'c' || normalizedAnswer === 'cancel')
160
+ return 'cancel';
161
+ throw new Error('处理方式必须是 accept、decline 或 cancel');
162
+ }
163
+ async function promptSchemaContent(terminal, schema) {
164
+ const fields = extractSchemaFields(schema);
165
+ if (fields.length === 0)
166
+ return undefined;
167
+ const content = {};
168
+ for (const field of fields) {
169
+ content[field.name] = await promptSchemaField(terminal, field);
170
+ }
171
+ return content;
172
+ }
173
+ async function promptSchemaField(terminal, field) {
174
+ const enumText = field.enumValues?.length ? ` (${field.enumValues.join(' | ')})` : '';
175
+ const defaultText = field.defaultValue === undefined ? '' : `,默认 ${String(field.defaultValue)}`;
176
+ const answer = await terminal.question(`${field.title}${enumText}${defaultText}: `);
177
+ const value = answer.trim() || field.defaultValue;
178
+ if (field.type === 'boolean')
179
+ return parseBooleanField(value);
180
+ if (field.type === 'number' || field.type === 'integer')
181
+ return Number(value);
182
+ return String(value ?? '');
183
+ }
184
+ // ─── Helpers ────────────────────────────────────────────────
185
+ function createBackendGateway(options) {
186
+ return new HttpBackendGateway({ baseUrl: options.server ?? `http://localhost:${DEFAULT_SERVER_PORT}`, tenantId: options.tenant });
187
+ }
188
+ function resolvePort(rawPort) {
189
+ const port = Number(rawPort);
190
+ return Number.isInteger(port) && port > 0 ? port : DEFAULT_SERVER_PORT;
191
+ }
192
+ function resolvePollInterval(rawInterval) {
193
+ const intervalMs = Number(rawInterval);
194
+ return Number.isInteger(intervalMs) && intervalMs > 0 ? intervalMs : 1000;
195
+ }
196
+ async function stopLocalServer(close) {
197
+ await close();
198
+ process.exit(0);
199
+ }
200
+ function parseResponseAction(action) {
201
+ if (action === 'accept' || action === 'decline' || action === 'cancel')
202
+ return action;
203
+ throw new Error('action 必须是 accept、decline 或 cancel');
204
+ }
205
+ function parseJsonRecord(content) {
206
+ if (!content)
207
+ return undefined;
208
+ const parsed = JSON.parse(content);
209
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
210
+ throw new Error('content 必须是 JSON object');
211
+ }
212
+ return parsed;
213
+ }
214
+ function extractClientRequests(response) {
215
+ if (!isRecord(response) || !Array.isArray(response.requests))
216
+ return [];
217
+ return response.requests.filter(isClientRequestView);
218
+ }
219
+ function isClientRequestView(value) {
220
+ if (!isRecord(value))
221
+ return false;
222
+ return typeof value.id === 'string' && typeof value.kind === 'string' && typeof value.status === 'string' && typeof value.message === 'string';
223
+ }
224
+ function extractSchemaFields(schema) {
225
+ if (!schema || !isRecord(schema.properties))
226
+ return [];
227
+ return Object.entries(schema.properties).map(([name, value]) => createSchemaField(name, value));
228
+ }
229
+ function createSchemaField(name, value) {
230
+ const property = isRecord(value) ? value : {};
231
+ const enumValues = Array.isArray(property.enum) ? property.enum.filter((item) => typeof item === 'string') : undefined;
232
+ const title = typeof property.title === 'string' ? property.title : name;
233
+ const type = typeof property.type === 'string' ? property.type : undefined;
234
+ return { name, title, type, enumValues, defaultValue: property.default };
235
+ }
236
+ function isActionOnlyRequest(kind) {
237
+ return kind === 'approval' || kind === 'permission' || kind === 'confirm';
238
+ }
239
+ function parseBooleanField(value) {
240
+ if (typeof value === 'boolean')
241
+ return value;
242
+ const normalizedValue = String(value).trim().toLowerCase();
243
+ return normalizedValue === 'true' || normalizedValue === 'yes' || normalizedValue === 'y' || normalizedValue === '1';
244
+ }
245
+ function isRecord(value) {
246
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
247
+ }
248
+ function wait(intervalMs) {
249
+ return new Promise((resolve) => setTimeout(resolve, intervalMs));
250
+ }
251
+ function printJson(value) {
252
+ console.log(JSON.stringify(value, null, 2));
253
+ }
254
+ //# sourceMappingURL=server-task-commands.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xfe-repo/cli",
3
- "version": "2.0.8",
3
+ "version": "2.0.9",
4
4
  "description": "XFE CLI - Ink-based terminal UI for project scaffolding",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -17,8 +17,8 @@
17
17
  "ink-link": "^5.0.0",
18
18
  "react": "^19.1.0",
19
19
  "zod": "^4.3.6",
20
- "@xfe-repo/cli-core": "2.0.4",
21
- "@xfe-repo/cli-presets": "2.0.4"
20
+ "@xfe-repo/cli-core": "2.0.5",
21
+ "@xfe-repo/cli-presets": "2.0.5"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@types/node": "^24.3.0",