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