bots-service-harness.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import { readFile } from "node:fs/promises";
  2. import type { ModelSelectionView } from "@zcode/provider";
  3. import type {
  4. BotsConfigFile,
  5. BotsStateFile,
  6. ModelSelection,
  7. ZCodeStreamEvent,
  8. } from "@zcode/shared";
  9. import { createBotsService, type IModelSelectionService } from "@zcode/services/node";
  10. import { resolveE2ERuntimePath } from "../../helpers/e2e-runtime-paths.js";
  11. const E2E_BOT_WORKSPACE = resolveE2ERuntimePath("bots", "e2e-bot-workspace");
  12. export interface RecordedRequest {
  13. url: string;
  14. method: string;
  15. body?: string;
  16. }
  17. export interface BotSyntheticFixture {
  18. caseId: string;
  19. classification: "synthetic";
  20. syntheticReason: string;
  21. timing: string;
  22. promptMarker?: string;
  23. }
  24. export async function readBotSyntheticFixture(filename: string): Promise<BotSyntheticFixture> {
  25. const url = new URL(`../../fixtures/bots/${filename}`, import.meta.url);
  26. return JSON.parse(await readFile(url, "utf8")) as BotSyntheticFixture;
  27. }
  28. export interface BotsServiceHarnessOptions {
  29. config: BotsConfigFile;
  30. state?: BotsStateFile;
  31. modelSelectionService?: Pick<IModelSelectionService, "getView">;
  32. fetch?: typeof fetch;
  33. remoteWorkspaceService?: Record<string, unknown>;
  34. runStartupBackgroundTasks?: boolean;
  35. broadcastService?: { send(message: unknown): Promise<void> };
  36. lastWorkspaceSession?: Array<
  37. Record<string, unknown> & { kind: "local" | "remote"; workspacePath: string }
  38. >;
  39. }
  40. export interface BotsServiceHarness {
  41. createTaskCalls: unknown[];
  42. readState: () => BotsStateFile;
  43. respondElicitationCalls: unknown[];
  44. sendPromptCalls: unknown[];
  45. service: ReturnType<typeof createBotsService>;
  46. subscriptions: Array<{
  47. params: Record<string, unknown>;
  48. listener: (event: ZCodeStreamEvent) => Promise<void> | void;
  49. }>;
  50. zcodeTaskService: Record<string, unknown>;
  51. }
  52. export function createBotModelSelectionView(): ModelSelectionView {
  53. const providerId = "bot-e2e-provider";
  54. const modelId = "bot-e2e-model";
  55. return {
  56. revision: 1,
  57. preferredSelection: { providerId, modelId },
  58. providers: [
  59. {
  60. providerId,
  61. providerName: "Bot E2E Provider",
  62. config: {
  63. api: {
  64. type: "anthropic-messages",
  65. baseUrl: "https://example.invalid/v1",
  66. },
  67. personalModelIds: [modelId],
  68. },
  69. models: [
  70. {
  71. modelId,
  72. config: {
  73. enabled: true,
  74. properties: {
  75. requiresMfjsToolSchema: false,
  76. contextWindow: 128_000,
  77. inputFormat: {
  78. supportsText: true,
  79. supportsImage: false,
  80. supportsVideo: false,
  81. supportsAudio: false,
  82. supportsPdf: false,
  83. },
  84. outputFormat: { supportsText: true },
  85. supportsToolCall: true,
  86. supportsJsonSchemaOutput: true,
  87. supportsNativeWebSearch: false,
  88. supportsMidConversationSystem: false,
  89. },
  90. optionSpecs: {
  91. reasoningLevel: { values: ["disabled"], map: "{}" },
  92. maxOutputTokens: {
  93. max: 8_192,
  94. map: '{"max_completion_tokens":maxOutputTokens}',
  95. },
  96. },
  97. },
  98. },
  99. ],
  100. },
  101. ],
  102. };
  103. }
  104. export function createBotsServiceHarness(options: BotsServiceHarnessOptions): BotsServiceHarness {
  105. let config = options.config;
  106. let state: BotsStateFile = options.state ?? { version: 3, bots: {} };
  107. const createTaskCalls: unknown[] = [];
  108. let taskModelSelection: ModelSelection | null = null;
  109. const sendPromptCalls: unknown[] = [];
  110. const respondElicitationCalls: unknown[] = [];
  111. const subscriptions: Array<{
  112. params: Record<string, unknown>;
  113. listener: (event: ZCodeStreamEvent) => Promise<void> | void;
  114. }> = [];
  115. const zcodeTaskService = {
  116. listTasks: async () => [],
  117. listDeletedTaskIds: async () => [],
  118. createTask: async (params: unknown) => {
  119. createTaskCalls.push(params);
  120. taskModelSelection = (params as { modelSelection?: ModelSelection }).modelSelection ?? null;
  121. return {
  122. taskId: "task-e2e-bot",
  123. title: "E2E Bot Task",
  124. workspacePath: E2E_BOT_WORKSPACE,
  125. provider: "glm",
  126. };
  127. },
  128. sendPrompt: async (params: unknown) => {
  129. sendPromptCalls.push(params);
  130. },
  131. setMode: async () => undefined,
  132. setConfigOption: async () => [],
  133. setModel: async (params: { modelSelection: ModelSelection }) => {
  134. taskModelSelection = params.modelSelection;
  135. return [];
  136. },
  137. setAutomationSessionConfig: async () => [],
  138. getTaskConfigOptions: async () => [],
  139. getTaskModelSelection: async () => taskModelSelection,
  140. getTaskSnapshot: async () => null,
  141. getTaskTokenUsage: async () => ({
  142. sessionId: "task-e2e-bot",
  143. totalTokens: 0,
  144. inputTokens: 0,
  145. outputTokens: 0,
  146. reasoningTokens: 0,
  147. cacheCreationTokens: 0,
  148. cacheReadTokens: 0,
  149. modelRequestCount: 0,
  150. modelErrorCount: 0,
  151. inputBaselineBySource: {},
  152. }),
  153. resumeTask: async () => ({
  154. taskId: "task-e2e-bot",
  155. title: "E2E Bot Task",
  156. workspacePath: E2E_BOT_WORKSPACE,
  157. provider: "glm",
  158. }),
  159. respondPermission: async () => true,
  160. respondElicitation: async (params: unknown) => {
  161. respondElicitationCalls.push(params);
  162. return true;
  163. },
  164. stopGeneration: async () => undefined,
  165. onDynamicTaskEvent:
  166. (params: Record<string, unknown>) =>
  167. (listener: (event: ZCodeStreamEvent) => Promise<void> | void) => {
  168. subscriptions.push({ params, listener });
  169. return { dispose() {} };
  170. },
  171. onDynamicStreamEvent: () => () => ({ dispose() {} }),
  172. };
  173. const service = createBotsService({
  174. credentialService: {
  175. load: async () => "app-secret-e2e",
  176. save: async () => undefined,
  177. delete: async () => undefined,
  178. },
  179. zcodeTaskService,
  180. settingService: {
  181. get: async () => ({
  182. locale: "zh-CN",
  183. recentProjects: [E2E_BOT_WORKSPACE],
  184. lastWorkspaceSession: options.lastWorkspaceSession ?? [
  185. { kind: "local", workspacePath: E2E_BOT_WORKSPACE },
  186. ],
  187. enabledBuiltinAgentCliProviders: ["glm"],
  188. }),
  189. update: async () => undefined,
  190. updateDataBaseDir: async () => undefined,
  191. ensureDefaultProject: async (path: string) => ({ path, created: false }),
  192. },
  193. repo: {
  194. readConfig: async () => config,
  195. writeConfig: async (next: BotsConfigFile) => (config = next),
  196. readState: async () => state,
  197. writeState: async (next: BotsStateFile) => (state = next),
  198. },
  199. modelSelectionService: options.modelSelectionService ?? {
  200. getView: async () => createBotModelSelectionView(),
  201. },
  202. remoteWorkspaceService: options.remoteWorkspaceService,
  203. broadcastService: options.broadcastService,
  204. runStartupBackgroundTasks: options.runStartupBackgroundTasks ?? false,
  205. warmCandidateCachesOnStartup: false,
  206. } as never);
  207. return {
  208. createTaskCalls,
  209. readState: () => structuredClone(state),
  210. respondElicitationCalls,
  211. sendPromptCalls,
  212. service,
  213. subscriptions,
  214. zcodeTaskService,
  215. };
  216. }
  217. export function createFeishuConfig(
  218. provider: "feishu" | "lark" = "feishu",
  219. id = `${provider}-e2e`,
  220. ): BotsConfigFile {
  221. return {
  222. version: 3,
  223. bots: [
  224. {
  225. id,
  226. name: `${provider} E2E`,
  227. provider,
  228. enabled: true,
  229. credentialRef: `${provider}-secret`,
  230. feishuAppId: `${provider}-app-e2e`,
  231. providerUserId: "ou_e2e_user",
  232. allowedWorkspaces: ["*"],
  233. allowedCommands: {
  234. status: true,
  235. new: true,
  236. workspace: true,
  237. model: true,
  238. thoughtLevel: true,
  239. sandboxMode: true,
  240. approvalPolicy: true,
  241. reply: true,
  242. },
  243. currentOptions: {},
  244. replyMode: "streaming_card",
  245. },
  246. ],
  247. };
  248. }
  249. export function createFeishuCallback(botId: string, text: string) {
  250. return {
  251. botId,
  252. event: {
  253. sender: { sender_id: { open_id: "ou_e2e_user" } },
  254. message: {
  255. chat_id: "oc_e2e_private",
  256. message_id: `om_${botId}_inbound`,
  257. chat_type: "p2p",
  258. message_type: "text",
  259. content: JSON.stringify({ text }),
  260. },
  261. },
  262. };
  263. }
  264. export function createRecordingFeishuFetch(requests: RecordedRequest[]): typeof fetch {
  265. return async (input, init) => {
  266. const url = String(input);
  267. const method = init?.method ?? "GET";
  268. requests.push({
  269. url,
  270. method,
  271. ...(typeof init?.body === "string" ? { body: init.body } : {}),
  272. });
  273. if (url.endsWith("/tenant_access_token/internal")) {
  274. return new Response(JSON.stringify({ code: 0, tenant_access_token: "token-e2e" }));
  275. }
  276. if (url.includes("/open-apis/im/v1/messages")) {
  277. return new Response(JSON.stringify({ code: 0, data: { message_id: "om_e2e_card" } }));
  278. }
  279. if (url.includes("/reactions") && method === "POST") {
  280. return new Response(JSON.stringify({ code: 0, data: { reaction_id: "reaction-e2e" } }));
  281. }
  282. if (url.includes("/contact/v3/users/")) {
  283. return new Response(JSON.stringify({ code: 0, data: { user: { name: "E2E User" } } }));
  284. }
  285. return new Response(JSON.stringify({ code: 0 }));
  286. };
  287. }