Commit 6f8605f7 by liimin

refactor(server): 将路由处理逻辑拆分到独立模块

1 parent 3309ef80
import { readFileSync, existsSync, statSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { ServerResponse } from 'node:http';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC_INDEX = path.join(__dirname, '..', 'public', 'index.html');
// Phase 2 前端工程构建产物:apps/web/dist。存在时优先托管它(支持 SPA 路由)。
export const WEB_DIST = path.join(__dirname, '..', '..', 'web', 'dist');
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.map': 'application/json',
};
/** 目录选择器中隐藏的“噪音”目录,保持文件树可读。 */
export const FS_NOISE = new Set([
'node_modules',
'.git',
'.next',
'.nuxt',
'.turbo',
'.cache',
'dist',
'build',
'out',
'coverage',
'.svelte-kit',
'.output',
'.workbuddy',
'.trash',
'.trash-win',
]);
/** 目录选择器的初始顶层根视图。 */
export function listRoots(): string[] {
if (process.platform === 'win32') {
const drives: string[] = [];
for (const c of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
try {
if (existsSync(`${c}:\\`)) drives.push(`${c}:\\`);
} catch {
/* 不可访问的盘符,跳过 */
}
}
return drives.length ? drives : ['C:\\'];
}
return ['/'];
}
/** 以正确的 MIME 类型读取并返回静态文件;失败返回 404。 */
export function serveStaticFile(res: ServerResponse, filePath: string): void {
try {
const data = readFileSync(filePath);
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, {
'Content-Type': MIME[ext] ?? 'application/octet-stream',
'Cache-Control': 'no-cache',
});
res.end(data);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not Found');
}
}
/** 解析要返回的 index.html:优先 Phase 2 构建产物,否则回退到 public 内置页。 */
export function resolveIndexHtml(): string {
if (WEB_DIST && existsSync(path.join(WEB_DIST, 'index.html'))) {
return path.join(WEB_DIST, 'index.html');
}
return PUBLIC_INDEX;
}
import type { Route } from './context';
/** 管理控制面:自重启、停止服务。 */
export const adminRoutes: Route[] = [
// ---- POST /api/admin/restart(自重启)----
{
method: 'POST',
path: '/api/admin/restart',
handle: ({ ctx, res }) => {
ctx.sendJson(res, 200, { ok: true, message: '服务正在重启…' });
// 直接触发重启,不依赖 res.on('finish'):否则连接被提前关闭时
// 回调可能不触发,导致「点了重启却没反应」。
ctx.admin.restart();
},
},
// ---- POST /api/admin/shutdown(停止服务)----
{
method: 'POST',
path: '/api/admin/shutdown',
handle: ({ ctx, res }) => {
ctx.sendJson(res, 200, { ok: true, message: '服务正在停止…' });
res.on('finish', () => ctx.admin.shutdown()); // 响应完成后再关闭
},
},
];
import type { Route } from './context';
import { configView } from '../config';
/** 配置视图与系统快照。 */
export const configRoutes: Route[] = [
// ---- GET /api/config:返回模型配置视图 ----
{
method: 'GET',
path: '/api/config',
handle: ({ ctx, res }) => {
const view = configView(ctx.model, ctx.opts.maxConcurrent);
ctx.sendJson(res, 200, view);
},
},
// ---- GET /api/admin/status(系统快照)----
{
method: 'GET',
path: '/api/admin/status',
handle: ({ ctx, res }) => {
ctx.sendJson(res, 200, ctx.computeStatus());
},
},
];
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { JobStore } from '../jobStore';
import type { JobQueue } from '../queue';
import type { PreviewManager } from '../preview';
import type { ProjectRunner } from '../project-runner';
import type { resolveServerOptions, loadServerModelConfig } from '../config';
import type { SystemStatus, LogEntry } from '../types';
/**
* 注入到所有路由 handler 的共享上下文。
* 等价于原 server.ts 闭包内共享的依赖与辅助函数,集中到一个对象里传递,
* 避免每个 handler 各自携带一长串参数。
*/
export interface ServerCtx {
store: JobStore;
queue: JobQueue;
preview: PreviewManager;
projectRunner: ProjectRunner;
opts: ReturnType<typeof resolveServerOptions>;
startTime: number;
serverVersion: string;
coderioVersion: string;
admin: { restart: () => void; shutdown: () => void };
model: ReturnType<typeof loadServerModelConfig>;
sseClients: Set<ServerResponse>;
recentLogs: LogEntry[];
broadcast: (event: string, data: unknown) => void;
sendJson: (res: ServerResponse, code: number, obj: unknown) => void;
readJsonBody: <T = Record<string, unknown>>(req: IncomingMessage) => Promise<T>;
computeStatus: () => SystemStatus;
/** 是否由后端托管 UI(COD_SERVE_WEB !== '0')。 */
SERVE_WEB: boolean;
/** Phase 2 前端构建产物目录;仅 SERVE_WEB 时有效。 */
WEB_DIST: string | undefined;
}
/** 一次请求 + 匹配出的路径参数,统一传给 handler。 */
export interface RouteContext {
ctx: ServerCtx;
req: IncomingMessage;
res: ServerResponse;
url: URL;
params: Record<string, string>;
}
/**
* 单条路由定义。
* handle 返回值语义:返回 `false` 表示“未处理,继续尝试下一条路由”;
* 返回 `true` / `undefined` / `void` 表示已处理(无论响应内容是什么)。
* 这用于实现 SPA fallback 等“条件命中”的路由。
*/
export interface Route {
method: string;
/** 精确路径,或含 `:param`(单段)与 `*`(`/assets/*` 等通配)的模式。 */
path: string;
handle: (rc: RouteContext) => Promise<boolean | void> | boolean | void;
}
/*
* @Author: liimin 17653212@qq.com
* @Date: 2026-09-15 16:31:34
* @LastEditors: liimin 17653212@qq.com
* @LastEditTime: 2026-09-15 17:02:32
* @FilePath: \coderio\apps\server\src\routes\fs.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import path from 'node:path';
import { existsSync, statSync, readdirSync } from 'node:fs';
import type { Route } from './context';
import { listRoots, FS_NOISE } from '../http-utils';
/** GET /api/fs/list:服务端目录浏览器,驱动前端目录选择器。 */
export const fsRoutes: Route[] = [
{
method: 'GET',
path: '/api/fs/list',
handle: ({ ctx, res, url }) => {
const dirParam = (url.searchParams.get('dir') || '').trim();
try {
if (!dirParam) {
ctx.sendJson(res, 200, { path: null, parent: null, dirs: listRoots(), isRoot: true });
return;
}
const abs = path.resolve(dirParam);
if (!existsSync(abs) || !statSync(abs).isDirectory()) {
ctx.sendJson(res, 400, { error: `目录不存在:${abs}` });
return;
}
const entries = readdirSync(abs, { withFileTypes: true });
const dirs = entries
.filter((e) => e.isDirectory() && !FS_NOISE.has(e.name))
.map((e) => e.name)
.sort((a, b) => a.localeCompare(b));
const parent = path.dirname(abs);
ctx.sendJson(res, 200, {
path: abs,
parent: parent !== abs ? parent : null,
dirs,
isRoot: false,
});
} catch (e) {
ctx.sendJson(res, 500, { error: e instanceof Error ? e.message : '读取目录失败' });
}
},
},
];
import path from 'node:path';
import { parseFigmaUrl } from 'coderio';
import type { Route } from './context';
import type { GenerateRequest, Job } from '../types';
/** POST /api/generate:核心入口,提交一次 Figma 转代码任务。 */
export const generateRoutes: Route[] = [
{
method: 'POST',
path: '/api/generate',
handle: async ({ ctx, req, res }) => {
let body: GenerateRequest;
try {
body = await ctx.readJsonBody<GenerateRequest>(req);
} catch {
ctx.sendJson(res, 400, { error: 'Invalid JSON body' });
return;
}
const figmaUrl = (body.figmaUrl || '').trim();
if (!figmaUrl) {
ctx.sendJson(res, 400, { error: 'figmaUrl 为必填项' });
return;
}
try {
// 校验 Figma URL 合法性(需含 design/file 链接与 ?node-id=)
parseFigmaUrl(figmaUrl);
} catch {
ctx.sendJson(res, 400, {
error: 'Invalid Figma URL(需包含 design/file 链接与 ?node-id=)',
});
return;
}
// 规范化生成模式(full / code / with-report),非法值回退到 full
const mode =
body.mode && ['full', 'code', 'with-report'].includes(body.mode)
? body.mode
: 'full';
// 构造 Job 对象:默认 queued 状态,记录输出目录、应用名、目标栈等参数
const job: Job = {
id: `job-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
status: 'queued',
figmaUrl,
mode,
outputDir: body.outputDir ? path.resolve(body.outputDir) : ctx.opts.outputDir,
appName: body.appName || 'my-app',
target: body.target ?? null,
stack: body.stack ?? null,
fillContainer: body.fillContainer ?? true,
resultDir: null,
reportPath: null,
error: null,
pid: null,
createdAt: new Date().toISOString(),
startedAt: null,
finishedAt: null,
};
ctx.queue.submit(job); // 入队
const position = ctx.queue.position(job.id); // 查询队列位置
ctx.sendJson(res, 200, {
jobId: job.id,
position,
message:
position > 0 ? `已加入队列,前方还有 ${position} 个任务` : '开始生成',
});
},
},
];
import type { Route } from './context';
import { staticRoutes } from './static';
import { streamRoutes } from './stream';
import { configRoutes } from './config';
import { profileRoutes } from './profile';
import { fsRoutes } from './fs';
import { generateRoutes } from './generate';
import { jobRoutes } from './jobs';
import { previewRoutes } from './preview';
import { projectRoutes } from './project';
import { adminRoutes } from './admin';
/**
* 全量路由表。注册顺序即匹配顺序,需保证:
* 1. static 段放在最后含 SPA catch-all (`/*`),它仅对非 /api、无后缀 GET 命中,
* 对 /api 路径返回 false 放行给后续业务路由;
* 2. 动态路由(`:id`)放在同名集合路由(如 `/api/jobs`)之后无冲突,
* 因为 `:id` 强制要求一段路径,精确集合路径不会误匹配。
*/
export const routes: Route[] = [
...staticRoutes,
...streamRoutes,
...configRoutes,
...profileRoutes,
...fsRoutes,
...generateRoutes,
...jobRoutes,
...previewRoutes,
...projectRoutes,
...adminRoutes,
];
import type { Route } from './context';
/** Job 管理:列表、详情、取消、删除单条、清空全部,以及日志历史。 */
export const jobRoutes: Route[] = [
// ---- GET /api/jobs:列出所有任务 ----
{
method: 'GET',
path: '/api/jobs',
handle: ({ ctx, res }) => {
ctx.sendJson(res, 200, { jobs: ctx.store.list() });
},
},
// ---- GET /api/logs:返回最近日志历史(非 SSE 的轮询兜底)----
{
method: 'GET',
path: '/api/logs',
handle: ({ ctx, res }) => {
ctx.sendJson(res, 200, { logs: ctx.recentLogs });
},
},
// ---- GET /api/job/:id:查询单个任务详情 ----
{
method: 'GET',
path: '/api/job/:id',
handle: ({ ctx, res, params }) => {
const job = ctx.store.get(params.id);
ctx.sendJson(res, job ? 200 : 404, job ?? { error: 'not found' });
},
},
// ---- POST /api/jobs/:id/cancel:取消(排队/运行中的)任务 ----
{
method: 'POST',
path: '/api/jobs/:id/cancel',
handle: ({ ctx, res, params }) => {
const ok = ctx.queue.cancel(params.id);
ctx.sendJson(res, ok ? 200 : 404, { ok });
},
},
// ---- DELETE /api/jobs/:id:删除单个任务 ----
{
method: 'DELETE',
path: '/api/jobs/:id',
handle: ({ ctx, res, params }) => {
const id = params.id;
const job = ctx.store.get(id);
if (!job) {
ctx.sendJson(res, 404, { ok: false, error: '任务不存在' });
return;
}
// 先中止仍在运行/排队中的子进程,避免泄漏游离子进程
if (job.status === 'running' || job.status === 'queued') {
ctx.queue.cancel(id);
}
ctx.store.delete(id);
ctx.broadcast('jobs', ctx.store.list()); // 通知前端任务列表变化
ctx.sendJson(res, 200, { ok: true });
},
},
// ---- DELETE /api/jobs:清空所有任务 ----
{
method: 'DELETE',
path: '/api/jobs',
handle: ({ ctx, res }) => {
const all = ctx.store.list();
for (const j of all) {
if (j.status === 'running' || j.status === 'queued') {
ctx.queue.cancel(j.id);
}
}
const count = ctx.store.clear();
ctx.broadcast('jobs', ctx.store.list());
ctx.sendJson(res, 200, { ok: true, count });
},
},
];
import path from 'node:path';
import { parseFigmaUrl } from 'coderio';
import type { Route } from './context';
import { PreviewManager } from '../preview';
/** 生成结果预览服务:状态、启动、停止、重启。 */
export const previewRoutes: Route[] = [
// ---- GET /api/preview:查询预览服务状态 ----
{
method: 'GET',
path: '/api/preview',
handle: ({ ctx, res }) => {
ctx.sendJson(res, 200, ctx.preview.state);
},
},
// ---- POST /api/preview(启动预览)----
{
method: 'POST',
path: '/api/preview',
handle: async ({ ctx, req, res }) => {
let body: { appPath?: string } = {};
try {
body = await ctx.readJsonBody<{ appPath?: string }>(req);
} catch {
/* 忽略解析失败,使用默认解析 */
}
// 解析生成的 app 目录:优先用最新完成任务的 Figma URL 重新解析(见下方说明),
// 而非信任持久化的 resultDir——后者由 server 进程在 spawn 时计算,若 coderio
// 包在 server 启动后被重建(开发期常见),存储值可能与引擎实际创建目录不一致,
// 导致 preview 找不到 my-app。仅在 URL 解析失败时才回退到存储值。
const latestDone = ctx.store.list().find((j) => j.status === 'done' && j.figmaUrl);
let resolvedDir: string | null = null;
if (latestDone?.figmaUrl) {
try {
const projectName = parseFigmaUrl(latestDone.figmaUrl).projectName;
if (projectName) {
resolvedDir = path.resolve(ctx.opts.outputDir, 'coderio', projectName);
}
} catch {
resolvedDir = null;
}
}
if (!resolvedDir && latestDone?.resultDir) {
resolvedDir = latestDone.resultDir;
}
const appPath = body.appPath || PreviewManager.defaultAppPath(resolvedDir);
const r = ctx.preview.start(appPath);
ctx.sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
},
},
// ---- POST /api/preview/stop:停止预览 ----
{
method: 'POST',
path: '/api/preview/stop',
handle: ({ ctx, res }) => {
ctx.preview.stop();
ctx.sendJson(res, 200, { ok: true });
},
},
// ---- POST /api/preview/restart:重启预览 ----
{
method: 'POST',
path: '/api/preview/restart',
handle: ({ ctx, res }) => {
const r = ctx.preview.restart();
ctx.sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
},
},
];
import type { Route } from './context';
import { loadProjectProfile, saveProjectProfile, projectProfileTemplate } from '../config';
import { scanProject } from '../project-scanner';
/** 目标项目画像(profile):读取、持久化、扫描草拟。 */
export const profileRoutes: Route[] = [
// ---- GET /api/project-profile ----
// 返回「项目接入」设置面板所用的目标项目画像;未设置时返回一份全新种子模板。
{
method: 'GET',
path: '/api/project-profile',
handle: ({ ctx, res }) => {
const profile = loadProjectProfile() ?? projectProfileTemplate();
const exists = loadProjectProfile() !== null;
ctx.sendJson(res, 200, { exists, profile });
},
},
// ---- PUT /api/project-profile ----
// 持久化 UI 编辑的画像。PUT 整体替换;引擎按次运行读取文件,无需重启即生效。
{
method: 'PUT',
path: '/api/project-profile',
handle: async ({ ctx, req, res }) => {
let incoming: unknown;
try {
incoming = await ctx.readJsonBody(req);
} catch {
ctx.sendJson(res, 400, { error: 'Invalid JSON body' });
return;
}
if (!incoming || typeof incoming !== 'object') {
ctx.sendJson(res, 400, { error: 'profile must be an object' });
return;
}
// 用模板兜底缺失字段,防止前端少传导致画像结构不完整
const profile = {
...projectProfileTemplate(),
...(incoming as Record<string, unknown>),
} as never;
try {
saveProjectProfile(profile);
ctx.sendJson(res, 200, { ok: true, profile });
} catch (e) {
ctx.sendJson(res, 500, { error: e instanceof Error ? e.message : '保存失败' });
}
},
},
// ---- POST /api/project-profile/scan ----
// 扫描目标项目根目录并草拟画像。Phase 1 扫描器:只读不写,返回草稿供 UI 审阅。
{
method: 'POST',
path: '/api/project-profile/scan',
handle: async ({ ctx, req, res }) => {
let body: { rootDir?: string } = {};
try {
body = await ctx.readJsonBody<{ rootDir?: string }>(req);
} catch {
ctx.sendJson(res, 400, { error: 'Invalid JSON body' });
return;
}
const rootDir = (body.rootDir || '').trim();
if (!rootDir) {
ctx.sendJson(res, 400, { error: 'rootDir 为必填项(目标项目根目录)' });
return;
}
try {
const result = scanProject(rootDir);
ctx.sendJson(res, 200, result);
} catch (e) {
ctx.sendJson(res, 500, { error: e instanceof Error ? e.message : '扫描失败' });
}
},
},
];
import type { Route } from './context';
import { loadProjectProfile } from '../config';
/** 目标项目 dev server:状态、启动、停止。 */
export const projectRoutes: Route[] = [
// ---- GET /api/project/run:查询目标项目 dev-server 状态 ----
{
method: 'GET',
path: '/api/project/run',
handle: ({ ctx, res }) => {
ctx.sendJson(res, 200, ctx.projectRunner.getStatus());
},
},
// ---- POST /api/project/run:启动目标项目 dev server ----
{
method: 'POST',
path: '/api/project/run',
handle: async ({ ctx, req, res }) => {
let body: { dir?: string } = {};
try {
body = await ctx.readJsonBody<{ dir?: string }>(req);
} catch {
/* 忽略解析失败 */
}
// 启动目录取请求体 dir,否则取项目画像的 rootDir
const dir = (body.dir || loadProjectProfile()?.rootDir || '').trim();
if (!dir) {
ctx.sendJson(res, 400, {
ok: false,
error: '未配置工作目录(请先在「项目接入」中选择目标项目根)',
});
return;
}
const r = ctx.projectRunner.start(dir);
ctx.sendJson(res, r.ok ? 200 : 409, { ok: r.ok, error: r.error });
},
},
// ---- POST /api/project/run/stop:停止目标项目 dev server ----
{
method: 'POST',
path: '/api/project/run/stop',
handle: ({ ctx, res }) => {
ctx.projectRunner.stop();
ctx.sendJson(res, 200, { ok: true });
},
},
];
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Route, ServerCtx } from './context';
interface CompiledRoute {
method: string;
regex: RegExp;
keys: string[];
handle: Route['handle'];
}
/** 把 `:param` / `*` 路径模式编译成正则 + 参数名列表。 */
function compile(path: string): { regex: RegExp; keys: string[] } {
const keys: string[] = [];
const parts = path.split('/').map((seg) => {
if (seg === '*') {
keys.push('splat'); // 通配段
return '(.*?)';
}
const named = /^:(.+)$/.exec(seg);
if (named) {
keys.push(named[1]);
return '([^/]+)';
}
// 转义正则元字符(保留我们自己的 token 已先行处理)
return seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
});
const regex = new RegExp('^' + parts.join('/') + '/?$');
return { regex, keys };
}
/**
* 极薄路由表:按注册顺序匹配 method + path,命中后调用 handler。
* 无框架、无中间件链;handler 直接操作 req/res,保持原生语义。
*/
export function createRouter(routes: Route[]) {
const compiled: CompiledRoute[] = routes.map((r) => {
const { regex, keys } = compile(r.path);
return { method: r.method, regex, keys, handle: r.handle };
});
return {
async dispatch(
ctx: ServerCtx,
req: IncomingMessage,
res: ServerResponse,
url: URL,
): Promise<boolean> {
for (const c of compiled) {
if (c.method !== req.method) continue;
const m = c.regex.exec(url.pathname);
if (!m) continue;
const params: Record<string, string> = {};
c.keys.forEach((k, i) => {
params[k] = decodeURIComponent(m[i + 1]);
});
const handled = await c.handle({ ctx, req, res, url, params });
if (handled !== false) return true;
}
return false;
},
};
}
import path from 'node:path';
import { existsSync, statSync } from 'node:fs';
import type { Route } from './context';
import { serveStaticFile, resolveIndexHtml } from '../http-utils';
/**
* 静态资源 & UI 托管 & 就绪探针。
* 注意顺序:spa catch-all (`/*`) 必须放在最后,且仅对非 /api、无后缀的 GET 生效,
* 对 /api 路径返回 false 以放行给后续业务路由。
*/
export const staticRoutes: Route[] = [
// ---- 就绪探针(轻量、首屏即开)----
// 端口仅在引擎加载 + sqlite 初始化全部完成后才 listen(),因此本端点
// 一旦返回 200,即可认定后端已完全就绪、可接收 /api/generate。前端用它
// 在「重启后端」的 boot 窗口期内门控「开始生成」按钮,避免点进未就绪的端口。
{
method: 'GET',
path: '/api/health',
handle: ({ res }) => {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true, uptime: Math.round(process.uptime()) }));
},
},
// ---- 根路径 ----
// 开发模式(COD_SERVE_WEB=0)下后端不托管 UI,跳转到前端 dev server;
// 否则返回 index.html(优先 Phase 2 构建产物)。
{
method: 'GET',
path: '/',
handle: ({ ctx, res }) => {
if (!ctx.SERVE_WEB) {
const webPort = process.env.COD_WEB_PORT || '5173';
res.writeHead(302, { Location: `http://localhost:${webPort}/` });
res.end();
return;
}
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('UI not found.');
}
},
},
// ---- 托管已构建的前端静态资源(apps/web/dist)----
{
method: 'GET',
path: '/assets/*',
handle: ({ ctx, res, params }) => {
if (!ctx.SERVE_WEB || !ctx.WEB_DIST) return false;
// 还原原始子路径:url.pathname 为 "/assets/...",拼接时需保留 assets 段
const fp = path.join(ctx.WEB_DIST, 'assets', params.splat ?? '');
if (existsSync(fp) && statSync(fp).isFile()) {
serveStaticFile(res, fp);
return;
}
return false; // 文件不存在 → 继续,最终 404
},
},
// ---- SPA 根 /index.html ----
{
method: 'GET',
path: '/index.html',
handle: ({ ctx, res }) => {
if (!ctx.SERVE_WEB) return false;
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('UI not found.');
}
},
},
// ---- SPA fallback(客户端路由)----
// 非 /api、无文件后缀的 GET 一律回 index.html;其余返回 false 放行。
{
method: 'GET',
path: '/*',
handle: ({ ctx, res, url }) => {
if (!ctx.SERVE_WEB) return false;
if (url.pathname.startsWith('/api')) return false;
if (path.extname(url.pathname)) return false;
const idx = resolveIndexHtml();
if (existsSync(idx)) {
serveStaticFile(res, idx);
return;
}
return false;
},
},
];
import type { Route } from './context';
/** SSE 实时流 /api/stream:建立长连接,回放日志/状态历史并保活。 */
export const streamRoutes: Route[] = [
{
method: 'GET',
path: '/api/stream',
handle: ({ ctx, req, res }) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
res.write('retry: 3000\n\n'); // 告知客户端断线后 3s 重连
ctx.sseClients.add(res);
// 重放最近的日志历史,避免 (重)连接时终端空白
for (const entry of ctx.recentLogs) {
res.write(`event: log\ndata: ${JSON.stringify(entry)}\n\n`);
}
ctx.broadcast('jobs', ctx.store.list()); // 补全当前 jobs 快照
res.write(`event: preview\ndata: ${JSON.stringify(ctx.preview.state)}\n\n`);
res.write(`event: projectRun\ndata: ${JSON.stringify(ctx.projectRunner.getStatus())}\n\n`);
// 每 15s 发一次心跳注释,保活连接
const ping = setInterval(() => {
try {
res.write(': ping\n\n');
} catch {
/* 忽略写入失败 */
}
}, 15000);
// 连接关闭时清理定时器与客户端集合
req.on('close', () => {
clearInterval(ping);
ctx.sseClients.delete(res);
});
},
},
];
# CodeRio 约束体系与组件库设计(详细规划)
> 配套 `coderio-progress-report.md` §4「约束体系」的详细工程设计与路线图。
> 面向实现,非面向决策层。 · 版本:2026-09-15
---
## 0. 设计哲学:约束即产品
CodeRio 的竞争力不在"AI 会写代码",而在"AI 写出的代码紧贴你的系统、不自由发挥"。
生成只是表象,**约束(Constraint)才是产品内核**。
我们把真实项目的既有资产——技术栈、组件库、设计令牌、工程约定、API 契约——转化为
AI 可执行的「白名单」与「硬规则」,从源头压制幻觉。每一条约束都对应一类被消灭的
"自由发挥"。本文档是这些约束的工程设计与落地路线。
约束的三个层次:
1. **词汇约束(白名单)**:AI 只能用系统允许的组件 / 令牌 / 工具,不能用裸 HTML、不能臆造。
2. **规则约束(硬规则)**:目录结构、命名、lint、类型复用等,生成物必须满足。
3. **回环约束(验证闭环)**:生成后实际运行、截图比对、偏差自动修正,是最后一道硬墙。
---
## 1. 约束机制全景
| 约束机制 | 形态 | 状态 | 防住的"自由发挥" |
|---|---|---|---|
| 项目画像(技术栈/组件库声明) | 词汇 | 已落地 | 用错框架 / 库 |
| 设计令牌映射 | 词汇 | 已落地 | 硬编码颜色 / 尺寸 |
| 组件白名单 + 降级链(Tier1>库>原生) | 词汇 | 已落地 | 裸 HTML、臆造组件 |
| 工程约定 prose(CODERIO.md) | 规则 | 已落地 | 违反团队规范 |
| 库映射表(componentId / 特征码) | 词汇 | 已落地(待沉淀) | 重复造组件 |
| 自检回环(截图比对 ≤3px) | 回环 | 已落地 | 还原度不达标 |
| 统一组件层 V* | 词汇 | **规划中** | 被底层库细节带偏 |
| API / 数据契约约束 | 词汇+规则 | **规划中** | 臆造字段名、表单/请求不对齐后端 |
| 工程化约束(eslint / prettier / 目录 / i18n) | 规则 | **规划中** | 不过项目 lint、风格漂移 |
| 类型 / 接口复用约束 | 规则 | **规划中** | 重复定义类型 |
> 已落地部分详见 `coderio-architecture.md`;下文聚焦规划中部分。
---
## 2. 项目画像(ProjectProfile)现状与扩展
### 2.1 现有 Schema(已实现)
类型定义位于 `packages/coderio/src/types/project-profile.ts`,核心字段:
- `framework` / `styling` / `componentLibrary`:技术栈声明,决定生成底层形态。
- `tokens: TokenMapping[]`:设计令牌 → 代码引用(如 `theme.colors.brand` ↔ `var(--color-brand)`),AI 不直接硬编码。
- `components: ComponentMapping[]`:组件白名单(name / importPath / props / variants),优先复用。
- `utils: UtilMapping[]`:共享工具 / hook 复用。
- `conventions?: string`:自由文本工程约定,即项目内的 **CODERIO.md** 内容,作为 system instruction 注入。
- `rootDir` / `landingPath` / `importAlias`:**落盘相关**字段,已预留。
- `stateManagement` / `dataFetching` / `routing`:协作模式声明。
### 2.2 消费链路(已实现)
```
/api/project-profile (GET/PUT)
→ setProjectProfile / loadProjectProfile
→ CODE 节点:组件白名单 + 令牌映射 + conventions(prose) 注入为 system instruction
扫描器 (/api/project-profile/scan) 自动识别真实项目并产出画像草稿
持久化:~/.coderio/coderio.project.json
```
**结论**:画像消费、令牌映射、组件白名单、conventions 注入**均已生效**,今天就在减少幻觉。
### 2.3 待做:直接写入现有工程(new-page / modify-slot)
当前引擎生成到独立 `data/output/coderio/<figmaName>/my-app`(standalone)。
Schema 已预留 `rootDir` / `landingPath` / `target`,runner 已透传 `target`
(`standalone` / `new-page` / `modify-slot`),但"槽内改写"实现未做。
目标形态:
| 模式 | 行为 | 关键难点 |
|---|---|---|
| `standalone` | 生成独立 my-app(现状) | — |
| `new-page` | 在 `rootDir/landingPath` 下新建页面目录,自动接入 router | import 别名、相对路径、依赖是否已安装 |
| `modify-slot` | 按 slot id 替换既有页面中某区域 | 既有组件 props 兼容、AST 级改写 |
里程碑(写入进展报告 §8 下一步):
1. 打通 `new-page`:生成页面 + 自动 router 注册 + 依赖校验。
2. 打通 `modify-slot`:基于 AST 的局部替换,保留既有上下文。
---
## 3. 统一组件层 V*(核心规划)
### 3.1 目标与原则
- **栈无关**:React / Vue / Vue2,底层 antd / element-ui / MUI,对外只暴露一套 `V*` 组件。
- **AI 只学一次**:模型只认识 `VButton` / `VInput`…,不关心底层是 antd 还是 element-ui。
- **换库不换知识**:底层 UI 库升级 / 替换,只改 adapter,AI 提示词与生成逻辑不变。
- **最强约束**:`V*` 作为最高优先级 Tier0 白名单,彻底杜绝裸 `<div>` 当按钮、杜绝臆造组件。
### 3.2 规范契约(V* 清单,可扩展)
每个 `V*` 组件定义**语义化 props**(与具体库解耦):
| V* 组件 | 语义 props(示例) | 备注 |
|---|---|---|
| `VButton` | `variant: primary/secondary/ghost/danger`、`size`、`disabled`、`loading` | |
| `VInput` | `variant`、`size`、`placeholder`、`disabled`、`readonly` | |
| `VTextarea` | `rows`、`disabled` | |
| `VSelect` | `options`、`multiple`、`clearable` | |
| `VCheckbox` / `VRadio` | `checked`、`value` | |
| `VSwitch` | `checked` | |
| `VDatePicker` | `value`、`format` | |
| `VTable` | `columns`、`data`、`pagination` | 复合组件 |
| `VForm` / `VFormItem` | `model`、`labelWidth` | 复合组件 |
| `VDialog` / `VDrawer` | `visible`、`title` | |
| `VTabs` / `VTabPane` | `active` | |
| `VCard` / `VTag` / `VTooltip` / `VDropdown` / `VMenu` / `VPagination` / `VBreadcrumb` | … | |
- 颜色 / size 走项目 `tokens`(见 §2.1),不硬编码。
- 规范以 JSON Schema 形式存放,供 AI 提示词生成与 adapter 校验共用。
### 3.3 Adapter 层
每个 `(framework, uiKit)` 组合一个 adapter,把 `V*` 解析到具体库:
```
VButton(variant=primary) ─┬─ React + AntD → <Button type="primary">
├─ Vue3 + Element Plus → <el-button type="primary">
└─ Vue2 + Element UI → <el-button type="primary">
```
- **props 归一化**:语义 props → 各库 props 映射表 + 默认值(如 `variant: ghost` → antd `type="default"` + `ghost`)。
- **解析时机**(二选一,建议 A):
- **A. 生成时直接解析**:CODE 节点按 `ProjectProfile.componentLibrary` 选 adapter,AI 输出即目标库代码(少一次转换)。
- **B. 先生成 V* 再 codemod 转写**:AI 只吐 `V*`,独立步骤转写(解耦更彻底,但多一道工序)。
### 3.4 接入 AI 词汇
- `V*` 作为 Tier0 白名单(高于 `LIBRARY_COMPONENT_CATALOG` 与原生)。
- 提示词明确:"优先使用 `V*` 组件;仅在 `V*` 无对应项时回退到库组件 / 原生"。
- 校验回环覆盖 `V*` 渲染(截图比对对 `V*` 同样有效)。
### 3.5 沉淀与治理
- `V*` 命中表 + 特征码:与现有 `LIBRARY_COMPONENT_CATALOG` 机制一致,逐步沉淀。
- 组件库升级:只改对应 adapter,AI 知识与生成逻辑零改动。
- 回退策略:adapter 缺失 / 未命中 → 回退到库组件 / 原生(仍可交付)。
### 3.6 阶段计划
| 阶段 | 内容 | 依赖 |
|---|---|---|
| P1 | 定义 `V*` 规范契约 + JSON Schema | 无 |
| P2 | 实现 React+antd、Vue3+Element Plus 两个 adapter | P1 |
| P3 | 接入 AI 词汇(Tier0)+ 校验回环覆盖 | P2 |
| P4 | 沉淀 / 治理工具(命中表、特征码、回退) | P3 |
---
## 4. API / 数据契约约束(规划)
### 4.1 来源
- OpenAPI / Swagger 文档,或一份轻量接口清单(endpoint / method / 字段名 / 类型 / 必填)。
### 4.2 约束形态
- 生成**表单 / 请求 / 列表**时,只能使用契约内字段,**禁止臆造字段名**。
- 自动生成类型定义与请求封装(对齐后端 DTO)。
- 作为 system instruction + 组件白名单同层注入。
### 4.3 价值
- 杜绝字段名臆造、表单 / 请求与后端不对齐。
- 与 `V*` 配合:表单用 `VForm` + 契约字段,端到端不漂移。
### 4.4 接入建议
1. 扫描器扩展:在 `project-scanner` 中解析 OpenAPI 产出 `apiContract` 字段并入画像。
2. CODE 节点消费 `apiContract` 生成类型与请求代码。
---
## 5. 工程化约束(规划)
| 约束 | 形态 | 接入方式 |
|---|---|---|
| eslint / prettier | 规则 | 生成物挂校验回环,过项目 lint |
| 目录结构 / 命名 | 规则 | 写入 conventions 或独立规则 |
| import 别名 / 状态管理 / i18n 模式 | 规则 | 写入 conventions |
| 类型 / 接口复用 | 规则 | 复用项目已有 TS 类型,禁止重定义 |
| 路由 / 页面注册 | 规则 | `new-page` 自动接入 router(见 §2.3) |
目标:生成物提交前即符合项目既有工程纪律,而非"能跑就行"。
---
## 6. 约束路线图与优先级
按「价值 × 可行性」排序(供排期参考):
| 优先级 | 项 | 价值 | 可行性 | 依赖 |
|---|---|---|---|---|
| P0 | 直接写入现有工程(new-page) | 高 | 中 | 画像已具备 |
| P1 | 统一组件层 V*(P1–P2) | 高 | 中 | 无 |
| P1 | API / 数据契约约束 | 高 | 中 | 扫描器扩展 |
| P2 | 工程化约束(lint / 目录 / i18n) | 中 | 高 | conventions 已具备 |
| P2 | 类型 / 接口复用约束 | 中 | 中 | 项目类型可探测 |
| P3 | 自检回环扩到工程纪律层 | 中 | 中 | 校验节点 |
> 详细进度以 `coderio-progress-report.md` §8 为准。
# CodeRio 优化开发计划(降本 + 提质)
> 目标:在不牺牲还原度的前提下,显著降低单页模型调用次数与 token 消耗,并提升生成代码质量。
> 对应汇报文档《coderio-progress-report.md》第 7 章"下一步计划"(7.1 优化成本 / 7.2 提升代码质量)。
> 创建日期:2026-09-15
## 0. 总目标与原则
- **还原度优先于速度**(硬约束,来自汇报 §1):任何优化均不得以降低还原度为代价。
- **一切可度量**:先建基线,再量化每次优化的节省,避免"感觉变快了"。
- **优雅降级**:任何优化缺失都不得导致功能不可用——未命中时一律回退到模型生成。
## 1. 现状基线(Phase 0,必须先做)
目的:没有度量就没有优化。先固化"优化前"的数字。
- 埋点:单次生成记录各环节(读设计 / 写代码 / 自检)的模型调用次数、token、耗时。
- 埋点:库命中率、缓存命中率(初始为 0)、回退率。
- 产出**基线报告**:单页约 90–120 次调用、250k–660k token(沿用汇报估算口径,待真实数据校准)。
- 选型:缓存介质确定使用 Redis(按汇报既定)。
验收:任意一次生成结束后,可输出上述指标报表。
## 2. 组件签名与缓存(Phase 1,其他优化的地基)
**为什么先做它**:Phase 2/3/4 都依赖"如何判断两个组件是同一个"。先把"组件签名"算清楚,缓存是它最便宜的直接收益。
- 定义**组件签名**:对设计协议做归一化——保留结构(子节点树)+ 设计令牌(颜色/圆角/字号),剔除易变字段(具体文案、Figma 唯一 ID、绝对坐标)。
- 实现签名提取器:在"读设计"阶段产出,供后续复用。
- 实现**组件结果缓存**:`签名 → 生成代码`,Redis 存储;命中即跳过模型调用。
- 处理缓存失效:团队组件库/设计规范更新时,相关缓存可刷新。
验收:同一签名组件第二次生成,模型调用 0 次,直接返回缓存。
## 3. 自建组件库零调用(Phase 2,最大收益)
**机制**(与汇报 7.1、风险点一致):
- 维护一张**项目级映射规则表**(存于项目画像):`componentId → 库组件`;`特征码(结构 + 关键参数组合)→ 库组件 + props 映射`。
- 匹配引擎优先级:`componentId 精确匹配` → `特征码匹配` → `未命中回退模型生成`。
- 令牌→props 映射:颜色、尺寸等差异作为组件属性值传递,不重新生成。
- **沉淀机制**:某次生成被采纳或人工修正后,把 `签名 → 库组件` 反写回映射表,使表随使用自然增长。
- **映射表管理**:在项目画像界面提供查看 / 编辑 / 标失效的能力(对应"映射资产需持续维护"的隐性成本,必须有管理入口)。
验收:
- 命中库组件的节点,模型调用 0 次,输出真实库组件调用代码。
- 库升级后失配的组件自动回退模型生成,不影响交付。
## 4. 相似合并与协议复用(Phase 3)
- **相似组件合并**:对"同类型、同样式,仅文案/尺寸微差"的组件做聚类(结构 diff 或 embedding 相似度),只生成一次,其余用模板填充文案。
- **协议复用**:跨组件复用中间"协议",避免每个组件重复走读设计/生成链路。
验收:含 N 个相似组件的页面,模型调用次数明显低于 N 次独立生成。
## 5. 稳定部分确定性生成(Phase 4)
- 识别稳定子结构(项目骨架、通用样板、确定性布局)→ 改用确定性生成,不调模型。
- 与 Phase 2 的"库组件"互补:库组件解决"用什么组件",确定性生成解决"哪些部分根本不用 AI"。
验收:骨架/样板类代码 0 模型调用。
## 6. 代码质量提升(Phase 5,对应 7.2)
- 优化代码生成逻辑与提示词。
- 结合自检报告形成闭环修正(偏差超阈值自动改,最多三轮)。
验收:生成代码可读性、规范贴合度较基线提升(可抽样评审)。
## 7. 依赖与顺序
```
Phase 0 基线 ──▶ Phase 1 签名+缓存 ──┬─▶ Phase 2 库零调用(最大收益)
├─▶ Phase 3 相似合并+协议复用
└─▶ Phase 4 稳定部分确定性生成
Phase 5 质量提升(可与 2/3/4 并行)
```
- Phase 1 的"签名"是 2/3/4 的共同地基,必须最先稳定。
- Phase 2 收益最大,但依赖项目画像与映射表管理 UI。
- 每阶段独立可验证、可回退,不阻塞主线交付。
## 8. 落实前需确认的前提
- 设计稿是否使用 Figma 组件实例?(决定 `componentId` 命中率上限)
- 首批支持的组件库清单(AntD / ElementPlus / shadcn / MUI / Tailwind…)。
- 映射表初始由谁、以何种方式录入(人工导入 / 从设计稿实例自动抽取 / AI 辅助生成)。
## 9. 风险(与汇报一致)
- **映射资产需持续维护**:库升级/新增组件需同步维护映射表,否则失配回退模型(仍可交付,但失去降本收益)。属需纳入工程治理的隐性成本。
- **缓存键过宽会牺牲还原度**:键必须只纳结构+设计令牌,剔除易变字段。
- **命中率依赖设计规范性**:自由绘制、每页定制的项目,缓存/库命中收益有限,目标应设合理预期。
{
"name": "@coderio/ai-client",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@langchain/openai": "^1.2.4",
"@langchain/core": "^1.1.19"
}
}
import { ChatOpenAI, type ChatOpenAIFields } from '@langchain/openai';
import type { BaseMessage } from '@langchain/core/messages';
import { getBuiltinDefaultConfig, getDefaultModelConfig } from './config.js';
import type { AiModelConfig, CompleteChatOptions } from './types.js';
/**
* `ChatOpenAIFields` plus the pass-through keys this client forwards verbatim.
*
* `maxRetries` is not modelled by `@langchain/openai` v1's field type, but the
* underlying client still honours it, so it is declared here rather than
* silently dropped (the engine relies on it for its short-timeout retry).
*/
type ChatRequestConfig = ChatOpenAIFields & { maxRetries?: number };
/**
* Merge the three config layers (per-call override > caller default > built-in)
* into one concrete identity, and fail loudly when the result cannot possibly
* reach an endpoint. Nothing is read from disk or env at this point.
*/
function resolveConfig(opts: CompleteChatOptions): AiModelConfig {
const userSet = getDefaultModelConfig();
const base = userSet ?? getBuiltinDefaultConfig();
const override = opts.config;
const merged: AiModelConfig = {
modelName: override?.modelName ?? base.modelName,
apiKey: override?.apiKey ?? base.apiKey,
baseUrl: override?.baseUrl ?? base.baseUrl,
temperature: override?.temperature ?? base.temperature,
maxTokens: override?.maxTokens ?? base.maxTokens,
};
if (!merged.modelName || !merged.apiKey) {
throw new Error(
'[ai-client] resolved config is missing modelName or apiKey. Pass opts.config, call setDefaultModelConfig(...), or edit the module default-config.ts.'
);
}
return merged;
}
/**
* Normalise whatever the transport hands back into a plain string.
* Kept defensive on purpose: providers differ in whether they return a bare
* string, an array of text parts, or an array of objects with a `text` field.
*/
function extractText(content: unknown): string {
if (typeof content === 'string') return content;
if (Array.isArray(content)) {
return content
.map((part: unknown) => {
if (typeof part === 'string') return part;
if (part && typeof part === 'object' && 'text' in part) {
return String((part as { text: unknown }).text);
}
return '';
})
.join('');
}
return content == null ? '' : String(content);
}
/**
* Send a list of chat messages to an OpenAI-compatible endpoint and return the
* model's text reply.
*
* This is the only public surface with business-agnostic I/O:
* input = messages (caller builds them) + transport options
* output = model text (string)
*
* No logging, no file IO, no global config files. Any vendor extension
* (reasoning toggle, custom sampling, ...) goes through `modelKwargs` and is
* forwarded verbatim — the client never learns what it means.
*/
export async function completeChat(messages: BaseMessage[], opts: CompleteChatOptions = {}): Promise<string> {
const cfg = resolveConfig(opts);
const requestConfig: ChatRequestConfig = {
modelName: cfg.modelName,
apiKey: cfg.apiKey,
temperature: opts.temperature ?? cfg.temperature ?? 0.1,
};
if (cfg.baseUrl) {
requestConfig.configuration = { baseURL: cfg.baseUrl };
}
if (opts.maxTokens ?? cfg.maxTokens) {
requestConfig.maxTokens = opts.maxTokens ?? cfg.maxTokens;
}
if (opts.timeout !== undefined) {
requestConfig.timeout = opts.timeout;
}
if (opts.maxRetries !== undefined) {
requestConfig.maxRetries = opts.maxRetries;
}
if (opts.streaming) {
requestConfig.streaming = true;
}
const modelKwargs: Record<string, unknown> = { ...(opts.modelKwargs ?? {}) };
if (opts.responseFormat) {
modelKwargs.response_format = opts.responseFormat;
}
if (Object.keys(modelKwargs).length > 0) {
requestConfig.modelKwargs = modelKwargs;
}
const model = new ChatOpenAI(requestConfig);
const message = await model.invoke(messages);
return extractText(message.content);
}
import { DEFAULT_MODEL_CONFIG } from './default-config.js';
import type { AiModelConfig, DefaultConfigManager } from './types.js';
/**
* The caller-set default, or null when the caller never configured one.
* Deliberately process-local and in-memory: no file IO, no env reads.
*/
let userConfig: AiModelConfig | null = null;
/**
* The module's internal default config (see default-config.ts). Returned when
* no caller-set config exists, so a bare completeChat() still resolves to a
* concrete model identity instead of failing.
*/
export function getBuiltinDefaultConfig(): AiModelConfig {
return DEFAULT_MODEL_CONFIG;
}
const defaultConfigManager: DefaultConfigManager = {
setDefaultModelConfig(cfg: AiModelConfig): void {
if (!cfg || !cfg.modelName || !cfg.apiKey) {
throw new Error('[ai-client] setDefaultModelConfig requires modelName and apiKey');
}
userConfig = cfg;
},
getDefaultModelConfig(): AiModelConfig | null {
return userConfig;
},
clearDefaultModelConfig(): void {
userConfig = null;
},
};
/** Set the process-wide default model config. */
export function setDefaultModelConfig(cfg: AiModelConfig): void {
defaultConfigManager.setDefaultModelConfig(cfg);
}
/**
* Read the caller-set default model config. Returns null until a caller sets
* one via setDefaultModelConfig — when null, completeChat falls back to the
* module's internal config file (default-config.ts) rather than failing.
*/
export function getDefaultModelConfig(): AiModelConfig | null {
return defaultConfigManager.getDefaultModelConfig();
}
/** Forget the process-wide default model config. */
export function clearDefaultModelConfig(): void {
defaultConfigManager.clearDefaultModelConfig();
}
export { defaultConfigManager };
import type { AiModelConfig } from './types.js';
/**
* Internal default configuration shipped with the module.
*
* Resolution order in completeChat:
* 1. per-call opts.config (highest precedence)
* 2. caller-set default (setDefaultModelConfig)
* 3. THIS internal config file (fallback)
*
* When a caller supplies nothing at all, completeChat falls back to these
* values. To talk to a real endpoint, either edit this file or pass a config
* explicitly — credentials are NEVER read from environment variables.
*
* apiKey is intentionally empty here: a bare completeChat() against an
* unconfigured key would be meaningless, so resolveConfig throws a clear
* "missing apiKey" error instead of silently hitting an endpoint.
*/
export const DEFAULT_MODEL_CONFIG: AiModelConfig = {
modelName: 'gpt-4o',
apiKey: '',
baseUrl: undefined,
temperature: 0.1,
maxTokens: 4096,
};
export type { AiModelConfig, CompleteChatOptions, DefaultConfigManager, BaseMessage } from './types.js';
export { setDefaultModelConfig, getDefaultModelConfig, getBuiltinDefaultConfig, clearDefaultModelConfig, defaultConfigManager } from './config.js';
export { completeChat } from './client.js';
import type { BaseMessage } from '@langchain/core/messages';
/**
* The minimal model identity the client needs to talk to an OpenAI-compatible
* endpoint. No business concepts (code / Figma / scaffold) leak in here.
*/
export interface AiModelConfig {
/** Model name, e.g. "gpt-4o", "qwen3.8-max". */
modelName: string;
/** API key for the endpoint. Never read from disk — the caller supplies it. */
apiKey: string;
/** OpenAI-compatible base URL (without the "/chat/completions" suffix). */
baseUrl?: string;
/** Default sampling temperature when the call does not override it. */
temperature?: number;
/** Default max output tokens when the call does not override it. */
maxTokens?: number;
}
/**
* Per-call options. Every field is optional: anything omitted falls back to the
* default config (see {@link setDefaultModelConfig}).
*/
export interface CompleteChatOptions {
/** Override part (or all) of the default model config for this call. */
config?: Partial<AiModelConfig>;
/** Cap on generated tokens for this call. */
maxTokens?: number;
/** Sampling temperature for this call. */
temperature?: number;
/** Force JSON or plain-text output (OpenAI `response_format`). */
responseFormat?: {
type: 'json_object' | 'text';
};
/** Per-request timeout in ms, forwarded to the transport client. */
timeout?: number;
/** How many times the transport retries a failed attempt. */
maxRetries?: number;
/**
* Vendor-specific extensions forwarded verbatim into the request body
* (e.g. Qwen's `enable_thinking`, Anthropic's `thinking`). The client
* never interprets these — it only pipes them through.
*/
modelKwargs?: Record<string, unknown>;
/** Pass-through flag for callers that want streaming semantics. */
streaming?: boolean;
}
/**
* In-memory holder for the default model config. Exposed so callers can swap
* the backing store if they need to (e.g. read once from env at boot).
*/
export interface DefaultConfigManager {
setDefaultModelConfig(cfg: AiModelConfig): void;
/**
* The caller-set default, or null if none was set. When null, completeChat
* falls back to the module's built-in default (see getBuiltinDefaultConfig)
* rather than failing — so external configuration is always optional.
*/
getDefaultModelConfig(): AiModelConfig | null;
clearDefaultModelConfig(): void;
}
/** A chat message in the OpenAI-compatible shape (re-exported for convenience). */
export type { BaseMessage };
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
// Plain `tsc` emits both the ESM js and the .d.ts surface — no bundler
// needed, so this package stays buildable (and copy-pasteable) anywhere.
"declaration": true,
"declarationMap": false,
"sourceMap": false
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
......@@ -67,6 +67,7 @@
"@langchain/openai": "^1.2.3",
"@types/pixelmatch": "^5.2.6",
"axios": "^1.13.2",
"@coderio/ai-client": "workspace:*",
"better-sqlite3": "^11.10.0",
"chalk": "^5.4.1",
"commander": "^12.1.0",
......
import { HumanMessage } from '@langchain/core/messages';
import { ChatOpenAI } from '@langchain/openai';
import { completeChat, getDefaultModelConfig, setDefaultModelConfig, type CompleteChatOptions } from '@coderio/ai-client';
import { logger } from './logger';
import { getDebugConfig, getModelConfig, type ModelConfig } from './config';
import { writeFile } from './file';
......@@ -35,6 +35,32 @@ function validateModelConfig(config: ModelConfig | null | undefined): asserts co
}
/**
* Push the engine-resolved model identity into the generic AI client.
*
* `@coderio/ai-client` is deliberately business-agnostic: it never reads
* config.yaml, never touches env vars and knows nothing about the engine. The
* engine is the only layer that knows where credentials come from
* (config.yaml / runtime override injected by the backend), so it hands them
* over here — once per process, and again whenever they actually change.
*/
function syncDefaultModelConfig(config: ModelConfig): void {
const current = getDefaultModelConfig();
if (
!current ||
current.modelName !== config.model ||
current.apiKey !== config.apiKey ||
current.baseUrl !== config.baseUrl
) {
setDefaultModelConfig({
modelName: config.model,
apiKey: config.apiKey,
baseUrl: config.baseUrl,
temperature: 0.1,
});
}
}
/**
* Call an LLM model with the given options
* @param options - Configuration options for the model call
* @returns The model's text response
......@@ -84,37 +110,9 @@ export async function callModel(options: CallModelOptions): Promise<string> {
throw error;
}
try {
const requestConfig = {
modelName: config.model,
apiKey: config.apiKey,
configuration: {
baseURL: config.baseUrl,
},
...(maxTokens && { maxTokens }),
temperature: 0.1,
timeout: requestTimeoutMs,
maxRetries,
streaming,
...(streaming && {
streamingOptions: {
includeUsage: true,
},
}),
...(!streaming && { streamUsage: true }),
// Qwen3 reasoning toggle. We always forward response_format (needed
// for json_object mode) and additionally disable thinking
// (enable_thinking: false) unless COD_R_ENABLE_THINKING=1. See the
// enableThinking note above.
...((responseFormat || !enableThinking) && {
modelKwargs: {
...(responseFormat ? { response_format: responseFormat } : {}),
...(enableThinking ? {} : { enable_thinking: false }),
},
}),
};
const agentModel = new ChatOpenAI(requestConfig);
syncDefaultModelConfig(config);
try {
// Build multimodal content parts: text + image_url
const contentParts: ContentPart[] = [];
contentParts.push({ type: 'text', text: question });
......@@ -134,9 +132,32 @@ export async function callModel(options: CallModelOptions): Promise<string> {
content: contentParts.length > 1 ? contentParts : question,
});
const message = await agentModel.invoke([userMessage]);
const aiOpts: CompleteChatOptions = {
maxTokens,
timeout: requestTimeoutMs,
maxRetries,
streaming,
};
// Qwen3 reasoning toggle. We always forward response_format (needed for
// json_object mode) and additionally disable thinking
// (enable_thinking: false) unless COD_R_ENABLE_THINKING=1. See the
// enableThinking note above. The AI client pipes these through without
// interpreting them.
const modelKwargs: Record<string, unknown> = {};
if (responseFormat) {
modelKwargs.response_format = responseFormat;
}
if (!enableThinking) {
modelKwargs.enable_thinking = false;
}
if (Object.keys(modelKwargs).length > 0) {
aiOpts.modelKwargs = modelKwargs;
}
const text = await completeChat([userMessage], aiOpts);
if (!message.text) {
if (!text) {
throw new Error('Model returned empty response');
}
......@@ -145,16 +166,28 @@ export async function callModel(options: CallModelOptions): Promise<string> {
if (isDebugEnabled) {
const debugContent = [
'------------config------------',
JSON.stringify(requestConfig, null, 2),
JSON.stringify(
{
model: config.model,
baseUrl: config.baseUrl,
maxTokens,
timeout: requestTimeoutMs,
maxRetries,
responseFormat,
enableThinking,
},
null,
2
),
'------------request------------',
JSON.stringify(contentParts, null, 2),
'------------response------------',
JSON.stringify(message.text, null, 2),
JSON.stringify(text, null, 2),
].join('\n');
writeFile(workspaceManager.path?.debug ?? '', `model_${new Date().toISOString().replace(/:/g, '-')}.md`, debugContent);
}
return message.text;
return text;
} catch (error) {
if (error instanceof Error) {
logger.printErrorLog(`[${config.model}] Error details: ${error.message}`);
......
......@@ -61,16 +61,12 @@ killStalePort(CTL_PORT);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300);
// ---- 前端 Vite(常驻,UI 入口)----
// 注意:web 不在启动时立即拉起,而是等后端健康检查通过后再启动(见底部 boot 序列),
// 避免 Vite 已就绪、前端立刻发起 /api/stream(SSE) 代理时后端 4173 尚未 listen 而
// 出现 ECONNREFUSED。后端「重启」不影响 web(web 仅启动一次)。
// detached: 让子进程脱离控制台前台进程组,Ctrl+C 不会直接发给被 cmd 包裹的
// npm/vite,从而避免 Windows 弹出 "Terminate batch job (Y/N)?" 卡住。回收由
// supervisor 的 SIGINT/SIGTERM handler 统一 taskkill 完成。
const web = spawn('npm', ['--prefix', 'apps/web', 'run', 'dev'], {
cwd: ROOT,
env: { ...process.env },
shell: true,
windowsHide: true,
detached: true,
});
const pipe = (stream, label) => {
let buf = '';
stream.on('data', (d) => {
......@@ -80,11 +76,23 @@ const pipe = (stream, label) => {
for (const line of lines) out_write(tag(label) + line + '\n');
});
};
pipe(web.stdout, 'web');
pipe(web.stderr, 'web');
web.on('exit', (code, signal) =>
out_write(tag('web') + `exited (code=${code ?? 'null'}, signal=${signal ?? 'null'})\n`),
);
let web = null;
function startWeb() {
if (web && !web.killed) return web;
web = spawn('npm', ['--prefix', 'apps/web', 'run', 'dev'], {
cwd: ROOT,
env: { ...process.env },
shell: true,
windowsHide: true,
detached: true,
});
pipe(web.stdout, 'web');
pipe(web.stderr, 'web');
web.on('exit', (code, signal) =>
out_write(tag('web') + `exited (code=${code ?? 'null'}, signal=${signal ?? 'null'})\n`),
);
return web;
}
// ---- 后端(受 supervisor 管理的子进程)----
let backend = null;
......@@ -110,6 +118,35 @@ function startBackend() {
return p;
}
// 轮询后端 /api/health,直到返回 200(或超时),用于启动初期与 web 同步,
// 确保 Vite 就绪时 4173 已在监听,避免 SSE 代理 ECONNREFUSED。
function waitForBackend(timeoutMs = 30000) {
return new Promise((resolve) => {
const probe = () => {
const req = http.get(
{ host: '127.0.0.1', port: BACKEND_PORT, path: '/api/health', timeout: 1000 },
(r) => {
r.resume();
if (r.statusCode === 200) {
out_write(tag('dev') + `后端已就绪 (http://127.0.0.1:${BACKEND_PORT}/)\n`);
resolve(true);
} else {
setTimeout(probe, 400);
}
},
);
req.on('error', () => setTimeout(probe, 400));
req.on('timeout', () => {
req.destroy();
setTimeout(probe, 400);
});
};
probe();
// 超时兜底:即便后端迟迟未就绪,也照常拉起前端(SSE 会自行重连)。
setTimeout(() => resolve(false), timeoutMs);
});
}
function stopBackend() {
if (!backend) return;
const p = backend;
......@@ -132,7 +169,15 @@ function restartBackend() {
setTimeout(startBackend, 600);
}
// 信号监听:在启动序列之前注册,确保等待后端就绪期间也能优雅退出并回收子进程。
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
// ---- 启动序列:后端先起,健康检查通过后(4173 已在监听)再拉起前端 ----
// 这样 Vite 就绪时后端已可用,前端首次 /api/stream(SSE) 代理不会 ECONNREFUSED。
startBackend();
await waitForBackend();
startWeb();
out_write(`\n\u001b[32mCodeRio 开发模式已启动(supervisor 常驻):\u001b[0m\n`);
out_write(` 前端 UI : http://localhost:${WEB_PORT}/\n`);
......@@ -214,5 +259,3 @@ function shutdown() {
}
setTimeout(() => process.exit(0), 600);
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!