返回 CodeWhale
stub-server.mjs
根目录 / integrations / bridge-core / test / support / stub-server.mjs
1 import http from "node:http";
2
3 export async function startStub() {
4 const state = {
5 threads: [],
6 nextThread: 1,
7 nextTurn: 1,
8 runtimeRequests: [],
9 approvalDecisions: [],
10 replies: [],
11 inbound: { wecom: [], feishu: [], telegram: [] },
12 nextUpdateId: 1,
13 failDetailUntil: 0
14 };
15
16 function thread(id) {
17 return state.threads.find((entry) => entry.id === id) || null;
18 }
19
20 function seedThread({ id, workspace, summary, runningTurnId, systemPrompt = null, pendingApprovals = [] }) {
21 const entry = { id, workspace, systemPrompt, pendingApprovals, turns: [], events: [], prompts: [], latestSummary: summary || "", createdBy: "seed" };
22 if (summary) entry.prompts.push(summary);
23 if (runningTurnId) entry.turns.push({ id: runningTurnId, status: "in_progress" });
24 state.threads.unshift(entry);
25 return entry;
26 }
27
28 function json(res, status, body) {
29 res.writeHead(status, { "content-type": "application/json" });
30 res.end(JSON.stringify(body));
31 }
32
33 async function readBody(req) {
34 const chunks = [];
35 for await (const chunk of req) chunks.push(chunk);
36 const raw = Buffer.concat(chunks).toString("utf8");
37 return raw ? JSON.parse(raw) : null;
38 }
39
40 function runtime(req, res, url, body) {
41 const route = `${req.method} ${url.pathname}`;
42 state.runtimeRequests.push({ route, body, query: url.search });
43 if (route === "GET /health") return json(res, 200, { status: "ok" });
44 if (route === "GET /v1/runtime/info") return json(res, 200, { version: "fake", bind_host: "127.0.0.1", port: 0, auth_required: true, capabilities: {} });
45 if (route === "GET /v1/workspace/status") return json(res, 200, { workspace: "/fake", git_repo: false });
46 if (route === "POST /v1/threads") {
47 const entry = { id: `thr-${state.nextThread++}`, workspace: body?.workspace || "", systemPrompt: body?.system_prompt || null, pendingApprovals: [], turns: [], events: [], prompts: [], latestSummary: "", createdBy: "bridge" };
48 state.threads.unshift(entry);
49 return json(res, 200, { id: entry.id });
50 }
51 if (route === "GET /v1/threads/summary") {
52 const limit = Number(url.searchParams.get("limit") || 50);
53 const ids = url.searchParams.get("thread_ids");
54 const wanted = ids == null ? null : new Set(ids.split(","));
55 const rows = state.threads
56 .filter((entry) => !wanted || wanted.has(entry.id))
57 .slice(0, limit)
58 .map((entry) => ({
59 id: entry.id,
60 title: entry.latestSummary ? entry.latestSummary.slice(0, 72) : "New Thread",
61 workspace: entry.workspace,
62 latest_turn_status: entry.turns.at(-1)?.status || null
63 }));
64 return json(res, 200, rows);
65 }
66 const approval = url.pathname.match(/^\/v1\/approvals\/([^/]+)$/);
67 if (approval && req.method === "POST") {
68 state.approvalDecisions.push({ id: decodeURIComponent(approval[1]), body });
69 return json(res, 200, { ok: true });
70 }
71 const match = url.pathname.match(/^\/v1\/threads\/([^/]+)(?:\/(.*))?$/);
72 if (!match) return json(res, 404, { message: "no route" });
73 const entry = thread(decodeURIComponent(match[1]));
74 if (!entry) return json(res, 404, { message: "thread not found" });
75 const rest = match[2] || "";
76 if (req.method === "GET" && rest === "" && Date.now() < state.failDetailUntil) return json(res, 503, { message: "runtime starting" });
77 if (req.method === "GET" && rest === "") {
78 return json(res, 200, { id: entry.id, thread: { id: entry.id, workspace: entry.workspace, system_prompt: entry.systemPrompt }, latest_seq: entry.events.length, turns: entry.turns, pending_approvals: entry.pendingApprovals });
79 }
80 if (req.method === "POST" && rest === "turns") {
81 const turn = { id: `turn-${state.nextTurn++}`, thread_id: entry.id, status: "completed" };
82 const history = entry.prompts.join(" | ");
83 entry.prompts.push(body.prompt);
84 entry.latestSummary = body.input_summary || body.prompt;
85 entry.turns.push(turn);
86 const base = entry.events.length;
87 entry.events.push({ seq: base + 1, thread_id: entry.id, turn_id: turn.id, event: "item.delta", payload: { kind: "agent_message", delta: `STUB-MODEL thread=${entry.id} earlier-inputs=[${history}]` } });
88 entry.events.push({ seq: base + 2, thread_id: entry.id, turn_id: turn.id, event: "turn.completed", payload: { turn: { status: "completed" } } });
89 return json(res, 200, { turn });
90 }
91 if (req.method === "GET" && rest === "events") {
92 const since = Number(url.searchParams.get("since_seq") || 0);
93 res.writeHead(200, { "content-type": "text/event-stream" });
94 for (const record of entry.events.filter((event) => event.seq > since)) {
95 res.write(`data: ${JSON.stringify(record)}\n\n`);
96 }
97 res.end(`data: ${JSON.stringify({ thread_id: entry.id, event: "stream.end" })}\n\n`);
98 return;
99 }
100 if (req.method === "POST" && /^turns\/[^/]+\/(steer|interrupt)$/.test(rest)) return json(res, 200, { ok: true });
101 if (req.method === "POST" && rest === "compact") return json(res, 200, { turn: { id: "turn-compact" } });
102 return json(res, 404, { message: "no route" });
103 }
104
105 function telegram(req, res, method, body) {
106 if (method === "getUpdates") {
107 const offset = Number(body?.offset || 0);
108 const deliver = () => json(res, 200, { ok: true, result: state.inbound.telegram.filter((update) => update.update_id >= offset) });
109 if (state.inbound.telegram.some((update) => update.update_id >= offset)) return deliver();
110 setTimeout(deliver, 150);
111 return;
112 }
113 if (method === "sendMessage") {
114 state.replies.push({ platform: "telegram", to: String(body.chat_id), text: String(body.text).replace(/\\(.)/g, "$1") });
115 return json(res, 200, { ok: true, result: { message_id: Date.now() } });
116 }
117 return json(res, 200, { ok: true, result: true });
118 }
119
120 const server = http.createServer(async (req, res) => {
121 try {
122 const url = new URL(req.url, "http://127.0.0.1");
123 const body = req.method === "POST" ? await readBody(req) : null;
124 if (url.pathname.startsWith("/tg/")) {
125 return telegram(req, res, url.pathname.split("/").at(-1), body);
126 }
127 if (url.pathname === "/fake/next") {
128 const queue = state.inbound[url.searchParams.get("platform")] || [];
129 return json(res, 200, queue.splice(0, queue.length));
130 }
131 if (url.pathname === "/fake/reply") {
132 state.replies.push(body);
133 return json(res, 200, { ok: true });
134 }
135 return runtime(req, res, url, body);
136 } catch {
137 json(res, 500, { message: "stub server error" });
138 }
139 });
140 await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
141 const url = `http://127.0.0.1:${server.address().port}`;
142
143 return {
144 url,
145 state,
146 seedThread,
147 thread,
148 pushWecom(userId, text) {
149 state.inbound.wecom.push({ body: { chattype: "single", from: { userid: userId }, msgid: `m-${Math.random()}`, msgtype: "text", text: { content: text } } });
150 },
151 pushFeishu(openId, chatId, text) {
152 state.inbound.feishu.push({
153 sender: { sender_id: { open_id: openId } },
154 message: { chat_id: chatId, message_id: `m-${Math.random()}`, chat_type: "p2p", message_type: "text", content: JSON.stringify({ text }) }
155 });
156 },
157 pushTelegram(userId, text) {
158 const update_id = state.nextUpdateId++;
159 state.inbound.telegram.push({ update_id, message: { message_id: update_id, chat: { id: userId, type: "private" }, from: { id: userId, is_bot: false }, text } });
160 },
161 close: () => new Promise((resolve) => { server.closeAllConnections?.(); server.close(resolve); })
162 };
163 }
164
164 lines Plain Text