index.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import { join } from 'node:path';
  2. import { mkdir } from 'node:fs/promises';
  3. import { getMainWindow } from 'ee-core/electron';
  4. import { logger } from 'ee-core/log';
  5. import { ApprovalBroker } from './approvalBroker';
  6. import { ensureCodexHome, getCodexDataDir, getCodexHome, getEventsDir } from './codexHome';
  7. import { CodexRuntime, type RuntimeStatus } from './codexRuntime';
  8. import { EventLog } from './eventLog';
  9. import { notificationToEvent } from './eventMapper';
  10. import { McpService } from './mcpService';
  11. import { readAppliedProvider } from './providerService';
  12. import { SkillService } from './skillService';
  13. import {
  14. asMessage,
  15. CODEX_APPROVAL_CHANNEL,
  16. CODEX_APPROVAL_CLOSED_CHANNEL,
  17. CODEX_DIAGNOSTIC_CHANNEL,
  18. CODEX_EVENT_CHANNEL,
  19. CODEX_STATUS_CHANNEL,
  20. type AppliedProviderInfo,
  21. type CodexStatusResult,
  22. } from './types';
  23. import type { JsonRpcServerRequest } from './jsonRpcPeer';
  24. /**
  25. * Codex 能力的装配层:懒启动单例、事件转发到渲染进程、诊断环形缓冲。
  26. * 刻意不在启动时自动带上 provider —— apiKey 只能由渲染进程从后端取到后传入,
  27. * 所以重启后需要页面重新「应用模型」,未应用时 MCP/Skill 管理照样可用。
  28. */
  29. const MAX_DIAGNOSTICS = 500;
  30. export interface CodexContainer {
  31. runtime: CodexRuntime;
  32. broker: ApprovalBroker;
  33. eventLog: EventLog;
  34. mcp: McpService;
  35. skills: SkillService;
  36. }
  37. let container: CodexContainer | null = null;
  38. let creating: Promise<CodexContainer> | null = null;
  39. let appliedCache: AppliedProviderInfo | null = null;
  40. let appliedLoaded = false;
  41. const diagnostics: Array<{ ts: string; line: string }> = [];
  42. function send(channel: string, payload: unknown): void {
  43. try {
  44. const win = getMainWindow();
  45. if (win && !win.isDestroyed()) win.webContents.send(channel, payload);
  46. } catch {
  47. // 窗口尚未就绪或已销毁:丢事件,不影响主流程
  48. }
  49. }
  50. function pushDiagnostic(line: string): void {
  51. const entry = { ts: new Date().toISOString(), line };
  52. diagnostics.push(entry);
  53. if (diagnostics.length > MAX_DIAGNOSTICS) {
  54. diagnostics.splice(0, diagnostics.length - MAX_DIAGNOSTICS);
  55. }
  56. // 环形缓冲只在内存里,进程一崩就没了:同步落 ee.log,否则启动失败无从复盘
  57. logger.warn(`[codex] ${line}`);
  58. send(CODEX_DIAGNOSTIC_CHANNEL, entry);
  59. }
  60. export async function getCodex(): Promise<CodexContainer> {
  61. if (container) return container;
  62. if (creating) return creating;
  63. creating = (async () => {
  64. await ensureCodexHome();
  65. const runtime = new CodexRuntime({ codexHome: getCodexHome() });
  66. const broker = new ApprovalBroker(runtime);
  67. const eventLog = new EventLog(getEventsDir());
  68. await eventLog.init();
  69. runtime.on('notification', (notification: { method: string; params?: unknown }) => {
  70. if (notification.method === 'serverRequest/resolved') {
  71. const requestId = (notification.params as { requestId?: string | number } | undefined)?.requestId;
  72. if (requestId !== undefined) broker.resolveFromServer(requestId);
  73. }
  74. const event = notificationToEvent(notification);
  75. if (!event) return;
  76. send(CODEX_EVENT_CHANNEL, event);
  77. eventLog.append(event).catch((error: unknown) => {
  78. logger.error('[codex] 事件落盘失败:', asMessage(error));
  79. });
  80. });
  81. runtime.on('status', (status: RuntimeStatus) => send(CODEX_STATUS_CHANNEL, toStatusResult(status)));
  82. runtime.on('diagnostic', (line: string) => pushDiagnostic(line));
  83. runtime.on('serverRequest', (request: JsonRpcServerRequest) => broker.handle(request));
  84. broker.on('approval', (approval: unknown) => send(CODEX_APPROVAL_CHANNEL, approval));
  85. broker.on('closed', (token: string) => send(CODEX_APPROVAL_CLOSED_CHANNEL, { token }));
  86. broker.on('expired', (approval: unknown) => {
  87. pushDiagnostic(`审批超时已自动拒绝:${JSON.stringify(approval)}`);
  88. });
  89. broker.on('diagnostic', (line: string) => pushDiagnostic(line));
  90. container = {
  91. runtime,
  92. broker,
  93. eventLog,
  94. mcp: new McpService(runtime),
  95. skills: new SkillService(runtime, { onDiagnostic: pushDiagnostic }),
  96. };
  97. return container;
  98. })();
  99. try {
  100. return await creating;
  101. } finally {
  102. creating = null;
  103. }
  104. }
  105. export async function getAppliedProvider(): Promise<AppliedProviderInfo | null> {
  106. if (!appliedLoaded) {
  107. appliedCache = await readAppliedProvider();
  108. appliedLoaded = true;
  109. }
  110. return appliedCache;
  111. }
  112. export function setAppliedProvider(value: AppliedProviderInfo | null): void {
  113. appliedCache = value;
  114. appliedLoaded = true;
  115. }
  116. export function toStatusResult(status: RuntimeStatus): CodexStatusResult {
  117. return {
  118. state: status.state,
  119. running: status.state === 'ready',
  120. version: status.version,
  121. binaryPath: status.binaryPath,
  122. codexHome: getCodexHome(),
  123. defaultModel: status.defaultModel,
  124. providerId: status.providerId,
  125. degraded: status.degraded,
  126. error: status.error,
  127. applied: appliedCache,
  128. };
  129. }
  130. export function tailDiagnostics(limit = 200): Array<{ ts: string; line: string }> {
  131. const size = Math.max(1, Math.min(MAX_DIAGNOSTICS, Math.trunc(limit)));
  132. return diagnostics.slice(-size);
  133. }
  134. /** 会话默认工作目录:用户没指定 cwd 时用,避免 Codex 直接在安装目录里动手 */
  135. export async function defaultWorkspaceDir(): Promise<string> {
  136. const dir = join(getCodexDataDir(), 'workspace');
  137. await mkdir(dir, { recursive: true });
  138. return dir;
  139. }
  140. export async function disposeCodex(): Promise<void> {
  141. const current = container;
  142. container = null;
  143. if (!current) return;
  144. current.broker.closeAll();
  145. await current.eventLog.flush().catch(() => undefined);
  146. await Promise.race([
  147. current.runtime.dispose(),
  148. new Promise<void>((resolve) => setTimeout(resolve, 3_000)),
  149. ]);
  150. }