model.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import { createServer } from "node:http";
  2. import { copyFile, readFile, writeFile } from "node:fs/promises";
  3. import { join, resolve } from "node:path";
  4. import { Events } from "./agent.js";
  5. // 确定性本地模型只返回预置工具调用;授权、认领、执行、取消仍走真实 Agent。
  6. export async function startModel(root: string, cli: string) {
  7. const readiness = JSON.parse(await readFile(join(root, "session-ready-provider.json"), "utf8"))
  8. .fixtures[0];
  9. const requests = new Events<any>();
  10. const plans: {
  11. key: string;
  12. delayed: boolean;
  13. holdStream?: boolean;
  14. toolName?: string;
  15. arguments?: Record<string, unknown>;
  16. status?: number;
  17. finishReason?: string;
  18. }[] = [];
  19. const aborted = new Events<string>();
  20. const releases = new Map<string, () => void>();
  21. const server = createServer(async (req, res) => {
  22. const chunks: Buffer[] = [];
  23. for await (const chunk of req) chunks.push(chunk);
  24. const body = JSON.parse(Buffer.concat(chunks).toString());
  25. const plan = plans.shift();
  26. const tool = body.tools?.find((t: any) =>
  27. t.function?.name.endsWith(`__${plan?.toolName ?? "page_edit"}`),
  28. );
  29. if (!body.stream) {
  30. const reply = () => {
  31. releases.delete(plan?.key ?? "");
  32. if (res.destroyed) return;
  33. if (plan?.status) {
  34. res.writeHead(plan.status, { "Content-Type": "application/json" });
  35. res.end(
  36. JSON.stringify({
  37. error: {
  38. message: "fixture provider denied",
  39. type: "authentication_error",
  40. code: "invalid_api_key",
  41. },
  42. }),
  43. );
  44. return;
  45. }
  46. res.writeHead(200, { "Content-Type": "application/json" });
  47. res.end(
  48. JSON.stringify({
  49. id: "sampling-fixture",
  50. object: "chat.completion",
  51. created: 1,
  52. model: "gpt-4o",
  53. choices: [
  54. {
  55. index: 0,
  56. message: { role: "assistant", content: `answer:${plan?.key ?? "sample"}` },
  57. finish_reason: plan?.finishReason ?? "stop",
  58. },
  59. ],
  60. usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },
  61. }),
  62. );
  63. };
  64. res.on("close", () => {
  65. if (!res.writableEnded) aborted.emit(plan?.key ?? "sample");
  66. releases.delete(plan?.key ?? "");
  67. });
  68. if (plan?.delayed) releases.set(plan.key, reply);
  69. requests.emit({ body, plan, tool, url: req.url });
  70. if (!plan?.delayed) reply();
  71. return;
  72. }
  73. requests.emit({ body, plan, tool, url: req.url });
  74. if (plan?.holdStream) {
  75. res.writeHead(200, { "Content-Type": "text/event-stream" });
  76. res.write(": fixture running\n\n");
  77. releases.set(plan.key, () => res.end("data: [DONE]\n\n"));
  78. res.on("close", () => releases.delete(plan.key));
  79. return;
  80. }
  81. const delta =
  82. plan && tool
  83. ? {
  84. role: "assistant",
  85. tool_calls: [
  86. {
  87. index: 0,
  88. id: `call_${plan.key}`,
  89. type: "function",
  90. function: {
  91. name: tool.function.name,
  92. arguments: JSON.stringify(plan.arguments ?? plan),
  93. },
  94. },
  95. ],
  96. }
  97. : {
  98. role: "assistant",
  99. content: readiness.match.bodyIncludes.every((marker: string) =>
  100. JSON.stringify(body).includes(marker),
  101. )
  102. ? readiness.response.text.text
  103. : "fixture complete",
  104. };
  105. const base = {
  106. id: "fixture-completion",
  107. object: "chat.completion.chunk",
  108. created: 1,
  109. model: "gpt-4o",
  110. };
  111. res.writeHead(200, { "Content-Type": "text/event-stream" });
  112. res.write(
  113. `data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta, finish_reason: null }] })}\n\n`,
  114. );
  115. res.write(
  116. `data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: plan && tool ? "tool_calls" : "stop" }], usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } })}\n\n`,
  117. );
  118. res.end("data: [DONE]\n\n");
  119. });
  120. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  121. const port = (server.address() as { port: number }).port;
  122. const builtin = join(root, "fixture-builtin.json"),
  123. personal = join(root, "fixture-personal.json");
  124. await copyFile(resolve(cli, "../../../../../../config/provider/zcode-builtin.json"), builtin);
  125. await writeFile(
  126. personal,
  127. JSON.stringify({
  128. schemaVersion: 1,
  129. config: {
  130. providerConfigRules: {
  131. providerRules: [
  132. {
  133. providerId: "fixture-local",
  134. config: {
  135. group: "standard-personal",
  136. access: { type: "api-key", apiKey: "fixture-only" },
  137. api: { type: "openai-chat-completions", baseUrl: `http://127.0.0.1:${port}/v1` },
  138. personalModelIds: ["gpt-4o", "gpt-4o-mini"],
  139. },
  140. },
  141. ],
  142. },
  143. modelConfigRules: {
  144. providerModelRules: ["gpt-4o", "gpt-4o-mini"].map((modelId) => ({
  145. providerId: "fixture-local",
  146. modelId,
  147. config: { properties: { inputFormat: { supportsImage: true } } },
  148. })),
  149. manualProviderModelRules: [],
  150. },
  151. defaultModelSelection: {
  152. providerId: "fixture-local",
  153. modelId: "gpt-4o",
  154. options: { reasoningLevel: "disabled" },
  155. },
  156. },
  157. }),
  158. );
  159. return {
  160. requests,
  161. plans,
  162. aborted,
  163. release: (key: string) => releases.get(key)?.(),
  164. env: {
  165. ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: builtin,
  166. ZCODE_PERSONAL_PROVIDER_CONFIG_FILE: personal,
  167. },
  168. selection: {
  169. providerId: "fixture-local",
  170. modelId: "gpt-4o",
  171. options: { reasoningLevel: "disabled" },
  172. },
  173. close: () =>
  174. new Promise<void>((resolve) => {
  175. server.closeAllConnections();
  176. server.close(() => resolve());
  177. }),
  178. };
  179. }