Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

codexAppServerManager.ts

1,419 lines45.4 KB

1import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
2import { randomUUID } from "node:crypto";
3import { EventEmitter } from "node:events";
4import readline from "node:readline";
5​
6import {
7 ApprovalRequestId,
8 EventId,
9 ProviderItemId,
10 ProviderRequestKind,
11 type ProviderUserInputAnswers,
12 ThreadId,
13 TurnId,
14 type ProviderApprovalDecision,
15 type ProviderEvent,
16 type ProviderSession,
17 type ProviderSessionStartInput,
18 type ProviderTurnStartResult,
19 RuntimeMode,
20 ProviderInteractionMode,
21} from "@t3tools/contracts";
22import { normalizeModelSlug } from "@t3tools/shared/model";
23import { Effect, ServiceMap } from "effect";
24​
25type PendingRequestKey = string;
26​
27interface PendingRequest {
28 method: string;
29 timeout: ReturnType<typeof setTimeout>;
30 resolve: (value: unknown) => void;
31 reject: (error: Error) => void;
33​
34interface PendingApprovalRequest {
35 requestId: ApprovalRequestId;
36 jsonRpcId: string | number;
37 method:
38 | "item/commandExecution/requestApproval"
39 | "item/fileChange/requestApproval"
40 | "item/fileRead/requestApproval";
41 requestKind: ProviderRequestKind;
42 threadId: ThreadId;
43 turnId?: TurnId;
44 itemId?: ProviderItemId;
46​
47interface PendingUserInputRequest {
48 requestId: ApprovalRequestId;
49 jsonRpcId: string | number;
50 threadId: ThreadId;
51 turnId?: TurnId;
52 itemId?: ProviderItemId;
54​
55interface CodexUserInputAnswer {
56 answers: string[];
58​
59interface CodexSessionContext {
60 session: ProviderSession;
61 child: ChildProcessWithoutNullStreams;
62 output: readline.Interface;
63 pending: Map<PendingRequestKey, PendingRequest>;
64 pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
65 pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
66 nextRequestId: number;
67 stopping: boolean;
69​
70interface JsonRpcError {
71 code?: number;
72 message?: string;
74​
75interface JsonRpcRequest {
76 id: string | number;
77 method: string;
78 params?: unknown;
80​
81interface JsonRpcResponse {
82 id: string | number;
83 result?: unknown;
84 error?: JsonRpcError;
86​
87interface JsonRpcNotification {
88 method: string;
89 params?: unknown;
91​
92export interface CodexAppServerSendTurnInput {
93 readonly threadId: ThreadId;
94 readonly input?: string;
95 readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
96 readonly model?: string;
97 readonly effort?: string;
98 readonly serviceTier?: string;
99 readonly interactionMode?: ProviderInteractionMode;
101​
102export interface CodexAppServerStartSessionInput {
103 readonly threadId: ThreadId;
104 readonly provider?: "codex";
105 readonly cwd?: string;
106 readonly model?: string;
107 readonly serviceTier?: string;
108 readonly resumeCursor?: unknown;
109 readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
110 readonly runtimeMode: RuntimeMode;
112​
113export interface CodexThreadTurnSnapshot {
114 id: TurnId;
115 items: unknown[];
117​
118export interface CodexThreadSnapshot {
119 threadId: string;
120 turns: CodexThreadTurnSnapshot[];
122​
123const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
124const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
125const CODEX_STDERR_LOG_REGEX =
126 /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/;
127const BENIGN_ERROR_LOG_SNIPPETS = [
128 "state db missing rollout path for thread",
129 "state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
130];
131const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
132 "not found",
133 "missing thread",
134 "no such thread",
135 "unknown thread",
136 "does not exist",
137];
138export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
139​
140You 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.
141​
142## Mode rules (strict)
143​
144You are in **Plan Mode** until a developer message explicitly ends it.
145​
146Plan 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.
147​
148## Plan Mode vs update_plan tool
149​
150Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
151​
152Separately, \`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.
153​
154## Execution vs. mutation in Plan Mode
155​
156You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
157​
158### Allowed (non-mutating, plan-improving)
159​
160Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
161​
162* Reading or searching files, configs, schemas, types, manifests, and docs
163* Static analysis, inspection, and repo exploration
164* Dry-run style commands when they do not edit repo-tracked files
165* 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
166​
167### Not allowed (mutating, plan-executing)
168​
169Actions that implement the plan or change repo-tracked state. Examples:
170​
171* Editing or writing files
172* Running formatters or linters that rewrite files
173* Applying patches, migrations, or codegen that updates repo-tracked files
174* Side-effectful commands whose purpose is to carry out the plan rather than refine it
175​
176When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
177​
178## PHASE 1 - Ground in the environment (explore first, ask second)
179​
180Begin 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.
181​
182Before 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.
183​
184Exception: 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.
185​
186Do 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.
187​
188## PHASE 2 - Intent chat (what they actually want)
189​
190* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
191* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
192​
193## PHASE 3 - Implementation chat (what/how we'll build)
194​
195* 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.
196​
197## Asking questions
198​
199Critical rules:
200​
201* Strongly prefer using the \`request_user_input\` tool to ask any questions.
202* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
203* 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.
204​
205You SHOULD ask many questions, but each question must:
206​
207* materially change the spec/plan, OR
208* confirm/lock an assumption, OR
209* choose between meaningful tradeoffs.
210* not be answerable by non-mutating commands.
211​
212Use 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.
213​
214## Two kinds of unknowns (treat differently)
215​
2161. **Discoverable facts** (repo/system truth): explore first.
217​
218 * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
219 * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
220 * If asking, present concrete candidates (paths/service names) + recommend one.
221 * Never ask questions you can answer from your environment (e.g., "where is this struct").
222​
2232. **Preferences/tradeoffs** (not discoverable): ask early.
224​
225 * These are intent or implementation preferences that cannot be derived from exploration.
226 * Provide 2-4 mutually exclusive options + a recommended default.
227 * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
228​
229## Finalization rule
230​
231Only output the final plan when it is decision complete and leaves no decisions to the implementer.
232​
233When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
234​
2351) The opening tag must be on its own line.
2362) Start the plan content on the next line (no text on the same line as the tag).
2373) The closing tag must be on its own line.
2384) Use Markdown inside the block.
2395) 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.
240​
241Example:
242​
243<proposed_plan>
244plan content
245</proposed_plan>
246​
247plan content should be human and agent digestible. The final plan must be plan-only and include:
248​
249* A clear title
250* A brief summary section
251* Important changes or additions to public APIs/interfaces/types
252* Test cases and scenarios
253* Explicit assumptions and defaults chosen where needed
254​
255Do 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.
256​
257Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
258</collaboration_mode>`;
259​
260export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
261​
262You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
263​
264Your 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.
265​
266## request_user_input availability
267​
268The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
269​
270In 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.
271</collaboration_mode>`;
272​
273function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
274 readonly approvalPolicy: "on-request" | "never";
275 readonly sandbox: "workspace-write" | "danger-full-access";
276} {
277 if (runtimeMode === "approval-required") {
278 return {
279 approvalPolicy: "on-request",
280 sandbox: "workspace-write",
281 };
282 }
283​
284 return {
285 approvalPolicy: "never",
286 sandbox: "danger-full-access",
287 };
289​
290/**
291 * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
292 * wrapper, leaving the actual command running. Use `taskkill /T` to kill the
293 * entire process tree instead.
294 */
295function killChildTree(child: ChildProcessWithoutNullStreams): void {
296 if (process.platform === "win32" && child.pid !== undefined) {
297 try {
298 spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
299 return;
300 } catch {
301 // fallback to direct kill
302 }
303 }
304 child.kill();
306​
307export function normalizeCodexModelSlug(
308 model: string | undefined | null,
309 preferredId?: string,
310): string | undefined {
311 const normalized = normalizeModelSlug(model);
312 if (!normalized) {
313 return undefined;
314 }
315​
316 if (preferredId?.endsWith("-codex") && preferredId !== normalized) {
317 return preferredId;
318 }
319​
320 return normalized;
322​
323export function buildCodexInitializeParams() {
324 return {
325 clientInfo: {
326 name: "t3code_desktop",
327 title: "T3 Code Desktop",
328 version: "0.1.0",
329 },
330 capabilities: {
331 experimentalApi: true,
332 },
333 } as const;
335​
336function buildCodexCollaborationMode(input: {
337 readonly interactionMode?: "default" | "plan";
338 readonly model?: string;
339 readonly effort?: string;
340}):
341 | {
342 mode: "default" | "plan";
343 settings: {
344 model: string;
345 reasoning_effort: string;
346 developer_instructions: string;
347 };
348 }
349 | undefined {
350 if (input.interactionMode === undefined) {
351 return undefined;
352 }
353 const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex";
354 return {
355 mode: input.interactionMode,
356 settings: {
357 model,
358 reasoning_effort: input.effort ?? "medium",
359 developer_instructions:
360 input.interactionMode === "plan"
361 ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
362 : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
363 },
364 };
366​
367function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer {
368 if (typeof value === "string") {
369 return { answers: [value] };
370 }
371​
372 if (Array.isArray(value)) {
373 const answers = value.filter((entry): entry is string => typeof entry === "string");
374 return { answers };
375 }
376​
377 if (value && typeof value === "object") {
378 const maybeAnswers = (value as { answers?: unknown }).answers;
379 if (Array.isArray(maybeAnswers)) {
380 const answers = maybeAnswers.filter((entry): entry is string => typeof entry === "string");
381 return { answers };
382 }
383 }
384​
385 throw new Error("User input answers must be strings or arrays of strings.");
387​
388function toCodexUserInputAnswers(
389 answers: ProviderUserInputAnswers,
390): Record<string, CodexUserInputAnswer> {
391 return Object.fromEntries(
392 Object.entries(answers).map(([questionId, value]) => [
393 questionId,
394 toCodexUserInputAnswer(value),
395 ]),
396 );
398​
399export function classifyCodexStderrLine(rawLine: string): { message: string } | null {
400 const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim();
401 if (!line) {
402 return null;
403 }
404​
405 const match = line.match(CODEX_STDERR_LOG_REGEX);
406 if (match) {
407 const level = match[1];
408 if (level && level !== "ERROR") {
409 return null;
410 }
411​
412 const isBenignError = BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet));
413 if (isBenignError) {
414 return null;
415 }
416 }
417​
418 return { message: line };
420​
421export function isRecoverableThreadResumeError(error: unknown): boolean {
422 const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
423 if (!message.includes("thread/resume")) {
424 return false;
425 }
426​
427 return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
429​
430export interface CodexAppServerManagerEvents {
431 event: [event: ProviderEvent];
433​
434export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
435 private readonly sessions = new Map<ThreadId, CodexSessionContext>();
436​
437 private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
438 constructor(services?: ServiceMap.ServiceMap<never>) {
439 super();
440 this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
441 }
442​
443 async startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {
444 const threadId = input.threadId;
445 const now = new Date().toISOString();
446 let context: CodexSessionContext | undefined;
447​
448 try {
449 const resolvedCwd = input.cwd ?? process.cwd();
450​
451 const session: ProviderSession = {
452 provider: "codex",
453 status: "connecting",
454 runtimeMode: input.runtimeMode,
455 model: normalizeCodexModelSlug(input.model),
456 cwd: resolvedCwd,
457 threadId,
458 createdAt: now,
459 updatedAt: now,
460 };
461​
462 const codexOptions = readCodexProviderOptions(input);
463 const codexBinaryPath = codexOptions.binaryPath ?? "codex";
464 const codexHomePath = codexOptions.homePath;
465 const child = spawn(codexBinaryPath, ["app-server"], {
466 cwd: resolvedCwd,
467 env: {
468 ...process.env,
469 ...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
470 },
471 stdio: ["pipe", "pipe", "pipe"],
472 shell: process.platform === "win32",
473 });
474 const output = readline.createInterface({ input: child.stdout });
475​
476 context = {
477 session,
478 child,
479 output,
480 pending: new Map(),
481 pendingApprovals: new Map(),
482 pendingUserInputs: new Map(),
483 nextRequestId: 1,
484 stopping: false,
485 };
486​
487 this.sessions.set(threadId, context);
488 this.attachProcessListeners(context);
489​
490 this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
491​
492 await this.sendRequest(context, "initialize", buildCodexInitializeParams());
493​
494 this.writeMessage(context, { method: "initialized" });
495​
496 const normalizedModel = normalizeCodexModelSlug(input.model);
497 const sessionOverrides = {
498 model: normalizedModel ?? null,
499 cwd: input.cwd ?? null,
500 ...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
501 ...mapCodexRuntimeMode(input.runtimeMode ?? "full-access"),
502 };
503​
504 const threadStartParams = {
505 ...sessionOverrides,
506 experimentalRawEvents: false,
507 };
508 const resumeThreadId = readResumeThreadId(input);
509 this.emitLifecycleEvent(
510 context,
511 "session/threadOpenRequested",
512 resumeThreadId
513 ? `Attempting to resume thread ${resumeThreadId}.`
514 : "Starting a new Codex thread.",
515 );
516 await Effect.logInfo("codex app-server opening thread", {
517 threadId,
518 requestedRuntimeMode: input.runtimeMode,
519 requestedModel: normalizedModel ?? null,
520 requestedCwd: resolvedCwd,
521 resumeThreadId: resumeThreadId ?? null,
522 }).pipe(this.runPromise);
523​
524 let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start";
525 let threadOpenResponse: unknown;
526 if (resumeThreadId) {
527 try {
528 threadOpenMethod = "thread/resume";
529 threadOpenResponse = await this.sendRequest(context, "thread/resume", {
530 ...sessionOverrides,
531 threadId: resumeThreadId,
532 });
533 } catch (error) {
534 if (!isRecoverableThreadResumeError(error)) {
535 this.emitErrorEvent(
536 context,
537 "session/threadResumeFailed",
538 error instanceof Error ? error.message : "Codex thread resume failed.",
539 );
540 await Effect.logWarning("codex app-server thread resume failed", {
541 threadId,
542 requestedRuntimeMode: input.runtimeMode,
543 resumeThreadId,
544 recoverable: false,
545 cause: error instanceof Error ? error.message : String(error),
546 }).pipe(this.runPromise);
547 throw error;
548 }
549​
550 threadOpenMethod = "thread/start";
551 this.emitLifecycleEvent(
552 context,
553 "session/threadResumeFallback",
554 `Could not resume thread ${resumeThreadId}; started a new thread instead.`,
555 );
556 await Effect.logWarning("codex app-server thread resume fell back to fresh start", {
557 threadId,
558 requestedRuntimeMode: input.runtimeMode,
559 resumeThreadId,
560 recoverable: true,
561 cause: error instanceof Error ? error.message : String(error),
562 }).pipe(this.runPromise);
563 threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
564 }
565 } else {
566 threadOpenMethod = "thread/start";
567 threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
568 }
569​
570 const threadOpenRecord = this.readObject(threadOpenResponse);
571 const threadIdRaw =
572 this.readString(this.readObject(threadOpenRecord, "thread"), "id") ??
573 this.readString(threadOpenRecord, "threadId");
574 if (!threadIdRaw) {
575 throw new Error(`${threadOpenMethod} response did not include a thread id.`);
576 }
577 const providerThreadId = threadIdRaw;
578​
579 this.updateSession(context, {
580 status: "ready",
581 resumeCursor: { threadId: providerThreadId },
582 });
583 this.emitLifecycleEvent(
584 context,
585 "session/threadOpenResolved",
586 `Codex ${threadOpenMethod} resolved.`,
587 );
588 await Effect.logInfo("codex app-server thread open resolved", {
589 threadId,
590 threadOpenMethod,
591 requestedResumeThreadId: resumeThreadId ?? null,
592 resolvedThreadId: providerThreadId,
593 requestedRuntimeMode: input.runtimeMode,
594 }).pipe(this.runPromise);
595 this.emitLifecycleEvent(context, "session/ready", `Connected to thread ${providerThreadId}`);
596 return { ...context.session };
597 } catch (error) {
598 const message = error instanceof Error ? error.message : "Failed to start Codex session.";
599 if (context) {
600 this.updateSession(context, {
601 status: "error",
602 lastError: message,
603 });
604 this.emitErrorEvent(context, "session/startFailed", message);
605 this.stopSession(threadId);
606 } else {
607 this.emitEvent({
608 id: EventId.makeUnsafe(randomUUID()),
609 kind: "error",
610 provider: "codex",
611 threadId,
612 createdAt: new Date().toISOString(),
613 method: "session/startFailed",
614 message,
615 });
616 }
617 throw new Error(message, { cause: error });
618 }
619 }
620​
621 async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
622 const context = this.requireSession(input.threadId);
623​
624 const turnInput: Array<
625 { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
626 > = [];
627 if (input.input) {
628 turnInput.push({
629 type: "text",
630 text: input.input,
631 text_elements: [],
632 });
633 }
634 for (const attachment of input.attachments ?? []) {
635 if (attachment.type === "image") {
636 turnInput.push({
637 type: "image",
638 url: attachment.url,
639 });
640 }
641 }
642 if (turnInput.length === 0) {
643 throw new Error("Turn input must include text or attachments.");
644 }
645​
646 const providerThreadId = readResumeThreadId({
647 threadId: context.session.threadId,
648 runtimeMode: context.session.runtimeMode,
649 resumeCursor: context.session.resumeCursor,
650 });
651 if (!providerThreadId) {
652 throw new Error("Session is missing provider resume thread id.");
653 }
654 const turnStartParams: {
655 threadId: string;
656 input: Array<
657 { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
658 >;
659 model?: string;
660 effort?: string;
661 serviceTier?: string;
662 collaborationMode?: {
663 mode: "default" | "plan";
664 settings: {
665 model: string;
666 reasoning_effort: string;
667 developer_instructions: string;
668 };
669 };
670 } = {
671 threadId: providerThreadId,
672 input: turnInput,
673 };
674 const normalizedModel = normalizeCodexModelSlug(input.model ?? context.session.model);
675 if (normalizedModel) {
676 turnStartParams.model = normalizedModel;
677 }
678 if (input.effort) {
679 turnStartParams.effort = input.effort;
680 }
681 if (input.serviceTier) {
682 turnStartParams.serviceTier = input.serviceTier;
683 }
684 const collaborationMode = buildCodexCollaborationMode({
685 ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
686 ...(normalizedModel !== undefined ? { model: normalizedModel } : {}),
687 ...(input.effort !== undefined ? { effort: input.effort } : {}),
688 });
689 if (collaborationMode) {
690 if (!turnStartParams.model) {
691 turnStartParams.model = collaborationMode.settings.model;
692 }
693 turnStartParams.collaborationMode = collaborationMode;
694 }
695​
696 const response = await this.sendRequest(context, "turn/start", turnStartParams);
697​
698 const turn = this.readObject(this.readObject(response), "turn");
699 const turnIdRaw = this.readString(turn, "id");
700 if (!turnIdRaw) {
701 throw new Error("turn/start response did not include a turn id.");
702 }
703 const turnId = TurnId.makeUnsafe(turnIdRaw);
704​
705 this.updateSession(context, {
706 status: "running",
707 activeTurnId: turnId,
708 ...(context.session.resumeCursor !== undefined
709 ? { resumeCursor: context.session.resumeCursor }
710 : {}),
711 });
712​
713 return {
714 threadId: context.session.threadId,
715 turnId,
716 ...(context.session.resumeCursor !== undefined
717 ? { resumeCursor: context.session.resumeCursor }
718 : {}),
719 };
720 }
721​
722 async interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise<void> {
723 const context = this.requireSession(threadId);
724 const effectiveTurnId = turnId ?? context.session.activeTurnId;
725​
726 const providerThreadId = readResumeThreadId({
727 threadId: context.session.threadId,
728 runtimeMode: context.session.runtimeMode,
729 resumeCursor: context.session.resumeCursor,
730 });
731 if (!effectiveTurnId || !providerThreadId) {
732 return;
733 }
734​
735 await this.sendRequest(context, "turn/interrupt", {
736 threadId: providerThreadId,
737 turnId: effectiveTurnId,
738 });
739 }
740​
741 async readThread(threadId: ThreadId): Promise<CodexThreadSnapshot> {
742 const context = this.requireSession(threadId);
743 const providerThreadId = readResumeThreadId({
744 threadId: context.session.threadId,
745 runtimeMode: context.session.runtimeMode,
746 resumeCursor: context.session.resumeCursor,
747 });
748 if (!providerThreadId) {
749 throw new Error("Session is missing a provider resume thread id.");
750 }
751​
752 const response = await this.sendRequest(context, "thread/read", {
753 threadId: providerThreadId,
754 includeTurns: true,
755 });
756 return this.parseThreadSnapshot("thread/read", response);
757 }
758​
759 async rollbackThread(threadId: ThreadId, numTurns: number): Promise<CodexThreadSnapshot> {
760 const context = this.requireSession(threadId);
761 const providerThreadId = readResumeThreadId({
762 threadId: context.session.threadId,
763 runtimeMode: context.session.runtimeMode,
764 resumeCursor: context.session.resumeCursor,
765 });
766 if (!providerThreadId) {
767 throw new Error("Session is missing a provider resume thread id.");
768 }
769 if (!Number.isInteger(numTurns) || numTurns < 1) {
770 throw new Error("numTurns must be an integer >= 1.");
771 }
772​
773 const response = await this.sendRequest(context, "thread/rollback", {
774 threadId: providerThreadId,
775 numTurns,
776 });
777 this.updateSession(context, {
778 status: "ready",
779 activeTurnId: undefined,
780 });
781 return this.parseThreadSnapshot("thread/rollback", response);
782 }
783​
784 async respondToRequest(
785 threadId: ThreadId,
786 requestId: ApprovalRequestId,
787 decision: ProviderApprovalDecision,
788 ): Promise<void> {
789 const context = this.requireSession(threadId);
790 const pendingRequest = context.pendingApprovals.get(requestId);
791 if (!pendingRequest) {
792 throw new Error(`Unknown pending approval request: ${requestId}`);
793 }
794​
795 context.pendingApprovals.delete(requestId);
796 this.writeMessage(context, {
797 id: pendingRequest.jsonRpcId,
798 result: {
799 decision,
800 },
801 });
802​
803 this.emitEvent({
804 id: EventId.makeUnsafe(randomUUID()),
805 kind: "notification",
806 provider: "codex",
807 threadId: context.session.threadId,
808 createdAt: new Date().toISOString(),
809 method: "item/requestApproval/decision",
810 turnId: pendingRequest.turnId,
811 itemId: pendingRequest.itemId,
812 requestId: pendingRequest.requestId,
813 requestKind: pendingRequest.requestKind,
814 payload: {
815 requestId: pendingRequest.requestId,
816 requestKind: pendingRequest.requestKind,
817 decision,
818 },
819 });
820 }
821​
822 async respondToUserInput(
823 threadId: ThreadId,
824 requestId: ApprovalRequestId,
825 answers: ProviderUserInputAnswers,
826 ): Promise<void> {
827 const context = this.requireSession(threadId);
828 const pendingRequest = context.pendingUserInputs.get(requestId);
829 if (!pendingRequest) {
830 throw new Error(`Unknown pending user input request: ${requestId}`);
831 }
832​
833 context.pendingUserInputs.delete(requestId);
834 const codexAnswers = toCodexUserInputAnswers(answers);
835 this.writeMessage(context, {
836 id: pendingRequest.jsonRpcId,
837 result: {
838 answers: codexAnswers,
839 },
840 });
841​
842 this.emitEvent({
843 id: EventId.makeUnsafe(randomUUID()),
844 kind: "notification",
845 provider: "codex",
846 threadId: context.session.threadId,
847 createdAt: new Date().toISOString(),
848 method: "item/tool/requestUserInput/answered",
849 turnId: pendingRequest.turnId,
850 itemId: pendingRequest.itemId,
851 requestId: pendingRequest.requestId,
852 payload: {
853 requestId: pendingRequest.requestId,
854 answers: codexAnswers,
855 },
856 });
857 }
858​
859 stopSession(threadId: ThreadId): void {
860 const context = this.sessions.get(threadId);
861 if (!context) {
862 return;
863 }
864​
865 context.stopping = true;
866​
867 for (const pending of context.pending.values()) {
868 clearTimeout(pending.timeout);
869 pending.reject(new Error("Session stopped before request completed."));
870 }
871 context.pending.clear();
872 context.pendingApprovals.clear();
873 context.pendingUserInputs.clear();
874​
875 context.output.close();
876​
877 if (!context.child.killed) {
878 killChildTree(context.child);
879 }
880​
881 this.updateSession(context, {
882 status: "closed",
883 activeTurnId: undefined,
884 });
885 this.emitLifecycleEvent(context, "session/closed", "Session stopped");
886 this.sessions.delete(threadId);
887 }
888​
889 listSessions(): ProviderSession[] {
890 return Array.from(this.sessions.values(), ({ session }) => ({
891 ...session,
892 }));
893 }
894​
895 hasSession(threadId: ThreadId): boolean {
896 return this.sessions.has(threadId);
897 }
898​
899 stopAll(): void {
900 for (const threadId of this.sessions.keys()) {
901 this.stopSession(threadId);
902 }
903 }
904​
905 private requireSession(threadId: ThreadId): CodexSessionContext {
906 const context = this.sessions.get(threadId);
907 if (!context) {
908 throw new Error(`Unknown session for thread: ${threadId}`);
909 }
910​
911 if (context.session.status === "closed") {
912 throw new Error(`Session is closed for thread: ${threadId}`);
913 }
914​
915 return context;
916 }
917​
918 private attachProcessListeners(context: CodexSessionContext): void {
919 context.output.on("line", (line) => {
920 this.handleStdoutLine(context, line);
921 });
922​
923 context.child.stderr.on("data", (chunk: Buffer) => {
924 const raw = chunk.toString();
925 const lines = raw.split(/\r?\n/g);
926 for (const rawLine of lines) {
927 const classified = classifyCodexStderrLine(rawLine);
928 if (!classified) {
929 continue;
930 }
931​
932 this.emitErrorEvent(context, "process/stderr", classified.message);
933 }
934 });
935​
936 context.child.on("error", (error) => {
937 const message = error.message || "codex app-server process errored.";
938 this.updateSession(context, {
939 status: "error",
940 lastError: message,
941 });
942 this.emitErrorEvent(context, "process/error", message);
943 });
944​
945 context.child.on("exit", (code, signal) => {
946 if (context.stopping) {
947 return;
948 }
949​
950 const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`;
951 this.updateSession(context, {
952 status: "closed",
953 activeTurnId: undefined,
954 lastError: code === 0 ? context.session.lastError : message,
955 });
956 this.emitLifecycleEvent(context, "session/exited", message);
957 this.sessions.delete(context.session.threadId);
958 });
959 }
960​
961 private handleStdoutLine(context: CodexSessionContext, line: string): void {
962 let parsed: unknown;
963 try {
964 parsed = JSON.parse(line);
965 } catch {
966 this.emitErrorEvent(
967 context,
968 "protocol/parseError",
969 "Received invalid JSON from codex app-server.",
970 );
971 return;
972 }
973​
974 if (!parsed || typeof parsed !== "object") {
975 this.emitErrorEvent(
976 context,
977 "protocol/invalidMessage",
978 "Received non-object protocol message.",
979 );
980 return;
981 }
982​
983 if (this.isServerRequest(parsed)) {
984 this.handleServerRequest(context, parsed);
985 return;
986 }
987​
988 if (this.isServerNotification(parsed)) {
989 this.handleServerNotification(context, parsed);
990 return;
991 }
992​
993 if (this.isResponse(parsed)) {
994 this.handleResponse(context, parsed);
995 return;
996 }
997​
998 this.emitErrorEvent(
999 context,
1000 "protocol/unrecognizedMessage",
1001 "Received protocol message in an unknown shape.",
1002 );
1004​
1005 private handleServerNotification(
1006 context: CodexSessionContext,
1007 notification: JsonRpcNotification,
1008 ): void {
1009 const route = this.readRouteFields(notification.params);
1010 const textDelta =
1011 notification.method === "item/agentMessage/delta"
1012 ? this.readString(notification.params, "delta")
1013 : undefined;
1014​
1015 this.emitEvent({
1016 id: EventId.makeUnsafe(randomUUID()),
1017 kind: "notification",
1018 provider: "codex",
1019 threadId: context.session.threadId,
1020 createdAt: new Date().toISOString(),
1021 method: notification.method,
1022 turnId: route.turnId,
1023 itemId: route.itemId,
1024 textDelta,
1025 payload: notification.params,
1026 });
1027​
1028 if (notification.method === "thread/started") {
1029 const providerThreadId = normalizeProviderThreadId(
1030 this.readString(this.readObject(notification.params)?.thread, "id"),
1031 );
1032 if (providerThreadId) {
1033 this.updateSession(context, { resumeCursor: { threadId: providerThreadId } });
1035 return;
1037​
1038 if (notification.method === "turn/started") {
1039 const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
1040 this.updateSession(context, {
1041 status: "running",
1042 activeTurnId: turnId,
1043 });
1044 return;
1046​
1047 if (notification.method === "turn/completed") {
1048 const turn = this.readObject(notification.params, "turn");
1049 const status = this.readString(turn, "status");
1050 const errorMessage = this.readString(this.readObject(turn, "error"), "message");
1051 this.updateSession(context, {
1052 status: status === "failed" ? "error" : "ready",
1053 activeTurnId: undefined,
1054 lastError: errorMessage ?? context.session.lastError,
1055 });
1056 return;
1058​
1059 if (notification.method === "error") {
1060 const message = this.readString(this.readObject(notification.params)?.error, "message");
1061 const willRetry = this.readBoolean(notification.params, "willRetry");
1062​
1063 this.updateSession(context, {
1064 status: willRetry ? "running" : "error",
1065 lastError: message ?? context.session.lastError,
1066 });
1069​
1070 private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
1071 const route = this.readRouteFields(request.params);
1072 const requestKind = this.requestKindForMethod(request.method);
1073 let requestId: ApprovalRequestId | undefined;
1074 if (requestKind) {
1075 requestId = ApprovalRequestId.makeUnsafe(randomUUID());
1076 const pendingRequest: PendingApprovalRequest = {
1077 requestId,
1078 jsonRpcId: request.id,
1079 method:
1080 requestKind === "command"
1081 ? "item/commandExecution/requestApproval"
1082 : requestKind === "file-read"
1083 ? "item/fileRead/requestApproval"
1084 : "item/fileChange/requestApproval",
1085 requestKind,
1086 threadId: context.session.threadId,
1087 ...(route.turnId ? { turnId: route.turnId } : {}),
1088 ...(route.itemId ? { itemId: route.itemId } : {}),
1089 };
1090 context.pendingApprovals.set(requestId, pendingRequest);
1092​
1093 if (request.method === "item/tool/requestUserInput") {
1094 requestId = ApprovalRequestId.makeUnsafe(randomUUID());
1095 context.pendingUserInputs.set(requestId, {
1096 requestId,
1097 jsonRpcId: request.id,
1098 threadId: context.session.threadId,
1099 ...(route.turnId ? { turnId: route.turnId } : {}),
1100 ...(route.itemId ? { itemId: route.itemId } : {}),
1101 });
1103​
1104 this.emitEvent({
1105 id: EventId.makeUnsafe(randomUUID()),
1106 kind: "request",
1107 provider: "codex",
1108 threadId: context.session.threadId,
1109 createdAt: new Date().toISOString(),
1110 method: request.method,
1111 turnId: route.turnId,
1112 itemId: route.itemId,
1113 requestId,
1114 requestKind,
1115 payload: request.params,
1116 });
1117​
1118 if (requestKind) {
1119 return;
1121​
1122 if (request.method === "item/tool/requestUserInput") {
1123 return;
1125​
1126 this.writeMessage(context, {
1127 id: request.id,
1128 error: {
1129 code: -32601,
1130 message: `Unsupported server request: ${request.method}`,
1131 },
1132 });
1134​
1135 private handleResponse(context: CodexSessionContext, response: JsonRpcResponse): void {
1136 const key = String(response.id);
1137 const pending = context.pending.get(key);
1138 if (!pending) {
1139 return;
1141​
1142 clearTimeout(pending.timeout);
1143 context.pending.delete(key);
1144​
1145 if (response.error?.message) {
1146 pending.reject(new Error(`${pending.method} failed: ${String(response.error.message)}`));
1147 return;
1149​
1150 pending.resolve(response.result);
1152​
1153 private async sendRequest<TResponse>(
1154 context: CodexSessionContext,
1155 method: string,
1156 params: unknown,
1157 timeoutMs = 20_000,
1158 ): Promise<TResponse> {
1159 const id = context.nextRequestId;
1160 context.nextRequestId += 1;
1161​
1162 const result = await new Promise<unknown>((resolve, reject) => {
1163 const timeout = setTimeout(() => {
1164 context.pending.delete(String(id));
1165 reject(new Error(`Timed out waiting for ${method}.`));
1166 }, timeoutMs);
1167​
1168 context.pending.set(String(id), {
1169 method,
1170 timeout,
1171 resolve,
1172 reject,
1173 });
1174 this.writeMessage(context, {
1175 method,
1176 id,
1177 params,
1178 });
1179 });
1180​
1181 return result as TResponse;
1183​
1184 private writeMessage(context: CodexSessionContext, message: unknown): void {
1185 const encoded = JSON.stringify(message);
1186 if (!context.child.stdin.writable) {
1187 throw new Error("Cannot write to codex app-server stdin.");
1189​
1190 context.child.stdin.write(`${encoded}\n`);
1192​
1193 private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
1194 this.emitEvent({
1195 id: EventId.makeUnsafe(randomUUID()),
1196 kind: "session",
1197 provider: "codex",
1198 threadId: context.session.threadId,
1199 createdAt: new Date().toISOString(),
1200 method,
1201 message,
1202 });
1204​
1205 private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
1206 this.emitEvent({
1207 id: EventId.makeUnsafe(randomUUID()),
1208 kind: "error",
1209 provider: "codex",
1210 threadId: context.session.threadId,
1211 createdAt: new Date().toISOString(),
1212 method,
1213 message,
1214 });
1216​
1217 private emitEvent(event: ProviderEvent): void {
1218 this.emit("event", event);
1220​
1221 private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void {
1222 context.session = {
1223 ...context.session,
1224 ...updates,
1225 updatedAt: new Date().toISOString(),
1226 };
1228​
1229 private requestKindForMethod(method: string): ProviderRequestKind | undefined {
1230 if (method === "item/commandExecution/requestApproval") {
1231 return "command";
1233​
1234 if (method === "item/fileRead/requestApproval") {
1235 return "file-read";
1237​
1238 if (method === "item/fileChange/requestApproval") {
1239 return "file-change";
1241​
1242 return undefined;
1244​
1245 private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
1246 const responseRecord = this.readObject(response);
1247 const thread = this.readObject(responseRecord, "thread");
1248 const threadIdRaw =
1249 this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
1250 if (!threadIdRaw) {
1251 throw new Error(`${method} response did not include a thread id.`);
1253 const turnsRaw =
1254 this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
1255 const turns = turnsRaw.map((turnValue, index) => {
1256 const turn = this.readObject(turnValue);
1257 const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
1258 const turnId = TurnId.makeUnsafe(turnIdRaw);
1259 const items = this.readArray(turn, "items") ?? [];
1260 return {
1261 id: turnId,
1262 items,
1263 };
1264 });
1265​
1266 return {
1267 threadId: threadIdRaw,
1268 turns,
1269 };
1271​
1272 private isServerRequest(value: unknown): value is JsonRpcRequest {
1273 if (!value || typeof value !== "object") {
1274 return false;
1276​
1277 const candidate = value as Record<string, unknown>;
1278 return (
1279 typeof candidate.method === "string" &&
1280 (typeof candidate.id === "string" || typeof candidate.id === "number")
1281 );
1283​
1284 private isServerNotification(value: unknown): value is JsonRpcNotification {
1285 if (!value || typeof value !== "object") {
1286 return false;
1288​
1289 const candidate = value as Record<string, unknown>;
1290 return typeof candidate.method === "string" && !("id" in candidate);
1292​
1293 private isResponse(value: unknown): value is JsonRpcResponse {
1294 if (!value || typeof value !== "object") {
1295 return false;
1297​
1298 const candidate = value as Record<string, unknown>;
1299 const hasId = typeof candidate.id === "string" || typeof candidate.id === "number";
1300 const hasMethod = typeof candidate.method === "string";
1301 return hasId && !hasMethod;
1303​
1304 private readRouteFields(params: unknown): {
1305 turnId?: TurnId;
1306 itemId?: ProviderItemId;
1307 } {
1308 const route: {
1309 turnId?: TurnId;
1310 itemId?: ProviderItemId;
1311 } = {};
1312​
1313 const turnId = toTurnId(
1314 this.readString(params, "turnId") ?? this.readString(this.readObject(params, "turn"), "id"),
1315 );
1316 const itemId = toProviderItemId(
1317 this.readString(params, "itemId") ?? this.readString(this.readObject(params, "item"), "id"),
1318 );
1319​
1320 if (turnId) {
1321 route.turnId = turnId;
1323​
1324 if (itemId) {
1325 route.itemId = itemId;
1327​
1328 return route;
1330​
1331 private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
1332 const target =
1333 key === undefined
1334 ? value
1335 : value && typeof value === "object"
1336 ? (value as Record<string, unknown>)[key]
1337 : undefined;
1338​
1339 if (!target || typeof target !== "object") {
1340 return undefined;
1342​
1343 return target as Record<string, unknown>;
1345​
1346 private readArray(value: unknown, key?: string): unknown[] | undefined {
1347 const target =
1348 key === undefined
1349 ? value
1350 : value && typeof value === "object"
1351 ? (value as Record<string, unknown>)[key]
1352 : undefined;
1353 return Array.isArray(target) ? target : undefined;
1355​
1356 private readString(value: unknown, key: string): string | undefined {
1357 if (!value || typeof value !== "object") {
1358 return undefined;
1360​
1361 const candidate = (value as Record<string, unknown>)[key];
1362 return typeof candidate === "string" ? candidate : undefined;
1364​
1365 private readBoolean(value: unknown, key: string): boolean | undefined {
1366 if (!value || typeof value !== "object") {
1367 return undefined;
1369​
1370 const candidate = (value as Record<string, unknown>)[key];
1371 return typeof candidate === "boolean" ? candidate : undefined;
1374​
1375function brandIfNonEmpty<T extends string>(
1376 value: string | undefined,
1377 maker: (value: string) => T,
1378): T | undefined {
1379 const normalized = value?.trim();
1380 return normalized?.length ? maker(normalized) : undefined;
1382​
1383function normalizeProviderThreadId(value: string | undefined): string | undefined {
1384 return brandIfNonEmpty(value, (normalized) => normalized);
1386​
1387function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
1388 readonly binaryPath?: string;
1389 readonly homePath?: string;
1390} {
1391 const options = input.providerOptions?.codex;
1392 if (!options) {
1393 return {};
1395 return {
1396 ...(options.binaryPath ? { binaryPath: options.binaryPath } : {}),
1397 ...(options.homePath ? { homePath: options.homePath } : {}),
1398 };
1400​
1401function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
1402 if (!resumeCursor || typeof resumeCursor !== "object" || Array.isArray(resumeCursor)) {
1403 return undefined;
1405 const rawThreadId = (resumeCursor as Record<string, unknown>).threadId;
1406 return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
1408​
1409function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
1410 return readResumeCursorThreadId(input.resumeCursor);
1412​
1413function toTurnId(value: string | undefined): TurnId | undefined {
1414 return brandIfNonEmpty(value, TurnId.makeUnsafe);
1416​
1417function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
1418 return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);