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