session-features-site-deploy.test.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { createServer, request as httpRequest, type Server } from "node:http";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  7. import {
  8. ZCODE_OFFICIAL_ENDPOINT_ENV_KEY,
  9. ZCODE_OFFICIAL_ENDPOINT_TOKEN_ENV_KEY,
  10. } from "@zcode/shared";
  11. import {
  12. SESSION_ENTRY_SESSION_FEATURES,
  13. getCurrentModelInvocationContext,
  14. type ExecutionPort,
  15. type ExecutionRequest,
  16. type ExecutionResult,
  17. type ModelRequestSessionFeature,
  18. } from "@zcode/contracts";
  19. import { createOfficialCommandEndpoint } from "../src/official-command-endpoint/index.js";
  20. import { createRegistryBackedTestApp as createZCodeApp } from "./helpers/registry-backed-test-app.js";
  21. // docs/design/v2/model/session-features-header.md「Sites 部署标签的补充规则」的装配层:
  22. // 真实的官方命令端点 + 假 zcode-server。假执行端口在收到部署命令时,像 zcode-site CLI 一样用请求 env
  23. // 里的端点地址和 token 发 POST,验证 create-app 把端点回调接到会话的 site_deploy 标签。
  24. const DEPLOY_COMMAND = "zcode-site deploy ./stage";
  25. const USAGE = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  26. const cleanups: Array<() => Promise<void>> = [];
  27. afterEach(async () => {
  28. while (cleanups.length > 0) await cleanups.pop()!();
  29. });
  30. async function startZCodeServer(status: number): Promise<string> {
  31. const server: Server = createServer((req, res) => {
  32. req.resume();
  33. req.on("end", () => {
  34. res.writeHead(status, { "content-type": "application/json" });
  35. res.end(JSON.stringify({ code: status === 200 ? 0 : 3610, msg: "", data: { id: "d-1" } }));
  36. });
  37. });
  38. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  39. cleanups.push(() => new Promise((resolve) => server.close(() => resolve())));
  40. return `http://127.0.0.1:${(server.address() as { port: number }).port}`;
  41. }
  42. function postDeployment(env: Record<string, string>): Promise<number> {
  43. return new Promise((resolve, reject) => {
  44. const req = httpRequest(
  45. {
  46. socketPath: env[ZCODE_OFFICIAL_ENDPOINT_ENV_KEY],
  47. path: "/api/v1/sites/s-1/deployments",
  48. method: "POST",
  49. headers: {
  50. Authorization: `Bearer ${env[ZCODE_OFFICIAL_ENDPOINT_TOKEN_ENV_KEY]}`,
  51. "Content-Type": "application/json",
  52. "Content-Length": "2",
  53. },
  54. },
  55. (res) => {
  56. res.resume();
  57. res.on("end", () => resolve(res.statusCode ?? 0));
  58. },
  59. );
  60. req.on("error", reject);
  61. req.end("{}");
  62. });
  63. }
  64. function completed(): ExecutionResult {
  65. const now = new Date();
  66. return {
  67. cancelled: false,
  68. completedAt: now,
  69. durationMs: 1,
  70. exitCode: 0,
  71. startedAt: now,
  72. status: "completed",
  73. stderr: { bytes: 0, text: "", truncated: false },
  74. stdout: { bytes: 2, text: "ok", truncated: false },
  75. timedOut: false,
  76. };
  77. }
  78. async function runScenario(upstreamStatus: number) {
  79. const root = await mkdtemp(join(tmpdir(), "zcode-site-deploy-feature-"));
  80. cleanups.push(() => rm(root, { force: true, recursive: true }));
  81. const sessionStore = await createSqliteSessionStore({ dbPath: ":memory:" });
  82. cleanups.push(async () => sessionStore.close());
  83. const origin = await startZCodeServer(upstreamStatus);
  84. const endpoint = createOfficialCommandEndpoint({
  85. fetch: globalThis.fetch,
  86. resolveHeaders: async () => ({ ok: true, headers: { Authorization: "Bearer jwt" } }),
  87. resolveZCodeApiOrigin: () => origin,
  88. });
  89. cleanups.push(() => endpoint.close());
  90. const deployStatuses: number[] = [];
  91. const executionPort: ExecutionPort = {
  92. async run(request: ExecutionRequest) {
  93. if (JSON.stringify(request.command).includes(DEPLOY_COMMAND)) {
  94. deployStatuses.push(await postDeployment(request.env?.set ?? {}));
  95. }
  96. return completed();
  97. },
  98. };
  99. const seen: Array<readonly ModelRequestSessionFeature[] | undefined> = [];
  100. const app = await createZCodeApp({
  101. env: {},
  102. executionPort,
  103. officialCommandEnv: (sessionId, workspace, observer) =>
  104. endpoint.envForSession(sessionId, workspace, observer),
  105. modelExecutor: {
  106. async generateText() {
  107. seen.push(getCurrentModelInvocationContext()?.modelRequestSessionFeatures);
  108. if (seen.length === 1)
  109. return {
  110. finishReason: "tool-calls",
  111. text: "",
  112. usage: USAGE,
  113. toolCalls: [{ id: "deploy", name: "Bash", input: { command: DEPLOY_COMMAND } }],
  114. } as never;
  115. return { finishReason: "stop", text: "done", usage: USAGE } as never;
  116. },
  117. },
  118. runtimeConfig: {
  119. workingDirectory: root,
  120. mode: "yolo",
  121. bashShellSelection: { dialect: "posix", source: "auto-detected", display: { name: "bash" } },
  122. },
  123. sessionStore,
  124. skipUserConfig: true,
  125. });
  126. cleanups.push(() => app.close());
  127. await app.submitPrompt("deploy the site");
  128. await app.submitPrompt("thanks");
  129. const entries = await sessionStore.sessionEntries?.({
  130. sessionID: app.sessionId as never,
  131. type: SESSION_ENTRY_SESSION_FEATURES,
  132. });
  133. return { deployStatuses, seen, entries: (entries ?? []).map((entry) => entry.data) };
  134. }
  135. describe("官方命令端点收到创建部署时打 site_deploy", () => {
  136. it("不看结果:部署请求被上游拒绝(409),之后的请求同样带上 site_deploy,并写入 entry", async () => {
  137. const result = await runScenario(409);
  138. expect(result.deployStatuses).toEqual([409]);
  139. expect(result.seen).toEqual([undefined, ["site_deploy"], ["site_deploy"]]);
  140. expect(result.entries).toEqual([{ features: ["site_deploy"] }]);
  141. });
  142. });