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

codexAppServerManager.ts

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