protocol.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // v4/conversation/contextComposition 协议层集成(spec §4 第 3、5 类与协议验收):
  2. // 真 sqlite sessionStore + ZCodeProtocolAgentServer + 真 app。
  3. // 规格:apps/zcode-cli/docs/design/v2/model/context-composition.md。
  4. import { mkdtemp, realpath, rm } from "node:fs/promises";
  5. import { tmpdir } from "node:os";
  6. import { join } from "node:path";
  7. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  8. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  9. import { zcodeProtocolMethods, type ZCodeProtocolMessage } from "@zcode/shared";
  10. import {
  11. V4_METHODS,
  12. V4_NOTIFICATIONS,
  13. commandAckSchema,
  14. v4ConversationContextCompositionChangedSchema,
  15. v4ConversationContextCompositionResultSchema,
  16. type ContextCompositionChangedEvent,
  17. } from "@zcode/shared/zcode-protocol-v4";
  18. import type { SessionId } from "@zcode/contracts";
  19. import { ZCodeProtocolAgentServer } from "../../src/zcode-protocol/server.js";
  20. import type { ZCodeProtocolAgentServerContext } from "../../src/zcode-protocol/server-types.js";
  21. import type { ZCodeApp } from "../../src/app/types.js";
  22. import {
  23. createRegistryBackedTestApp,
  24. createTestProviderRegistry,
  25. } from "../helpers/registry-backed-test-app.js";
  26. import { answerReplyLanguageRequest } from "../helpers/fake-host-requests.js";
  27. const MODEL = { providerId: "zai", modelId: "glm-4.6", options: { reasoningLevel: "low" } };
  28. async function bootServer(root: string) {
  29. const store = await createSqliteSessionStore({ dbPath: join(root, "sessions.db") });
  30. const apps: ZCodeApp[] = [];
  31. const env = { ZCODE_DATA_BASE_DIR: join(root, "data"), HOME: root };
  32. const providerRegistry = createTestProviderRegistry([MODEL]);
  33. const notifications: ContextCompositionChangedEvent[] = [];
  34. const server = new ZCodeProtocolAgentServer({
  35. cwd: root,
  36. env,
  37. sessionStore: store,
  38. createZCodeApp: async (options = {}) => {
  39. const app = await createRegistryBackedTestApp({
  40. ...options,
  41. // 内置 MCP 子进程与本用例无关,关闭避免进程握手噪声。
  42. runtimeConfig: { ...options.runtimeConfig, mcp: { enabled: false } },
  43. env,
  44. skipUserConfig: true,
  45. providerRegistry,
  46. modelExecutor: {
  47. async generateText() {
  48. return {
  49. finishReason: "stop" as const,
  50. text: "answer",
  51. usage: { inputTokens: 4_321, outputTokens: 3, totalTokens: 4_324 },
  52. };
  53. },
  54. async *streamText() {
  55. yield { type: "text_delta" as const, text: "answer" };
  56. yield {
  57. type: "finish" as const,
  58. finishReason: "stop" as const,
  59. usage: { inputTokens: 4_321, outputTokens: 3, totalTokens: 4_324 },
  60. };
  61. },
  62. },
  63. });
  64. apps.push(app);
  65. return app;
  66. },
  67. });
  68. server.setNotificationSink((message) => {
  69. if (answerReplyLanguageRequest(server, message)) return;
  70. if (
  71. "method" in message &&
  72. message.method === V4_NOTIFICATIONS.conversationContextCompositionChanged
  73. ) {
  74. notifications.push(v4ConversationContextCompositionChangedSchema.parse(message.params));
  75. return;
  76. }
  77. if (!("id" in message)) return;
  78. if (message.method === zcodeProtocolMethods.sessionRequestRuntimePreferences) {
  79. void server.handleMessage({
  80. id: message.id,
  81. result: { nativeSearchEnhancementsEnabled: false, memoryEnabled: false },
  82. });
  83. }
  84. });
  85. const context = (server as unknown as { context: ZCodeProtocolAgentServerContext }).context;
  86. return {
  87. server,
  88. store,
  89. apps,
  90. context,
  91. notifications,
  92. close: async () => {
  93. await server.shutdown();
  94. server.disposeProjections();
  95. for (const app of apps) await app.close();
  96. store.close();
  97. },
  98. };
  99. }
  100. async function requestResult(server: ZCodeProtocolAgentServer, message: ZCodeProtocolMessage) {
  101. const response = await server.handleMessage(message);
  102. if (!response || !("result" in response)) {
  103. throw new Error(`Expected protocol success response: ${JSON.stringify(response)}`);
  104. }
  105. return response.result;
  106. }
  107. function command(id: string, type: string, payload: Record<string, unknown>) {
  108. return {
  109. id,
  110. method: V4_METHODS.command,
  111. params: {
  112. commandId: id,
  113. clientId: "client-context-composition",
  114. sessionId: null,
  115. type,
  116. payload,
  117. issuedAt: 1_700_000_000_000,
  118. },
  119. };
  120. }
  121. async function createSession(
  122. booted: Awaited<ReturnType<typeof bootServer>>,
  123. id: string,
  124. payload: Record<string, unknown>,
  125. ) {
  126. const ack = commandAckSchema.parse(
  127. await requestResult(booted.server, command(id, "createSession", payload)),
  128. );
  129. if (ack.result?.type !== "createSession") throw new Error("Expected createSession result");
  130. return ack.result.sessionId;
  131. }
  132. async function queryComposition(
  133. booted: Awaited<ReturnType<typeof bootServer>>,
  134. params: Record<string, unknown>,
  135. ) {
  136. return v4ConversationContextCompositionResultSchema.parse(
  137. await requestResult(booted.server, {
  138. id: `composition-${Math.random()}`,
  139. method: V4_METHODS.conversationContextComposition,
  140. params,
  141. }),
  142. ).composition;
  143. }
  144. const tokensOf = (
  145. composition: { categories: Array<{ id: string; tokens: number }> } | null,
  146. id: string,
  147. ) => composition?.categories.find((category) => category.id === id)?.tokens ?? 0;
  148. async function waitFor(predicate: () => Promise<boolean> | boolean, timeoutMs = 10_000) {
  149. const deadline = Date.now() + timeoutMs;
  150. while (!(await predicate())) {
  151. if (Date.now() > deadline) throw new Error("waitFor timed out");
  152. await new Promise((resolve) => setTimeout(resolve, 20));
  153. }
  154. }
  155. describe("v4 contextComposition protocol", { timeout: 30_000 }, () => {
  156. let root: string;
  157. beforeEach(async () => {
  158. root = await realpath(await mkdtemp(join(tmpdir(), "zcode-context-composition-")));
  159. });
  160. afterEach(async () => {
  161. await rm(root, { force: true, recursive: true });
  162. });
  163. it("previews a draft without promoting it and returns null for a session that is not in memory", async () => {
  164. const booted = await bootServer(root);
  165. try {
  166. const sessionId = await createSession(booted, "create-draft", { workspaceId: root });
  167. expect(booted.context.sessions.get(sessionId)?.persistence).toBe("deferred");
  168. const composition = await queryComposition(booted, { sessionId, modelSelection: MODEL });
  169. expect(composition).toMatchObject({
  170. sessionId,
  171. phase: "draft-preview",
  172. tokenMethod: "estimated",
  173. model: { providerId: MODEL.providerId, modelId: MODEL.modelId },
  174. });
  175. expect(tokensOf(composition, "system_prompt")).toBeGreaterThan(0);
  176. expect(tokensOf(composition, "system_tool_schemas")).toBeGreaterThan(0);
  177. expect(composition?.revision).toEqual(expect.any(Number));
  178. // 预演之后仍是草稿:record 未提升、runtime 未持久化、存储里没有会话行和消息。
  179. const record = booted.context.sessions.get(sessionId)!;
  180. expect(record.persistence).toBe("deferred");
  181. expect(record.app.runtime.isSessionPersisted()).toBe(false);
  182. expect(await booted.store.getSession(sessionId as SessionId)).toBeNull();
  183. expect(await booted.store.messages({ sessionID: sessionId as SessionId })).toEqual([]);
  184. expect(await queryComposition(booted, { sessionId: "sess_not_in_memory" })).toBeNull();
  185. } finally {
  186. await booted.close();
  187. }
  188. });
  189. it("returns the request composition after a turn and notifies on change", async () => {
  190. const booted = await bootServer(root);
  191. try {
  192. const sessionId = await createSession(booted, "create-with-input", {
  193. workspaceId: root,
  194. firstInput: { text: "hello", modelSelection: MODEL },
  195. });
  196. await waitFor(async () => {
  197. const messages = await booted.store.messages({ sessionID: sessionId as SessionId });
  198. return messages.some((message) => message.info.role === "assistant");
  199. });
  200. await waitFor(
  201. () => booted.context.sessions.get(sessionId)?.app.runtime.getActiveTurnInfo() === undefined,
  202. );
  203. const composition = await queryComposition(booted, { sessionId });
  204. expect(composition?.phase).toBe("request");
  205. expect(composition?.providerInputTokens).toBe(4_321);
  206. expect(composition?.providerContextTokens).toBe(4_324);
  207. expect(tokensOf(composition, "messages")).toBeGreaterThan(0);
  208. const forSession = () => booted.notifications.filter((item) => item.sessionId === sessionId);
  209. expect(forSession().length).toBeGreaterThan(0);
  210. expect(composition?.revision).toBe(forSession().at(-1)?.revision);
  211. // 换模型:tracker 发出更大的修订号,请求组成作废,查询改为预演。
  212. const before = forSession().at(-1)!.revision;
  213. await booted.context.sessions.get(sessionId)!.app.setModel(MODEL);
  214. await waitFor(() => (forSession().at(-1)?.revision ?? 0) > before);
  215. expect(forSession().at(-1)!.revision).toBe(before + 1);
  216. expect((await queryComposition(booted, { sessionId }))?.phase).toBe("draft-preview");
  217. } finally {
  218. await booted.close();
  219. }
  220. });
  221. });