codexRuntime.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. import { EventEmitter } from 'node:events';
  2. import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
  3. import { locateCodexBinary, readCodexVersion } from './codexLocator';
  4. import { JsonRpcPeer, type JsonRpcServerRequest } from './jsonRpcPeer';
  5. /**
  6. * 移植自 Noobi.ai src/main/codexAppServer.ts,主要改动:
  7. * 1. 删掉全部账号相关能力(account/read、account/login/start、account/logout)——本模块不做任何登录;
  8. * 2. 不再传 --strict-config(用户与程序共写 config.toml,未知字段只应告警不该退出);
  9. * 3. 新增 provider 注入:用 -c 覆盖 model_provider / model / model_providers.*,api_key 只走子进程环境变量;
  10. * 4. clientInfo 改为本项目标识。
  11. */
  12. export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
  13. export interface ModelOption {
  14. id: string;
  15. model: string;
  16. displayName: string;
  17. description: string;
  18. isDefault: boolean;
  19. defaultEffort: string;
  20. efforts: string[];
  21. }
  22. export interface RuntimeCapabilities {
  23. namespaceTools: boolean;
  24. imageGeneration: boolean;
  25. webSearch: boolean;
  26. }
  27. export interface RuntimeStatus {
  28. state: 'stopped' | 'starting' | 'ready' | 'error';
  29. binaryPath: string | null;
  30. version: string | null;
  31. codexHome: string | null;
  32. models: ModelOption[];
  33. capabilities: RuntimeCapabilities;
  34. providerId: string | null;
  35. defaultModel: string | null;
  36. /** model/list 拿不到可用模型时为 true */
  37. degraded: boolean;
  38. error: string | null;
  39. }
  40. export interface CodexMcpServerStatus {
  41. name: string;
  42. authStatus: string;
  43. connected: boolean;
  44. toolCount: number;
  45. tools: Array<{ name: string; description: string }>;
  46. }
  47. export interface CodexSkillSummary {
  48. name: string;
  49. description: string;
  50. path: string;
  51. scope: 'user' | 'repo' | 'system' | 'admin' | string;
  52. enabled: boolean;
  53. cwd: string;
  54. }
  55. /** 一次 spawn 用的模型来源:一律是自定义 provider,Codex 的内置 id 是保留字、不可覆盖 */
  56. export interface CodexProviderSpec {
  57. id: string;
  58. name?: string | null;
  59. baseUrl: string;
  60. model: string;
  61. /** apiKey 只注入子进程环境变量,不落任何盘 */
  62. apiKey?: string | null;
  63. envKey?: string;
  64. httpHeaders?: Record<string, string> | null;
  65. envHttpHeaders?: Record<string, string> | null;
  66. /** 仅放行 request_max_retries / stream_max_retries / stream_idle_timeout_ms / supports_websockets / query_params */
  67. extra?: Record<string, JsonValue> | null;
  68. }
  69. export interface CodexRuntimeOptions {
  70. codexHome: string;
  71. provider?: CodexProviderSpec | null;
  72. clientInfo?: { name: string; title: string; version: string };
  73. }
  74. export interface StartThreadOptions {
  75. cwd: string;
  76. model?: string | null;
  77. sandbox?: 'read-only' | 'workspace-write' | 'danger-full-access';
  78. approvalPolicy?: 'untrusted' | 'on-request' | 'never';
  79. developerInstructions?: string;
  80. ephemeral?: boolean;
  81. }
  82. export interface StartTurnOptions {
  83. threadId: string;
  84. prompt: string;
  85. cwd?: string;
  86. model?: string | null;
  87. effort?: string | null;
  88. approvalPolicy?: 'untrusted' | 'on-request' | 'never';
  89. skills?: Array<{ name: string; path: string }>;
  90. /** 仅宿主侧的完成期限,不会发给 App Server */
  91. timeoutMs?: number;
  92. }
  93. export interface TurnResult {
  94. turnId: string;
  95. status: string;
  96. text: string;
  97. raw: unknown;
  98. }
  99. interface SkillsListResponse {
  100. data: Array<{
  101. cwd: string;
  102. skills: Array<{
  103. name: string;
  104. description: string;
  105. path: string;
  106. scope: string;
  107. enabled: boolean;
  108. }>;
  109. }>;
  110. }
  111. interface ListMcpServerStatusResponse {
  112. data: Array<{
  113. name: string;
  114. serverInfo: unknown | null;
  115. tools: Record<string, unknown>;
  116. authStatus: string;
  117. }>;
  118. nextCursor: string | null;
  119. }
  120. interface InitializeResponse {
  121. userAgent: string;
  122. codexHome: string;
  123. platformFamily: string;
  124. platformOs: string;
  125. }
  126. interface ModelListResponse {
  127. data: Array<{
  128. id: string;
  129. model: string;
  130. displayName: string;
  131. description: string;
  132. isDefault: boolean;
  133. defaultReasoningEffort: string;
  134. supportedReasoningEfforts: Array<{ reasoningEffort: string }>;
  135. }>;
  136. nextCursor: string | null;
  137. }
  138. interface ModelProviderCapabilitiesResponse {
  139. namespaceTools: boolean;
  140. imageGeneration: boolean;
  141. webSearch: boolean;
  142. }
  143. interface ThreadResponse {
  144. thread: { id: string };
  145. model: string;
  146. }
  147. interface TurnStartResponse {
  148. turn: { id: string; status: string };
  149. }
  150. interface EarlyTurnState {
  151. text: string;
  152. completed: TurnResult | null;
  153. }
  154. interface TurnWaiter {
  155. text: string;
  156. resolve(result: TurnResult): void;
  157. reject(error: Error): void;
  158. timer: NodeJS.Timeout;
  159. }
  160. const TURN_TIMEOUT_MS = 20 * 60 * 1_000;
  161. /** 退出事件可能比 stderr 落地慢半拍,等一下再拼错误信息 */
  162. const EXIT_GRACE_MS = 300;
  163. const STDERR_TAIL_LINES = 40;
  164. export const DEFAULT_API_KEY_ENV = 'ZSJZ_CODEX_API_KEY';
  165. const PROVIDER_EXTRA_ALLOWLIST = new Set([
  166. 'request_max_retries',
  167. 'stream_max_retries',
  168. 'stream_idle_timeout_ms',
  169. 'supports_websockets',
  170. 'query_params',
  171. ]);
  172. export class CodexRuntime extends EventEmitter {
  173. readonly #codexHome: string;
  174. readonly #clientInfo: { name: string; title: string; version: string };
  175. #provider: CodexProviderSpec | null;
  176. #child: ChildProcessWithoutNullStreams | null = null;
  177. #peer: JsonRpcPeer | null = null;
  178. #startPromise: Promise<RuntimeStatus> | null = null;
  179. #runtime: RuntimeStatus = emptyRuntimeStatus();
  180. #turnWaiters = new Map<string, TurnWaiter>();
  181. #earlyTurnStates = new Map<string, EarlyTurnState>();
  182. #runTurnStartsInFlight = 0;
  183. #generation = 0;
  184. constructor(options: CodexRuntimeOptions) {
  185. super();
  186. this.#codexHome = options.codexHome;
  187. this.#provider = options.provider ?? null;
  188. this.#clientInfo = options.clientInfo ?? {
  189. name: 'zsjz_ai',
  190. title: '清鉴线索调查工具',
  191. version: '0.1.0',
  192. };
  193. }
  194. get status(): RuntimeStatus {
  195. return structuredClone(this.#runtime);
  196. }
  197. get provider(): CodexProviderSpec | null {
  198. return this.#provider ? { ...this.#provider, apiKey: null } : null;
  199. }
  200. /** 换 provider 必须重启子进程:api_key 走的是子进程环境变量,无法热更新 */
  201. async applyProvider(provider: CodexProviderSpec | null): Promise<RuntimeStatus> {
  202. const previous = this.#provider;
  203. this.#provider = provider;
  204. if (this.#child) await this.stop();
  205. try {
  206. return await this.start();
  207. } catch (error) {
  208. // 失败要回滚:坏 spec 留在内存里,之后每次 start 都会重放同一组参数,
  209. // 一条选错的模型能把运行时锁死到重启应用为止。
  210. this.#provider = previous;
  211. throw error;
  212. }
  213. }
  214. async start(): Promise<RuntimeStatus> {
  215. if (this.#runtime.state === 'ready' && this.#peer) return this.status;
  216. if (this.#startPromise) return this.#startPromise;
  217. const generation = ++this.#generation;
  218. this.#startPromise = this.#start(generation);
  219. try {
  220. return await this.#startPromise;
  221. } finally {
  222. this.#startPromise = null;
  223. }
  224. }
  225. async refresh(): Promise<RuntimeStatus> {
  226. await this.start();
  227. let models: ModelOption[] = [];
  228. let degraded = false;
  229. try {
  230. models = await this.listModels();
  231. } catch (error) {
  232. // 第三方/本地端点常常不实现 model/list,这里降级而不是失败
  233. degraded = true;
  234. this.emit('diagnostic', `model/list 不可用:${asError(error).message}`);
  235. }
  236. const capabilities = await this.readModelProviderCapabilities().catch(() => emptyCapabilities());
  237. this.#runtime = {
  238. ...this.#runtime,
  239. models,
  240. capabilities,
  241. degraded: degraded || models.length === 0,
  242. // model/list 返回的是 Codex 内置模型目录(与自定义 provider 无关),
  243. // 实际会用的是 provider 里配置的模型,所以它优先
  244. defaultModel: this.#provider?.model ?? models.find((item) => item.isDefault)?.model ?? null,
  245. state: 'ready',
  246. error: null,
  247. };
  248. this.emit('status', this.status);
  249. return this.status;
  250. }
  251. async readModelProviderCapabilities(): Promise<RuntimeCapabilities> {
  252. const result = await this.#request<ModelProviderCapabilitiesResponse>(
  253. 'modelProvider/capabilities/read',
  254. {},
  255. );
  256. return {
  257. namespaceTools: result.namespaceTools === true,
  258. imageGeneration: result.imageGeneration === true,
  259. webSearch: result.webSearch === true,
  260. };
  261. }
  262. async listModels(): Promise<ModelOption[]> {
  263. const models: ModelOption[] = [];
  264. let cursor: string | null = null;
  265. for (let page = 0; page < 10; page += 1) {
  266. const result: ModelListResponse = await this.#request<ModelListResponse>('model/list', {
  267. cursor,
  268. limit: 100,
  269. includeHidden: false,
  270. });
  271. models.push(
  272. ...result.data.map((model) => ({
  273. id: model.id,
  274. model: model.model,
  275. displayName: model.displayName,
  276. description: model.description,
  277. isDefault: model.isDefault,
  278. defaultEffort: model.defaultReasoningEffort,
  279. efforts: model.supportedReasoningEfforts.map((item) => item.reasoningEffort),
  280. })),
  281. );
  282. cursor = result.nextCursor;
  283. if (!cursor) break;
  284. }
  285. return models;
  286. }
  287. async listSkills(options: { cwds?: string[]; forceReload?: boolean } = {}): Promise<CodexSkillSummary[]> {
  288. await this.start();
  289. const result = await this.#request<SkillsListResponse>('skills/list', {
  290. ...(options.cwds?.length ? { cwds: options.cwds } : {}),
  291. forceReload: options.forceReload ?? false,
  292. });
  293. return result.data.flatMap((entry) =>
  294. entry.skills.map((skill) => ({
  295. name: skill.name,
  296. description: skill.description,
  297. path: skill.path,
  298. scope: skill.scope,
  299. enabled: skill.enabled,
  300. cwd: entry.cwd,
  301. })),
  302. );
  303. }
  304. async setSkillEnabled(selector: { path?: string; name?: string }, enabled: boolean): Promise<boolean> {
  305. await this.start();
  306. const result = await this.#request<{ effectiveEnabled: boolean }>('skills/config/write', {
  307. ...(selector.path ? { path: selector.path } : {}),
  308. ...(!selector.path && selector.name ? { name: selector.name } : {}),
  309. enabled,
  310. });
  311. return result.effectiveEnabled;
  312. }
  313. async listMcpServerStatuses(): Promise<CodexMcpServerStatus[]> {
  314. await this.start();
  315. const statuses: CodexMcpServerStatus[] = [];
  316. let cursor: string | null = null;
  317. for (let page = 0; page < 20; page += 1) {
  318. const result: ListMcpServerStatusResponse = await this.#request<ListMcpServerStatusResponse>(
  319. 'mcpServerStatus/list',
  320. {
  321. cursor,
  322. limit: 100,
  323. detail: 'toolsAndAuthOnly',
  324. },
  325. );
  326. statuses.push(
  327. ...result.data.map((server) => ({
  328. name: server.name,
  329. authStatus: server.authStatus,
  330. connected: server.serverInfo !== null,
  331. toolCount: Object.keys(server.tools ?? {}).length,
  332. tools: toToolSummaries(server.tools),
  333. })),
  334. );
  335. cursor = result.nextCursor;
  336. if (!cursor) break;
  337. }
  338. return statuses;
  339. }
  340. async readConfig(): Promise<Record<string, unknown>> {
  341. await this.start();
  342. const result = await this.#request<{ config: Record<string, unknown> }>('config/read', {
  343. includeLayers: false,
  344. });
  345. return structuredClone(result.config);
  346. }
  347. /** 局部写:Codex 自己也持有 config.toml 写权,禁止整文件覆盖 */
  348. async writeConfigValue(keyPath: string, value: JsonValue): Promise<void> {
  349. await this.start();
  350. await this.#request<unknown>('config/value/write', { keyPath, value, mergeStrategy: 'replace' });
  351. }
  352. async reloadMcpServers(): Promise<void> {
  353. await this.start();
  354. await this.#request<unknown>('config/mcpServer/reload');
  355. }
  356. async startThread(options: StartThreadOptions): Promise<string> {
  357. await this.start();
  358. const result = await this.#request<ThreadResponse>('thread/start', {
  359. cwd: options.cwd,
  360. ...(options.model ? { model: options.model } : {}),
  361. sandbox: options.sandbox ?? 'workspace-write',
  362. approvalPolicy: options.approvalPolicy ?? 'never',
  363. ...(options.developerInstructions ? { developerInstructions: options.developerInstructions } : {}),
  364. ...(options.ephemeral === undefined ? {} : { ephemeral: options.ephemeral }),
  365. experimentalRawEvents: false,
  366. });
  367. return result.thread.id;
  368. }
  369. async resumeThread(threadId: string, options: StartThreadOptions): Promise<string> {
  370. await this.start();
  371. const result = await this.#request<ThreadResponse>('thread/resume', {
  372. threadId,
  373. cwd: options.cwd,
  374. ...(options.model ? { model: options.model } : {}),
  375. sandbox: options.sandbox ?? 'workspace-write',
  376. approvalPolicy: options.approvalPolicy ?? 'never',
  377. ...(options.developerInstructions ? { developerInstructions: options.developerInstructions } : {}),
  378. // excludeTurns 不影响上游收到的历史(实测 true/false 两轮上下文都完整带回)
  379. excludeTurns: true,
  380. });
  381. return result.thread.id;
  382. }
  383. async startTurn(options: StartTurnOptions): Promise<string> {
  384. await this.start();
  385. const result = await this.#request<TurnStartResponse>('turn/start', {
  386. threadId: options.threadId,
  387. input: [
  388. { type: 'text', text: options.prompt, text_elements: [] },
  389. ...(options.skills ?? []).map((skill) => ({
  390. type: 'skill' as const,
  391. name: skill.name,
  392. path: skill.path,
  393. })),
  394. ],
  395. ...(options.cwd ? { cwd: options.cwd } : {}),
  396. ...(options.model ? { model: options.model } : {}),
  397. ...(options.effort ? { effort: options.effort } : {}),
  398. ...(options.approvalPolicy ? { approvalPolicy: options.approvalPolicy } : {}),
  399. });
  400. return result.turn.id;
  401. }
  402. async runTurn(options: StartTurnOptions): Promise<TurnResult> {
  403. this.#runTurnStartsInFlight += 1;
  404. let turnId: string;
  405. try {
  406. turnId = await this.startTurn(options);
  407. } catch (error) {
  408. this.#releaseRunTurnStart();
  409. throw error;
  410. }
  411. // turn/completed 可能早于 turn/start 的响应回来,先存起来
  412. const early = this.#earlyTurnStates.get(turnId);
  413. this.#earlyTurnStates.delete(turnId);
  414. if (early?.completed) {
  415. this.#releaseRunTurnStart();
  416. return early.completed;
  417. }
  418. return new Promise<TurnResult>((resolve, reject) => {
  419. const timeoutMs =
  420. options.timeoutMs === undefined
  421. ? TURN_TIMEOUT_MS
  422. : Math.min(TURN_TIMEOUT_MS, Math.max(1_000, Math.trunc(options.timeoutMs)));
  423. const timer = setTimeout(() => {
  424. this.#turnWaiters.delete(turnId);
  425. void this.interruptTurn(options.threadId, turnId).catch(() => undefined);
  426. reject(new Error(`Codex turn ${turnId} 超时`));
  427. }, timeoutMs);
  428. timer.unref();
  429. this.#turnWaiters.set(turnId, { text: early?.text ?? '', resolve, reject, timer });
  430. this.#releaseRunTurnStart();
  431. });
  432. }
  433. async interruptTurn(threadId: string, turnId: string): Promise<void> {
  434. await this.#request<Record<string, never>>('turn/interrupt', { threadId, turnId });
  435. }
  436. async unsubscribeThread(threadId: string): Promise<void> {
  437. await this.#request<{ status: string }>('thread/unsubscribe', { threadId });
  438. }
  439. respondToServerRequest(requestId: string | number, result: unknown): void {
  440. if (!this.#peer) throw new Error('Codex App Server 未运行');
  441. this.#peer.respond(requestId, result);
  442. }
  443. rejectServerRequest(requestId: string | number, code: number, message: string): void {
  444. if (!this.#peer) throw new Error('Codex App Server 未运行');
  445. this.#peer.respondError(requestId, { code, message });
  446. }
  447. async stop(): Promise<void> {
  448. this.#generation += 1;
  449. const child = this.#child;
  450. const peer = this.#peer;
  451. this.#child = null;
  452. this.#peer = null;
  453. for (const waiter of this.#turnWaiters.values()) {
  454. clearTimeout(waiter.timer);
  455. waiter.reject(new Error('Codex App Server 在本轮对话进行中被停止'));
  456. }
  457. this.#turnWaiters.clear();
  458. this.#earlyTurnStates.clear();
  459. this.#runTurnStartsInFlight = 0;
  460. if (child && child.exitCode === null) {
  461. peer?.endOutput();
  462. await Promise.race([
  463. new Promise<void>((resolve) => child.once('exit', () => resolve())),
  464. new Promise<void>((resolve) => setTimeout(resolve, 1_500)),
  465. ]);
  466. if (child.exitCode === null) {
  467. child.kill('SIGTERM');
  468. await Promise.race([
  469. new Promise<void>((resolve) => child.once('exit', () => resolve())),
  470. new Promise<void>((resolve) => setTimeout(resolve, 1_000)),
  471. ]);
  472. }
  473. if (child.exitCode === null) child.kill('SIGKILL');
  474. }
  475. peer?.close(new Error('Codex App Server 已停止'));
  476. this.#runtime = { ...emptyRuntimeStatus(), providerId: this.#provider?.id ?? null };
  477. this.emit('status', this.status);
  478. }
  479. async dispose(): Promise<void> {
  480. await this.stop();
  481. this.removeAllListeners();
  482. }
  483. async #start(generation: number): Promise<RuntimeStatus> {
  484. this.#runtime = { ...emptyRuntimeStatus(), state: 'starting', providerId: this.#provider?.id ?? null };
  485. this.emit('status', this.status);
  486. let child: ChildProcessWithoutNullStreams | null = null;
  487. let peer: JsonRpcPeer | null = null;
  488. let watcher: ExitWatcher | null = null;
  489. try {
  490. const binaryPath = await locateCodexBinary();
  491. this.#assertGeneration(generation);
  492. const version = readCodexVersion(binaryPath);
  493. this.#assertGeneration(generation);
  494. const provider = this.#provider;
  495. child = spawn(binaryPath, buildArgs(provider), {
  496. cwd: process.cwd(),
  497. env: buildEnv(this.#codexHome, provider),
  498. stdio: ['pipe', 'pipe', 'pipe'],
  499. windowsHide: true,
  500. });
  501. this.#child = child;
  502. peer = new JsonRpcPeer(child.stdout, child.stdin);
  503. this.#peer = peer;
  504. const spawnedChild = child;
  505. const spawnedPeer = peer;
  506. peer.on('notification', (notification) => this.#handleNotification(notification));
  507. peer.on('serverRequest', (request: JsonRpcServerRequest) => this.emit('serverRequest', request));
  508. peer.on('protocolError', (error) => this.emit('diagnostic', asError(error).message));
  509. watcher = createExitWatcher(
  510. spawnedChild,
  511. (line) => this.emit('diagnostic', sanitizeDiagnostic(line)),
  512. (error) => {
  513. if (this.#peer !== spawnedPeer || this.#child !== spawnedChild) return;
  514. this.#handleExit(spawnedChild, error);
  515. },
  516. );
  517. child.stderr.setEncoding('utf8');
  518. child.stderr.on('data', (chunk: string) => {
  519. for (const line of chunk.split(/\r?\n/u).filter(Boolean)) watcher?.noteStderr(line);
  520. });
  521. child.once('error', (error) => watcher?.shutdown(error.message));
  522. child.once('exit', () => watcher?.shutdown('Codex App Server 已退出'));
  523. peer.once('closed', (error) => watcher?.shutdown(asError(error).message));
  524. peer.start();
  525. const initialized = await peer.request<InitializeResponse>('initialize', {
  526. clientInfo: this.#clientInfo,
  527. capabilities: { experimentalApi: true },
  528. });
  529. this.#assertGeneration(generation);
  530. peer.notify('initialized');
  531. this.#runtime = {
  532. ...emptyRuntimeStatus(),
  533. state: 'ready',
  534. binaryPath,
  535. version,
  536. codexHome: initialized.codexHome,
  537. providerId: provider?.id ?? null,
  538. };
  539. return await this.refresh();
  540. } catch (error) {
  541. // 子进程启动即退出的话真话只在 stderr 里:等它落定,别把「协议流已关闭」丢给用户猜
  542. const fallback = asError(error).message;
  543. const message = watcher ? (await watcher.describe(fallback)).message : fallback;
  544. peer?.close(new Error(message));
  545. if (this.#peer === peer) this.#peer = null;
  546. if (this.#child === child) this.#child = null;
  547. if (child && child.exitCode === null) child.kill('SIGTERM');
  548. if (generation === this.#generation) {
  549. this.#runtime = { ...this.#runtime, state: 'error', error: sanitizeDiagnostic(message) };
  550. this.emit('status', this.status);
  551. }
  552. // 换掉原文而不是换掉错误对象:调用方拿到的类型与 stack 不变,只是话变清楚了
  553. if (error instanceof Error) error.message = message;
  554. throw error;
  555. }
  556. }
  557. #request<T>(method: string, params?: unknown): Promise<T> {
  558. if (!this.#peer) throw new Error('Codex App Server 未运行');
  559. return this.#peer.request<T>(method, params);
  560. }
  561. #handleNotification(notification: { method: string; params?: unknown }): void {
  562. const params = asRecord(notification.params);
  563. const turnId = readString(params?.turnId) ?? readString(asRecord(params?.turn)?.id);
  564. if (turnId) {
  565. const waiter = this.#turnWaiters.get(turnId);
  566. if (waiter && notification.method === 'item/agentMessage/delta') {
  567. waiter.text += readString(params?.delta) ?? '';
  568. }
  569. if (waiter && notification.method === 'item/completed') {
  570. const item = asRecord(params?.item);
  571. if (item?.type === 'agentMessage' && typeof item.text === 'string') waiter.text = item.text;
  572. }
  573. if (waiter && notification.method === 'turn/completed') {
  574. clearTimeout(waiter.timer);
  575. this.#turnWaiters.delete(turnId);
  576. const turn = asRecord(params?.turn);
  577. waiter.resolve({
  578. turnId,
  579. status: readString(turn?.status) ?? 'completed',
  580. text: waiter.text,
  581. raw: params,
  582. });
  583. }
  584. if (!waiter && this.#runTurnStartsInFlight > 0) {
  585. const early = this.#earlyTurnStates.get(turnId) ?? { text: '', completed: null };
  586. if (notification.method === 'item/agentMessage/delta') {
  587. early.text += readString(params?.delta) ?? '';
  588. }
  589. if (notification.method === 'item/completed') {
  590. const item = asRecord(params?.item);
  591. if (item?.type === 'agentMessage' && typeof item.text === 'string') early.text = item.text;
  592. }
  593. if (notification.method === 'turn/completed') {
  594. const turn = asRecord(params?.turn);
  595. early.completed = {
  596. turnId,
  597. status: readString(turn?.status) ?? 'completed',
  598. text: early.text,
  599. raw: params,
  600. };
  601. }
  602. this.#earlyTurnStates.set(turnId, early);
  603. }
  604. }
  605. this.emit('notification', notification);
  606. }
  607. #handleExit(child: ChildProcessWithoutNullStreams, error: Error): void {
  608. if (this.#child !== child) return;
  609. this.#peer?.close(error);
  610. this.#peer = null;
  611. this.#child = null;
  612. this.#runtime = {
  613. ...this.#runtime,
  614. state: 'error',
  615. degraded: true,
  616. error: sanitizeDiagnostic(error.message),
  617. };
  618. for (const waiter of this.#turnWaiters.values()) {
  619. clearTimeout(waiter.timer);
  620. waiter.reject(error);
  621. }
  622. this.#turnWaiters.clear();
  623. this.#earlyTurnStates.clear();
  624. this.#runTurnStartsInFlight = 0;
  625. this.emit('status', this.status);
  626. }
  627. #assertGeneration(generation: number): void {
  628. if (generation !== this.#generation) throw new Error('Codex App Server 的启动已被取消');
  629. }
  630. #releaseRunTurnStart(): void {
  631. this.#runTurnStartsInFlight = Math.max(0, this.#runTurnStartsInFlight - 1);
  632. if (this.#runTurnStartsInFlight === 0) this.#earlyTurnStates.clear();
  633. }
  634. }
  635. /** 每个配置项单独一个 -c,避免手写嵌套 inline table */
  636. export function buildArgs(provider: CodexProviderSpec | null): string[] {
  637. const args = ['app-server', '--listen', 'stdio://'];
  638. if (!provider) return args;
  639. args.push('-c', `model_provider=${tomlString(provider.id)}`);
  640. args.push('-c', `model=${tomlString(provider.model)}`);
  641. const prefix = `model_providers.${provider.id}`;
  642. if (provider.name) args.push('-c', `${prefix}.name=${tomlString(provider.name)}`);
  643. if (provider.baseUrl) args.push('-c', `${prefix}.base_url=${tomlString(provider.baseUrl)}`);
  644. // wire_api 只支持 responses:0.155.1 已下线 chat
  645. args.push('-c', `${prefix}.wire_api="responses"`);
  646. args.push('-c', `${prefix}.requires_openai_auth=false`);
  647. if (provider.apiKey) {
  648. args.push('-c', `${prefix}.env_key=${tomlString(provider.envKey ?? DEFAULT_API_KEY_ENV)}`);
  649. }
  650. if (provider.httpHeaders && Object.keys(provider.httpHeaders).length) {
  651. args.push('-c', `${prefix}.http_headers=${tomlInlineTable(provider.httpHeaders)}`);
  652. }
  653. if (provider.envHttpHeaders && Object.keys(provider.envHttpHeaders).length) {
  654. args.push('-c', `${prefix}.env_http_headers=${tomlInlineTable(provider.envHttpHeaders)}`);
  655. }
  656. for (const [key, value] of Object.entries(provider.extra ?? {})) {
  657. if (!PROVIDER_EXTRA_ALLOWLIST.has(key) || value === null || value === undefined) continue;
  658. args.push('-c', `${prefix}.${key}=${tomlValue(value)}`);
  659. }
  660. return args;
  661. }
  662. function buildEnv(codexHome: string, provider: CodexProviderSpec | null): NodeJS.ProcessEnv {
  663. const env: NodeJS.ProcessEnv = {
  664. ...process.env,
  665. CODEX_HOME: codexHome,
  666. RUST_LOG: process.env.RUST_LOG ?? 'warn',
  667. LOG_FORMAT: 'json',
  668. };
  669. // 密钥只存在于子进程环境变量,config.toml 里只写 env_key 名字
  670. if (provider?.apiKey) {
  671. env[provider.envKey ?? DEFAULT_API_KEY_ENV] = provider.apiKey;
  672. }
  673. return env;
  674. }
  675. function tomlString(value: string): string {
  676. return JSON.stringify(value);
  677. }
  678. function tomlInlineTable(value: Record<string, string>): string {
  679. const entries = Object.entries(value).map(([key, item]) => `${tomlKey(key)}=${tomlString(item)}`);
  680. return `{${entries.join(',')}}`;
  681. }
  682. function tomlKey(key: string): string {
  683. return /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key);
  684. }
  685. function tomlValue(value: JsonValue): string {
  686. if (typeof value === 'string') return tomlString(value);
  687. if (typeof value === 'number' || typeof value === 'boolean') return String(value);
  688. if (Array.isArray(value)) {
  689. return `[${value.filter((item) => item !== null).map(tomlValue).join(',')}]`;
  690. }
  691. if (value && typeof value === 'object') {
  692. // TOML inline table 用 `=` 而不是 JSON 的 `:`,不能直接 JSON.stringify
  693. return tomlInlineTable(
  694. Object.fromEntries(
  695. Object.entries(value as Record<string, JsonValue>)
  696. .filter(([, item]) => typeof item === 'string')
  697. .map(([key, item]) => [key, String(item)]),
  698. ),
  699. );
  700. }
  701. return '""';
  702. }
  703. function emptyRuntimeStatus(): RuntimeStatus {
  704. return {
  705. state: 'stopped',
  706. binaryPath: null,
  707. version: null,
  708. codexHome: null,
  709. models: [],
  710. capabilities: emptyCapabilities(),
  711. providerId: null,
  712. defaultModel: null,
  713. degraded: false,
  714. error: null,
  715. };
  716. }
  717. function emptyCapabilities(): RuntimeCapabilities {
  718. return { namespaceTools: false, imageGeneration: false, webSearch: false };
  719. }
  720. function asRecord(value: unknown): Record<string, unknown> | null {
  721. return value && typeof value === 'object' && !Array.isArray(value)
  722. ? (value as Record<string, unknown>)
  723. : null;
  724. }
  725. function readString(value: unknown): string | null {
  726. return typeof value === 'string' ? value : null;
  727. }
  728. /**
  729. * mcpServerStatus/list 的 tools 是「工具名 → 详情」映射,详情结构由 Codex 版本决定。
  730. * 这里只认 name / description,认不出的形态退化成只留 key 名,避免协议一变列表就空掉。
  731. */
  732. export function toToolSummaries(
  733. tools: Record<string, unknown> | null | undefined,
  734. ): Array<{ name: string; description: string }> {
  735. return Object.entries(tools ?? {}).map(([key, value]) => {
  736. const detail = asRecord(value);
  737. return {
  738. name: readString(detail?.name) || key,
  739. description: readString(detail?.description) || '',
  740. };
  741. });
  742. }
  743. function asError(value: unknown): Error {
  744. return value instanceof Error ? value : new Error(String(value));
  745. }
  746. export function sanitizeDiagnostic(value: string): string {
  747. return value
  748. .replace(/sk-[A-Za-z0-9_-]{12,}/gu, 'sk-[redacted]')
  749. .replace(/Bearer\s+[A-Za-z0-9._~-]+/giu, 'Bearer [redacted]')
  750. .slice(0, 4_000);
  751. }
  752. function delay(ms: number): Promise<void> {
  753. return new Promise((resolve) => {
  754. const timer = setTimeout(resolve, ms);
  755. timer.unref();
  756. });
  757. }
  758. /**
  759. * Codex 的致命错误由 anyhow 打成纯文本(`Error: ...`),RUST_LOG 的常规日志是 JSON 行;
  760. * 纯文本里还混着 `WARNING: ...` 这类噪音,所以优先取 Error 行,取不到才退化成第一条纯文本行。
  761. */
  762. function pickFatalLine(tail: string[]): string | null {
  763. const plain = tail
  764. .map((line) => line.trim())
  765. .filter((line) => line && !line.startsWith('{'));
  766. if (!plain.length) return null;
  767. const fatal = plain.find((line) => /^(error|panic)\b/iu.test(line) || line.includes('panicked at'));
  768. return sanitizeDiagnostic((fatal ?? plain[0]).slice(0, 500));
  769. }
  770. interface ExitWatcher {
  771. /** 收 stderr:既实时推诊断,也留尾部若干行用于拼退出原因 */
  772. noteStderr(line: string): void;
  773. /** 统一退出出口(流关闭 / 进程退出 / spawn 失败),只生效一次 */
  774. shutdown(fallback: string): void;
  775. /** 等 stderr 收完,把没有信息量的 fallback 换成带 exit code 与原因原文的错误 */
  776. describe(fallback: string): Promise<Error>;
  777. }
  778. function createExitWatcher(
  779. child: ChildProcessWithoutNullStreams,
  780. onDiagnostic: (line: string) => void,
  781. onExit: (error: Error) => void,
  782. ): ExitWatcher {
  783. const tail: string[] = [];
  784. const closed = new Promise<void>((resolve) => child.once('close', () => resolve()));
  785. let shuttingDown = false;
  786. const describe = async (fallback: string): Promise<Error> => {
  787. // 等不到 close 也得往下走:一次卡住的退出不能把启动的 Promise 挂在那里
  788. await Promise.race([closed, delay(EXIT_GRACE_MS)]);
  789. const code = child.exitCode ?? child.signalCode;
  790. const reason = code === null || code === undefined ? fallback : `Codex App Server 退出(${code})`;
  791. const detail = pickFatalLine(tail);
  792. return new Error(detail ? `${reason}:${detail}` : reason);
  793. };
  794. return {
  795. noteStderr(line: string): void {
  796. tail.push(line);
  797. if (tail.length > STDERR_TAIL_LINES) tail.shift();
  798. onDiagnostic(line);
  799. },
  800. describe,
  801. shutdown(fallback: string): void {
  802. if (shuttingDown) return;
  803. shuttingDown = true;
  804. void describe(fallback).then((error) => {
  805. // 流都关了进程还活着(卡死的子进程)只能自己收
  806. if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');
  807. onExit(error);
  808. });
  809. },
  810. };
  811. }