-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathcodexAppServerManager.ts
More file actions
1679 lines (1448 loc) · 53.5 KB
/
codexAppServerManager.ts
File metadata and controls
1679 lines (1448 loc) · 53.5 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 { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { EventEmitter } from "node:events";
import readline from "node:readline";
import {
ApprovalRequestId,
EventId,
ProviderItemId,
ProviderRequestKind,
type ProviderUserInputAnswers,
ThreadId,
TurnId,
type ProviderApprovalDecision,
type ProviderEvent,
type ProviderSession,
type ProviderSessionStartInput,
type ProviderTurnStartResult,
RuntimeMode,
ProviderInteractionMode,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { Effect, ServiceMap } from "effect";
import {
formatCodexCliUpgradeMessage,
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "./provider/codexCliVersion";
type PendingRequestKey = string;
interface PendingRequest {
method: string;
timeout: ReturnType<typeof setTimeout>;
resolve: (value: unknown) => void;
reject: (error: Error) => void;
}
interface PendingApprovalRequest {
requestId: ApprovalRequestId;
jsonRpcId: string | number;
method:
| "item/commandExecution/requestApproval"
| "item/fileChange/requestApproval"
| "item/fileRead/requestApproval";
requestKind: ProviderRequestKind;
threadId: ThreadId;
turnId?: TurnId;
itemId?: ProviderItemId;
}
interface PendingUserInputRequest {
requestId: ApprovalRequestId;
jsonRpcId: string | number;
threadId: ThreadId;
turnId?: TurnId;
itemId?: ProviderItemId;
}
interface CodexUserInputAnswer {
answers: string[];
}
interface CodexSessionContext {
session: ProviderSession;
account: CodexAccountSnapshot;
child: ChildProcessWithoutNullStreams;
output: readline.Interface;
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
collabReceiverTurns: Map<string, TurnId>;
nextRequestId: number;
stopping: boolean;
}
interface JsonRpcError {
code?: number;
message?: string;
}
interface JsonRpcRequest {
id: string | number;
method: string;
params?: unknown;
}
interface JsonRpcResponse {
id: string | number;
result?: unknown;
error?: JsonRpcError;
}
interface JsonRpcNotification {
method: string;
params?: unknown;
}
type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export interface CodexAppServerSendTurnInput {
readonly threadId: ThreadId;
readonly input?: string;
readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
readonly model?: string;
readonly serviceTier?: string | null;
readonly effort?: string;
readonly interactionMode?: ProviderInteractionMode;
}
export interface CodexAppServerStartSessionInput {
readonly threadId: ThreadId;
readonly provider?: "codex";
readonly cwd?: string;
readonly model?: string;
readonly serviceTier?: string;
readonly resumeCursor?: unknown;
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
readonly runtimeMode: RuntimeMode;
}
export interface CodexThreadTurnSnapshot {
id: TurnId;
items: unknown[];
}
export interface CodexThreadSnapshot {
threadId: string;
turns: CodexThreadTurnSnapshot[];
}
const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000;
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
const CODEX_STDERR_LOG_REGEX =
/^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/;
const BENIGN_ERROR_LOG_SNIPPETS = [
"state db missing rollout path for thread",
"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
];
const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"not found",
"missing thread",
"no such thread",
"unknown thread",
"does not exist",
];
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: true,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: true,
};
}
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
## Mode rules (strict)
You are in **Plan Mode** until a developer message explicitly ends it.
Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
## Plan Mode vs update_plan tool
Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error.
## Execution vs. mutation in Plan Mode
You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
### Allowed (non-mutating, plan-improving)
Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
* Reading or searching files, configs, schemas, types, manifests, and docs
* Static analysis, inspection, and repo exploration
* Dry-run style commands when they do not edit repo-tracked files
* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files
### Not allowed (mutating, plan-executing)
Actions that implement the plan or change repo-tracked state. Examples:
* Editing or writing files
* Running formatters or linters that rewrite files
* Applying patches, migrations, or codegen that updates repo-tracked files
* Side-effectful commands whose purpose is to carry out the plan rather than refine it
When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
## PHASE 1 - Ground in the environment (explore first, ask second)
Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
## PHASE 2 - Intent chat (what they actually want)
* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
## PHASE 3 - Implementation chat (what/how we'll build)
* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.
## Asking questions
Critical rules:
* Strongly prefer using the \`request_user_input\` tool to ask any questions.
* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.
You SHOULD ask many questions, but each question must:
* materially change the spec/plan, OR
* confirm/lock an assumption, OR
* choose between meaningful tradeoffs.
* not be answerable by non-mutating commands.
Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
## Two kinds of unknowns (treat differently)
1. **Discoverable facts** (repo/system truth): explore first.
* Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
* Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
* If asking, present concrete candidates (paths/service names) + recommend one.
* Never ask questions you can answer from your environment (e.g., "where is this struct").
2. **Preferences/tradeoffs** (not discoverable): ask early.
* These are intent or implementation preferences that cannot be derived from exploration.
* Provide 2-4 mutually exclusive options + a recommended default.
* If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
## Finalization rule
Only output the final plan when it is decision complete and leaves no decisions to the implementer.
When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
1) The opening tag must be on its own line.
2) Start the plan content on the next line (no text on the same line as the tag).
3) The closing tag must be on its own line.
4) Use Markdown inside the block.
5) Keep the tags exactly as \`<proposed_plan>\` and \`</proposed_plan>\` (do not translate or rename them), even if the plan content is in another language.
Example:
<proposed_plan>
plan content
</proposed_plan>
plan content should be human and agent digestible. The final plan must be plan-only and include:
* A clear title
* A brief summary section
* Important changes or additions to public APIs/interfaces/types
* Test cases and scenarios
* Explicit assumptions and defaults chosen where needed
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
</collaboration_mode>`;
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
## request_user_input availability
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
</collaboration_mode>`;
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
readonly approvalPolicy: "on-request" | "never";
readonly sandbox: "workspace-write" | "danger-full-access";
} {
if (runtimeMode === "approval-required") {
return {
approvalPolicy: "on-request",
sandbox: "workspace-write",
};
}
return {
approvalPolicy: "never",
sandbox: "danger-full-access",
};
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChildTree(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill();
}
export function normalizeCodexModelSlug(
model: string | undefined | null,
preferredId?: string,
): string | undefined {
const normalized = normalizeModelSlug(model);
if (!normalized) {
return undefined;
}
if (preferredId?.endsWith("-codex") && preferredId !== normalized) {
return preferredId;
}
return normalized;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
function buildCodexCollaborationMode(input: {
readonly interactionMode?: "default" | "plan";
readonly model?: string;
readonly effort?: string;
}):
| {
mode: "default" | "plan";
settings: {
model: string;
reasoning_effort: string;
developer_instructions: string;
};
}
| undefined {
if (input.interactionMode === undefined) {
return undefined;
}
const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex";
return {
mode: input.interactionMode,
settings: {
model,
reasoning_effort: input.effort ?? "medium",
developer_instructions:
input.interactionMode === "plan"
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
},
};
}
function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer {
if (typeof value === "string") {
return { answers: [value] };
}
if (Array.isArray(value)) {
const answers = value.filter((entry): entry is string => typeof entry === "string");
return { answers };
}
if (value && typeof value === "object") {
const maybeAnswers = (value as { answers?: unknown }).answers;
if (Array.isArray(maybeAnswers)) {
const answers = maybeAnswers.filter((entry): entry is string => typeof entry === "string");
return { answers };
}
}
throw new Error("User input answers must be strings or arrays of strings.");
}
function toCodexUserInputAnswers(
answers: ProviderUserInputAnswers,
): Record<string, CodexUserInputAnswer> {
return Object.fromEntries(
Object.entries(answers).map(([questionId, value]) => [
questionId,
toCodexUserInputAnswer(value),
]),
);
}
export function classifyCodexStderrLine(rawLine: string): { message: string } | null {
const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim();
if (!line) {
return null;
}
const match = line.match(CODEX_STDERR_LOG_REGEX);
if (match) {
const level = match[1];
if (level && level !== "ERROR") {
return null;
}
const isBenignError = BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet));
if (isBenignError) {
return null;
}
}
return { message: line };
}
export function isRecoverableThreadResumeError(error: unknown): boolean {
const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
if (!message.includes("thread/resume")) {
return false;
}
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
}
export interface CodexAppServerManagerEvents {
event: [event: ProviderEvent];
}
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
constructor(services?: ServiceMap.ServiceMap<never>) {
super();
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
}
async startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {
const threadId = input.threadId;
const now = new Date().toISOString();
let context: CodexSessionContext | undefined;
try {
const resolvedCwd = input.cwd ?? process.cwd();
const session: ProviderSession = {
provider: "codex",
status: "connecting",
runtimeMode: input.runtimeMode,
model: normalizeCodexModelSlug(input.model),
cwd: resolvedCwd,
threadId,
createdAt: now,
updatedAt: now,
};
const codexOptions = readCodexProviderOptions(input);
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
const codexHomePath = codexOptions.homePath;
this.assertSupportedCodexCliVersion({
binaryPath: codexBinaryPath,
cwd: resolvedCwd,
...(codexHomePath ? { homePath: codexHomePath } : {}),
});
const child = spawn(codexBinaryPath, ["app-server"], {
cwd: resolvedCwd,
env: {
...process.env,
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
shell: process.platform === "win32",
});
const output = readline.createInterface({ input: child.stdout });
context = {
session,
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
child,
output,
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
nextRequestId: 1,
stopping: false,
};
this.sessions.set(threadId, context);
this.attachProcessListeners(context);
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
await this.sendRequest(context, "initialize", buildCodexInitializeParams());
this.writeMessage(context, { method: "initialized" });
try {
const modelListResponse = await this.sendRequest(context, "model/list", {});
await Effect.logInfo("codex model/list response", { response: modelListResponse }).pipe(
this.runPromise,
);
} catch (error) {
await Effect.logWarning("codex model/list failed", {
cause: error instanceof Error ? error.message : String(error),
}).pipe(this.runPromise);
}
try {
const accountReadResponse = await this.sendRequest(context, "account/read", {});
await Effect.logInfo("codex account/read response", { response: accountReadResponse }).pipe(
this.runPromise,
);
context.account = readCodexAccountSnapshot(accountReadResponse);
await Effect.logInfo("codex subscription status", {
type: context.account.type,
planType: context.account.planType,
sparkEnabled: context.account.sparkEnabled,
}).pipe(this.runPromise);
} catch (error) {
await Effect.logWarning("codex account/read failed", {
cause: error instanceof Error ? error.message : String(error),
}).pipe(this.runPromise);
}
const normalizedModel = resolveCodexModelForAccount(
normalizeCodexModelSlug(input.model),
context.account,
);
const sessionOverrides = {
model: normalizedModel ?? null,
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
cwd: input.cwd ?? null,
...mapCodexRuntimeMode(input.runtimeMode ?? "full-access"),
};
const threadStartParams = {
...sessionOverrides,
experimentalRawEvents: false,
};
const resumeThreadId = readResumeThreadId(input);
this.emitLifecycleEvent(
context,
"session/threadOpenRequested",
resumeThreadId
? `Attempting to resume thread ${resumeThreadId}.`
: "Starting a new Codex thread.",
);
await Effect.logInfo("codex app-server opening thread", {
threadId,
requestedRuntimeMode: input.runtimeMode,
requestedModel: normalizedModel ?? null,
requestedCwd: resolvedCwd,
resumeThreadId: resumeThreadId ?? null,
}).pipe(this.runPromise);
let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start";
let threadOpenResponse: unknown;
if (resumeThreadId) {
try {
threadOpenMethod = "thread/resume";
threadOpenResponse = await this.sendRequest(context, "thread/resume", {
...sessionOverrides,
threadId: resumeThreadId,
});
} catch (error) {
if (!isRecoverableThreadResumeError(error)) {
this.emitErrorEvent(
context,
"session/threadResumeFailed",
error instanceof Error ? error.message : "Codex thread resume failed.",
);
await Effect.logWarning("codex app-server thread resume failed", {
threadId,
requestedRuntimeMode: input.runtimeMode,
resumeThreadId,
recoverable: false,
cause: error instanceof Error ? error.message : String(error),
}).pipe(this.runPromise);
throw error;
}
threadOpenMethod = "thread/start";
this.emitLifecycleEvent(
context,
"session/threadResumeFallback",
`Could not resume thread ${resumeThreadId}; started a new thread instead.`,
);
await Effect.logWarning("codex app-server thread resume fell back to fresh start", {
threadId,
requestedRuntimeMode: input.runtimeMode,
resumeThreadId,
recoverable: true,
cause: error instanceof Error ? error.message : String(error),
}).pipe(this.runPromise);
threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
}
} else {
threadOpenMethod = "thread/start";
threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
}
const threadOpenRecord = this.readObject(threadOpenResponse);
const threadIdRaw =
this.readString(this.readObject(threadOpenRecord, "thread"), "id") ??
this.readString(threadOpenRecord, "threadId");
if (!threadIdRaw) {
throw new Error(`${threadOpenMethod} response did not include a thread id.`);
}
const providerThreadId = threadIdRaw;
this.updateSession(context, {
status: "ready",
resumeCursor: { threadId: providerThreadId },
});
this.emitLifecycleEvent(
context,
"session/threadOpenResolved",
`Codex ${threadOpenMethod} resolved.`,
);
await Effect.logInfo("codex app-server thread open resolved", {
threadId,
threadOpenMethod,
requestedResumeThreadId: resumeThreadId ?? null,
resolvedThreadId: providerThreadId,
requestedRuntimeMode: input.runtimeMode,
}).pipe(this.runPromise);
this.emitLifecycleEvent(context, "session/ready", `Connected to thread ${providerThreadId}`);
return { ...context.session };
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
if (context) {
this.updateSession(context, {
status: "error",
lastError: message,
});
this.emitErrorEvent(context, "session/startFailed", message);
this.stopSession(threadId);
} else {
this.emitEvent({
id: EventId.makeUnsafe(randomUUID()),
kind: "error",
provider: "codex",
threadId,
createdAt: new Date().toISOString(),
method: "session/startFailed",
message,
});
}
throw new Error(message, { cause: error });
}
}
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.threadId);
context.collabReceiverTurns.clear();
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
type: "text",
text: input.input,
text_elements: [],
});
}
for (const attachment of input.attachments ?? []) {
if (attachment.type === "image") {
turnInput.push({
type: "image",
url: attachment.url,
});
}
}
if (turnInput.length === 0) {
throw new Error("Turn input must include text or attachments.");
}
const providerThreadId = readResumeThreadId({
threadId: context.session.threadId,
runtimeMode: context.session.runtimeMode,
resumeCursor: context.session.resumeCursor,
});
if (!providerThreadId) {
throw new Error("Session is missing provider resume thread id.");
}
const turnStartParams: {
threadId: string;
input: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
serviceTier?: string | null;
effort?: string;
collaborationMode?: {
mode: "default" | "plan";
settings: {
model: string;
reasoning_effort: string;
developer_instructions: string;
};
};
} = {
threadId: providerThreadId,
input: turnInput,
};
const normalizedModel = resolveCodexModelForAccount(
normalizeCodexModelSlug(input.model ?? context.session.model),
context.account,
);
if (normalizedModel) {
turnStartParams.model = normalizedModel;
}
if (input.serviceTier !== undefined) {
turnStartParams.serviceTier = input.serviceTier;
}
if (input.effort) {
turnStartParams.effort = input.effort;
}
const collaborationMode = buildCodexCollaborationMode({
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
...(normalizedModel !== undefined ? { model: normalizedModel } : {}),
...(input.effort !== undefined ? { effort: input.effort } : {}),
});
if (collaborationMode) {
if (!turnStartParams.model) {
turnStartParams.model = collaborationMode.settings.model;
}
turnStartParams.collaborationMode = collaborationMode;
}
const response = await this.sendRequest(context, "turn/start", turnStartParams);
const turn = this.readObject(this.readObject(response), "turn");
const turnIdRaw = this.readString(turn, "id");
if (!turnIdRaw) {
throw new Error("turn/start response did not include a turn id.");
}
const turnId = TurnId.makeUnsafe(turnIdRaw);
this.updateSession(context, {
status: "running",
activeTurnId: turnId,
...(context.session.resumeCursor !== undefined
? { resumeCursor: context.session.resumeCursor }
: {}),
});
return {
threadId: context.session.threadId,
turnId,
...(context.session.resumeCursor !== undefined
? { resumeCursor: context.session.resumeCursor }
: {}),
};
}
async interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise<void> {
const context = this.requireSession(threadId);
const effectiveTurnId = turnId ?? context.session.activeTurnId;
const providerThreadId = readResumeThreadId({
threadId: context.session.threadId,
runtimeMode: context.session.runtimeMode,
resumeCursor: context.session.resumeCursor,
});
if (!effectiveTurnId || !providerThreadId) {
return;
}
await this.sendRequest(context, "turn/interrupt", {
threadId: providerThreadId,
turnId: effectiveTurnId,
});
}
async readThread(threadId: ThreadId): Promise<CodexThreadSnapshot> {
const context = this.requireSession(threadId);
const providerThreadId = readResumeThreadId({
threadId: context.session.threadId,
runtimeMode: context.session.runtimeMode,
resumeCursor: context.session.resumeCursor,
});
if (!providerThreadId) {
throw new Error("Session is missing a provider resume thread id.");
}
const response = await this.sendRequest(context, "thread/read", {
threadId: providerThreadId,
includeTurns: true,
});
return this.parseThreadSnapshot("thread/read", response);
}
async rollbackThread(threadId: ThreadId, numTurns: number): Promise<CodexThreadSnapshot> {
const context = this.requireSession(threadId);
const providerThreadId = readResumeThreadId({
threadId: context.session.threadId,
runtimeMode: context.session.runtimeMode,
resumeCursor: context.session.resumeCursor,
});
if (!providerThreadId) {
throw new Error("Session is missing a provider resume thread id.");
}
if (!Number.isInteger(numTurns) || numTurns < 1) {
throw new Error("numTurns must be an integer >= 1.");
}
const response = await this.sendRequest(context, "thread/rollback", {
threadId: providerThreadId,
numTurns,
});
this.updateSession(context, {
status: "ready",
activeTurnId: undefined,
});
return this.parseThreadSnapshot("thread/rollback", response);
}
async respondToRequest(
threadId: ThreadId,
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
): Promise<void> {
const context = this.requireSession(threadId);
const pendingRequest = context.pendingApprovals.get(requestId);
if (!pendingRequest) {
throw new Error(`Unknown pending approval request: ${requestId}`);
}
context.pendingApprovals.delete(requestId);
this.writeMessage(context, {
id: pendingRequest.jsonRpcId,
result: {
decision,
},
});
this.emitEvent({
id: EventId.makeUnsafe(randomUUID()),
kind: "notification",
provider: "codex",
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: "item/requestApproval/decision",
turnId: pendingRequest.turnId,
itemId: pendingRequest.itemId,
requestId: pendingRequest.requestId,
requestKind: pendingRequest.requestKind,
payload: {
requestId: pendingRequest.requestId,
requestKind: pendingRequest.requestKind,
decision,
},
});
}
async respondToUserInput(
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
): Promise<void> {
const context = this.requireSession(threadId);
const pendingRequest = context.pendingUserInputs.get(requestId);
if (!pendingRequest) {
throw new Error(`Unknown pending user input request: ${requestId}`);
}
context.pendingUserInputs.delete(requestId);
const codexAnswers = toCodexUserInputAnswers(answers);
this.writeMessage(context, {
id: pendingRequest.jsonRpcId,
result: {
answers: codexAnswers,
},
});
this.emitEvent({
id: EventId.makeUnsafe(randomUUID()),
kind: "notification",
provider: "codex",
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
turnId: pendingRequest.turnId,
itemId: pendingRequest.itemId,
requestId: pendingRequest.requestId,
payload: {
requestId: pendingRequest.requestId,
answers: codexAnswers,
},
});
}
stopSession(threadId: ThreadId): void {
const context = this.sessions.get(threadId);
if (!context) {
return;
}
context.stopping = true;
for (const pending of context.pending.values()) {
clearTimeout(pending.timeout);
pending.reject(new Error("Session stopped before request completed."));
}
context.pending.clear();
context.pendingApprovals.clear();
context.pendingUserInputs.clear();