codexCtl.ts 13 KB

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