refactor: 移除不再使用的轻代码路由,优化 OpenCode 客户端的端口配置

This commit is contained in:
2026-01-27 22:21:51 +08:00
parent 14f2dad837
commit 220b008b90
6 changed files with 36 additions and 77 deletions

View File

@@ -2,8 +2,6 @@ import { app, assistantConfig } from '../app.ts';
import './config/index.ts'; import './config/index.ts';
import './shop-install/index.ts'; import './shop-install/index.ts';
import './ai/index.ts'; import './ai/index.ts';
// TODO:
// import './light-code/index.ts';
import './user/index.ts'; import './user/index.ts';
import './call/index.ts' import './call/index.ts'
@@ -64,18 +62,16 @@ export const checkAuth = async (ctx: any, isAdmin = false) => {
} }
authCache.set(token, tokenUser); authCache.set(token, tokenUser);
} }
if (ctx.state) {
ctx.state = { ctx.state = {
...ctx.state, ...ctx.state,
token, token,
tokenUser, tokenUser,
}; };
}
const { username } = tokenUser; const { username } = tokenUser;
if (!auth.username) { if (!auth.username) {
// 初始管理员账号 // 初始管理员账号
auth.username = username; auth.username = username;
assistantConfig.setConfig({ auth }); assistantConfig.setConfig({ auth, token: token });
} }
if (isAdmin && auth.username) { if (isAdmin && auth.username) {
const admins = config.auth?.admin || []; const admins = config.auth?.admin || [];
@@ -83,6 +79,12 @@ export const checkAuth = async (ctx: any, isAdmin = false) => {
const admin = auth.username; const admin = auth.username;
if (admin === username) { if (admin === username) {
isCheckAdmin = true; isCheckAdmin = true;
const _token = config.token;
if (!_token) {
assistantConfig.setConfig({ token: token });
} else if (_token && _token.startsWith('st-') && _token !== token) {
assistantConfig.setConfig({ token: token });
}
} }
if (!isCheckAdmin && admins.length > 0 && admins.includes(username)) { if (!isCheckAdmin && admins.length > 0 && admins.includes(username)) {
isCheckAdmin = true; isCheckAdmin = true;
@@ -122,7 +124,7 @@ app
description: '管理员鉴权, 获取用户信息,并验证是否为管理员。', description: '管理员鉴权, 获取用户信息,并验证是否为管理员。',
}) })
.define(async (ctx) => { .define(async (ctx) => {
logger.debug('query', ctx.query); // logger.debug('query', ctx.query);
if (!ctx.query?.token && ctx.appId === app.appId) { if (!ctx.query?.token && ctx.appId === app.appId) {
return; return;
} }

View File

@@ -1,31 +0,0 @@
import { app, assistantConfig } from '../../app.ts'
import path from 'path'
import { runCode } from '../../module/light-code/run.ts'
// http://localhost:4005/api/router?path=call
app.route({
path: 'light-code',
key: 'call',
// middleware: ['auth']
}).define(async (ctx) => {
const filename = ctx.query?.filename || 'root/light-code-demo/demo-router.ts'
const data = ctx.query?.data || {}
const appsConfigPath = assistantConfig.configPath?.appsDir || '';
const testA = path.join(appsConfigPath, filename)
try {
const resulst = await runCode(testA, data);
if (resulst.success) {
const callResult = resulst.data;
if (callResult.code === 200) ctx.body = callResult.data
else {
const callError = `调用程序错误: ${callResult.message}`
ctx.throw(callResult.code, callError)
}
} else {
ctx.body = `执行脚本错误: ${resulst.error}`
}
} catch (error) {
ctx.body = `执行脚本异常: ${error?.message || error}`
}
}).addTo(app)

View File

@@ -1,3 +0,0 @@
import './call.ts'
import './upload.ts'

View File

@@ -1,10 +0,0 @@
import { app } from '../../app.ts';
app.route({
path: 'light-code',
key: 'upload',
middleware: ['auth'],
description: '上传轻代码应用代码',
}).define(async (ctx) => {
const files = ctx.query.files;
}).addTo(app);

View File

@@ -18,12 +18,12 @@ app.route({
title: '创建 OpenCode 客户端', title: '创建 OpenCode 客户端',
summary: '创建 OpenCode 客户端,如果存在则复用', summary: '创建 OpenCode 客户端,如果存在则复用',
args: { args: {
port: tool.schema.number().optional().describe('OpenCode 服务端口,默认为 5000')
} }
}) })
}, },
}).define(async (ctx) => { }).define(async (ctx) => {
const client = await opencodeManager.getClient(); const client = await opencodeManager.getClient({ port: ctx.query.port });
ctx.body = { content: `${opencodeManager.url} OpenCode 客户端已就绪` }; ctx.body = { content: `${opencodeManager.url} OpenCode 客户端已就绪` };
}).addTo(app); }).addTo(app);
@@ -62,12 +62,12 @@ app.route({
title: '获取 OpenCode 服务 URL', title: '获取 OpenCode 服务 URL',
summary: '获取当前 OpenCode 服务的 URL 地址', summary: '获取当前 OpenCode 服务的 URL 地址',
args: { args: {
port: tool.schema.number().optional().describe('OpenCode 服务端口,默认为 5000')
} }
}) })
}, },
}).define(async (ctx) => { }).define(async (ctx) => {
const url = await opencodeManager.getUrl(); const url = await opencodeManager.getUrl({ port: ctx.query.port });
const cnbURL = useKey('CNB_VSCODE_PROXY_URI') as string | undefined; const cnbURL = useKey('CNB_VSCODE_PROXY_URI') as string | undefined;
let content = `本地访问地址: ${url}` let content = `本地访问地址: ${url}`
if (cnbURL) { if (cnbURL) {
@@ -75,6 +75,7 @@ app.route({
} }
ctx.body = { content }; ctx.body = { content };
}).addTo(app); }).addTo(app);
// 调用 path: opencode key: ls-projects // 调用 path: opencode key: ls-projects
app.route({ app.route({
path: 'opencode', path: 'opencode',

View File

@@ -6,13 +6,13 @@ import path from "node:path";
import fs from "node:fs"; import fs from "node:fs";
import { execSync } from "node:child_process"; import { execSync } from "node:child_process";
const DEFAULT_PORT = 5000;
export class OpencodeManager { export class OpencodeManager {
private static instance: OpencodeManager | null = null; private static instance: OpencodeManager | null = null;
private client: OpencodeClient | null = null; private client: OpencodeClient | null = null;
private server: { url: string; close(): void } | null = null; private server: { url: string; close(): void } | null = null;
private isInitializing: boolean = false; private isInitializing: boolean = false;
private currentPort: number | null = null;
public url: string = ''; public url: string = '';
private constructor() { } private constructor() { }
@@ -24,23 +24,21 @@ export class OpencodeManager {
return OpencodeManager.instance; return OpencodeManager.instance;
} }
async getClient(): Promise<OpencodeClient> { async getClient(opts?: { port?: number }): Promise<OpencodeClient> {
// 如果已经有 client直接返回 const port = opts?.port ?? DEFAULT_PORT;
if (this.client) { if (this.client) {
return this.client; return this.client;
} }
// 如果正在初始化,等待初始化完成
if (this.isInitializing) { if (this.isInitializing) {
await new Promise(resolve => setTimeout(resolve, 100)); await new Promise(resolve => setTimeout(resolve, 100));
return this.getClient(); return this.getClient(opts);
} }
// 开始初始化
this.isInitializing = true; this.isInitializing = true;
try { try {
const port = 5000; const currentPort = await getPort({ port });
const currentPort = await getPort({ port: port });
if (port === currentPort) { if (port === currentPort) {
const result = await createOpencode({ const result = await createOpencode({
hostname: '0.0.0.0', hostname: '0.0.0.0',
@@ -59,6 +57,7 @@ export class OpencodeManager {
this.isInitializing = false; this.isInitializing = false;
} }
} }
async createOpencodeProject({ async createOpencodeProject({
directory, directory,
port = 5000 port = 5000
@@ -69,11 +68,10 @@ export class OpencodeManager {
}); });
return client; return client;
} }
async killPort(port: number): Promise<void> { async killPort(port: number): Promise<void> {
try { try {
// 尝试 使用命令行去关闭 port为5000的服务
if (os.platform() === 'win32') { if (os.platform() === 'win32') {
// Windows 平台
execSync(`netstat -ano | findstr :${port} | findstr LISTENING`).toString().split('\n').forEach(line => { execSync(`netstat -ano | findstr :${port} | findstr LISTENING`).toString().split('\n').forEach(line => {
const parts = line.trim().split(/\s+/); const parts = line.trim().split(/\s+/);
const pid = parts[parts.length - 1]; const pid = parts[parts.length - 1];
@@ -83,7 +81,6 @@ export class OpencodeManager {
} }
}); });
} else { } else {
// Unix-like 平台
const result = execSync(`lsof -i :${port} -t`).toString(); const result = execSync(`lsof -i :${port} -t`).toString();
result.split('\n').forEach(pid => { result.split('\n').forEach(pid => {
if (pid) { if (pid) {
@@ -96,14 +93,15 @@ export class OpencodeManager {
console.error('Failed to close OpenCode server:', error); console.error('Failed to close OpenCode server:', error);
} }
} }
async close(): Promise<void> {
async close(opts?: { port?: number }): Promise<void> {
if (this.server) { if (this.server) {
this.server.close(); this.server.close();
this.server = null; this.server = null;
return return
} }
const port = 5000; const port = opts?.port ?? DEFAULT_PORT;
const currentPort = await getPort({ port: port }); const currentPort = await getPort({ port });
if (port === currentPort) { if (port === currentPort) {
this.client = null; this.client = null;
return; return;
@@ -113,14 +111,16 @@ export class OpencodeManager {
this.client = null; this.client = null;
} }
async getUrl(): Promise<string> {
async getUrl(opts?: { port?: number }): Promise<string> {
const port = opts?.port ?? DEFAULT_PORT;
if (this.url) { if (this.url) {
return this.url; return this.url;
} }
if (!this.url) { if (!this.url) {
await this.getClient(); await this.getClient(opts);
} }
return 'http://localhost:5000'; return `http://localhost:${port}`;
} }
} }