index.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. send(CODEX_DIAGNOSTIC_CHANNEL, entry);
  57. }
  58. export async function getCodex(): Promise<CodexContainer> {
  59. if (container) return container;
  60. if (creating) return creating;
  61. creating = (async () => {
  62. await ensureCodexHome();
  63. const runtime = new CodexRuntime({ codexHome: getCodexHome() });
  64. const broker = new ApprovalBroker(runtime);
  65. const eventLog = new EventLog(getEventsDir());
  66. await eventLog.init();
  67. runtime.on('notification', (notification: { method: string; params?: unknown }) => {
  68. if (notification.method === 'serverRequest/resolved') {
  69. const requestId = (notification.params as { requestId?: string | number } | undefined)?.requestId;
  70. if (requestId !== undefined) broker.resolveFromServer(requestId);
  71. }
  72. const event = notificationToEvent(notification);
  73. if (!event) return;
  74. send(CODEX_EVENT_CHANNEL, event);
  75. eventLog.append(event).catch((error: unknown) => {
  76. logger.error('[codex] 事件落盘失败:', asMessage(error));
  77. });
  78. });
  79. runtime.on('status', (status: RuntimeStatus) => send(CODEX_STATUS_CHANNEL, toStatusResult(status)));
  80. runtime.on('diagnostic', (line: string) => pushDiagnostic(line));
  81. runtime.on('serverRequest', (request: JsonRpcServerRequest) => broker.handle(request));
  82. broker.on('approval', (approval: unknown) => send(CODEX_APPROVAL_CHANNEL, approval));
  83. broker.on('closed', (token: string) => send(CODEX_APPROVAL_CLOSED_CHANNEL, { token }));
  84. broker.on('expired', (approval: unknown) => {
  85. pushDiagnostic(`审批超时已自动拒绝:${JSON.stringify(approval)}`);
  86. });
  87. broker.on('diagnostic', (line: string) => pushDiagnostic(line));
  88. container = {
  89. runtime,
  90. broker,
  91. eventLog,
  92. mcp: new McpService(runtime),
  93. skills: new SkillService(runtime, { onDiagnostic: pushDiagnostic }),
  94. };
  95. return container;
  96. })();
  97. try {
  98. return await creating;
  99. } finally {
  100. creating = null;
  101. }
  102. }
  103. export async function getAppliedProvider(): Promise<AppliedProviderInfo | null> {
  104. if (!appliedLoaded) {
  105. appliedCache = await readAppliedProvider();
  106. appliedLoaded = true;
  107. }
  108. return appliedCache;
  109. }
  110. export function setAppliedProvider(value: AppliedProviderInfo | null): void {
  111. appliedCache = value;
  112. appliedLoaded = true;
  113. }
  114. export function toStatusResult(status: RuntimeStatus): CodexStatusResult {
  115. return {
  116. state: status.state,
  117. running: status.state === 'ready',
  118. version: status.version,
  119. binaryPath: status.binaryPath,
  120. codexHome: getCodexHome(),
  121. defaultModel: status.defaultModel,
  122. providerId: status.providerId,
  123. degraded: status.degraded,
  124. error: status.error,
  125. applied: appliedCache,
  126. };
  127. }
  128. export function tailDiagnostics(limit = 200): Array<{ ts: string; line: string }> {
  129. const size = Math.max(1, Math.min(MAX_DIAGNOSTICS, Math.trunc(limit)));
  130. return diagnostics.slice(-size);
  131. }
  132. /** 会话默认工作目录:用户没指定 cwd 时用,避免 Codex 直接在安装目录里动手 */
  133. export async function defaultWorkspaceDir(): Promise<string> {
  134. const dir = join(getCodexDataDir(), 'workspace');
  135. await mkdir(dir, { recursive: true });
  136. return dir;
  137. }
  138. export async function disposeCodex(): Promise<void> {
  139. const current = container;
  140. container = null;
  141. if (!current) return;
  142. current.broker.closeAll();
  143. await current.eventLog.flush().catch(() => undefined);
  144. await Promise.race([
  145. current.runtime.dispose(),
  146. new Promise<void>((resolve) => setTimeout(resolve, 3_000)),
  147. ]);
  148. }