Files
curriculum-project-hub/hub/src/server.ts
T
hongjr03 a4d52e1850 feat(hub): workspace 文件工具 + cph 子进程工具(hub↔courseware 耦合点)
agent 的窄工具面补全:
- workspace.ts: read_file/write_file/list_files,路径全 confinement 到
  ctx.workspaceDir(ADR-0007 目录树);.. 与绝对路径逃逸返 error JSON 不中断 run
- cph.ts: cph_check/cph_build 子进程,cwd=workspace;ADR-0016 版本契约由 cph
  自身在 load 阶段校验(cphVersionMismatch),Hub 透传诊断不重复校验;
  CPH_BIN 可配,缺二进制返 exitCode 127 不抛
- server.ts: 注册全部 5 个工具
修 dynamic import(rule: ts-no-dynamic-import)——mkdir 改顶部静态 import;
三个 handler 的 confine 包进 try(操作性错误返 JSON 而非冒泡中断 run)。
tsc rc=0;smoke 通过(逃逸拒绝/读写回环/列举/cph ENOENT)。
2026-07-06 23:19:28 +08:00

97 lines
3.5 KiB
TypeScript

/**
* Hub entry — Fastify server + Feishu WebSocket listener.
*
* Wires the full trigger path: lark ws receives `im.message.receive_v1` →
* trigger handler resolves chat→project (ADR-0001), creates AgentRun + acquires
* the project lock (ADR-0002), runs the provider-agnostic agent loop
* (ADR-0017), and releases the lock on finish. Feishu context reads inside the
* loop are ADR-0003-authorized (chat must match binding).
*
* Env (see .env.example):
* DATABASE_URL, OPENROUTER_API_KEY, FEISHU_APP_ID/SECRET/BOT_OPEN_ID, PORT
*/
import "dotenv/config";
import Fastify from "fastify";
import { prisma } from "./db.js";
import { OpenRouterProvider } from "./agent/openrouter-provider.js";
import { InMemoryModelRegistry } from "./agent/models.js";
import { ToolRegistry, feishuContextTool } from "./agent/tools.js";
import { readFileTool, writeFileTool, listFilesTool } from "./agent/workspace.js";
import { cphCheckTool, cphBuildTool } from "./agent/cph.js";
import { startFeishuListener } from "./feishu/client.js";
import { makeTriggerHandler } from "./feishu/trigger.js";
function requireEnv(name: string): string {
const v = process.env[name];
if (v === undefined || v === "") {
console.error(`[hub] missing required env: ${name}`);
process.exit(1);
}
return v;
}
async function main(): Promise<void> {
const databaseUrl = requireEnv("DATABASE_URL");
void databaseUrl; // prisma reads DATABASE_URL from env directly
const openrouterKey = requireEnv("OPENROUTER_API_KEY");
const feishuAppId = requireEnv("FEISHU_APP_ID");
const feishuAppSecret = requireEnv("FEISHU_APP_SECRET");
const feishuBotOpenId = requireEnv("FEISHU_BOT_OPEN_ID");
const port = Number(process.env["PORT"] ?? "8788");
const app = Fastify({ logger: true });
app.get("/api/healthz", async () => ({ ok: true, ts: Date.now() }));
// --- Agent seam wiring ---
const provider = new OpenRouterProvider({ apiKey: openrouterKey });
const models = new InMemoryModelRegistry(
[
{ id: "z-ai/glm-4.6", label: "GLM-4.6", toolCapable: true },
{ id: "anthropic/claude-3.5-sonnet", label: "Claude 3.5 Sonnet", toolCapable: true },
],
[
{ id: "draft", label: "草稿", defaultModel: "z-ai/glm-4.6" },
{ id: "review", label: "审校", defaultModel: "anthropic/claude-3.5-sonnet" },
],
);
const tools = new ToolRegistry();
tools.register(
// ADR-0003: the handler enforces chat==boundChat before any Feishu API call.
// Real impl wraps @larksuiteoapi/node-sdk's im.message.list/read APIs.
feishuContextTool(async (args, ctx) => {
return JSON.stringify({ stub: true, anchor: args.anchor, id: args.id, projectId: ctx.projectId });
}),
);
// Workspace file tools (ADR-0007 directory tree, path-confined).
tools.register(readFileTool());
tools.register(writeFileTool());
tools.register(listFilesTool());
// cph CLI tools (ADR-0016 version contract enforced by cph itself).
tools.register(cphCheckTool());
tools.register(cphBuildTool());
// --- Feishu listener ---
const trigger = makeTriggerHandler({ prisma, provider, tools, models, logger: app.log });
const feishuCtx = startFeishuListener(
{ appId: feishuAppId, appSecret: feishuAppSecret, botOpenId: feishuBotOpenId },
app.log,
trigger,
);
void feishuCtx;
app.listen({ port, host: "0.0.0.0" }, (err, address) => {
if (err !== null) {
app.log.error({ err }, "listen failed");
process.exit(1);
}
app.log.info({ address }, "hub listening");
});
}
main().catch((e) => {
console.error("[hub] fatal:", e);
process.exit(1);
});