coding-plan-data-plane-response.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import type { UpstreamReplayFixture } from "./upstream-replay-server.js";
  2. // MCP 回放复用通用 matcher 与次数约束,fixture 同时满足回放规则的形状。
  3. export type DataPlaneTurnFixture = UpstreamReplayFixture & {
  4. match: { lastUserMessageIncludes: string[] };
  5. response: { body: string };
  6. };
  7. /** 账号数据面按最后一条 user message 回放;非流式标题旁路返回 JSON message。 */
  8. function createDataPlaneTurnResponder(
  9. fixtures: readonly DataPlaneTurnFixture[],
  10. options: { fallbackBody: string; title: { id: string; text: string } },
  11. ) {
  12. return (requestBody: string) => {
  13. const request = JSON.parse(requestBody) as {
  14. stream?: boolean;
  15. messages?: Array<{ role: string; content: unknown }>;
  16. };
  17. if (request.stream !== true)
  18. return JSON.stringify({
  19. id: options.title.id,
  20. type: "message",
  21. role: "assistant",
  22. model: "GLM-5.2",
  23. content: [{ type: "text", text: options.title.text }],
  24. stop_reason: "end_turn",
  25. usage: { input_tokens: 10, output_tokens: 4 },
  26. });
  27. const messages = request.messages ?? [];
  28. const lastUser = JSON.stringify(
  29. messages.findLast((message) => message.role === "user")?.content,
  30. );
  31. return (
  32. fixtures.find((fixture) =>
  33. fixture.match.lastUserMessageIncludes.every((marker) => lastUser?.includes(marker)),
  34. )?.response.body ?? options.fallbackBody
  35. );
  36. };
  37. }
  38. export function createCodingPlanDataPlaneResponse(
  39. fixtures: readonly DataPlaneTurnFixture[] | null,
  40. options: { fallbackBody: string; title: { id: string; text: string } },
  41. ) {
  42. // 原因:默认账号 mock 曾无条件返回 SSE,非流式标题请求无法解析;统一按请求协议响应。
  43. return {
  44. body: createDataPlaneTurnResponder(fixtures ?? [], options),
  45. headers: dataPlaneResponseHeaders,
  46. };
  47. }
  48. /** 按请求协议选择响应类型:非流式标题请求返回 JSON,模型轮次返回 SSE。 */
  49. export function dataPlaneResponseHeaders(requestBody: string): Record<string, string> {
  50. return {
  51. "content-type":
  52. JSON.parse(requestBody).stream !== true
  53. ? "application/json; charset=utf-8"
  54. : "text/event-stream; charset=utf-8",
  55. };
  56. }