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