index.ts 6.0 KB

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