codexRuntime.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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. }
  46. export interface CodexSkillSummary {
  47. name: string;
  48. description: string;
  49. path: string;
  50. scope: 'user' | 'repo' | 'system' | 'admin' | string;
  51. enabled: boolean;
  52. cwd: string;
  53. }
  54. /** 一次 spawn 用的模型来源。id 为 null 表示使用 Codex 内置 provider(ollama / lmstudio) */
  55. export interface CodexProviderSpec {
  56. id: string | null;
  57. name?: string | null;
  58. baseUrl?: string | null;
  59. model: string;
  60. /** 内置 provider id,例如 'ollama';给了就不再写 model_providers 段 */
  61. builtinProvider?: string | null;
  62. /** apiKey 只注入子进程环境变量,不落任何盘 */
  63. apiKey?: string | null;
  64. envKey?: string;
  65. httpHeaders?: Record<string, string> | null;
  66. envHttpHeaders?: Record<string, string> | null;
  67. /** 仅放行 request_max_retries / stream_max_retries / stream_idle_timeout_ms / query_params */
  68. extra?: Record<string, JsonValue> | null;
  69. }
  70. export interface CodexRuntimeOptions {
  71. codexHome: string;
  72. provider?: CodexProviderSpec | null;
  73. clientInfo?: { name: string; title: string; version: string };
  74. }
  75. export interface StartThreadOptions {
  76. cwd: string;
  77. model?: string | null;
  78. sandbox?: 'read-only' | 'workspace-write' | 'danger-full-access';
  79. approvalPolicy?: 'untrusted' | 'on-request' | 'never';
  80. developerInstructions?: string;
  81. ephemeral?: boolean;
  82. }
  83. export interface StartTurnOptions {
  84. threadId: string;
  85. prompt: string;
  86. cwd?: string;
  87. model?: string | null;
  88. effort?: string | null;
  89. approvalPolicy?: 'untrusted' | 'on-request' | 'never';
  90. skills?: Array<{ name: string; path: string }>;
  91. /** 仅宿主侧的完成期限,不会发给 App Server */
  92. timeoutMs?: number;
  93. }
  94. export interface TurnResult {
  95. turnId: string;
  96. status: string;
  97. text: string;
  98. raw: unknown;
  99. }
  100. interface SkillsListResponse {
  101. data: Array<{
  102. cwd: string;
  103. skills: Array<{
  104. name: string;
  105. description: string;
  106. path: string;
  107. scope: string;
  108. enabled: boolean;
  109. }>;
  110. }>;
  111. }
  112. interface ListMcpServerStatusResponse {
  113. data: Array<{
  114. name: string;
  115. serverInfo: unknown | null;
  116. tools: Record<string, unknown>;
  117. authStatus: string;
  118. }>;
  119. nextCursor: string | null;
  120. }
  121. interface InitializeResponse {
  122. userAgent: string;
  123. codexHome: string;
  124. platformFamily: string;
  125. platformOs: string;
  126. }
  127. interface ModelListResponse {
  128. data: Array<{
  129. id: string;
  130. model: string;
  131. displayName: string;
  132. description: string;
  133. isDefault: boolean;
  134. defaultReasoningEffort: string;
  135. supportedReasoningEfforts: Array<{ reasoningEffort: string }>;
  136. }>;
  137. nextCursor: string | null;
  138. }
  139. interface ModelProviderCapabilitiesResponse {
  140. namespaceTools: boolean;
  141. imageGeneration: boolean;
  142. webSearch: boolean;
  143. }
  144. interface ThreadResponse {
  145. thread: { id: string };
  146. model: string;
  147. }
  148. interface TurnStartResponse {
  149. turn: { id: string; status: string };
  150. }
  151. interface EarlyTurnState {
  152. text: string;
  153. completed: TurnResult | null;
  154. }
  155. interface TurnWaiter {
  156. text: string;
  157. resolve(result: TurnResult): void;
  158. reject(error: Error): void;
  159. timer: NodeJS.Timeout;
  160. }
  161. const TURN_TIMEOUT_MS = 20 * 60 * 1_000;
  162. export const DEFAULT_API_KEY_ENV = 'ZSJZ_CODEX_API_KEY';
  163. const PROVIDER_EXTRA_ALLOWLIST = new Set([
  164. 'request_max_retries',
  165. 'stream_max_retries',
  166. 'stream_idle_timeout_ms',
  167. 'query_params',
  168. ]);
  169. export class CodexRuntime extends EventEmitter {
  170. readonly #codexHome: string;
  171. readonly #clientInfo: { name: string; title: string; version: string };
  172. #provider: CodexProviderSpec | null;
  173. #child: ChildProcessWithoutNullStreams | null = null;
  174. #peer: JsonRpcPeer | null = null;
  175. #startPromise: Promise<RuntimeStatus> | null = null;
  176. #runtime: RuntimeStatus = emptyRuntimeStatus();
  177. #turnWaiters = new Map<string, TurnWaiter>();
  178. #earlyTurnStates = new Map<string, EarlyTurnState>();
  179. #runTurnStartsInFlight = 0;
  180. #generation = 0;
  181. constructor(options: CodexRuntimeOptions) {
  182. super();
  183. this.#codexHome = options.codexHome;
  184. this.#provider = options.provider ?? null;
  185. this.#clientInfo = options.clientInfo ?? {
  186. name: 'zsjz_ai',
  187. title: '清鉴线索调查工具',
  188. version: '0.1.0',
  189. };
  190. }
  191. get status(): RuntimeStatus {
  192. return structuredClone(this.#runtime);
  193. }
  194. get provider(): CodexProviderSpec | null {
  195. return this.#provider ? { ...this.#provider, apiKey: null } : null;
  196. }
  197. /** 换 provider 必须重启子进程:api_key 走的是子进程环境变量,无法热更新 */
  198. async applyProvider(provider: CodexProviderSpec | null): Promise<RuntimeStatus> {
  199. this.#provider = provider;
  200. if (this.#child) await this.stop();
  201. return this.start();
  202. }
  203. async start(): Promise<RuntimeStatus> {
  204. if (this.#runtime.state === 'ready' && this.#peer) return this.status;
  205. if (this.#startPromise) return this.#startPromise;
  206. const generation = ++this.#generation;
  207. this.#startPromise = this.#start(generation);
  208. try {
  209. return await this.#startPromise;
  210. } finally {
  211. this.#startPromise = null;
  212. }
  213. }
  214. async refresh(): Promise<RuntimeStatus> {
  215. await this.start();
  216. let models: ModelOption[] = [];
  217. let degraded = false;
  218. try {
  219. models = await this.listModels();
  220. } catch (error) {
  221. // 第三方/本地端点常常不实现 model/list,这里降级而不是失败
  222. degraded = true;
  223. this.emit('diagnostic', `model/list 不可用:${asError(error).message}`);
  224. }
  225. const capabilities = await this.readModelProviderCapabilities().catch(() => emptyCapabilities());
  226. this.#runtime = {
  227. ...this.#runtime,
  228. models,
  229. capabilities,
  230. degraded: degraded || models.length === 0,
  231. // model/list 返回的是 Codex 内置模型目录(与自定义 provider 无关),
  232. // 实际会用的是 provider 里配置的模型,所以它优先
  233. defaultModel: this.#provider?.model ?? models.find((item) => item.isDefault)?.model ?? null,
  234. state: 'ready',
  235. error: null,
  236. };
  237. this.emit('status', this.status);
  238. return this.status;
  239. }
  240. async readModelProviderCapabilities(): Promise<RuntimeCapabilities> {
  241. const result = await this.#request<ModelProviderCapabilitiesResponse>(
  242. 'modelProvider/capabilities/read',
  243. {},
  244. );
  245. return {
  246. namespaceTools: result.namespaceTools === true,
  247. imageGeneration: result.imageGeneration === true,
  248. webSearch: result.webSearch === true,
  249. };
  250. }
  251. async listModels(): Promise<ModelOption[]> {
  252. const models: ModelOption[] = [];
  253. let cursor: string | null = null;
  254. for (let page = 0; page < 10; page += 1) {
  255. const result: ModelListResponse = await this.#request<ModelListResponse>('model/list', {
  256. cursor,
  257. limit: 100,
  258. includeHidden: false,
  259. });
  260. models.push(
  261. ...result.data.map((model) => ({
  262. id: model.id,
  263. model: model.model,
  264. displayName: model.displayName,
  265. description: model.description,
  266. isDefault: model.isDefault,
  267. defaultEffort: model.defaultReasoningEffort,
  268. efforts: model.supportedReasoningEfforts.map((item) => item.reasoningEffort),
  269. })),
  270. );
  271. cursor = result.nextCursor;
  272. if (!cursor) break;
  273. }
  274. return models;
  275. }
  276. async listSkills(options: { cwds?: string[]; forceReload?: boolean } = {}): Promise<CodexSkillSummary[]> {
  277. await this.start();
  278. const result = await this.#request<SkillsListResponse>('skills/list', {
  279. ...(options.cwds?.length ? { cwds: options.cwds } : {}),
  280. forceReload: options.forceReload ?? false,
  281. });
  282. return result.data.flatMap((entry) =>
  283. entry.skills.map((skill) => ({
  284. name: skill.name,
  285. description: skill.description,
  286. path: skill.path,
  287. scope: skill.scope,
  288. enabled: skill.enabled,
  289. cwd: entry.cwd,
  290. })),
  291. );
  292. }
  293. async setSkillEnabled(selector: { path?: string; name?: string }, enabled: boolean): Promise<boolean> {
  294. await this.start();
  295. const result = await this.#request<{ effectiveEnabled: boolean }>('skills/config/write', {
  296. ...(selector.path ? { path: selector.path } : {}),
  297. ...(!selector.path && selector.name ? { name: selector.name } : {}),
  298. enabled,
  299. });
  300. return result.effectiveEnabled;
  301. }
  302. async listMcpServerStatuses(): Promise<CodexMcpServerStatus[]> {
  303. await this.start();
  304. const statuses: CodexMcpServerStatus[] = [];
  305. let cursor: string | null = null;
  306. for (let page = 0; page < 20; page += 1) {
  307. const result: ListMcpServerStatusResponse = await this.#request<ListMcpServerStatusResponse>(
  308. 'mcpServerStatus/list',
  309. {
  310. cursor,
  311. limit: 100,
  312. detail: 'toolsAndAuthOnly',
  313. },
  314. );
  315. statuses.push(
  316. ...result.data.map((server) => ({
  317. name: server.name,
  318. authStatus: server.authStatus,
  319. connected: server.serverInfo !== null,
  320. toolCount: Object.keys(server.tools ?? {}).length,
  321. })),
  322. );
  323. cursor = result.nextCursor;
  324. if (!cursor) break;
  325. }
  326. return statuses;
  327. }
  328. async readConfig(): Promise<Record<string, unknown>> {
  329. await this.start();
  330. const result = await this.#request<{ config: Record<string, unknown> }>('config/read', {
  331. includeLayers: false,
  332. });
  333. return structuredClone(result.config);
  334. }
  335. /** 局部写:Codex 自己也持有 config.toml 写权,禁止整文件覆盖 */
  336. async writeConfigValue(keyPath: string, value: JsonValue): Promise<void> {
  337. await this.start();
  338. await this.#request<unknown>('config/value/write', { keyPath, value, mergeStrategy: 'replace' });
  339. }
  340. async reloadMcpServers(): Promise<void> {
  341. await this.start();
  342. await this.#request<unknown>('config/mcpServer/reload');
  343. }
  344. async startThread(options: StartThreadOptions): Promise<string> {
  345. await this.start();
  346. const result = await this.#request<ThreadResponse>('thread/start', {
  347. cwd: options.cwd,
  348. ...(options.model ? { model: options.model } : {}),
  349. sandbox: options.sandbox ?? 'workspace-write',
  350. approvalPolicy: options.approvalPolicy ?? 'never',
  351. ...(options.developerInstructions ? { developerInstructions: options.developerInstructions } : {}),
  352. ...(options.ephemeral === undefined ? {} : { ephemeral: options.ephemeral }),
  353. experimentalRawEvents: false,
  354. });
  355. return result.thread.id;
  356. }
  357. async resumeThread(threadId: string, options: StartThreadOptions): Promise<string> {
  358. await this.start();
  359. const result = await this.#request<ThreadResponse>('thread/resume', {
  360. threadId,
  361. cwd: options.cwd,
  362. ...(options.model ? { model: options.model } : {}),
  363. sandbox: options.sandbox ?? 'workspace-write',
  364. approvalPolicy: options.approvalPolicy ?? 'never',
  365. ...(options.developerInstructions ? { developerInstructions: options.developerInstructions } : {}),
  366. excludeTurns: true,
  367. });
  368. return result.thread.id;
  369. }
  370. async startTurn(options: StartTurnOptions): Promise<string> {
  371. await this.start();
  372. const result = await this.#request<TurnStartResponse>('turn/start', {
  373. threadId: options.threadId,
  374. input: [
  375. { type: 'text', text: options.prompt, text_elements: [] },
  376. ...(options.skills ?? []).map((skill) => ({
  377. type: 'skill' as const,
  378. name: skill.name,
  379. path: skill.path,
  380. })),
  381. ],
  382. ...(options.cwd ? { cwd: options.cwd } : {}),
  383. ...(options.model ? { model: options.model } : {}),
  384. ...(options.effort ? { effort: options.effort } : {}),
  385. ...(options.approvalPolicy ? { approvalPolicy: options.approvalPolicy } : {}),
  386. });
  387. return result.turn.id;
  388. }
  389. async runTurn(options: StartTurnOptions): Promise<TurnResult> {
  390. this.#runTurnStartsInFlight += 1;
  391. let turnId: string;
  392. try {
  393. turnId = await this.startTurn(options);
  394. } catch (error) {
  395. this.#releaseRunTurnStart();
  396. throw error;
  397. }
  398. // turn/completed 可能早于 turn/start 的响应回来,先存起来
  399. const early = this.#earlyTurnStates.get(turnId);
  400. this.#earlyTurnStates.delete(turnId);
  401. if (early?.completed) {
  402. this.#releaseRunTurnStart();
  403. return early.completed;
  404. }
  405. return new Promise<TurnResult>((resolve, reject) => {
  406. const timeoutMs =
  407. options.timeoutMs === undefined
  408. ? TURN_TIMEOUT_MS
  409. : Math.min(TURN_TIMEOUT_MS, Math.max(1_000, Math.trunc(options.timeoutMs)));
  410. const timer = setTimeout(() => {
  411. this.#turnWaiters.delete(turnId);
  412. void this.interruptTurn(options.threadId, turnId).catch(() => undefined);
  413. reject(new Error(`Codex turn ${turnId} 超时`));
  414. }, timeoutMs);
  415. timer.unref();
  416. this.#turnWaiters.set(turnId, { text: early?.text ?? '', resolve, reject, timer });
  417. this.#releaseRunTurnStart();
  418. });
  419. }
  420. async interruptTurn(threadId: string, turnId: string): Promise<void> {
  421. await this.#request<Record<string, never>>('turn/interrupt', { threadId, turnId });
  422. }
  423. async unsubscribeThread(threadId: string): Promise<void> {
  424. await this.#request<{ status: string }>('thread/unsubscribe', { threadId });
  425. }
  426. respondToServerRequest(requestId: string | number, result: unknown): void {
  427. if (!this.#peer) throw new Error('Codex App Server 未运行');
  428. this.#peer.respond(requestId, result);
  429. }
  430. rejectServerRequest(requestId: string | number, code: number, message: string): void {
  431. if (!this.#peer) throw new Error('Codex App Server 未运行');
  432. this.#peer.respondError(requestId, { code, message });
  433. }
  434. async stop(): Promise<void> {
  435. this.#generation += 1;
  436. const child = this.#child;
  437. const peer = this.#peer;
  438. this.#child = null;
  439. this.#peer = null;
  440. for (const waiter of this.#turnWaiters.values()) {
  441. clearTimeout(waiter.timer);
  442. waiter.reject(new Error('Codex App Server 在本轮对话进行中被停止'));
  443. }
  444. this.#turnWaiters.clear();
  445. this.#earlyTurnStates.clear();
  446. this.#runTurnStartsInFlight = 0;
  447. if (child && child.exitCode === null) {
  448. peer?.endOutput();
  449. await Promise.race([
  450. new Promise<void>((resolve) => child.once('exit', () => resolve())),
  451. new Promise<void>((resolve) => setTimeout(resolve, 1_500)),
  452. ]);
  453. if (child.exitCode === null) {
  454. child.kill('SIGTERM');
  455. await Promise.race([
  456. new Promise<void>((resolve) => child.once('exit', () => resolve())),
  457. new Promise<void>((resolve) => setTimeout(resolve, 1_000)),
  458. ]);
  459. }
  460. if (child.exitCode === null) child.kill('SIGKILL');
  461. }
  462. peer?.close(new Error('Codex App Server 已停止'));
  463. this.#runtime = { ...emptyRuntimeStatus(), providerId: this.#provider?.id ?? null };
  464. this.emit('status', this.status);
  465. }
  466. async dispose(): Promise<void> {
  467. await this.stop();
  468. this.removeAllListeners();
  469. }
  470. async #start(generation: number): Promise<RuntimeStatus> {
  471. this.#runtime = { ...emptyRuntimeStatus(), state: 'starting', providerId: this.#provider?.id ?? null };
  472. this.emit('status', this.status);
  473. let child: ChildProcessWithoutNullStreams | null = null;
  474. let peer: JsonRpcPeer | null = null;
  475. try {
  476. const binaryPath = await locateCodexBinary();
  477. this.#assertGeneration(generation);
  478. const version = readCodexVersion(binaryPath);
  479. this.#assertGeneration(generation);
  480. const provider = this.#provider;
  481. child = spawn(binaryPath, buildArgs(provider), {
  482. cwd: process.cwd(),
  483. env: buildEnv(this.#codexHome, provider),
  484. stdio: ['pipe', 'pipe', 'pipe'],
  485. windowsHide: true,
  486. });
  487. this.#child = child;
  488. peer = new JsonRpcPeer(child.stdout, child.stdin);
  489. this.#peer = peer;
  490. peer.on('notification', (notification) => this.#handleNotification(notification));
  491. peer.on('serverRequest', (request: JsonRpcServerRequest) => this.emit('serverRequest', request));
  492. peer.on('protocolError', (error) => this.emit('diagnostic', asError(error).message));
  493. peer.once('closed', (error) => {
  494. if (this.#peer !== peer || this.#child !== child) return;
  495. if (child?.exitCode === null) child.kill('SIGTERM');
  496. this.#handleExit(child!, asError(error));
  497. });
  498. peer.start();
  499. child.stderr.setEncoding('utf8');
  500. child.stderr.on('data', (chunk: string) => {
  501. for (const line of chunk.split(/\r?\n/u).filter(Boolean)) {
  502. this.emit('diagnostic', sanitizeDiagnostic(line));
  503. }
  504. });
  505. child.once('error', (error) => this.#handleExit(child!, error));
  506. child.once('exit', (code, signal) => {
  507. this.#handleExit(child!, new Error(`Codex App Server 退出(${code ?? signal ?? 'unknown'})`));
  508. });
  509. const initialized = await peer.request<InitializeResponse>('initialize', {
  510. clientInfo: this.#clientInfo,
  511. capabilities: { experimentalApi: true },
  512. });
  513. this.#assertGeneration(generation);
  514. peer.notify('initialized');
  515. this.#runtime = {
  516. ...emptyRuntimeStatus(),
  517. state: 'ready',
  518. binaryPath,
  519. version,
  520. codexHome: initialized.codexHome,
  521. providerId: provider?.id ?? provider?.builtinProvider ?? null,
  522. };
  523. return await this.refresh();
  524. } catch (error) {
  525. const message = asError(error).message;
  526. peer?.close(asError(error));
  527. if (this.#peer === peer) this.#peer = null;
  528. if (this.#child === child) this.#child = null;
  529. if (child && child.exitCode === null) child.kill('SIGTERM');
  530. if (generation === this.#generation) {
  531. this.#runtime = { ...this.#runtime, state: 'error', error: sanitizeDiagnostic(message) };
  532. this.emit('status', this.status);
  533. }
  534. throw error;
  535. }
  536. }
  537. #request<T>(method: string, params?: unknown): Promise<T> {
  538. if (!this.#peer) throw new Error('Codex App Server 未运行');
  539. return this.#peer.request<T>(method, params);
  540. }
  541. #handleNotification(notification: { method: string; params?: unknown }): void {
  542. const params = asRecord(notification.params);
  543. const turnId = readString(params?.turnId) ?? readString(asRecord(params?.turn)?.id);
  544. if (turnId) {
  545. const waiter = this.#turnWaiters.get(turnId);
  546. if (waiter && notification.method === 'item/agentMessage/delta') {
  547. waiter.text += readString(params?.delta) ?? '';
  548. }
  549. if (waiter && notification.method === 'item/completed') {
  550. const item = asRecord(params?.item);
  551. if (item?.type === 'agentMessage' && typeof item.text === 'string') waiter.text = item.text;
  552. }
  553. if (waiter && notification.method === 'turn/completed') {
  554. clearTimeout(waiter.timer);
  555. this.#turnWaiters.delete(turnId);
  556. const turn = asRecord(params?.turn);
  557. waiter.resolve({
  558. turnId,
  559. status: readString(turn?.status) ?? 'completed',
  560. text: waiter.text,
  561. raw: params,
  562. });
  563. }
  564. if (!waiter && this.#runTurnStartsInFlight > 0) {
  565. const early = this.#earlyTurnStates.get(turnId) ?? { text: '', completed: null };
  566. if (notification.method === 'item/agentMessage/delta') {
  567. early.text += readString(params?.delta) ?? '';
  568. }
  569. if (notification.method === 'item/completed') {
  570. const item = asRecord(params?.item);
  571. if (item?.type === 'agentMessage' && typeof item.text === 'string') early.text = item.text;
  572. }
  573. if (notification.method === 'turn/completed') {
  574. const turn = asRecord(params?.turn);
  575. early.completed = {
  576. turnId,
  577. status: readString(turn?.status) ?? 'completed',
  578. text: early.text,
  579. raw: params,
  580. };
  581. }
  582. this.#earlyTurnStates.set(turnId, early);
  583. }
  584. }
  585. this.emit('notification', notification);
  586. }
  587. #handleExit(child: ChildProcessWithoutNullStreams, error: Error): void {
  588. if (this.#child !== child) return;
  589. this.#peer?.close(error);
  590. this.#peer = null;
  591. this.#child = null;
  592. this.#runtime = {
  593. ...this.#runtime,
  594. state: 'error',
  595. degraded: true,
  596. error: sanitizeDiagnostic(error.message),
  597. };
  598. for (const waiter of this.#turnWaiters.values()) {
  599. clearTimeout(waiter.timer);
  600. waiter.reject(error);
  601. }
  602. this.#turnWaiters.clear();
  603. this.#earlyTurnStates.clear();
  604. this.#runTurnStartsInFlight = 0;
  605. this.emit('status', this.status);
  606. }
  607. #assertGeneration(generation: number): void {
  608. if (generation !== this.#generation) throw new Error('Codex App Server 的启动已被取消');
  609. }
  610. #releaseRunTurnStart(): void {
  611. this.#runTurnStartsInFlight = Math.max(0, this.#runTurnStartsInFlight - 1);
  612. if (this.#runTurnStartsInFlight === 0) this.#earlyTurnStates.clear();
  613. }
  614. }
  615. /** 每个配置项单独一个 -c,避免手写嵌套 inline table */
  616. export function buildArgs(provider: CodexProviderSpec | null): string[] {
  617. const args = ['app-server', '--listen', 'stdio://'];
  618. if (!provider) return args;
  619. const providerKey = provider.builtinProvider ?? provider.id;
  620. if (!providerKey) return args;
  621. args.push('-c', `model_provider=${tomlString(providerKey)}`);
  622. args.push('-c', `model=${tomlString(provider.model)}`);
  623. if (provider.builtinProvider) {
  624. // 内置 provider 只允许覆盖 base_url,其余字段由 Codex 自己决定;
  625. // 不覆盖就会打到 localhost:11434,远端 Ollama / LM Studio 连不上
  626. if (provider.baseUrl) {
  627. args.push('-c', `model_providers.${provider.builtinProvider}.base_url=${tomlString(provider.baseUrl)}`);
  628. }
  629. return args;
  630. }
  631. const prefix = `model_providers.${provider.id}`;
  632. if (provider.name) args.push('-c', `${prefix}.name=${tomlString(provider.name)}`);
  633. if (provider.baseUrl) args.push('-c', `${prefix}.base_url=${tomlString(provider.baseUrl)}`);
  634. // wire_api 只支持 responses:0.155.1 已下线 chat
  635. args.push('-c', `${prefix}.wire_api="responses"`);
  636. args.push('-c', `${prefix}.requires_openai_auth=false`);
  637. if (provider.apiKey) {
  638. args.push('-c', `${prefix}.env_key=${tomlString(provider.envKey ?? DEFAULT_API_KEY_ENV)}`);
  639. }
  640. if (provider.httpHeaders && Object.keys(provider.httpHeaders).length) {
  641. args.push('-c', `${prefix}.http_headers=${tomlInlineTable(provider.httpHeaders)}`);
  642. }
  643. if (provider.envHttpHeaders && Object.keys(provider.envHttpHeaders).length) {
  644. args.push('-c', `${prefix}.env_http_headers=${tomlInlineTable(provider.envHttpHeaders)}`);
  645. }
  646. for (const [key, value] of Object.entries(provider.extra ?? {})) {
  647. if (!PROVIDER_EXTRA_ALLOWLIST.has(key) || value === null || value === undefined) continue;
  648. args.push('-c', `${prefix}.${key}=${tomlValue(value)}`);
  649. }
  650. return args;
  651. }
  652. function buildEnv(codexHome: string, provider: CodexProviderSpec | null): NodeJS.ProcessEnv {
  653. const env: NodeJS.ProcessEnv = {
  654. ...process.env,
  655. CODEX_HOME: codexHome,
  656. RUST_LOG: process.env.RUST_LOG ?? 'warn',
  657. LOG_FORMAT: 'json',
  658. };
  659. // 密钥只存在于子进程环境变量,config.toml 里只写 env_key 名字
  660. if (provider?.apiKey && !provider.builtinProvider) {
  661. env[provider.envKey ?? DEFAULT_API_KEY_ENV] = provider.apiKey;
  662. }
  663. return env;
  664. }
  665. function tomlString(value: string): string {
  666. return JSON.stringify(value);
  667. }
  668. function tomlInlineTable(value: Record<string, string>): string {
  669. const entries = Object.entries(value).map(([key, item]) => `${tomlKey(key)}=${tomlString(item)}`);
  670. return `{${entries.join(',')}}`;
  671. }
  672. function tomlKey(key: string): string {
  673. return /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key);
  674. }
  675. function tomlValue(value: JsonValue): string {
  676. if (typeof value === 'string') return tomlString(value);
  677. if (typeof value === 'number' || typeof value === 'boolean') return String(value);
  678. if (Array.isArray(value)) {
  679. return `[${value.filter((item) => item !== null).map(tomlValue).join(',')}]`;
  680. }
  681. if (value && typeof value === 'object') {
  682. // TOML inline table 用 `=` 而不是 JSON 的 `:`,不能直接 JSON.stringify
  683. return tomlInlineTable(
  684. Object.fromEntries(
  685. Object.entries(value as Record<string, JsonValue>)
  686. .filter(([, item]) => typeof item === 'string')
  687. .map(([key, item]) => [key, String(item)]),
  688. ),
  689. );
  690. }
  691. return '""';
  692. }
  693. function emptyRuntimeStatus(): RuntimeStatus {
  694. return {
  695. state: 'stopped',
  696. binaryPath: null,
  697. version: null,
  698. codexHome: null,
  699. models: [],
  700. capabilities: emptyCapabilities(),
  701. providerId: null,
  702. defaultModel: null,
  703. degraded: false,
  704. error: null,
  705. };
  706. }
  707. function emptyCapabilities(): RuntimeCapabilities {
  708. return { namespaceTools: false, imageGeneration: false, webSearch: false };
  709. }
  710. function asRecord(value: unknown): Record<string, unknown> | null {
  711. return value && typeof value === 'object' && !Array.isArray(value)
  712. ? (value as Record<string, unknown>)
  713. : null;
  714. }
  715. function readString(value: unknown): string | null {
  716. return typeof value === 'string' ? value : null;
  717. }
  718. function asError(value: unknown): Error {
  719. return value instanceof Error ? value : new Error(String(value));
  720. }
  721. export function sanitizeDiagnostic(value: string): string {
  722. return value
  723. .replace(/sk-[A-Za-z0-9_-]{12,}/gu, 'sk-[redacted]')
  724. .replace(/Bearer\s+[A-Za-z0-9._~-]+/giu, 'Bearer [redacted]')
  725. .slice(0, 4_000);
  726. }