protocol.test.ts 8.9 KB

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