codexRuntime.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  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/false 两轮上下文都完整带回)
  378. excludeTurns: true,
  379. });
  380. return result.thread.id;
  381. }
  382. async startTurn(options: StartTurnOptions): Promise<string> {
  383. await this.start();
  384. const result = await this.#request<TurnStartResponse>('turn/start', {
  385. threadId: options.threadId,
  386. input: [
  387. { type: 'text', text: options.prompt, text_elements: [] },
  388. ...(options.skills ?? []).map((skill) => ({
  389. type: 'skill' as const,
  390. name: skill.name,
  391. path: skill.path,
  392. })),
  393. ],
  394. ...(options.cwd ? { cwd: options.cwd } : {}),
  395. ...(options.model ? { model: options.model } : {}),
  396. ...(options.effort ? { effort: options.effort } : {}),
  397. ...(options.approvalPolicy ? { approvalPolicy: options.approvalPolicy } : {}),
  398. });
  399. return result.turn.id;
  400. }
  401. async runTurn(options: StartTurnOptions): Promise<TurnResult> {
  402. this.#runTurnStartsInFlight += 1;
  403. let turnId: string;
  404. try {
  405. turnId = await this.startTurn(options);
  406. } catch (error) {
  407. this.#releaseRunTurnStart();
  408. throw error;
  409. }
  410. // turn/completed 可能早于 turn/start 的响应回来,先存起来
  411. const early = this.#earlyTurnStates.get(turnId);
  412. this.#earlyTurnStates.delete(turnId);
  413. if (early?.completed) {
  414. this.#releaseRunTurnStart();
  415. return early.completed;
  416. }
  417. return new Promise<TurnResult>((resolve, reject) => {
  418. const timeoutMs =
  419. options.timeoutMs === undefined
  420. ? TURN_TIMEOUT_MS
  421. : Math.min(TURN_TIMEOUT_MS, Math.max(1_000, Math.trunc(options.timeoutMs)));
  422. const timer = setTimeout(() => {
  423. this.#turnWaiters.delete(turnId);
  424. void this.interruptTurn(options.threadId, turnId).catch(() => undefined);
  425. reject(new Error(`Codex turn ${turnId} 超时`));
  426. }, timeoutMs);
  427. timer.unref();
  428. this.#turnWaiters.set(turnId, { text: early?.text ?? '', resolve, reject, timer });
  429. this.#releaseRunTurnStart();
  430. });
  431. }
  432. async interruptTurn(threadId: string, turnId: string): Promise<void> {
  433. await this.#request<Record<string, never>>('turn/interrupt', { threadId, turnId });
  434. }
  435. async unsubscribeThread(threadId: string): Promise<void> {
  436. await this.#request<{ status: string }>('thread/unsubscribe', { threadId });
  437. }
  438. respondToServerRequest(requestId: string | number, result: unknown): void {
  439. if (!this.#peer) throw new Error('Codex App Server 未运行');
  440. this.#peer.respond(requestId, result);
  441. }
  442. rejectServerRequest(requestId: string | number, code: number, message: string): void {
  443. if (!this.#peer) throw new Error('Codex App Server 未运行');
  444. this.#peer.respondError(requestId, { code, message });
  445. }
  446. async stop(): Promise<void> {
  447. this.#generation += 1;
  448. const child = this.#child;
  449. const peer = this.#peer;
  450. this.#child = null;
  451. this.#peer = null;
  452. for (const waiter of this.#turnWaiters.values()) {
  453. clearTimeout(waiter.timer);
  454. waiter.reject(new Error('Codex App Server 在本轮对话进行中被停止'));
  455. }
  456. this.#turnWaiters.clear();
  457. this.#earlyTurnStates.clear();
  458. this.#runTurnStartsInFlight = 0;
  459. if (child && child.exitCode === null) {
  460. peer?.endOutput();
  461. await Promise.race([
  462. new Promise<void>((resolve) => child.once('exit', () => resolve())),
  463. new Promise<void>((resolve) => setTimeout(resolve, 1_500)),
  464. ]);
  465. if (child.exitCode === null) {
  466. child.kill('SIGTERM');
  467. await Promise.race([
  468. new Promise<void>((resolve) => child.once('exit', () => resolve())),
  469. new Promise<void>((resolve) => setTimeout(resolve, 1_000)),
  470. ]);
  471. }
  472. if (child.exitCode === null) child.kill('SIGKILL');
  473. }
  474. peer?.close(new Error('Codex App Server 已停止'));
  475. this.#runtime = { ...emptyRuntimeStatus(), providerId: this.#provider?.id ?? null };
  476. this.emit('status', this.status);
  477. }
  478. async dispose(): Promise<void> {
  479. await this.stop();
  480. this.removeAllListeners();
  481. }
  482. async #start(generation: number): Promise<RuntimeStatus> {
  483. this.#runtime = { ...emptyRuntimeStatus(), state: 'starting', providerId: this.#provider?.id ?? null };
  484. this.emit('status', this.status);
  485. let child: ChildProcessWithoutNullStreams | null = null;
  486. let peer: JsonRpcPeer | null = null;
  487. let watcher: ExitWatcher | null = null;
  488. try {
  489. const binaryPath = await locateCodexBinary();
  490. this.#assertGeneration(generation);
  491. const version = readCodexVersion(binaryPath);
  492. this.#assertGeneration(generation);
  493. const provider = this.#provider;
  494. child = spawn(binaryPath, buildArgs(provider), {
  495. cwd: process.cwd(),
  496. env: buildEnv(this.#codexHome, provider),
  497. stdio: ['pipe', 'pipe', 'pipe'],
  498. windowsHide: true,
  499. });
  500. this.#child = child;
  501. peer = new JsonRpcPeer(child.stdout, child.stdin);
  502. this.#peer = peer;
  503. const spawnedChild = child;
  504. const spawnedPeer = peer;
  505. peer.on('notification', (notification) => this.#handleNotification(notification));
  506. peer.on('serverRequest', (request: JsonRpcServerRequest) => this.emit('serverRequest', request));
  507. peer.on('protocolError', (error) => this.emit('diagnostic', asError(error).message));
  508. watcher = createExitWatcher(
  509. spawnedChild,
  510. (line) => this.emit('diagnostic', sanitizeDiagnostic(line)),
  511. (error) => {
  512. if (this.#peer !== spawnedPeer || this.#child !== spawnedChild) return;
  513. this.#handleExit(spawnedChild, error);
  514. },
  515. );
  516. child.stderr.setEncoding('utf8');
  517. child.stderr.on('data', (chunk: string) => {
  518. for (const line of chunk.split(/\r?\n/u).filter(Boolean)) watcher?.noteStderr(line);
  519. });
  520. child.once('error', (error) => watcher?.shutdown(error.message));
  521. child.once('exit', () => watcher?.shutdown('Codex App Server 已退出'));
  522. peer.once('closed', (error) => watcher?.shutdown(asError(error).message));
  523. peer.start();
  524. const initialized = await peer.request<InitializeResponse>('initialize', {
  525. clientInfo: this.#clientInfo,
  526. capabilities: { experimentalApi: true },
  527. });
  528. this.#assertGeneration(generation);
  529. peer.notify('initialized');
  530. this.#runtime = {
  531. ...emptyRuntimeStatus(),
  532. state: 'ready',
  533. binaryPath,
  534. version,
  535. codexHome: initialized.codexHome,
  536. providerId: provider?.id ?? null,
  537. };
  538. return await this.refresh();
  539. } catch (error) {
  540. // 子进程启动即退出的话真话只在 stderr 里:等它落定,别把「协议流已关闭」丢给用户猜
  541. const fallback = asError(error).message;
  542. const message = watcher ? (await watcher.describe(fallback)).message : fallback;
  543. peer?.close(new Error(message));
  544. if (this.#peer === peer) this.#peer = null;
  545. if (this.#child === child) this.#child = null;
  546. if (child && child.exitCode === null) child.kill('SIGTERM');
  547. if (generation === this.#generation) {
  548. this.#runtime = { ...this.#runtime, state: 'error', error: sanitizeDiagnostic(message) };
  549. this.emit('status', this.status);
  550. }
  551. // 换掉原文而不是换掉错误对象:调用方拿到的类型与 stack 不变,只是话变清楚了
  552. if (error instanceof Error) error.message = message;
  553. throw error;
  554. }
  555. }
  556. #request<T>(method: string, params?: unknown): Promise<T> {
  557. if (!this.#peer) throw new Error('Codex App Server 未运行');
  558. return this.#peer.request<T>(method, params);
  559. }
  560. #handleNotification(notification: { method: string; params?: unknown }): void {
  561. const params = asRecord(notification.params);
  562. const turnId = readString(params?.turnId) ?? readString(asRecord(params?.turn)?.id);
  563. if (turnId) {
  564. const waiter = this.#turnWaiters.get(turnId);
  565. if (waiter && notification.method === 'item/agentMessage/delta') {
  566. waiter.text += readString(params?.delta) ?? '';
  567. }
  568. if (waiter && notification.method === 'item/completed') {
  569. const item = asRecord(params?.item);
  570. if (item?.type === 'agentMessage' && typeof item.text === 'string') waiter.text = item.text;
  571. }
  572. if (waiter && notification.method === 'turn/completed') {
  573. clearTimeout(waiter.timer);
  574. this.#turnWaiters.delete(turnId);
  575. const turn = asRecord(params?.turn);
  576. waiter.resolve({
  577. turnId,
  578. status: readString(turn?.status) ?? 'completed',
  579. text: waiter.text,
  580. raw: params,
  581. });
  582. }
  583. if (!waiter && this.#runTurnStartsInFlight > 0) {
  584. const early = this.#earlyTurnStates.get(turnId) ?? { text: '', completed: null };
  585. if (notification.method === 'item/agentMessage/delta') {
  586. early.text += readString(params?.delta) ?? '';
  587. }
  588. if (notification.method === 'item/completed') {
  589. const item = asRecord(params?.item);
  590. if (item?.type === 'agentMessage' && typeof item.text === 'string') early.text = item.text;
  591. }
  592. if (notification.method === 'turn/completed') {
  593. const turn = asRecord(params?.turn);
  594. early.completed = {
  595. turnId,
  596. status: readString(turn?.status) ?? 'completed',
  597. text: early.text,
  598. raw: params,
  599. };
  600. }
  601. this.#earlyTurnStates.set(turnId, early);
  602. }
  603. }
  604. this.emit('notification', notification);
  605. }
  606. #handleExit(child: ChildProcessWithoutNullStreams, error: Error): void {
  607. if (this.#child !== child) return;
  608. this.#peer?.close(error);
  609. this.#peer = null;
  610. this.#child = null;
  611. this.#runtime = {
  612. ...this.#runtime,
  613. state: 'error',
  614. degraded: true,
  615. error: sanitizeDiagnostic(error.message),
  616. };
  617. for (const waiter of this.#turnWaiters.values()) {
  618. clearTimeout(waiter.timer);
  619. waiter.reject(error);
  620. }
  621. this.#turnWaiters.clear();
  622. this.#earlyTurnStates.clear();
  623. this.#runTurnStartsInFlight = 0;
  624. this.emit('status', this.status);
  625. }
  626. #assertGeneration(generation: number): void {
  627. if (generation !== this.#generation) throw new Error('Codex App Server 的启动已被取消');
  628. }
  629. #releaseRunTurnStart(): void {
  630. this.#runTurnStartsInFlight = Math.max(0, this.#runTurnStartsInFlight - 1);
  631. if (this.#runTurnStartsInFlight === 0) this.#earlyTurnStates.clear();
  632. }
  633. }
  634. /** 每个配置项单独一个 -c,避免手写嵌套 inline table */
  635. export function buildArgs(provider: CodexProviderSpec | null): string[] {
  636. const args = ['app-server', '--listen', 'stdio://'];
  637. if (!provider) return args;
  638. args.push('-c', `model_provider=${tomlString(provider.id)}`);
  639. args.push('-c', `model=${tomlString(provider.model)}`);
  640. const prefix = `model_providers.${provider.id}`;
  641. if (provider.name) args.push('-c', `${prefix}.name=${tomlString(provider.name)}`);
  642. if (provider.baseUrl) args.push('-c', `${prefix}.base_url=${tomlString(provider.baseUrl)}`);
  643. // wire_api 只支持 responses:0.155.1 已下线 chat
  644. args.push('-c', `${prefix}.wire_api="responses"`);
  645. args.push('-c', `${prefix}.requires_openai_auth=false`);
  646. if (provider.apiKey) {
  647. args.push('-c', `${prefix}.env_key=${tomlString(provider.envKey ?? DEFAULT_API_KEY_ENV)}`);
  648. }
  649. if (provider.httpHeaders && Object.keys(provider.httpHeaders).length) {
  650. args.push('-c', `${prefix}.http_headers=${tomlInlineTable(provider.httpHeaders)}`);
  651. }
  652. if (provider.envHttpHeaders && Object.keys(provider.envHttpHeaders).length) {
  653. args.push('-c', `${prefix}.env_http_headers=${tomlInlineTable(provider.envHttpHeaders)}`);
  654. }
  655. for (const [key, value] of Object.entries(provider.extra ?? {})) {
  656. if (!PROVIDER_EXTRA_ALLOWLIST.has(key) || value === null || value === undefined) continue;
  657. args.push('-c', `${prefix}.${key}=${tomlValue(value)}`);
  658. }
  659. return args;
  660. }
  661. function buildEnv(codexHome: string, provider: CodexProviderSpec | null): NodeJS.ProcessEnv {
  662. const env: NodeJS.ProcessEnv = {
  663. ...process.env,
  664. CODEX_HOME: codexHome,
  665. RUST_LOG: process.env.RUST_LOG ?? 'warn',
  666. LOG_FORMAT: 'json',
  667. };
  668. // 密钥只存在于子进程环境变量,config.toml 里只写 env_key 名字
  669. if (provider?.apiKey) {
  670. env[provider.envKey ?? DEFAULT_API_KEY_ENV] = provider.apiKey;
  671. }
  672. return env;
  673. }
  674. function tomlString(value: string): string {
  675. return JSON.stringify(value);
  676. }
  677. function tomlInlineTable(value: Record<string, string>): string {
  678. const entries = Object.entries(value).map(([key, item]) => `${tomlKey(key)}=${tomlString(item)}`);
  679. return `{${entries.join(',')}}`;
  680. }
  681. function tomlKey(key: string): string {
  682. return /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key);
  683. }
  684. function tomlValue(value: JsonValue): string {
  685. if (typeof value === 'string') return tomlString(value);
  686. if (typeof value === 'number' || typeof value === 'boolean') return String(value);
  687. if (Array.isArray(value)) {
  688. return `[${value.filter((item) => item !== null).map(tomlValue).join(',')}]`;
  689. }
  690. if (value && typeof value === 'object') {
  691. // TOML inline table 用 `=` 而不是 JSON 的 `:`,不能直接 JSON.stringify
  692. return tomlInlineTable(
  693. Object.fromEntries(
  694. Object.entries(value as Record<string, JsonValue>)
  695. .filter(([, item]) => typeof item === 'string')
  696. .map(([key, item]) => [key, String(item)]),
  697. ),
  698. );
  699. }
  700. return '""';
  701. }
  702. function emptyRuntimeStatus(): RuntimeStatus {
  703. return {
  704. state: 'stopped',
  705. binaryPath: null,
  706. version: null,
  707. codexHome: null,
  708. models: [],
  709. capabilities: emptyCapabilities(),
  710. providerId: null,
  711. defaultModel: null,
  712. degraded: false,
  713. error: null,
  714. };
  715. }
  716. function emptyCapabilities(): RuntimeCapabilities {
  717. return { namespaceTools: false, imageGeneration: false, webSearch: false };
  718. }
  719. function asRecord(value: unknown): Record<string, unknown> | null {
  720. return value && typeof value === 'object' && !Array.isArray(value)
  721. ? (value as Record<string, unknown>)
  722. : null;
  723. }
  724. function readString(value: unknown): string | null {
  725. return typeof value === 'string' ? value : null;
  726. }
  727. /**
  728. * mcpServerStatus/list 的 tools 是「工具名 → 详情」映射,详情结构由 Codex 版本决定。
  729. * 这里只认 name / description,认不出的形态退化成只留 key 名,避免协议一变列表就空掉。
  730. */
  731. export function toToolSummaries(
  732. tools: Record<string, unknown> | null | undefined,
  733. ): Array<{ name: string; description: string }> {
  734. return Object.entries(tools ?? {}).map(([key, value]) => {
  735. const detail = asRecord(value);
  736. return {
  737. name: readString(detail?.name) || key,
  738. description: readString(detail?.description) || '',
  739. };
  740. });
  741. }
  742. function asError(value: unknown): Error {
  743. return value instanceof Error ? value : new Error(String(value));
  744. }
  745. export function sanitizeDiagnostic(value: string): string {
  746. return value
  747. .replace(/sk-[A-Za-z0-9_-]{12,}/gu, 'sk-[redacted]')
  748. .replace(/Bearer\s+[A-Za-z0-9._~-]+/giu, 'Bearer [redacted]')
  749. .slice(0, 4_000);
  750. }
  751. function delay(ms: number): Promise<void> {
  752. return new Promise((resolve) => {
  753. const timer = setTimeout(resolve, ms);
  754. timer.unref();
  755. });
  756. }
  757. /**
  758. * Codex 的致命错误由 anyhow 打成纯文本(`Error: ...`),RUST_LOG 的常规日志是 JSON 行;
  759. * 纯文本里还混着 `WARNING: ...` 这类噪音,所以优先取 Error 行,取不到才退化成第一条纯文本行。
  760. */
  761. function pickFatalLine(tail: string[]): string | null {
  762. const plain = tail
  763. .map((line) => line.trim())
  764. .filter((line) => line && !line.startsWith('{'));
  765. if (!plain.length) return null;
  766. const fatal = plain.find((line) => /^(error|panic)\b/iu.test(line) || line.includes('panicked at'));
  767. return sanitizeDiagnostic((fatal ?? plain[0]).slice(0, 500));
  768. }
  769. interface ExitWatcher {
  770. /** 收 stderr:既实时推诊断,也留尾部若干行用于拼退出原因 */
  771. noteStderr(line: string): void;
  772. /** 统一退出出口(流关闭 / 进程退出 / spawn 失败),只生效一次 */
  773. shutdown(fallback: string): void;
  774. /** 等 stderr 收完,把没有信息量的 fallback 换成带 exit code 与原因原文的错误 */
  775. describe(fallback: string): Promise<Error>;
  776. }
  777. function createExitWatcher(
  778. child: ChildProcessWithoutNullStreams,
  779. onDiagnostic: (line: string) => void,
  780. onExit: (error: Error) => void,
  781. ): ExitWatcher {
  782. const tail: string[] = [];
  783. const closed = new Promise<void>((resolve) => child.once('close', () => resolve()));
  784. let shuttingDown = false;
  785. const describe = async (fallback: string): Promise<Error> => {
  786. // 等不到 close 也得往下走:一次卡住的退出不能把启动的 Promise 挂在那里
  787. await Promise.race([closed, delay(EXIT_GRACE_MS)]);
  788. const code = child.exitCode ?? child.signalCode;
  789. const reason = code === null || code === undefined ? fallback : `Codex App Server 退出(${code})`;
  790. const detail = pickFatalLine(tail);
  791. return new Error(detail ? `${reason}:${detail}` : reason);
  792. };
  793. return {
  794. noteStderr(line: string): void {
  795. tail.push(line);
  796. if (tail.length > STDERR_TAIL_LINES) tail.shift();
  797. onDiagnostic(line);
  798. },
  799. describe,
  800. shutdown(fallback: string): void {
  801. if (shuttingDown) return;
  802. shuttingDown = true;
  803. void describe(fallback).then((error) => {
  804. // 流都关了进程还活着(卡死的子进程)只能自己收
  805. if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');
  806. onExit(error);
  807. });
  808. },
  809. };
  810. }