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

CodexSessionRuntime.ts

1,349 lines45.2 KB

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