-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodex-app-server-runtime.ts
More file actions
4012 lines (3881 loc) · 134 KB
/
Copy pathcodex-app-server-runtime.ts
File metadata and controls
4012 lines (3881 loc) · 134 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
summarizeCodexAppServerDebugMessage,
extractCodexAppServerErrorMessage,
} from "./codex-app-server-errors";
export { summarizeCodexAppServerDebugMessage } from "./codex-app-server-errors";
import { CodexClientLifetime } from "./codex-thread-lifetime";
import {
buildCodexCompactionCompletedEvent,
compactCodexThreadWithClient,
} from "./codex-compaction";
import { requireCompactResumeSession } from "../../src/lib/providers/native-compaction";
import type {
BridgeEvent,
ProviderResponderResult,
ProviderSteerResponder,
StreamTurnArgs,
} from "./types";
import type {
ConnectedToolId,
ConnectedToolStatusResponse,
} from "../../src/lib/providers/connected-tool-status";
import type {
CodexAppServerSnapshot,
CodexAppServerSnapshotResponse,
CodexExternalAgentConfigMigrationItem,
CodexModelCatalogResponse,
CodexMutationResponse,
CodexPluginDetailResponse,
CodexPluginInstallResponse,
CodexPluginMarketplaceSnapshot,
CodexReviewStartResponse,
CodexThreadForkResponse,
CodexThreadReadResponse,
} from "../../src/lib/providers/provider.types";
import {
buildCodexCliEnv,
resolveCodexCliExecutablePath,
} from "./cli-path-env";
import {
resolveCodexChatgptAuthTokensRefreshResponse,
type CodexAccountReadResponse,
type CodexChatgptAuthTokensRefreshParams,
type CodexGetAuthStatusResponse,
} from "./codex-chatgpt-auth-tokens";
export { resolveCodexChatgptAuthTokensRefreshResponse };
import { describeJsonRpcLinePrefix } from "../shared/json-rpc-line";
import { stripReservedSecretEnvNames } from "../../src/lib/secrets/secrets";
import { mapCodexUserInputQuestions } from "./codex-user-input-mapping";
import { createTurnDiffTracker } from "./turn-diff-tracker";
import { toText } from "./utils";
import {
getProviderNativeSlashCommandInput,
resolveProviderResumeSessionId,
} from "../../src/lib/providers/provider-request-translators";
import {
buildIntentGuardPrompt,
buildReviewDiffPrompt,
parseReviewFindings,
PRE_PR_REVIEW_OUTPUT_SCHEMA,
type PrePrReviewFinding,
} from "../../src/lib/source-control-review";
import { parsePullRequestSuggestionResponse } from "../../src/lib/source-control-pr";
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import path from "node:path";
import {
appendBoundedText,
createBoundedBridgeEventCollector,
measureBridgeEventBytes,
truncateBufferedText,
} from "./provider-buffering";
import { byteLengthUtf8 } from "../shared/bounded-text";
import { Utf8LineBuffer } from "../shared/utf8-line-buffer";
import { normalizeConnectedToolIds } from "../../src/lib/providers/connected-tool-status";
import {
createCodexConnectedToolStatusEntry,
mapCodexMcpServerStatus,
type CodexMcpServerStatus,
} from "./codex-app-server-mcp-status";
import { readPrimaryStaveLocalMcpManifest } from "../main/stave-local-mcp-manifest";
import { resolveBoundSecretEnv } from "../main/browser/secret-service";
import {
buildCodexThreadKey,
resolveCodexWorkerProfile,
} from "./codex-runtime-config";
import {
buildWorkerExecutionMetadata,
type WorkerExecutionMetadata,
} from "../../src/lib/providers/worker-mode";
import {
getCodexMcpConfigPathGroups,
McpConfigRefreshTracker,
} from "./mcp-config-refresh";
import {
registerPendingCodexAppServerResponse,
rejectAllPendingCodexAppServerResponses,
takePendingCodexAppServerResponse,
type PendingCodexAppServerResponse,
} from "./codex-app-server-pending-request";
import {
buildCodexTurnSteerParams,
CODEX_STEER_REQUEST_TIMEOUT_MS,
} from "./codex-app-server-steer";
import { mapCodexThreadForkResponse } from "./codex-thread-actions";
import { isRecord } from "./codex-app-server-json";
import { DEFAULT_READ_ONLY_PROMPT_LABEL } from "./read-only-prompt-labels";
import {
buildCodexTerminalFailureEvents,
resolveCodexTurnCompletionStopReason,
toCodexUserFacingErrorMessage,
toErrorMessage,
} from "./codex-app-server-errors";
import {
runCodexReadOnlyPromptWithClient,
type CodexReadOnlyPromptArgs,
type CodexReadOnlyPromptResult,
} from "./codex-read-only-prompt";
import { resolveGitHeadRef } from "./git-head-ref";
import {
buildCodexGoalStatusEvent,
normalizeCodexThreadGoal,
readCodexGoalStatusEvent,
runCodexCompactSlashCommand,
runCodexGoalSlashCommand,
} from "./codex-goal-commands";
import {
recordCodexRateLimits,
requestCodexRateLimitBuckets,
} from "./codex-rate-limits-cache";
import {
mapCodexConfigSnapshot,
mapCodexHookCatalogGroups,
mapCodexMcpStatusSnapshot,
mapCodexModelCatalogEntry,
mapCodexPluginDetail,
mapCodexPluginSummary,
mapCodexRateLimitBuckets,
mapCodexSkillCatalogGroups,
mapCodexThreadSnapshot,
} from "./codex-snapshot-mappers";
import {
coerceElicitationAnswer,
mapCodexElicitationToApproval,
mapCodexElicitationToUserInput,
shouldAutoApproveStaveLocalMcpElicitation,
type ElicitationFieldDescriptor,
} from "./codex-elicitation-mapping";
import {
buildBoundSecretFingerprint,
buildCodexSecondaryServerRequestDenial,
buildCodexThreadResumeParams,
buildCodexThreadStartParams,
buildCodexTurnStartParams,
buildSecretShellOverrides,
deleteCodexSecondaryThread,
resolveCodexSecondaryConfigOverrides,
resolveCodexSecondaryRuntimeOptions,
type CodexConfigOverrides,
} from "./codex-app-server-params";
import { mergeCodexTurnConfigOverrides } from "./codex-app-server-config-overrides";
import { parsePositiveIntEnv } from "./runtime-shared";
import { createCodexMcpManagement } from "./codex-mcp-management";
import {
downgradeUnsupportedCodexRuntimeOptions,
getCodexVersionCapabilities,
} from "./codex-runtime-capabilities";
import { mapCodexHookNotificationToBridgeEvent } from "./codex-hook-mapping";
import {
buildCodexFileChangeToolEvent,
emitCodexFileChangeEvents,
} from "./codex-file-change-mapping";
import { createCodexAppServerElicitationPauseController } from "./codex-elicitation-pause";
import { createCodexWorkerActivityMapper } from "./codex-worker-activity";
import {
parseProviderBrowserDomains,
shouldActivateProviderBrowser,
} from "../../src/lib/provider-browser";
import {
buildCodexNativeBrowserTurnConfigOverrides,
resolveCodexNativeBrowserPluginEnabled,
} from "./codex-runtime-config";
import { prepareCodexImageAwareTurnInput } from "./native-image-input";
import {
normalizeCodexTokenUsage,
normalizeCodexContextUsage,
} from "./codex-token-usage";
// This module stays the public entry point for the Codex App Server runtime, so
// helpers that moved into sibling modules are re-exported here unchanged.
export { formatCodexAppServerErrorMessage } from "./codex-app-server-errors";
export {
formatCodexGoal,
isCodexCompactSlashCommand,
mapCodexThreadGoalToProviderGoal,
parseCodexGoalSlashCommand,
runCodexCompactSlashCommand,
runCodexGoalSlashCommand,
type CodexGoalSlashCommand,
type CodexThreadGoal,
type CodexThreadGoalStatus,
} from "./codex-goal-commands";
export { toCodexConfigLayerDisplayValue } from "./codex-snapshot-mappers";
export {
buildCodexConfigOverrides,
buildCodexMcpDisableConfigOverrides,
buildCodexSecondaryServerRequestDenial,
buildCodexThreadResumeParams,
buildCodexThreadStartParams,
buildCodexTurnStartParams,
buildSandboxPolicy,
} from "./codex-app-server-params";
export { buildCodexUnattendedAutomationMcpOverrides } from "./codex-app-server-config-overrides";
export { applyCodexRuntimeCapabilityDowngrades } from "./codex-runtime-capabilities";
export { describeJsonRpcLinePrefix } from "../shared/json-rpc-line";
export { mapCodexHookNotificationToBridgeEvent } from "./codex-hook-mapping";
export { createCodexAppServerElicitationPauseController } from "./codex-elicitation-pause";
export {
mapCodexElicitationToApproval,
mapCodexElicitationToUserInput,
shouldAutoApproveStaveLocalMcpElicitation,
} from "./codex-elicitation-mapping";
const threadIdByTask = new Map<string, string>();
const threadExecutableByTask = new Map<string, string>();
const clientByExecutablePath = new Map<string, CodexAppServerClient>();
const codexGlobalMcpConfigRefreshTracker = new McpConfigRefreshTracker();
const codexProjectMcpConfigRefreshTracker = new McpConfigRefreshTracker();
const freshCodexThreadExecutables = new Set<string>();
const activeCodexTurnsByExecutable = new Map<string, number>();
const pendingMcpRefreshExecutables = new Set<string>();
const APP_SERVER_INTERRUPT_GRACE_MS = 10_000;
const CODEX_CONFIG_READ_TIMEOUT_MS = 5_000;
/**
* How long a Codex approval / user-input request can sit unanswered before
* Stave auto-declines it. Mirrors Claude's
* `CLAUDE_APPROVAL_DECISION_TIMEOUT_DEFAULT_MS` (claude-sdk-runtime.ts):
* without an equivalent fallback here, a dropped or never-delivered Codex
* approval/user-input prompt (renderer never rendered it, IPC glitch, user
* simply never responds) leaves the per-turn timeout controller paused
* indefinitely (see `createTurnTimeoutController` in `runtime.ts`, which only
* releases a decision's pause on that request's responder delivery, a
* `tool_result` matching its id, or an `error` bridge event) — the turn, and
* its task/workspace, would then show "active" forever.
*/
export const CODEX_APPROVAL_DECISION_TIMEOUT_DEFAULT_MS = 45 * 60 * 1000;
export function resolveCodexApprovalDecisionTimeoutMs(args: {
envValue?: string;
override?: number;
}) {
if (typeof args.override === "number" && Number.isFinite(args.override)) {
return Math.max(0, Math.floor(args.override));
}
return parsePositiveIntEnv({
value: args.envValue,
fallback: CODEX_APPROVAL_DECISION_TIMEOUT_DEFAULT_MS,
});
}
const CODEX_APP_SERVER_STDOUT_BUFFER_MAX_BYTES = 64 * 1024 * 1024;
const CODEX_APP_SERVER_STDOUT_SOFT_LINE_MAX_BYTES = 1 * 1024 * 1024;
const CODEX_APP_SERVER_STDOUT_HARD_LINE_MAX_BYTES = 32 * 1024 * 1024;
/**
* Grace period between the teardown SIGTERM and the SIGKILL escalation. A
* wedged app-server that ignores SIGTERM would otherwise survive its own
* teardown while a fresh one respawns, accumulating ghost processes.
*/
const CODEX_APP_SERVER_KILL_ESCALATION_MS = 2_000;
const CODEX_APP_SERVER_COLLECTED_EVENTS_MAX_BYTES = 512 * 1024;
const CODEX_APP_SERVER_MESSAGE_BUFFER_MAX_BYTES = 256 * 1024;
const CODEX_APP_SERVER_PLAN_BUFFER_MAX_BYTES = 128 * 1024;
const CODEX_APP_SERVER_TOOL_OUTPUT_BUFFER_MAX_BYTES = 256 * 1024;
const CODEX_APP_SERVER_PARTIAL_TOOL_OUTPUT_MAX_BYTES = 128 * 1024;
const CODEX_APP_SERVER_FINAL_TOOL_OUTPUT_MAX_BYTES = 256 * 1024;
const CODEX_APP_SERVER_PLAN_EVENT_MAX_BYTES = 64 * 1024;
const CODEX_APP_SERVER_PARTIAL_PLAN_EMIT_THROTTLE_MS = 80;
const CODEX_APP_SERVER_PARTIAL_TOOL_EMIT_THROTTLE_MS = 200;
/** Throttle live usage updates; completion still emits the authoritative total. */
const CODEX_APP_SERVER_USAGE_EMIT_THROTTLE_MS = 1_000;
const CODEX_APP_SERVER_OVERFLOW_TAIL_EVENTS: BridgeEvent[] = [
{
type: "error",
message:
"Codex App Server turn output was truncated in non-stream replay because the retained snapshot limit was exceeded.",
recoverable: true,
},
{ type: "done", stop_reason: "output_overflow" },
];
const CODEX_APP_SERVER_OVERFLOW_TAIL_BYTES =
CODEX_APP_SERVER_OVERFLOW_TAIL_EVENTS.reduce(
(total, event) => total + measureBridgeEventBytes(event),
0,
);
type JsonRpcId = string | number;
type JsonRpcMessage = {
jsonrpc?: string;
id?: JsonRpcId;
method?: string;
params?: unknown;
result?: unknown;
error?: { code?: number; message?: string; data?: unknown };
};
type ServerRequestMethod =
| "item/commandExecution/requestApproval"
| "item/fileChange/requestApproval"
| "item/permissions/requestApproval"
| "item/tool/requestUserInput"
| "mcpServer/elicitation/request"
| "applyPatchApproval"
| "execCommandApproval"
| "item/tool/call"
| "account/chatgptAuthTokens/refresh";
interface PendingApprovalRequest {
serverRequestId: JsonRpcId;
responseKind:
| "review"
| "commandExecution"
| "fileChange"
| "permissions"
| "elicitation";
permissions?: {
network?: unknown;
fileSystem?: unknown;
} | null;
}
interface PendingUserInputRequest {
serverRequestId: JsonRpcId;
responseKind: "tool" | "elicitation";
elicitationMode?: "form" | "url";
elicitationFields?: ElicitationFieldDescriptor[];
}
function buildCodexEnv(args: { executablePath?: string } = {}) {
return buildCodexCliEnv({ executablePath: args.executablePath });
}
async function refreshCodexChatgptAuthTokens(args: {
executablePath: string;
previousAccountId?: string | null;
}) {
const client = new CodexAppServerClient(args.executablePath);
try {
const [authStatus, accountStatus] = await Promise.all([
client.request<CodexGetAuthStatusResponse>("getAuthStatus", {
includeToken: true,
refreshToken: true,
}),
client.request<CodexAccountReadResponse>("account/read", {
refreshToken: true,
}),
]);
const response = resolveCodexChatgptAuthTokensRefreshResponse({
authStatus,
accountStatus,
previousAccountId: args.previousAccountId,
});
if (!response) {
throw new Error(
"Codex ChatGPT token refresh requires an active ChatGPT login with a refreshable access token.",
);
}
return response;
} finally {
client.dispose("Closed temporary Codex auth refresh client.");
}
}
/**
* Whether this thread will actually see `stave_lens_*` tools: the server has to
* be attached *and* still be registering the browser tools. Instructing a
* model to prioritize tools it does not have is the same failure the
* connection gate exists to prevent, just reached from the other side.
*/
async function hasStaveLensToolsForCodex(hasEmbeddedStaveLocalMcp: boolean) {
if (!hasEmbeddedStaveLocalMcp) {
return false;
}
try {
// Imported lazily: `stave-mcp-config` reads `electron.app` at module scope,
// which this runtime module must not require just to be loadable.
const { readStaveLocalMcpConfig } =
await import("../main/stave-mcp-config");
return (await readStaveLocalMcpConfig()).browserToolsEnabled !== false;
} catch {
return true;
}
}
function appendBoundedCodexBuffer(args: {
current: string;
chunk: string;
keep: "prefix" | "suffix";
maxBytes: number;
}) {
return appendBoundedText({
current: args.current,
chunk: args.chunk,
keep: args.keep,
maxBytes: args.maxBytes,
});
}
function truncateCodexSnapshot(args: { value: string; maxBytes: number }) {
return truncateBufferedText({
value: args.value,
maxBytes: args.maxBytes,
});
}
type CodexMcpToolCallItem = {
id?: string;
type?: string;
server?: string;
tool?: string;
arguments?: unknown;
result?: unknown;
error?: { message?: string | null } | null;
status?: string;
};
function serializeCodexMcpToolCallArguments(value: unknown) {
if (typeof value === "string") {
return value;
}
try {
return JSON.stringify(value ?? {});
} catch {
return toText(value ?? {});
}
}
function buildCodexMcpToolCallInputEvent(
item: CodexMcpToolCallItem,
workerExecution?: WorkerExecutionMetadata | null,
): Extract<BridgeEvent, { type: "tool" }> {
const itemId = typeof item.id === "string" ? item.id : "";
const normalizedToolName = `${item.server ?? "mcp"}:${item.tool ?? "tool"}`
.toLowerCase()
.replace(/[^a-z0-9]+/g, "");
return {
type: "tool",
...(itemId ? { toolUseId: itemId } : {}),
toolName: `${item.server ?? "mcp"}:${item.tool ?? "tool"}`,
input: truncateCodexSnapshot({
value: serializeCodexMcpToolCallArguments(item.arguments),
maxBytes: CODEX_APP_SERVER_TOOL_OUTPUT_BUFFER_MAX_BYTES,
}),
state: "input-available",
...(workerExecution && normalizedToolName.endsWith("spawnagent")
? { workerExecution }
: {}),
};
}
function resolveThreadId(args: {
threadKey: string;
executablePath: string;
fallbackThreadId?: string;
}) {
return threadExecutableByTask.get(args.threadKey) === args.executablePath
? (threadIdByTask.get(args.threadKey) ?? args.fallbackThreadId?.trim())
: args.fallbackThreadId?.trim();
}
function rememberThreadId(args: {
threadKey: string;
threadId?: string;
executablePath: string;
}) {
const nextThreadId = args.threadId?.trim();
if (!nextThreadId) {
return;
}
threadIdByTask.set(args.threadKey, nextThreadId);
threadExecutableByTask.set(args.threadKey, args.executablePath);
}
function resolveCodexResumeThreadFallback(args: {
conversation?: StreamTurnArgs["conversation"];
runtimeOptions?: StreamTurnArgs["runtimeOptions"];
}) {
return resolveProviderResumeSessionId({
conversation: args.conversation,
fallbackResumeId: args.runtimeOptions?.codexResumeThreadId,
});
}
function buildCodexThreadStartedEvents(args: {
threadId?: string;
}): BridgeEvent[] {
const threadId = args.threadId?.trim();
if (!threadId) {
return [];
}
return [
{
type: "provider_session",
providerId: "codex",
nativeSessionId: threadId,
},
];
}
export function resolveCodexExecutablePath(
args: { explicitPath?: string } = {},
) {
return resolveCodexCliExecutablePath({
explicitPath: args.explicitPath,
});
}
function buildApprovalDescription(args: {
method: ServerRequestMethod;
params: Record<string, unknown>;
}) {
const reason =
typeof args.params.reason === "string" &&
args.params.reason.trim().length > 0
? args.params.reason.trim()
: null;
if (
typeof args.params.command === "string" &&
args.params.command.trim().length > 0
) {
return reason ? `${args.params.command}\n\n${reason}` : args.params.command;
}
if (args.method === "item/fileChange/requestApproval") {
const grantRoot =
typeof args.params.grantRoot === "string"
? args.params.grantRoot.trim()
: "";
if (grantRoot) {
return reason
? `${reason}\n\nGrant root: ${grantRoot}`
: `Grant root: ${grantRoot}`;
}
}
return reason ?? `Codex requested approval for ${args.method}.`;
}
function buildApprovalInput(args: { params: Record<string, unknown> }) {
return typeof args.params.command === "string" &&
args.params.command.trim().length > 0
? args.params.command.trim()
: undefined;
}
function mapApprovalToolName(method: ServerRequestMethod) {
switch (method) {
case "item/commandExecution/requestApproval":
case "execCommandApproval":
return "bash";
case "item/fileChange/requestApproval":
case "applyPatchApproval":
return "apply_patch";
case "item/permissions/requestApproval":
return "permissions";
default:
return method;
}
}
function shouldDebugCodexAppServerMessage(message: JsonRpcMessage) {
return (
message.method === "error" ||
message.method === "turn/started" ||
message.method === "turn/completed"
);
}
class CodexAppServerClient {
private process: ChildProcessWithoutNullStreams | null = null;
private processStartedAt: number | null = null;
private startupPromise: Promise<void> | null = null;
private nextRequestId = 1;
private pendingResponses = new Map<
JsonRpcId,
PendingCodexAppServerResponse
>();
private listeners = new Set<(message: JsonRpcMessage) => void>();
private exitListeners = new Set<(message: string) => void>();
private readonly lifetime = new CodexClientLifetime({
isRunning: () => this.process !== null && this.initialized,
isBusy: () =>
Boolean(this.startupPromise) ||
this.pendingResponses.size > 0 ||
this.listeners.size > 0 ||
(activeCodexTurnsByExecutable.get(this.executablePath) ?? 0) > 0,
retire: () => this.dispose("Closed idle Codex App Server."),
unsubscribe: async (threadId) => {
await this.sendRequest(
"thread/unsubscribe",
{ threadId },
{ timeoutMs: 5_000 },
);
},
onError: () =>
console.warn(
"[codex-app-server-runtime] idle thread release failed; idle client retirement remains enabled.",
),
});
readonly threadLifetime = this.lifetime.threads;
private initialized = false;
private lastErrorMessage: string | null = null;
constructor(
private readonly executablePath: string,
private readonly secretEnv: Record<string, string> = {},
) {}
async ensureStarted() {
if (this.process && this.initialized) {
return;
}
if (this.startupPromise) {
return this.startupPromise;
}
this.startupPromise = this.start();
try {
await this.startupPromise;
} finally {
this.startupPromise = null;
}
}
subscribe(listener: (message: JsonRpcMessage) => void) {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
onProcessExit(listener: (message: string) => void) {
this.exitListeners.add(listener);
return () => {
this.exitListeners.delete(listener);
};
}
async request<T = unknown>(
method: string,
params: unknown,
options?: { timeoutMs?: number },
): Promise<T> {
this.lifetime.suspend();
try {
await this.ensureStarted();
// JSON-RPC carries unknown data; the caller owns the response contract.
return (await this.sendRequest(method, params, options)) as T;
} finally {
this.lifetime.schedule();
}
}
async respond(requestId: JsonRpcId, result: unknown) {
await this.ensureStarted();
const child = this.process;
if (!child) {
return;
}
this.writeToProcessStdin(child, {
jsonrpc: "2.0",
id: requestId,
result,
});
}
async respondError(
requestId: JsonRpcId,
error: { code: number; message: string; data?: unknown },
) {
await this.ensureStarted();
const child = this.process;
if (!child) {
return;
}
this.writeToProcessStdin(child, {
jsonrpc: "2.0",
id: requestId,
error,
});
}
getLastErrorMessage() {
return this.lastErrorMessage;
}
getProcessStartedAt() {
return this.processStartedAt;
}
dispose(message = "Codex App Server closed.") {
if (!this.process) {
this.lastErrorMessage = message;
return;
}
this.teardownProcess(message);
}
private async start() {
if (this.process) {
this.teardownProcess("Restarting Codex App Server.");
}
const processStartedAt = Date.now();
const child = spawn(
this.executablePath,
["app-server", "--listen", "stdio://"],
{
stdio: ["pipe", "pipe", "pipe"],
// Runtime-owned env is spread last, and reserved names are stripped
// from the bound secrets first, so an injected secret can never claim a
// Stave runtime variable. Mirrors `buildClaudeQueryOptions`.
env: {
...stripReservedSecretEnvNames(this.secretEnv),
...buildCodexEnv({ executablePath: this.executablePath }),
},
cwd: process.cwd(),
},
);
this.process = child;
this.processStartedAt = processStartedAt;
this.initialized = false;
const stdoutLineBuffer = new Utf8LineBuffer({
label: "codex-app-server stdout",
maxBufferBytes: CODEX_APP_SERVER_STDOUT_BUFFER_MAX_BYTES,
maxLineBytes: CODEX_APP_SERVER_STDOUT_HARD_LINE_MAX_BYTES,
// Drop oversized lines without taking down unrelated shared sessions.
// Log only size and JSON-RPC envelope metadata, never payload content.
onOversizedLine: ({ lineBytes, linePrefix }) => {
const described = describeJsonRpcLinePrefix(linePrefix);
console.warn(
"[codex-app-server-runtime] dropped oversized stdout line",
{
lineBytes,
maxLineBytes: CODEX_APP_SERVER_STDOUT_HARD_LINE_MAX_BYTES,
...described,
},
);
// Reject a dropped pending response instead of waiting for its deadline.
if (described.responseId !== null) {
const pending = takePendingCodexAppServerResponse({
pendingResponses: this.pendingResponses,
requestId: described.responseId,
});
if (pending) {
pending.reject(
new Error(
`Codex App Server response was dropped: oversized line (${lineBytes} bytes) exceeded ${CODEX_APP_SERVER_STDOUT_HARD_LINE_MAX_BYTES} bytes.`,
),
);
}
}
},
});
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk: string) => {
if (child !== this.process) {
return;
}
let lines: string[];
try {
lines = stdoutLineBuffer.append(chunk);
} catch (error) {
this.teardownProcess(
error instanceof Error ? error.message : String(error),
);
return;
}
for (const line of lines) {
if (line.length === 0) {
continue;
}
if (!this.handleProtocolLine(line)) {
return;
}
}
});
child.stderr.on("data", (chunk) => {
const text = String(chunk);
if (text.trim().length > 0) {
this.lastErrorMessage = text.trim();
}
});
child.once("exit", (_code, signal) => {
// A superseded child's late exit must not tear down its replacement.
if (child !== this.process) {
return;
}
this.teardownProcess(
signal
? `Codex App Server exited with signal ${signal}.`
: "Codex App Server exited.",
);
});
// A spawn failure (ENOENT/EACCES/EMFILE) or an async stdin write failure
// (EPIPE against a dying process) surfaces as an 'error' event; without a
// listener it becomes an uncaught exception that takes down the entire
// shared host service instead of failing just this client.
child.on("error", (error) => {
if (child !== this.process) {
return;
}
this.teardownProcess(
`Codex App Server process error: ${error instanceof Error ? error.message : String(error)}`,
);
});
child.stdin.on?.("error", (error: unknown) => {
if (child !== this.process) {
return;
}
this.teardownProcess(
`Codex App Server stdin error: ${error instanceof Error ? error.message : String(error)}`,
);
});
await this.sendRequest("initialize", {
clientInfo: {
name: "stave",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
});
this.writeToProcessStdin(child, {
jsonrpc: "2.0",
method: "initialized",
params: {},
});
this.initialized = true;
}
/**
* Best-effort framed write that never throws: a destroyed or unwritable
* stdin reports failure instead of crashing the caller, and async write
* errors are handled by the stdin 'error' listener installed in start().
*/
private writeToProcessStdin(
child: ChildProcessWithoutNullStreams,
payload: unknown,
): boolean {
const stdin = child.stdin;
if (!stdin || stdin.destroyed || stdin.writable === false) {
return false;
}
try {
stdin.write(JSON.stringify(payload) + "\n");
return true;
} catch {
return false;
}
}
private async sendRequest(
method: string,
params: unknown,
options?: { timeoutMs?: number },
): Promise<unknown> {
const child = this.process;
if (!child) {
throw new Error("Codex App Server is not running.");
}
const requestId = this.nextRequestId++;
return new Promise<unknown>((resolve, reject) => {
registerPendingCodexAppServerResponse({
pendingResponses: this.pendingResponses,
requestId,
method,
timeoutMs: options?.timeoutMs,
resolve,
reject,
});
const wrote = this.writeToProcessStdin(child, {
jsonrpc: "2.0",
id: requestId,
method,
params,
});
if (!wrote) {
// Reject immediately instead of waiting for the request deadline on a
// write that never reached the process.
const pending = takePendingCodexAppServerResponse({
pendingResponses: this.pendingResponses,
requestId,
});
pending?.reject(
new Error(`Codex App Server stdin is not writable (${method}).`),
);
}
});
}
private handleMessage(line: string) {
const message = this.parseMessage(line);
if (!message) {
return;
}
this.dispatchMessage(message);
}
private parseMessage(line: string) {
try {
return JSON.parse(line) as JsonRpcMessage;
} catch {
return null;
}
}
private handleProtocolLine(line: string) {
const lineBytes = byteLengthUtf8(line);
if (lineBytes > CODEX_APP_SERVER_STDOUT_SOFT_LINE_MAX_BYTES) {
const message = this.parseMessage(line);
if (!message) {
this.teardownProcess(
`Codex App Server protocol overflow: oversized line (${lineBytes} bytes) was not valid JSON-RPC.`,
);
return false;
}
this.dispatchMessage(message);
return true;
}
this.handleMessage(line);
return true;
}
private dispatchMessage(message: JsonRpcMessage) {
this.lifetime.observe(message);
try {
codexMcpManagement.captureNotification(this.executablePath, message);
} catch (error) {
// Diagnostics capture must never break protocol dispatch.
console.warn(
"[codex-app-server-runtime] failed to capture notification",
error,
);
}
const hasResponseId =
Object.prototype.hasOwnProperty.call(message, "id") &&
(Object.prototype.hasOwnProperty.call(message, "result") ||
Object.prototype.hasOwnProperty.call(message, "error"));
if (hasResponseId) {
const id = message.id as JsonRpcId;
const pending = takePendingCodexAppServerResponse({
pendingResponses: this.pendingResponses,
requestId: id,
});
if (!pending) {
return;
}
if (message.error) {
pending.reject(
new Error(
message.error.message || "Codex App Server request failed.",
),
);
} else {
pending.resolve(message.result);
}
return;
}
for (const listener of this.listeners) {
try {
listener(message);
} catch (error) {
// A throwing subscriber runs inside the stdout 'data' callback; an
// escaped exception there would take down the whole host service.
console.warn(
"[codex-app-server-runtime] notification listener failed",
error,
);
}
}
}
private teardownProcess(message: string) {
this.lifetime.clear();
const current = this.process;
this.process = null;
this.processStartedAt = null;
this.initialized = false;
this.lastErrorMessage = message;
if (current && !current.killed) {
current.kill();
}
// Escalate to SIGKILL if the process ignores SIGTERM; otherwise a wedged
// app-server survives its own teardown while a replacement respawns.
if (current && current.exitCode === null && current.signalCode === null) {
const killTimer = setTimeout(() => {