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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. export interface DataPlaneTurnFixture {
  2. match: { lastUserMessageIncludes: string[] };
  3. response: { body: string };
  4. }
  5. /** 账号数据面按最后一条 user message 回放;非流式标题旁路返回 JSON message。 */
  6. function createDataPlaneTurnResponder(
  7. fixtures: readonly DataPlaneTurnFixture[],
  8. options: { fallbackBody: string; title: { id: string; text: string } },
  9. ) {
  10. return (requestBody: string) => {
  11. const request = JSON.parse(requestBody) as {
  12. stream?: boolean;
  13. messages?: Array<{ role: string; content: unknown }>;
  14. };
  15. if (request.stream !== true)
  16. return JSON.stringify({
  17. id: options.title.id,
  18. type: "message",
  19. role: "assistant",
  20. model: "GLM-5.2",
  21. content: [{ type: "text", text: options.title.text }],
  22. stop_reason: "end_turn",
  23. usage: { input_tokens: 10, output_tokens: 4 },
  24. });
  25. const messages = request.messages ?? [];
  26. const lastUser = JSON.stringify(
  27. messages.findLast((message) => message.role === "user")?.content,
  28. );
  29. return (
  30. fixtures.find((fixture) =>
  31. fixture.match.lastUserMessageIncludes.every((marker) => lastUser?.includes(marker)),
  32. )?.response.body ?? options.fallbackBody
  33. );
  34. };
  35. }
  36. export function createCodingPlanDataPlaneResponse(
  37. fixtures: readonly DataPlaneTurnFixture[] | null,
  38. options: { fallbackBody: string; title: { id: string; text: string } },
  39. ) {
  40. // 原因:默认账号 mock 曾无条件返回 SSE,非流式标题请求无法解析;统一按请求协议响应。
  41. return {
  42. body: createDataPlaneTurnResponder(fixtures ?? [], options),
  43. headers: (requestBody: string) => ({
  44. "content-type":
  45. JSON.parse(requestBody).stream !== true
  46. ? "application/json; charset=utf-8"
  47. : "text/event-stream; charset=utf-8",
  48. }),
  49. };
  50. }