codexCtl.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import { shell } from 'electron';
  2. import { logger } from 'ee-core/log';
  3. import { registerArtifactRoot } from '../service/codex/codexArtifactService';
  4. import { getCodexHome, getSkillsDir, isInsideDir } from '../service/codex/codexHome';
  5. import { probeCodexBinary } from '../service/codex/codexLocator';
  6. import {
  7. applyProvider as applyProviderToRuntime,
  8. baseUrlHint,
  9. clearProvider as clearRuntimeProvider,
  10. describeDroppedKeys,
  11. probeResponsesEndpoint,
  12. } from '../service/codex/providerService';
  13. import {
  14. defaultWorkspaceDir,
  15. getAppliedProvider,
  16. getCodex,
  17. setAppliedProvider,
  18. tailDiagnostics,
  19. toStatusResult,
  20. } from '../service/codex/index';
  21. import {
  22. asMessage,
  23. fail,
  24. ok,
  25. type ApprovalAnswers,
  26. type ApprovalDecision,
  27. type ApplyProviderInput,
  28. type CodexPingResult,
  29. type CodexStatusResult,
  30. type Rpc,
  31. } from '../service/codex/types';
  32. import type { ModelOption } from '../service/codex/codexRuntime';
  33. import type { McpServerInput, McpServerSetting } from '../service/codex/mcpService';
  34. import type { SkillListItem, SkillReadResult } from '../service/codex/skillService';
  35. import type { AgentEvent } from '../service/codex/types';
  36. const APPROVAL_DECISIONS: readonly ApprovalDecision[] = ['accept', 'acceptForSession', 'decline', 'cancel'];
  37. /** 统一的异常包装:ee-core 的 ipcMain.handle 不 catch,抛错会被 Electron 包成 "Error occurred in handler for ..." */
  38. async function guard<T>(label: string, run: () => Promise<T>): Promise<Rpc<T>> {
  39. try {
  40. return ok(await run());
  41. } catch (error) {
  42. const message = asMessage(error);
  43. logger.error(`[codexCtl] ${label} failed:`, message);
  44. return fail(message);
  45. }
  46. }
  47. function requireString(value: unknown, label: string): string {
  48. if (typeof value !== 'string' || !value.trim()) throw new Error(`${label} 不能为空`);
  49. return value.trim();
  50. }
  51. function toBytes(value: unknown): Uint8Array {
  52. if (value instanceof Uint8Array) return value;
  53. if (value instanceof ArrayBuffer) return new Uint8Array(value);
  54. if (Array.isArray(value)) return new Uint8Array(value as number[]);
  55. if (value && typeof value === 'object' && 'data' in value) {
  56. return toBytes((value as { data: unknown }).data);
  57. }
  58. throw new Error('文件内容必须是二进制数据');
  59. }
  60. class CodexCtl {
  61. /** 只探测二进制与 CODEX_HOME,不 spawn 子进程 */
  62. async ping(): Promise<Rpc<CodexPingResult>> {
  63. return guard('ping', async () => {
  64. // getCodex() 会顺带建好 CODEX_HOME 与 skills 目录
  65. await getCodex();
  66. const probe = await probeCodexBinary();
  67. return { ...probe, codexHome: getCodexHome() };
  68. });
  69. }
  70. async status(): Promise<Rpc<CodexStatusResult>> {
  71. return guard('status', async () => {
  72. const { runtime } = await getCodex();
  73. await getAppliedProvider();
  74. return toStatusResult(runtime.status);
  75. });
  76. }
  77. async start(): Promise<Rpc<CodexStatusResult>> {
  78. return guard('start', async () => {
  79. const { runtime } = await getCodex();
  80. await getAppliedProvider();
  81. return toStatusResult(await runtime.start());
  82. });
  83. }
  84. async stop(): Promise<Rpc<CodexStatusResult>> {
  85. return guard('stop', async () => {
  86. const { runtime } = await getCodex();
  87. await runtime.stop();
  88. return toStatusResult(runtime.status);
  89. });
  90. }
  91. async restart(): Promise<Rpc<CodexStatusResult>> {
  92. return guard('restart', async () => {
  93. const { runtime } = await getCodex();
  94. await runtime.stop();
  95. await getAppliedProvider();
  96. return toStatusResult(await runtime.start());
  97. });
  98. }
  99. async listModels(): Promise<Rpc<ModelOption[]>> {
  100. return guard('listModels', async () => {
  101. const { runtime } = await getCodex();
  102. return runtime.listModels();
  103. });
  104. }
  105. async providerCapabilities(): Promise<Rpc<unknown>> {
  106. return guard('providerCapabilities', async () => {
  107. const { runtime } = await getCodex();
  108. return runtime.readModelProviderCapabilities();
  109. });
  110. }
  111. /** 只做端点探测,不改运行时;页面在「应用」前给用户预览兼容性 */
  112. async probeProvider(params: { baseUrl?: string; apiKey?: string | null }): Promise<Rpc<unknown>> {
  113. return guard('probeProvider', async () => {
  114. const baseUrl = requireString(params?.baseUrl, 'baseUrl');
  115. const result = await probeResponsesEndpoint(baseUrl, params?.apiKey ?? null);
  116. return { ...result, hint: baseUrlHint(baseUrl) };
  117. });
  118. }
  119. /** 应用后端「模型管理」里的一条记录;会重启子进程(api key 走环境变量) */
  120. async applyProvider(params: ApplyProviderInput & { modelRecordId?: string | number | null }): Promise<Rpc<unknown>> {
  121. return guard('applyProvider', async () => {
  122. if (!params || typeof params !== 'object') throw new Error('缺少模型配置');
  123. const { runtime } = await getCodex();
  124. const applied = await applyProviderToRuntime(runtime, params);
  125. setAppliedProvider(applied);
  126. return {
  127. applied,
  128. hint: baseUrlHint(applied.baseUrl),
  129. droppedConfigKeys: describeDroppedKeys(params),
  130. status: toStatusResult(runtime.status),
  131. };
  132. });
  133. }
  134. async clearProvider(): Promise<Rpc<CodexStatusResult>> {
  135. return guard('clearProvider', async () => {
  136. const { runtime } = await getCodex();
  137. await clearRuntimeProvider(runtime);
  138. setAppliedProvider(null);
  139. return toStatusResult(runtime.status);
  140. });
  141. }
  142. async mcpList(): Promise<Rpc<McpServerSetting[]>> {
  143. return guard('mcpList', async () => (await getCodex()).mcp.list());
  144. }
  145. async mcpSave(params: McpServerInput): Promise<Rpc<McpServerSetting[]>> {
  146. return guard('mcpSave', async () => (await getCodex()).mcp.save(params));
  147. }
  148. async mcpRemove(params: { id?: string }): Promise<Rpc<McpServerSetting[]>> {
  149. return guard('mcpRemove', async () =>
  150. (await getCodex()).mcp.remove(requireString(params?.id, 'id')),
  151. );
  152. }
  153. async skillList(params?: { forceReload?: boolean }): Promise<Rpc<SkillListItem[]>> {
  154. return guard('skillList', async () =>
  155. (await getCodex()).skills.list({ forceReload: params?.forceReload === true }),
  156. );
  157. }
  158. async skillRead(params: { path?: string; name?: string }): Promise<Rpc<SkillReadResult>> {
  159. return guard('skillRead', async () => (await getCodex()).skills.read(params ?? {}));
  160. }
  161. async skillInstallFolder(params: {
  162. srcPath?: string;
  163. name?: string | null;
  164. overwrite?: boolean;
  165. }): Promise<Rpc<SkillListItem[]>> {
  166. return guard('skillInstallFolder', async () =>
  167. (await getCodex()).skills.installFromFolder(requireString(params?.srcPath, 'srcPath'), {
  168. name: params?.name ?? null,
  169. overwrite: params?.overwrite === true,
  170. }),
  171. );
  172. }
  173. async skillInstallZip(params: {
  174. data?: unknown;
  175. name?: string | null;
  176. overwrite?: boolean;
  177. }): Promise<Rpc<SkillListItem[]>> {
  178. return guard('skillInstallZip', async () =>
  179. (await getCodex()).skills.installFromZip(toBytes(params?.data), {
  180. name: params?.name ?? null,
  181. overwrite: params?.overwrite === true,
  182. }),
  183. );
  184. }
  185. async skillRemove(params: { path?: string; name?: string }): Promise<Rpc<SkillListItem[]>> {
  186. return guard('skillRemove', async () => (await getCodex()).skills.remove(params ?? {}));
  187. }
  188. async skillSetEnabled(params: {
  189. path?: string;
  190. name?: string;
  191. enabled?: boolean;
  192. }): Promise<Rpc<{ effectiveEnabled: boolean }>> {
  193. return guard('skillSetEnabled', async () => {
  194. if (typeof params?.enabled !== 'boolean') throw new Error('enabled 必须是布尔值');
  195. const effectiveEnabled = await (await getCodex()).skills.setEnabled(params, params.enabled);
  196. return { effectiveEnabled };
  197. });
  198. }
  199. /** 只允许打开用户 skills 目录或其中的某个 skill */
  200. async skillOpenFolder(params?: { path?: string }): Promise<Rpc<{ path: string }>> {
  201. return guard('skillOpenFolder', async () => {
  202. const skillsDir = getSkillsDir();
  203. const target = params?.path ? params.path : skillsDir;
  204. if (!isInsideDir(skillsDir, target) && target !== skillsDir) {
  205. throw new Error('只能打开 skills 目录内的路径');
  206. }
  207. const result = await shell.openPath(target);
  208. if (result) throw new Error(result);
  209. return { path: target };
  210. });
  211. }
  212. /** 会话默认工作目录(渲染进程也需要知道真实值,产物栏要与 cwd 对齐) */
  213. async defaultWorkspace(): Promise<Rpc<{ cwd: string }>> {
  214. return guard('defaultWorkspace', async () => ({ cwd: await defaultWorkspaceDir() }));
  215. }
  216. async threadStart(params?: {
  217. cwd?: string | null;
  218. model?: string | null;
  219. approvalPolicy?: 'untrusted' | 'on-request' | 'never';
  220. sandbox?: 'read-only' | 'workspace-write' | 'danger-full-access';
  221. }): Promise<Rpc<{ threadId: string; cwd: string }>> {
  222. return guard('threadStart', async () => {
  223. const { runtime } = await getCodex();
  224. const cwd = params?.cwd?.trim() || (await defaultWorkspaceDir());
  225. const threadId = await runtime.startThread({
  226. cwd,
  227. model: params?.model ?? null,
  228. approvalPolicy: params?.approvalPolicy ?? 'never',
  229. sandbox: params?.sandbox ?? 'workspace-write',
  230. });
  231. // 登记产物白名单:产物读写只允许发生在会话工作目录内
  232. registerArtifactRoot(cwd);
  233. return { threadId, cwd };
  234. });
  235. }
  236. /** 跑一整轮并等结果;事件流同时通过 codex/event 推给渲染进程 */
  237. async turnRun(params: {
  238. threadId?: string;
  239. input?: string;
  240. cwd?: string | null;
  241. model?: string | null;
  242. approvalPolicy?: 'untrusted' | 'on-request' | 'never';
  243. timeoutMs?: number;
  244. }): Promise<Rpc<{ turnId: string; status: string; text: string }>> {
  245. return guard('turnRun', async () => {
  246. const { runtime } = await getCodex();
  247. const threadId = requireString(params?.threadId, 'threadId');
  248. const cwd = params?.cwd?.trim() || undefined;
  249. if (cwd) registerArtifactRoot(cwd);
  250. const result = await runtime.runTurn({
  251. threadId,
  252. prompt: requireString(params?.input, 'input'),
  253. cwd,
  254. model: params?.model ?? null,
  255. approvalPolicy: params?.approvalPolicy ?? 'never',
  256. timeoutMs: typeof params?.timeoutMs === 'number' ? params.timeoutMs : undefined,
  257. });
  258. return { turnId: result.turnId, status: result.status, text: result.text };
  259. });
  260. }
  261. async turnInterrupt(params: { threadId?: string; turnId?: string }): Promise<Rpc<Record<string, never>>> {
  262. return guard('turnInterrupt', async () => {
  263. const { runtime } = await getCodex();
  264. await runtime.interruptTurn(requireString(params?.threadId, 'threadId'), requireString(params?.turnId, 'turnId'));
  265. return {};
  266. });
  267. }
  268. async threadUnsubscribe(params: { threadId?: string }): Promise<Rpc<Record<string, never>>> {
  269. return guard('threadUnsubscribe', async () => {
  270. const { runtime } = await getCodex();
  271. await runtime.unsubscribeThread(requireString(params?.threadId, 'threadId'));
  272. return {};
  273. });
  274. }
  275. async approvalResolve(params: {
  276. token?: string;
  277. decision?: ApprovalDecision;
  278. answers?: ApprovalAnswers;
  279. }): Promise<Rpc<Record<string, never>>> {
  280. return guard('approvalResolve', async () => {
  281. const { broker } = await getCodex();
  282. const token = requireString(params?.token, 'token');
  283. const decision = params?.decision;
  284. if (!decision || !APPROVAL_DECISIONS.includes(decision)) throw new Error('decision 不合法');
  285. broker.resolve(token, decision, params?.answers);
  286. return {};
  287. });
  288. }
  289. /** 读回某个 thread 已落盘的事件(页面刷新后恢复现场) */
  290. async eventsRead(params: { threadId?: string; limit?: number }): Promise<Rpc<AgentEvent[]>> {
  291. return guard('eventsRead', async () => {
  292. const { eventLog } = await getCodex();
  293. const threadId = requireString(params?.threadId, 'threadId');
  294. return eventLog.read(threadId, typeof params?.limit === 'number' ? params.limit : undefined);
  295. });
  296. }
  297. async logsTail(params?: { limit?: number }): Promise<Rpc<Array<{ ts: string; line: string }>>> {
  298. return guard('logsTail', async () =>
  299. tailDiagnostics(typeof params?.limit === 'number' ? params.limit : undefined),
  300. );
  301. }
  302. }
  303. CodexCtl.toString = () => 'CodexCtl';
  304. export default CodexCtl;