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

CodexSessionRuntime.ts

1,331 lines44.6 KB

1import { randomUUID } from "node:crypto";
2​
3import {
4 ApprovalRequestId,
5 DEFAULT_MODEL_BY_PROVIDER,
6 EventId,
7 ProviderItemId,
8 type ProviderApprovalDecision,
9 type ProviderEvent,
10 type ProviderInteractionMode,
11 type ProviderRequestKind,
12 type ProviderSession,
13 type ProviderTurnStartResult,
14 type ProviderUserInputAnswers,
15 RuntimeMode,
16 ThreadId,
17 TurnId,
18} from "@t3tools/contracts";
19import { normalizeModelSlug } from "@t3tools/shared/model";
20import { Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Schema, Stream } from "effect";
21import * as SchemaIssue from "effect/SchemaIssue";
22import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
23import * as CodexClient from "effect-codex-app-server/client";
24import * as CodexErrors from "effect-codex-app-server/errors";
25import * as CodexRpc from "effect-codex-app-server/rpc";
26import * as EffectCodexSchema from "effect-codex-app-server/schema";
27​
28import { buildCodexInitializeParams } from "./CodexProvider.ts";
29import {
30 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
31 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
32} from "../CodexDeveloperInstructions.ts";
33import { expandHomePath } from "../../pathExpansion.ts";
34​
35const PROVIDER = "codex" as const;
36​
37const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
38const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
39const CODEX_STDERR_LOG_REGEX =
40 /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/;
41const BENIGN_ERROR_LOG_SNIPPETS = [
42 "state db missing rollout path for thread",
43 "state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
44];
45const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
46 "not found",
47 "missing thread",
48 "no such thread",
49 "unknown thread",
50 "does not exist",
51];
52​
53export const CodexResumeCursorSchema = Schema.Struct({
54 threadId: Schema.String,
55});
56const CodexUserInputAnswerObject = Schema.Struct({
57 answers: Schema.Array(Schema.String),
58});
59​
60// TODO: Verify `packages/effect-codex-app-server/scripts/generate.ts` so the generated
61// `V2TurnStartParams` schema includes `collaborationMode` directly.
62const CodexTurnStartParamsWithCollaborationMode = EffectCodexSchema.V2TurnStartParams.pipe(
63 Schema.fieldsAssign({
64 collaborationMode: Schema.optionalKey(EffectCodexSchema.V2TurnStartParams__CollaborationMode),
65 }),
66);
67​
68export type CodexTurnStartParamsWithCollaborationMode =
69 typeof CodexTurnStartParamsWithCollaborationMode.Type;
70const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
71​
72export type CodexResumeCursor = typeof CodexResumeCursorSchema.Type;
73type CodexThreadItem =
74 | EffectCodexSchema.V2ThreadReadResponse["thread"]["turns"][number]["items"][number]
75 | EffectCodexSchema.V2ThreadRollbackResponse["thread"]["turns"][number]["items"][number];
76​
77export interface CodexSessionRuntimeOptions {
78 readonly threadId: ThreadId;
79 readonly binaryPath: string;
80 readonly homePath?: string;
81 readonly cwd: string;
82 readonly runtimeMode: RuntimeMode;
83 readonly model?: string;
84 readonly serviceTier?: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined;
85 readonly resumeCursor?: CodexResumeCursor;
87​
88export interface CodexSessionRuntimeSendTurnInput {
89 readonly input?: string;
90 readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;
91 readonly model?: string;
92 readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier | undefined;
93 readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined;
94 readonly interactionMode?: ProviderInteractionMode;
96​
97export interface CodexThreadTurnSnapshot {
98 readonly id: TurnId;
99 readonly items: ReadonlyArray<CodexThreadItem>;
101​
102export interface CodexThreadSnapshot {
103 readonly threadId: string;
104 readonly turns: ReadonlyArray<CodexThreadTurnSnapshot>;
106​
107export interface CodexSessionRuntimeShape {
108 readonly start: () => Effect.Effect<ProviderSession, CodexSessionRuntimeError>;
109 readonly getSession: Effect.Effect<ProviderSession>;
110 readonly sendTurn: (
111 input: CodexSessionRuntimeSendTurnInput,
112 ) => Effect.Effect<ProviderTurnStartResult, CodexSessionRuntimeError>;
113 readonly interruptTurn: (turnId?: TurnId) => Effect.Effect<void, CodexSessionRuntimeError>;
114 readonly readThread: Effect.Effect<CodexThreadSnapshot, CodexSessionRuntimeError>;
115 readonly rollbackThread: (
116 numTurns: number,
117 ) => Effect.Effect<CodexThreadSnapshot, CodexSessionRuntimeError>;
118 readonly respondToRequest: (
119 requestId: ApprovalRequestId,
120 decision: ProviderApprovalDecision,
121 ) => Effect.Effect<void, CodexSessionRuntimeError>;
122 readonly respondToUserInput: (
123 requestId: ApprovalRequestId,
124 answers: ProviderUserInputAnswers,
125 ) => Effect.Effect<void, CodexSessionRuntimeError>;
126 readonly events: Stream.Stream<ProviderEvent, never>;
127 readonly close: Effect.Effect<void>;
129​
130export type CodexSessionRuntimeError =
131 | CodexErrors.CodexAppServerError
132 | CodexSessionRuntimePendingApprovalNotFoundError
133 | CodexSessionRuntimePendingUserInputNotFoundError
134 | CodexSessionRuntimeInvalidUserInputAnswersError
135 | CodexSessionRuntimeThreadIdMissingError;
136​
137export class CodexSessionRuntimePendingApprovalNotFoundError extends Schema.TaggedErrorClass<CodexSessionRuntimePendingApprovalNotFoundError>()(
138 "CodexSessionRuntimePendingApprovalNotFoundError",
139 {
140 requestId: Schema.String,
141 },
142) {
143 override get message(): string {
144 return `Unknown pending Codex approval request: ${this.requestId}`;
145 }
147​
148export class CodexSessionRuntimePendingUserInputNotFoundError extends Schema.TaggedErrorClass<CodexSessionRuntimePendingUserInputNotFoundError>()(
149 "CodexSessionRuntimePendingUserInputNotFoundError",
150 {
151 requestId: Schema.String,
152 },
153) {
154 override get message(): string {
155 return `Unknown pending Codex user input request: ${this.requestId}`;
156 }
158​
159export class CodexSessionRuntimeInvalidUserInputAnswersError extends Schema.TaggedErrorClass<CodexSessionRuntimeInvalidUserInputAnswersError>()(
160 "CodexSessionRuntimeInvalidUserInputAnswersError",
161 {
162 questionId: Schema.String,
163 },
164) {
165 override get message(): string {
166 return `Invalid Codex user input answers for question '${this.questionId}'`;
167 }
169​
170export class CodexSessionRuntimeThreadIdMissingError extends Schema.TaggedErrorClass<CodexSessionRuntimeThreadIdMissingError>()(
171 "CodexSessionRuntimeThreadIdMissingError",
172 {
173 threadId: Schema.String,
174 },
175) {
176 override get message(): string {
177 return `Codex session is missing a provider thread id for ${this.threadId}`;
178 }
180​
181interface PendingApproval {
182 readonly requestId: ApprovalRequestId;
183 readonly jsonRpcId: string;
184 readonly requestKind: ProviderRequestKind;
185 readonly turnId: TurnId | undefined;
186 readonly itemId: ProviderItemId | undefined;
187 readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
189​
190interface ApprovalCorrelation {
191 readonly requestId: ApprovalRequestId;
192 readonly requestKind: ProviderRequestKind;
193 readonly turnId: TurnId | undefined;
194 readonly itemId: ProviderItemId | undefined;
196​
197interface PendingUserInput {
198 readonly requestId: ApprovalRequestId;
199 readonly turnId: TurnId | undefined;
200 readonly itemId: ProviderItemId | undefined;
201 readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
203​
204type CodexServerNotification = {
205 readonly [M in CodexRpc.ServerNotificationMethod]: {
206 readonly method: M;
207 readonly params: CodexRpc.ServerNotificationParamsByMethod[M];
208 };
209}[CodexRpc.ServerNotificationMethod];
210​
211function makeCodexServerNotification<M extends CodexRpc.ServerNotificationMethod>(
212 method: M,
213 params: CodexRpc.ServerNotificationParamsByMethod[M],
214): CodexServerNotification {
215 return { method, params } as CodexServerNotification;
217​
218function normalizeCodexModelSlug(
219 model: string | undefined | null,
220 preferredId?: string,
221): string | undefined {
222 const normalized = normalizeModelSlug(model);
223 if (!normalized) {
224 return undefined;
225 }
226 if (preferredId?.endsWith("-codex") && preferredId !== normalized) {
227 return preferredId;
228 }
229 return normalized;
231​
232function readResumeCursorThreadId(
233 resumeCursor: ProviderSession["resumeCursor"],
234): string | undefined {
235 return Schema.is(CodexResumeCursorSchema)(resumeCursor) ? resumeCursor.threadId : undefined;
237​
238function runtimeModeToThreadConfig(input: RuntimeMode): {
239 readonly approvalPolicy: EffectCodexSchema.V2ThreadStartParams__AskForApproval;
240 readonly sandbox: EffectCodexSchema.V2ThreadStartParams__SandboxMode;
241} {
242 switch (input) {
243 case "approval-required":
244 return {
245 approvalPolicy: "untrusted",
246 sandbox: "read-only",
247 };
248 case "auto-accept-edits":
249 return {
250 approvalPolicy: "on-request",
251 sandbox: "workspace-write",
252 };
253 case "full-access":
254 default:
255 return {
256 approvalPolicy: "never",
257 sandbox: "danger-full-access",
258 };
259 }
261​
262function buildThreadStartParams(input: {
263 readonly cwd: string;
264 readonly runtimeMode: RuntimeMode;
265 readonly model: string | undefined;
266 readonly serviceTier: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined;
267}): EffectCodexSchema.V2ThreadStartParams {
268 const config = runtimeModeToThreadConfig(input.runtimeMode);
269 return {
270 cwd: input.cwd,
271 approvalPolicy: config.approvalPolicy,
272 sandbox: config.sandbox,
273 ...(input.model ? { model: input.model } : {}),
274 ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
275 };
277​
278function runtimeModeToTurnSandboxPolicy(
279 input: RuntimeMode,
280): EffectCodexSchema.V2TurnStartParams__SandboxPolicy {
281 switch (input) {
282 case "approval-required":
283 return {
284 type: "readOnly",
285 };
286 case "auto-accept-edits":
287 return {
288 type: "workspaceWrite",
289 };
290 case "full-access":
291 default:
292 return {
293 type: "dangerFullAccess",
294 };
295 }
297​
298function buildCodexCollaborationMode(input: {
299 readonly interactionMode?: ProviderInteractionMode;
300 readonly model?: string;
301 readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;
302}): EffectCodexSchema.V2TurnStartParams__CollaborationMode | undefined {
303 if (input.interactionMode === undefined) {
304 return undefined;
305 }
306 const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL_BY_PROVIDER.codex;
307 return {
308 mode: input.interactionMode,
309 settings: {
310 model,
311 reasoning_effort: input.effort ?? "medium",
312 developer_instructions:
313 input.interactionMode === "plan"
314 ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
315 : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
316 },
317 };
319​
320export function buildTurnStartParams(input: {
321 readonly threadId: string;
322 readonly runtimeMode: RuntimeMode;
323 readonly prompt?: string;
324 readonly attachments?: ReadonlyArray<{ readonly type: "image"; readonly url: string }>;
325 readonly model?: string;
326 readonly serviceTier?: EffectCodexSchema.V2TurnStartParams__ServiceTier;
327 readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;
328 readonly interactionMode?: ProviderInteractionMode;
329}): Effect.Effect<
330 CodexTurnStartParamsWithCollaborationMode,
331 CodexErrors.CodexAppServerProtocolParseError
332> {
333 const turnInput: Array<EffectCodexSchema.V2TurnStartParams__UserInput> = [];
334 if (input.prompt) {
335 turnInput.push({
336 type: "text",
337 text: input.prompt,
338 });
339 }
340 for (const attachment of input.attachments ?? []) {
341 turnInput.push(attachment);
342 }
343​
344 const config = runtimeModeToThreadConfig(input.runtimeMode);
345 const collaborationMode = buildCodexCollaborationMode({
346 ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
347 ...(input.model ? { model: input.model } : {}),
348 ...(input.effort ? { effort: input.effort } : {}),
349 });
350​
351 return Schema.decodeUnknownEffect(CodexTurnStartParamsWithCollaborationMode)({
352 threadId: input.threadId,
353 input: turnInput,
354 approvalPolicy: config.approvalPolicy,
355 sandboxPolicy: runtimeModeToTurnSandboxPolicy(input.runtimeMode),
356 ...(input.model ? { model: input.model } : {}),
357 ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
358 ...(input.effort ? { effort: input.effort } : {}),
359 ...(collaborationMode ? { collaborationMode } : {}),
360 }).pipe(
361 Effect.mapError((error) => toProtocolParseError("Invalid turn/start request payload", error)),
362 );
364​
365function classifyCodexStderrLine(rawLine: string): { readonly message: string } | null {
366 const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim();
367 if (!line) {
368 return null;
369 }
370​
371 const match = line.match(CODEX_STDERR_LOG_REGEX);
372 if (match) {
373 const level = match[1];
374 if (level && level !== "ERROR") {
375 return null;
376 }
377 if (BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet))) {
378 return null;
379 }
380 }
381​
382 return { message: line };
384​
385export function isRecoverableThreadResumeError(error: unknown): boolean {
386 const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
387 if (!message.includes("thread")) {
388 return false;
389 }
390 return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
392​
393type CodexThreadOpenResponse =
394 | CodexRpc.ClientRequestResponsesByMethod["thread/start"]
395 | CodexRpc.ClientRequestResponsesByMethod["thread/resume"];
396​
397type CodexThreadOpenMethod = "thread/start" | "thread/resume";
398​
399interface CodexThreadOpenClient {
400 readonly request: <M extends CodexThreadOpenMethod>(
401 method: M,
402 payload: CodexRpc.ClientRequestParamsByMethod[M],
403 ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexErrors.CodexAppServerError>;
405​
406export const openCodexThread = (input: {
407 readonly client: CodexThreadOpenClient;
408 readonly threadId: ThreadId;
409 readonly runtimeMode: RuntimeMode;
410 readonly cwd: string;
411 readonly requestedModel: string | undefined;
412 readonly serviceTier: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined;
413 readonly resumeThreadId: string | undefined;
414}): Effect.Effect<CodexThreadOpenResponse, CodexErrors.CodexAppServerError> => {
415 const resumeThreadId = input.resumeThreadId;
416 const startParams = buildThreadStartParams({
417 cwd: input.cwd,
418 runtimeMode: input.runtimeMode,
419 model: input.requestedModel,
420 serviceTier: input.serviceTier,
421 });
422​
423 if (resumeThreadId === undefined) {
424 return input.client.request("thread/start", startParams);
425 }
426​
427 return input.client
428 .request("thread/resume", {
429 threadId: resumeThreadId,
430 ...startParams,
431 })
432 .pipe(
433 Effect.catchIf(isRecoverableThreadResumeError, (error) =>
434 Effect.logWarning("codex app-server thread resume fell back to fresh start", {
435 threadId: input.threadId,
436 requestedRuntimeMode: input.runtimeMode,
437 resumeThreadId,
438 recoverable: true,
439 cause: error.message,
440 }).pipe(Effect.andThen(input.client.request("thread/start", startParams))),
441 ),
442 );
443};
444​
445function readNotificationThreadId(notification: CodexServerNotification): string | undefined {
446 switch (notification.method) {
447 case "thread/started":
448 return notification.params.thread.id;
449 case "error":
450 case "thread/status/changed":
451 case "thread/archived":
452 case "thread/unarchived":
453 case "thread/closed":
454 case "thread/name/updated":
455 case "thread/tokenUsage/updated":
456 case "turn/started":
457 case "hook/started":
458 case "turn/completed":
459 case "hook/completed":
460 case "turn/diff/updated":
461 case "turn/plan/updated":
462 case "item/started":
463 case "item/autoApprovalReview/started":
464 case "item/autoApprovalReview/completed":
465 case "item/completed":
466 case "rawResponseItem/completed":
467 case "item/agentMessage/delta":
468 case "item/plan/delta":
469 case "item/commandExecution/outputDelta":
470 case "item/commandExecution/terminalInteraction":
471 case "item/fileChange/outputDelta":
472 case "item/fileChange/patchUpdated":
473 case "serverRequest/resolved":
474 case "item/mcpToolCall/progress":
475 case "item/reasoning/summaryTextDelta":
476 case "item/reasoning/summaryPartAdded":
477 case "item/reasoning/textDelta":
478 case "thread/compacted":
479 case "thread/realtime/started":
480 case "thread/realtime/itemAdded":
481 case "thread/realtime/transcript/delta":
482 case "thread/realtime/transcript/done":
483 case "thread/realtime/outputAudio/delta":
484 case "thread/realtime/sdp":
485 case "thread/realtime/error":
486 case "thread/realtime/closed":
487 return notification.params.threadId;
488 default:
489 return undefined;
490 }
492​
493function readRouteFields(notification: CodexServerNotification): {
494 readonly turnId: TurnId | undefined;
495 readonly itemId: ProviderItemId | undefined;
496} {
497 switch (notification.method) {
498 case "thread/started":
499 return {
500 turnId: undefined,
501 itemId: undefined,
502 };
503 case "turn/started":
504 case "turn/completed":
505 return {
506 turnId: TurnId.make(notification.params.turn.id),
507 itemId: undefined,
508 };
509 case "error":
510 return {
511 turnId: TurnId.make(notification.params.turnId),
512 itemId: undefined,
513 };
514 case "turn/diff/updated":
515 case "turn/plan/updated":
516 return {
517 turnId: TurnId.make(notification.params.turnId),
518 itemId: undefined,
519 };
520 case "serverRequest/resolved":
521 return {
522 turnId: undefined,
523 itemId: undefined,
524 };
525 case "item/started":
526 case "item/completed":
527 return {
528 turnId: TurnId.make(notification.params.turnId),
529 itemId: ProviderItemId.make(notification.params.item.id),
530 };
531 case "item/agentMessage/delta":
532 case "item/plan/delta":
533 case "item/commandExecution/outputDelta":
534 case "item/commandExecution/terminalInteraction":
535 case "item/fileChange/outputDelta":
536 case "item/fileChange/patchUpdated":
537 case "item/reasoning/summaryTextDelta":
538 case "item/reasoning/summaryPartAdded":
539 case "item/reasoning/textDelta":
540 return {
541 turnId: TurnId.make(notification.params.turnId),
542 itemId: ProviderItemId.make(notification.params.itemId),
543 };
544 default:
545 return {
546 turnId: undefined,
547 itemId: undefined,
548 };
549 }
551​
552function rememberCollabReceiverTurns(
553 collabReceiverTurns: Map<string, TurnId>,
554 notification: CodexServerNotification,
555 parentTurnId: TurnId | undefined,
556): void {
557 if (!parentTurnId) {
558 return;
559 }
560​
561 if (notification.method !== "item/started" && notification.method !== "item/completed") {
562 return;
563 }
564​
565 if (notification.params.item.type !== "collabAgentToolCall") {
566 return;
567 }
568​
569 for (const receiverThreadId of notification.params.item.receiverThreadIds) {
570 collabReceiverTurns.set(receiverThreadId, parentTurnId);
571 }
573​
574function shouldSuppressChildConversationNotification(
575 method: CodexRpc.ServerNotificationMethod,
576): boolean {
577 return (
578 method === "thread/started" ||
579 method === "thread/status/changed" ||
580 method === "thread/archived" ||
581 method === "thread/unarchived" ||
582 method === "thread/closed" ||
583 method === "thread/compacted" ||
584 method === "thread/name/updated" ||
585 method === "thread/tokenUsage/updated" ||
586 method === "turn/started" ||
587 method === "turn/completed" ||
588 method === "turn/plan/updated" ||
589 method === "item/plan/delta"
590 );
592​
593function toCodexUserInputAnswer(
594 questionId: string,
595 value: ProviderUserInputAnswers[string],
596): Effect.Effect<
597 EffectCodexSchema.ToolRequestUserInputResponse__ToolRequestUserInputAnswer,
598 CodexSessionRuntimeInvalidUserInputAnswersError
599> {
600 if (typeof value === "string") {
601 return Effect.succeed({ answers: [value] });
602 }
603 if (Array.isArray(value)) {
604 const answers = value.filter((entry): entry is string => typeof entry === "string");
605 return Effect.succeed({ answers });
606 }
607 if (Schema.is(CodexUserInputAnswerObject)(value)) {
608 return Effect.succeed({ answers: value.answers });
609 }
610 return Effect.fail(new CodexSessionRuntimeInvalidUserInputAnswersError({ questionId }));
612​
613function toCodexUserInputAnswers(
614 answers: ProviderUserInputAnswers,
615): Effect.Effect<
616 EffectCodexSchema.ToolRequestUserInputResponse["answers"],
617 CodexSessionRuntimeInvalidUserInputAnswersError
618> {
619 return Effect.forEach(
620 Object.entries(answers),
621 ([questionId, value]) =>
622 toCodexUserInputAnswer(questionId, value).pipe(
623 Effect.map((answer) => [questionId, answer] as const),
624 ),
625 { concurrency: 1 },
626 ).pipe(Effect.map((entries) => Object.fromEntries(entries)));
628​
629function toProtocolParseError(
630 detail: string,
631 cause: Schema.SchemaError,
632): CodexErrors.CodexAppServerProtocolParseError {
633 return new CodexErrors.CodexAppServerProtocolParseError({
634 detail: `${detail}: ${formatSchemaIssue(cause.issue)}`,
635 cause,
636 });
638​
639function currentProviderThreadId(session: ProviderSession): string | undefined {
640 return readResumeCursorThreadId(session.resumeCursor);
642​
643function updateSession(
644 sessionRef: Ref.Ref<ProviderSession>,
645 updates: Partial<ProviderSession>,
646): Effect.Effect<void> {
647 return Ref.update(sessionRef, (session) => ({
648 ...session,
649 ...updates,
650 updatedAt: new Date().toISOString(),
651 }));
653​
654function parseThreadSnapshot(
655 response: EffectCodexSchema.V2ThreadReadResponse | EffectCodexSchema.V2ThreadRollbackResponse,
656): CodexThreadSnapshot {
657 return {
658 threadId: response.thread.id,
659 turns: response.thread.turns.map((turn) => ({
660 id: TurnId.make(turn.id),
661 items: turn.items,
662 })),
663 };
665​
666export const makeCodexSessionRuntime = (
667 options: CodexSessionRuntimeOptions,
668): Effect.Effect<
669 CodexSessionRuntimeShape,
670 CodexErrors.CodexAppServerError,
671 ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
672> =>
673 Effect.gen(function* () {
674 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
675 const runtimeScope = yield* Scope.Scope;
676 const events = yield* Queue.unbounded<ProviderEvent>();
677 const pendingApprovalsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingApproval>());
678 const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());
679 const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());
680 const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
681 const closedRef = yield* Ref.make(false);
682​
683 const child = yield* spawner
684 .spawn(
685 ChildProcess.make(options.binaryPath, ["app-server"], {
686 cwd: options.cwd,
687 ...(options.homePath
688 ? { env: { ...process.env, CODEX_HOME: expandHomePath(options.homePath) } }
689 : {}),
690 shell: process.platform === "win32",
691 }),
692 )
693 .pipe(
694 Effect.provideService(Scope.Scope, runtimeScope),
695 Effect.mapError(
696 (cause) =>
697 new CodexErrors.CodexAppServerSpawnError({
698 command: `${options.binaryPath} app-server`,
699 cause,
700 }),
701 ),
702 );
703​
704 const clientContext = yield* CodexClient.layerChildProcess(child).pipe(
705 Layer.build,
706 Effect.provideService(Scope.Scope, runtimeScope),
707 );
708 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
709 Effect.provide(clientContext),
710 );
711 const serverNotifications = yield* Queue.unbounded<CodexServerNotification>();
712​
713 const initialSession = {
714 provider: PROVIDER,
715 status: "connecting",
716 runtimeMode: options.runtimeMode,
717 cwd: options.cwd,
718 ...(options.model ? { model: options.model } : {}),
719 threadId: options.threadId,
720 ...(options.resumeCursor !== undefined ? { resumeCursor: options.resumeCursor } : {}),
721 createdAt: new Date().toISOString(),
722 updatedAt: new Date().toISOString(),
723 } satisfies ProviderSession;
724 const sessionRef = yield* Ref.make<ProviderSession>(initialSession);
725 const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);
726​
727 const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
728 offerEvent({
729 id: EventId.make(randomUUID()),
730 provider: PROVIDER,
731 createdAt: new Date().toISOString(),
732 ...event,
733 });
734​
735 const emitSessionEvent = (method: string, message: string) =>
736 emitEvent({
737 kind: "session",
738 threadId: options.threadId,
739 method,
740 message,
741 });
742​
743 const settlePendingApprovals = (decision: ProviderApprovalDecision) =>
744 Ref.get(pendingApprovalsRef).pipe(
745 Effect.flatMap((pendingApprovals) =>
746 Effect.forEach(
747 Array.from(pendingApprovals.values()),
748 (pendingApproval) =>
749 Deferred.succeed(pendingApproval.decision, decision).pipe(Effect.ignore),
750 { discard: true },
751 ),
752 ),
753 );
754​
755 const settlePendingUserInputs = (answers: ProviderUserInputAnswers) =>
756 Ref.get(pendingUserInputsRef).pipe(
757 Effect.flatMap((pendingUserInputs) =>
758 Effect.forEach(
759 Array.from(pendingUserInputs.values()),
760 (pendingUserInput) =>
761 Deferred.succeed(pendingUserInput.answers, answers).pipe(Effect.ignore),
762 { discard: true },
763 ),
764 ),
765 );
766​
767 const handleRawNotification = (notification: CodexServerNotification) =>
768 Effect.gen(function* () {
769 const payload = notification.params;
770 const route = readRouteFields(notification);
771 const collabReceiverTurns = yield* Ref.get(collabReceiverTurnsRef);
772 const childParentTurnId = (() => {
773 const providerConversationId = readNotificationThreadId(notification);
774 return providerConversationId
775 ? collabReceiverTurns.get(providerConversationId)
776 : undefined;
777 })();
778​
779 rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);
780 if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) {
781 yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
782 return;
783 }
784​
785 let requestId: ApprovalRequestId | undefined;
786 let requestKind: ProviderRequestKind | undefined;
787 let turnId = childParentTurnId ?? route.turnId;
788 let itemId = route.itemId;
789​
790 if (notification.method === "serverRequest/resolved") {
791 const rawRequestId =
792 typeof notification.params.requestId === "string"
793 ? notification.params.requestId
794 : String(notification.params.requestId);
795 const correlation = rawRequestId
796 ? (yield* Ref.get(approvalCorrelationsRef)).get(rawRequestId)
797 : undefined;
798 if (correlation) {
799 requestId = correlation.requestId;
800 requestKind = correlation.requestKind;
801 turnId = correlation.turnId ?? turnId;
802 itemId = correlation.itemId ?? itemId;
803 yield* Ref.update(approvalCorrelationsRef, (current) => {
804 const next = new Map(current);
805 next.delete(rawRequestId);
806 return next;
807 });
808 }
809 }
810​
811 yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
812 yield* emitEvent({
813 kind: "notification",
814 threadId: options.threadId,
815 method: notification.method,
816 ...(turnId ? { turnId } : {}),
817 ...(itemId ? { itemId } : {}),
818 ...(requestId ? { requestId } : {}),
819 ...(requestKind ? { requestKind } : {}),
820 ...(notification.method === "item/agentMessage/delta"
821 ? { textDelta: notification.params.delta }
822 : {}),
823 ...(payload !== undefined ? { payload } : {}),
824 });
825 });
826​
827 const currentSessionProviderThreadId = Effect.map(Ref.get(sessionRef), currentProviderThreadId);
828​
829 yield* client.handleServerNotification("thread/started", (payload) =>
830 currentSessionProviderThreadId.pipe(
831 Effect.flatMap((providerThreadId) => {
832 if (providerThreadId && payload.thread.id !== providerThreadId) {
833 return Effect.void;
834 }
835 return updateSession(sessionRef, {
836 resumeCursor: { threadId: payload.thread.id },
837 });
838 }),
839 ),
840 );
841​
842 yield* client.handleServerNotification("turn/started", (payload) =>
843 currentSessionProviderThreadId.pipe(
844 Effect.flatMap((providerThreadId) => {
845 if (providerThreadId && payload.threadId !== providerThreadId) {
846 return Effect.void;
847 }
848 return updateSession(sessionRef, {
849 status: "running",
850 activeTurnId: TurnId.make(payload.turn.id),
851 });
852 }),
853 ),
854 );
855​
856 yield* client.handleServerNotification("turn/completed", (payload) =>
857 currentSessionProviderThreadId.pipe(
858 Effect.flatMap((providerThreadId) => {
859 if (providerThreadId && payload.threadId !== providerThreadId) {
860 return Effect.void;
861 }
862 const lastError =
863 payload.turn.status === "failed" && "error" in payload.turn && payload.turn.error
864 ? payload.turn.error.message
865 : undefined;
866 return updateSession(sessionRef, {
867 status: payload.turn.status === "failed" ? "error" : "ready",
868 activeTurnId: undefined,
869 ...(lastError ? { lastError } : {}),
870 });
871 }),
872 ),
873 );
874​
875 yield* client.handleServerNotification("error", (payload) =>
876 currentSessionProviderThreadId.pipe(
877 Effect.flatMap((providerThreadId) => {
878 const payloadThreadId = payload.threadId;
879 if (providerThreadId && payloadThreadId && payloadThreadId !== providerThreadId) {
880 return Effect.void;
881 }
882 const errorMessage = payload.error.message;
883 const willRetry = payload.willRetry;
884 return updateSession(sessionRef, {
885 status: willRetry ? "running" : "error",
886 ...(errorMessage ? { lastError: errorMessage } : {}),
887 });
888 }),
889 ),
890 );
891​
892 yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) =>
893 Effect.gen(function* () {
894 const requestId = ApprovalRequestId.make(randomUUID());
895 const turnId = TurnId.make(payload.turnId);
896 const itemId = ProviderItemId.make(payload.itemId);
897 const decision = yield* Deferred.make<ProviderApprovalDecision>();
898​
899 yield* Ref.update(pendingApprovalsRef, (current) => {
900 const next = new Map(current);
901 next.set(requestId, {
902 requestId,
903 jsonRpcId: payload.approvalId ?? payload.itemId,
904 requestKind: "command",
905 turnId,
906 itemId,
907 decision,
908 });
909 return next;
910 });
911 yield* Ref.update(approvalCorrelationsRef, (current) => {
912 const next = new Map(current);
913 next.set(payload.approvalId ?? payload.itemId, {
914 requestId,
915 requestKind: "command",
916 turnId,
917 itemId,
918 });
919 return next;
920 });
921​
922 yield* emitEvent({
923 kind: "request",
924 threadId: options.threadId,
925 method: "item/commandExecution/requestApproval",
926 requestId,
927 requestKind: "command",
928 ...(turnId ? { turnId } : {}),
929 ...(itemId ? { itemId } : {}),
930 payload,
931 });
932​
933 const resolved = yield* Deferred.await(decision).pipe(
934 Effect.ensuring(
935 Ref.update(pendingApprovalsRef, (current) => {
936 const next = new Map(current);
937 next.delete(requestId);
938 return next;
939 }),
940 ),
941 );
942 return {
943 decision: resolved,
944 } satisfies EffectCodexSchema.CommandExecutionRequestApprovalResponse;
945 }),
946 );
947​
948 yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) =>
949 Effect.gen(function* () {
950 const requestId = ApprovalRequestId.make(randomUUID());
951 const turnId = TurnId.make(payload.turnId);
952 const itemId = ProviderItemId.make(payload.itemId);
953 const decision = yield* Deferred.make<ProviderApprovalDecision>();
954​
955 yield* Ref.update(pendingApprovalsRef, (current) => {
956 const next = new Map(current);
957 next.set(requestId, {
958 requestId,
959 jsonRpcId: payload.itemId,
960 requestKind: "file-change",
961 turnId,
962 itemId,
963 decision,
964 });
965 return next;
966 });
967 yield* Ref.update(approvalCorrelationsRef, (current) => {
968 const next = new Map(current);
969 next.set(payload.itemId, {
970 requestId,
971 requestKind: "file-change",
972 turnId,
973 itemId,
974 });
975 return next;
976 });
977​
978 yield* emitEvent({
979 kind: "request",
980 threadId: options.threadId,
981 method: "item/fileChange/requestApproval",
982 requestId,
983 requestKind: "file-change",
984 ...(turnId ? { turnId } : {}),
985 ...(itemId ? { itemId } : {}),
986 payload,
987 });
988​
989 const resolved = yield* Deferred.await(decision).pipe(
990 Effect.ensuring(
991 Ref.update(pendingApprovalsRef, (current) => {
992 const next = new Map(current);
993 next.delete(requestId);
994 return next;
995 }),
996 ),
997 );
998 return {
999 decision: resolved,
1000 } satisfies EffectCodexSchema.FileChangeRequestApprovalResponse;
1001 }),
1002 );
1003​
1004 yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
1005 Effect.gen(function* () {
1006 const requestId = ApprovalRequestId.make(randomUUID());
1007 const turnId = TurnId.make(payload.turnId);
1008 const itemId = ProviderItemId.make(payload.itemId);
1009 const answers = yield* Deferred.make<ProviderUserInputAnswers>();
1010​
1011 yield* Ref.update(pendingUserInputsRef, (current) => {
1012 const next = new Map(current);
1013 next.set(requestId, {
1014 requestId,
1015 turnId,
1016 itemId,
1017 answers,
1018 });
1019 return next;
1020 });
1021​
1022 yield* emitEvent({
1023 kind: "request",
1024 threadId: options.threadId,
1025 method: "item/tool/requestUserInput",
1026 requestId,
1027 ...(turnId ? { turnId } : {}),
1028 ...(itemId ? { itemId } : {}),
1029 payload,
1030 });
1031​
1032 const resolvedAnswers = yield* Deferred.await(answers).pipe(
1033 Effect.ensuring(
1034 Ref.update(pendingUserInputsRef, (current) => {
1035 const next = new Map(current);
1036 next.delete(requestId);
1037 return next;
1038 }),
1039 ),
1040 );
1041​
1042 return {
1043 answers: yield* toCodexUserInputAnswers(resolvedAnswers).pipe(
1044 Effect.mapError((error) =>
1045 CodexErrors.CodexAppServerRequestError.invalidParams(error.message, {
1046 questionId: error.questionId,
1047 }),
1048 ),
1049 ),
1050 } satisfies EffectCodexSchema.ToolRequestUserInputResponse;
1051 }),
1052 );
1053​
1054 yield* client.handleUnknownServerRequest((method) =>
1055 Effect.fail(CodexErrors.CodexAppServerRequestError.methodNotFound(method)),
1056 );
1057​
1058 const registerServerNotification = <M extends CodexRpc.ServerNotificationMethod>(method: M) =>
1059 client.handleServerNotification(method, (params) =>
1060 Queue.offer(serverNotifications, makeCodexServerNotification(method, params)).pipe(
1061 Effect.asVoid,
1062 ),
1063 );
1064​
1065 yield* Effect.forEach(
1066 Object.values(
1067 CodexRpc.SERVER_NOTIFICATION_METHODS,
1068 ) as ReadonlyArray<CodexRpc.ServerNotificationMethod>,
1069 registerServerNotification,
1070 { concurrency: 1, discard: true },
1071 );
1072​
1073 yield* Stream.fromQueue(serverNotifications).pipe(
1074 Stream.runForEach(handleRawNotification),
1075 Effect.forkIn(runtimeScope),
1076 );
1077​
1078 const stderrRemainderRef = yield* Ref.make("");
1079 yield* child.stderr.pipe(
1080 Stream.decodeText(),
1081 Stream.runForEach((chunk) =>
1082 Ref.modify(stderrRemainderRef, (current) => {
1083 const combined = current + chunk;
1084 const lines = combined.split("\n");
1085 const remainder = lines.pop() ?? "";
1086 return [lines.map((line) => line.replace(/\r$/, "")), remainder] as const;
1087 }).pipe(
1088 Effect.flatMap((lines) =>
1089 Effect.forEach(
1090 lines,
1091 (line) => {
1092 const classified = classifyCodexStderrLine(line);
1093 if (!classified) {
1094 return Effect.void;
1096 return emitEvent({
1097 kind: "notification",
1098 threadId: options.threadId,
1099 method: "process/stderr",
1100 message: classified.message,
1101 });
1102 },
1103 { discard: true },
1104 ),
1105 ),
1106 ),
1107 ),
1108 Effect.forkIn(runtimeScope),
1109 );
1110​
1111 yield* child.exitCode.pipe(
1112 Effect.flatMap((exitCode) =>
1113 Ref.get(closedRef).pipe(
1114 Effect.flatMap((closed) => {
1115 if (closed) {
1116 return Effect.void;
1118 const nextStatus = exitCode === 0 ? "closed" : "error";
1119 return updateSession(sessionRef, {
1120 status: nextStatus,
1121 activeTurnId: undefined,
1122 }).pipe(
1123 Effect.andThen(
1124 emitSessionEvent(
1125 "session/exited",
1126 exitCode === 0
1127 ? "Codex App Server exited."
1128 : `Codex App Server exited with code ${exitCode}.`,
1129 ),
1130 ),
1131 );
1132 }),
1133 ),
1134 ),
1135 Effect.forkIn(runtimeScope),
1136 );
1137​
1138 const start = Effect.fn("CodexSessionRuntime.start")(function* () {
1139 yield* emitSessionEvent("session/connecting", "Starting Codex App Server session.");
1140 yield* client.request("initialize", buildCodexInitializeParams());
1141 yield* client.notify("initialized", undefined);
1142​
1143 const requestedModel = normalizeCodexModelSlug(options.model);
1144​
1145 const opened = yield* openCodexThread({
1146 client,
1147 threadId: options.threadId,
1148 runtimeMode: options.runtimeMode,
1149 cwd: options.cwd,
1150 requestedModel,
1151 serviceTier: options.serviceTier,
1152 resumeThreadId: readResumeCursorThreadId(options.resumeCursor),
1153 });
1154​
1155 const providerThreadId = opened.thread.id;
1156 const session = {
1157 ...(yield* Ref.get(sessionRef)),
1158 status: "ready",
1159 cwd: opened.cwd,
1160 model: opened.model,
1161 resumeCursor: { threadId: providerThreadId },
1162 updatedAt: new Date().toISOString(),
1163 } satisfies ProviderSession;
1164 yield* Ref.set(sessionRef, session);
1165 yield* emitSessionEvent("session/ready", "Codex App Server session ready.");
1166 return session;
1167 });
1168​
1169 const readProviderThreadId = Effect.gen(function* () {
1170 const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
1171 if (!providerThreadId) {
1172 return yield* new CodexSessionRuntimeThreadIdMissingError({
1173 threadId: options.threadId,
1174 });
1176 return providerThreadId;
1177 });
1178​
1179 const close = Effect.gen(function* () {
1180 const alreadyClosed = yield* Ref.getAndSet(closedRef, true);
1181 if (alreadyClosed) {
1182 return;
1184 yield* settlePendingApprovals("cancel");
1185 yield* settlePendingUserInputs({});
1186 yield* updateSession(sessionRef, {
1187 status: "closed",
1188 activeTurnId: undefined,
1189 });
1190 yield* emitSessionEvent("session/closed", "Session stopped");
1191 yield* Scope.close(runtimeScope, Exit.void);
1192 yield* Queue.shutdown(serverNotifications);
1193 yield* Queue.shutdown(events);
1194 });
1195​
1196 return {
1197 start,
1198 getSession: Ref.get(sessionRef),
1199 sendTurn: (input) =>
1200 Effect.gen(function* () {
1201 const providerThreadId = yield* readProviderThreadId;
1202 const normalizedModel = normalizeCodexModelSlug(
1203 input.model ?? (yield* Ref.get(sessionRef)).model,
1204 );
1205 const params = yield* buildTurnStartParams({
1206 threadId: providerThreadId,
1207 runtimeMode: options.runtimeMode,
1208 ...(input.input ? { prompt: input.input } : {}),
1209 ...(input.attachments ? { attachments: input.attachments } : {}),
1210 ...(normalizedModel ? { model: normalizedModel } : {}),
1211 ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
1212 ...(input.effort ? { effort: input.effort } : {}),
1213 ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
1214 });
1215 const rawResponse = yield* client.raw.request("turn/start", params);
1216 const response = yield* Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse)(
1217 rawResponse,
1218 ).pipe(
1219 Effect.mapError((error) =>
1220 toProtocolParseError("Invalid turn/start response payload", error),
1221 ),
1222 );
1223 const turnId = TurnId.make(response.turn.id);
1224 yield* updateSession(sessionRef, {
1225 status: "running",
1226 activeTurnId: turnId,
1227 ...(normalizedModel ? { model: normalizedModel } : {}),
1228 });
1229 const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
1230 return {
1231 threadId: options.threadId,
1232 turnId,
1233 ...(resumedProviderThreadId
1234 ? { resumeCursor: { threadId: resumedProviderThreadId } }
1235 : {}),
1236 } satisfies ProviderTurnStartResult;
1237 }),
1238 interruptTurn: (turnId) =>
1239 Effect.gen(function* () {
1240 const providerThreadId = yield* readProviderThreadId;
1241 const session = yield* Ref.get(sessionRef);
1242 const effectiveTurnId = turnId ?? session.activeTurnId;
1243 if (!effectiveTurnId) {
1244 return;
1246 yield* client.request("turn/interrupt", {
1247 threadId: providerThreadId,
1248 turnId: effectiveTurnId,
1249 });
1250 }),
1251 readThread: Effect.gen(function* () {
1252 const providerThreadId = yield* readProviderThreadId;
1253 const response = yield* client.request("thread/read", {
1254 threadId: providerThreadId,
1255 includeTurns: true,
1256 });
1257 return parseThreadSnapshot(response);
1258 }),
1259 rollbackThread: (numTurns) =>
1260 Effect.gen(function* () {
1261 const providerThreadId = yield* readProviderThreadId;
1262 const response = yield* client.request("thread/rollback", {
1263 threadId: providerThreadId,
1264 numTurns,
1265 });
1266 yield* updateSession(sessionRef, {
1267 status: "ready",
1268 activeTurnId: undefined,
1269 });
1270 return parseThreadSnapshot(response);
1271 }),
1272 respondToRequest: (requestId, decision) =>
1273 Effect.gen(function* () {
1274 const pending = (yield* Ref.get(pendingApprovalsRef)).get(requestId);
1275 if (!pending) {
1276 return yield* new CodexSessionRuntimePendingApprovalNotFoundError({
1277 requestId,
1278 });
1280 yield* Ref.update(pendingApprovalsRef, (current) => {
1281 const next = new Map(current);
1282 next.delete(requestId);
1283 return next;
1284 });
1285 yield* Deferred.succeed(pending.decision, decision);
1286 yield* emitEvent({
1287 kind: "notification",
1288 threadId: options.threadId,
1289 method: "item/requestApproval/decision",
1290 requestId: pending.requestId,
1291 requestKind: pending.requestKind,
1292 ...(pending.turnId ? { turnId: pending.turnId } : {}),
1293 ...(pending.itemId ? { itemId: pending.itemId } : {}),
1294 payload: {
1295 requestId: pending.requestId,
1296 requestKind: pending.requestKind,
1297 decision,
1298 },
1299 });
1300 }),
1301 respondToUserInput: (requestId, answers) =>
1302 Effect.gen(function* () {
1303 const pending = (yield* Ref.get(pendingUserInputsRef)).get(requestId);
1304 if (!pending) {
1305 return yield* new CodexSessionRuntimePendingUserInputNotFoundError({
1306 requestId,
1307 });
1309 const codexAnswers = yield* toCodexUserInputAnswers(answers);
1310 yield* Ref.update(pendingUserInputsRef, (current) => {
1311 const next = new Map(current);
1312 next.delete(requestId);
1313 return next;
1314 });
1315 yield* Deferred.succeed(pending.answers, answers);
1316 yield* emitEvent({
1317 kind: "notification",
1318 threadId: options.threadId,
1319 method: "item/tool/requestUserInput/answered",
1320 requestId: pending.requestId,
1321 ...(pending.turnId ? { turnId: pending.turnId } : {}),
1322 ...(pending.itemId ? { itemId: pending.itemId } : {}),
1323 payload: {
1324 answers: codexAnswers,
1325 },
1326 });
1327 }),
1328 events: Stream.fromQueue(events),
1329 close,
1330 } satisfies CodexSessionRuntimeShape;
1331 });