codexRuntime.ts 30 KB

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