codexCtl.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. probeEndpoint,
  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: {
  113. baseUrl?: string;
  114. apiKey?: string | null;
  115. modelId?: string | null;
  116. providerType?: string | null;
  117. }): Promise<Rpc<unknown>> {
  118. return guard('probeProvider', async () => {
  119. const baseUrl = requireString(params?.baseUrl, 'baseUrl');
  120. const result = await probeEndpoint({
  121. baseUrl,
  122. modelId: params?.modelId ?? null,
  123. apiKey: params?.apiKey ?? null,
  124. providerType: params?.providerType ?? null,
  125. });
  126. return { ...result, hint: baseUrlHint(baseUrl) };
  127. });
  128. }
  129. /** 应用后端「模型管理」里的一条记录;会重启子进程(api key 走环境变量) */
  130. async applyProvider(params: ApplyProviderInput & { modelRecordId?: string | number | null }): Promise<Rpc<unknown>> {
  131. return guard('applyProvider', async () => {
  132. if (!params || typeof params !== 'object') throw new Error('缺少模型配置');
  133. const { runtime } = await getCodex();
  134. const applied = await applyProviderToRuntime(runtime, params);
  135. setAppliedProvider(applied);
  136. return {
  137. applied,
  138. hint: baseUrlHint(applied.baseUrl),
  139. droppedConfigKeys: describeDroppedKeys(params),
  140. status: toStatusResult(runtime.status),
  141. };
  142. });
  143. }
  144. async clearProvider(): Promise<Rpc<CodexStatusResult>> {
  145. return guard('clearProvider', async () => {
  146. const { runtime } = await getCodex();
  147. await clearRuntimeProvider(runtime);
  148. setAppliedProvider(null);
  149. return toStatusResult(runtime.status);
  150. });
  151. }
  152. async mcpList(): Promise<Rpc<McpServerSetting[]>> {
  153. return guard('mcpList', async () => (await getCodex()).mcp.list());
  154. }
  155. async mcpSave(params: McpServerInput): Promise<Rpc<McpServerSetting[]>> {
  156. return guard('mcpSave', async () => (await getCodex()).mcp.save(params));
  157. }
  158. async mcpRemove(params: { id?: string }): Promise<Rpc<McpServerSetting[]>> {
  159. return guard('mcpRemove', async () =>
  160. (await getCodex()).mcp.remove(requireString(params?.id, 'id')),
  161. );
  162. }
  163. async skillList(params?: { forceReload?: boolean }): Promise<Rpc<SkillListItem[]>> {
  164. return guard('skillList', async () =>
  165. (await getCodex()).skills.list({ forceReload: params?.forceReload === true }),
  166. );
  167. }
  168. async skillRead(params: { path?: string; name?: string }): Promise<Rpc<SkillReadResult>> {
  169. return guard('skillRead', async () => (await getCodex()).skills.read(params ?? {}));
  170. }
  171. async skillInstallFolder(params: {
  172. srcPath?: string;
  173. name?: string | null;
  174. overwrite?: boolean;
  175. }): Promise<Rpc<SkillListItem[]>> {
  176. return guard('skillInstallFolder', async () =>
  177. (await getCodex()).skills.installFromFolder(requireString(params?.srcPath, 'srcPath'), {
  178. name: params?.name ?? null,
  179. overwrite: params?.overwrite === true,
  180. }),
  181. );
  182. }
  183. async skillInstallZip(params: {
  184. data?: unknown;
  185. name?: string | null;
  186. overwrite?: boolean;
  187. }): Promise<Rpc<SkillListItem[]>> {
  188. return guard('skillInstallZip', async () =>
  189. (await getCodex()).skills.installFromZip(toBytes(params?.data), {
  190. name: params?.name ?? null,
  191. overwrite: params?.overwrite === true,
  192. }),
  193. );
  194. }
  195. async skillRemove(params: { path?: string; name?: string }): Promise<Rpc<SkillListItem[]>> {
  196. return guard('skillRemove', async () => (await getCodex()).skills.remove(params ?? {}));
  197. }
  198. async skillSetEnabled(params: {
  199. path?: string;
  200. name?: string;
  201. enabled?: boolean;
  202. }): Promise<Rpc<{ effectiveEnabled: boolean }>> {
  203. return guard('skillSetEnabled', async () => {
  204. if (typeof params?.enabled !== 'boolean') throw new Error('enabled 必须是布尔值');
  205. const effectiveEnabled = await (await getCodex()).skills.setEnabled(params, params.enabled);
  206. return { effectiveEnabled };
  207. });
  208. }
  209. /** 只允许打开用户 skills 目录或其中的某个 skill */
  210. async skillOpenFolder(params?: { path?: string }): Promise<Rpc<{ path: string }>> {
  211. return guard('skillOpenFolder', async () => {
  212. const skillsDir = getSkillsDir();
  213. const target = params?.path ? params.path : skillsDir;
  214. if (!isInsideDir(skillsDir, target) && target !== skillsDir) {
  215. throw new Error('只能打开 skills 目录内的路径');
  216. }
  217. const result = await shell.openPath(target);
  218. if (result) throw new Error(result);
  219. return { path: target };
  220. });
  221. }
  222. /** 会话默认工作目录(渲染进程也需要知道真实值,产物栏要与 cwd 对齐) */
  223. async defaultWorkspace(): Promise<Rpc<{ cwd: string }>> {
  224. return guard('defaultWorkspace', async () => ({ cwd: await defaultWorkspaceDir() }));
  225. }
  226. async threadStart(params?: {
  227. cwd?: string | null;
  228. model?: string | null;
  229. approvalPolicy?: 'untrusted' | 'on-request' | 'never';
  230. sandbox?: 'read-only' | 'workspace-write' | 'danger-full-access';
  231. }): Promise<Rpc<{ threadId: string; cwd: string }>> {
  232. return guard('threadStart', async () => {
  233. const { runtime } = await getCodex();
  234. const cwd = params?.cwd?.trim() || (await defaultWorkspaceDir());
  235. const threadId = await runtime.startThread({
  236. cwd,
  237. model: params?.model ?? null,
  238. approvalPolicy: params?.approvalPolicy ?? 'never',
  239. sandbox: params?.sandbox ?? 'workspace-write',
  240. });
  241. // 登记产物白名单:产物读写只允许发生在会话工作目录内
  242. registerArtifactRoot(cwd);
  243. return { threadId, cwd };
  244. });
  245. }
  246. /** 跑一整轮并等结果;事件流同时通过 codex/event 推给渲染进程 */
  247. async turnRun(params: {
  248. threadId?: string;
  249. input?: string;
  250. cwd?: string | null;
  251. model?: string | null;
  252. approvalPolicy?: 'untrusted' | 'on-request' | 'never';
  253. timeoutMs?: number;
  254. }): Promise<Rpc<{ turnId: string; status: string; text: string }>> {
  255. return guard('turnRun', async () => {
  256. const { runtime } = await getCodex();
  257. const threadId = requireString(params?.threadId, 'threadId');
  258. const cwd = params?.cwd?.trim() || undefined;
  259. if (cwd) registerArtifactRoot(cwd);
  260. const result = await runtime.runTurn({
  261. threadId,
  262. prompt: requireString(params?.input, 'input'),
  263. cwd,
  264. model: params?.model ?? null,
  265. approvalPolicy: params?.approvalPolicy ?? 'never',
  266. timeoutMs: typeof params?.timeoutMs === 'number' ? params.timeoutMs : undefined,
  267. });
  268. return { turnId: result.turnId, status: result.status, text: result.text };
  269. });
  270. }
  271. async turnInterrupt(params: { threadId?: string; turnId?: string }): Promise<Rpc<Record<string, never>>> {
  272. return guard('turnInterrupt', async () => {
  273. const { runtime } = await getCodex();
  274. await runtime.interruptTurn(requireString(params?.threadId, 'threadId'), requireString(params?.turnId, 'turnId'));
  275. return {};
  276. });
  277. }
  278. async threadUnsubscribe(params: { threadId?: string }): Promise<Rpc<Record<string, never>>> {
  279. return guard('threadUnsubscribe', async () => {
  280. const { runtime } = await getCodex();
  281. await runtime.unsubscribeThread(requireString(params?.threadId, 'threadId'));
  282. return {};
  283. });
  284. }
  285. async approvalResolve(params: {
  286. token?: string;
  287. decision?: ApprovalDecision;
  288. answers?: ApprovalAnswers;
  289. }): Promise<Rpc<Record<string, never>>> {
  290. return guard('approvalResolve', async () => {
  291. const { broker } = await getCodex();
  292. const token = requireString(params?.token, 'token');
  293. const decision = params?.decision;
  294. if (!decision || !APPROVAL_DECISIONS.includes(decision)) throw new Error('decision 不合法');
  295. broker.resolve(token, decision, params?.answers);
  296. return {};
  297. });
  298. }
  299. /** 读回某个 thread 已落盘的事件(页面刷新后恢复现场) */
  300. async eventsRead(params: { threadId?: string; limit?: number }): Promise<Rpc<AgentEvent[]>> {
  301. return guard('eventsRead', async () => {
  302. const { eventLog } = await getCodex();
  303. const threadId = requireString(params?.threadId, 'threadId');
  304. return eventLog.read(threadId, typeof params?.limit === 'number' ? params.limit : undefined);
  305. });
  306. }
  307. async logsTail(params?: { limit?: number }): Promise<Rpc<Array<{ ts: string; line: string }>>> {
  308. return guard('logsTail', async () =>
  309. tailDiagnostics(typeof params?.limit === 'number' ? params.limit : undefined),
  310. );
  311. }
  312. }
  313. CodexCtl.toString = () => 'CodexCtl';
  314. export default CodexCtl;