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

CodexSessionRuntime.ts

1,371 lines46.2 KB

1import {
2 ApprovalRequestId,
3 DEFAULT_MODEL,
4 EventId,
5 ProviderDriverKind,
6 ProviderItemId,
7 type ProviderInstanceId,
8 type ProviderApprovalDecision,
9 type ProviderEvent,
10 type ProviderInteractionMode,
11 type ProviderRequestKind,
12 type ProviderSession,
13 type ProviderTurnStartResult,
14 type ProviderUserInputAnswers,
15 RuntimeMode,
16 ThreadId,
17 TurnId,
18} from "@t3tools/contracts";
19import { normalizeModelSlug } from "@t3tools/shared/model";
20import * as DateTime from "effect/DateTime";
21import * as Deferred from "effect/Deferred";
22import * as Effect from "effect/Effect";
23import * as Exit from "effect/Exit";
24import * as Layer from "effect/Layer";
25import * as Queue from "effect/Queue";
26import * as Ref from "effect/Ref";
27import * as Scope from "effect/Scope";
28import * as Random from "effect/Random";
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;
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;
119​
120export interface CodexThreadTurnSnapshot {
121 readonly id: TurnId;
122 readonly items: ReadonlyArray<CodexThreadItem>;
124​
125export interface CodexThreadSnapshot {
126 readonly threadId: string;
127 readonly turns: ReadonlyArray<CodexThreadTurnSnapshot>;
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>;
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 }
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 }
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 }
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 }
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>;
212​
213interface ApprovalCorrelation {
214 readonly requestId: ApprovalRequestId;
215 readonly requestKind: ProviderRequestKind;
216 readonly turnId: TurnId | undefined;
217 readonly itemId: ProviderItemId | undefined;
219​
220interface PendingUserInput {
221 readonly requestId: ApprovalRequestId;
222 readonly turnId: TurnId | undefined;
223 readonly itemId: ProviderItemId | undefined;
224 readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
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;
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;
254​
255function readResumeCursorThreadId(
256 resumeCursor: ProviderSession["resumeCursor"],
257): string | undefined {
258 return isCodexResumeCursorSchema(resumeCursor) ? resumeCursor.threadId : undefined;
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 }
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 };
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 }
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 };
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 );
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 };
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));
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>;
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 }
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 }
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 }
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 );
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 }));
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)));
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 });
664​
665function currentProviderThreadId(session: ProviderSession): string | undefined {
666 return readResumeCursorThreadId(session.resumeCursor);
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 });
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 };
694​
695export const makeCodexSessionRuntime = (
696 options: CodexSessionRuntimeOptions,
697): Effect.Effect<
698 CodexSessionRuntimeShape,
699 CodexErrors.CodexAppServerError,
700 ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
701> =>
702 Effect.gen(function* () {
703 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
704 const runtimeScope = yield* Scope.Scope;
705 const events = yield* Queue.unbounded<ProviderEvent>();
706 const pendingApprovalsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingApproval>());
707 const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());
708 const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());
709 const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
710 const closedRef = yield* Ref.make(false);
711​
712 // `~` is not shell-expanded when env vars are set via
713 // `child_process.spawn`; `expandHomePath` lets a configured
714 // `CODEX_HOME=~/.codex_work` reach codex as an absolute path.
715 const resolvedHomePath = options.homePath ? expandHomePath(options.homePath) : undefined;
716 const env = {
717 ...(options.environment ?? process.env),
718 ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
719 };
720 const child = yield* spawner
721 .spawn(
722 ChildProcess.make(options.binaryPath, ["app-server"], {
723 cwd: options.cwd,
724 env,
725 forceKillAfter: CODEX_APP_SERVER_FORCE_KILL_AFTER,
726 shell: process.platform === "win32",
727 }),
728 )
729 .pipe(
730 Effect.provideService(Scope.Scope, runtimeScope),
731 Effect.mapError(
732 (cause) =>
733 new CodexErrors.CodexAppServerSpawnError({
734 command: `${options.binaryPath} app-server`,
735 cause,
736 }),
737 ),
738 );
739​
740 const clientContext = yield* CodexClient.layerChildProcess(child).pipe(
741 Layer.build,
742 Effect.provideService(Scope.Scope, runtimeScope),
743 );
744 const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
745 Effect.provide(clientContext),
746 );
747 const serverNotifications = yield* Queue.unbounded<CodexServerNotification>();
748 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
749​
750 const sessionCreatedAt = yield* nowIso;
751 const initialSession = {
752 provider: PROVIDER,
753 ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),
754 status: "connecting",
755 runtimeMode: options.runtimeMode,
756 cwd: options.cwd,
757 ...(options.model ? { model: options.model } : {}),
758 threadId: options.threadId,
759 ...(options.resumeCursor !== undefined ? { resumeCursor: options.resumeCursor } : {}),
760 createdAt: sessionCreatedAt,
761 updatedAt: sessionCreatedAt,
762 } satisfies ProviderSession;
763 const sessionRef = yield* Ref.make<ProviderSession>(initialSession);
764 const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);
765​
766 const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
767 Effect.gen(function* () {
768 const id = yield* Random.nextUUIDv4;
769 return yield* offerEvent({
770 id: EventId.make(id),
771 provider: PROVIDER,
772 ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),
773 createdAt: yield* nowIso,
774 ...event,
775 });
776 });
777 const emitSessionEvent = (method: string, message: string) =>
778 emitEvent({
779 kind: "session",
780 threadId: options.threadId,
781 method,
782 message,
783 });
784​
785 const settlePendingApprovals = (decision: ProviderApprovalDecision) =>
786 Ref.get(pendingApprovalsRef).pipe(
787 Effect.flatMap((pendingApprovals) =>
788 Effect.forEach(
789 Array.from(pendingApprovals.values()),
790 (pendingApproval) =>
791 Deferred.succeed(pendingApproval.decision, decision).pipe(Effect.ignore),
792 { discard: true },
793 ),
794 ),
795 );
796​
797 const settlePendingUserInputs = (answers: ProviderUserInputAnswers) =>
798 Ref.get(pendingUserInputsRef).pipe(
799 Effect.flatMap((pendingUserInputs) =>
800 Effect.forEach(
801 Array.from(pendingUserInputs.values()),
802 (pendingUserInput) =>
803 Deferred.succeed(pendingUserInput.answers, answers).pipe(Effect.ignore),
804 { discard: true },
805 ),
806 ),
807 );
808​
809 const handleRawNotification = (notification: CodexServerNotification) =>
810 Effect.gen(function* () {
811 const payload = notification.params;
812 const route = readRouteFields(notification);
813 const collabReceiverTurns = yield* Ref.get(collabReceiverTurnsRef);
814 const childParentTurnId = (() => {
815 const providerConversationId = readNotificationThreadId(notification);
816 return providerConversationId
817 ? collabReceiverTurns.get(providerConversationId)
818 : undefined;
819 })();
820​
821 rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);
822 if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) {
823 yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
824 return;
825 }
826​
827 let requestId: ApprovalRequestId | undefined;
828 let requestKind: ProviderRequestKind | undefined;
829 let turnId = childParentTurnId ?? route.turnId;
830 let itemId = route.itemId;
831​
832 if (notification.method === "serverRequest/resolved") {
833 const rawRequestId =
834 typeof notification.params.requestId === "string"
835 ? notification.params.requestId
836 : String(notification.params.requestId);
837 const correlation = rawRequestId
838 ? (yield* Ref.get(approvalCorrelationsRef)).get(rawRequestId)
839 : undefined;
840 if (correlation) {
841 requestId = correlation.requestId;
842 requestKind = correlation.requestKind;
843 turnId = correlation.turnId ?? turnId;
844 itemId = correlation.itemId ?? itemId;
845 yield* Ref.update(approvalCorrelationsRef, (current) => {
846 const next = new Map(current);
847 next.delete(rawRequestId);
848 return next;
849 });
850 }
851 }
852​
853 yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
854 yield* emitEvent({
855 kind: "notification",
856 threadId: options.threadId,
857 method: notification.method,
858 ...(turnId ? { turnId } : {}),
859 ...(itemId ? { itemId } : {}),
860 ...(requestId ? { requestId } : {}),
861 ...(requestKind ? { requestKind } : {}),
862 ...(notification.method === "item/agentMessage/delta"
863 ? { textDelta: notification.params.delta }
864 : {}),
865 ...(payload !== undefined ? { payload } : {}),
866 });
867 });
868​
869 const currentSessionProviderThreadId = Effect.map(Ref.get(sessionRef), currentProviderThreadId);
870​
871 yield* client.handleServerNotification("thread/started", (payload) =>
872 currentSessionProviderThreadId.pipe(
873 Effect.flatMap((providerThreadId) => {
874 if (providerThreadId && payload.thread.id !== providerThreadId) {
875 return Effect.void;
876 }
877 return updateSession(sessionRef, {
878 resumeCursor: { threadId: payload.thread.id },
879 });
880 }),
881 ),
882 );
883​
884 yield* client.handleServerNotification("turn/started", (payload) =>
885 currentSessionProviderThreadId.pipe(
886 Effect.flatMap((providerThreadId) => {
887 if (providerThreadId && payload.threadId !== providerThreadId) {
888 return Effect.void;
889 }
890 return updateSession(sessionRef, {
891 status: "running",
892 activeTurnId: TurnId.make(payload.turn.id),
893 });
894 }),
895 ),
896 );
897​
898 yield* client.handleServerNotification("turn/completed", (payload) =>
899 currentSessionProviderThreadId.pipe(
900 Effect.flatMap((providerThreadId) => {
901 if (providerThreadId && payload.threadId !== providerThreadId) {
902 return Effect.void;
903 }
904 const lastError =
905 payload.turn.status === "failed" && "error" in payload.turn && payload.turn.error
906 ? payload.turn.error.message
907 : undefined;
908 return updateSession(sessionRef, {
909 status: payload.turn.status === "failed" ? "error" : "ready",
910 activeTurnId: undefined,
911 ...(lastError ? { lastError } : {}),
912 });
913 }),
914 ),
915 );
916​
917 yield* client.handleServerNotification("error", (payload) =>
918 currentSessionProviderThreadId.pipe(
919 Effect.flatMap((providerThreadId) => {
920 const payloadThreadId = payload.threadId;
921 if (providerThreadId && payloadThreadId && payloadThreadId !== providerThreadId) {
922 return Effect.void;
923 }
924 const errorMessage = payload.error.message;
925 const willRetry = payload.willRetry;
926 return updateSession(sessionRef, {
927 status: willRetry ? "running" : "error",
928 ...(errorMessage ? { lastError: errorMessage } : {}),
929 });
930 }),
931 ),
932 );
933​
934 yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) =>
935 Effect.gen(function* () {
936 const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
937 const turnId = TurnId.make(payload.turnId);
938 const itemId = ProviderItemId.make(payload.itemId);
939 const decision = yield* Deferred.make<ProviderApprovalDecision>();
940​
941 yield* Ref.update(pendingApprovalsRef, (current) => {
942 const next = new Map(current);
943 next.set(requestId, {
944 requestId,
945 jsonRpcId: payload.approvalId ?? payload.itemId,
946 requestKind: "command",
947 turnId,
948 itemId,
949 decision,
950 });
951 return next;
952 });
953 yield* Ref.update(approvalCorrelationsRef, (current) => {
954 const next = new Map(current);
955 next.set(payload.approvalId ?? payload.itemId, {
956 requestId,
957 requestKind: "command",
958 turnId,
959 itemId,
960 });
961 return next;
962 });
963​
964 yield* emitEvent({
965 kind: "request",
966 threadId: options.threadId,
967 method: "item/commandExecution/requestApproval",
968 requestId,
969 requestKind: "command",
970 ...(turnId ? { turnId } : {}),
971 ...(itemId ? { itemId } : {}),
972 payload,
973 });
974​
975 const resolved = yield* Deferred.await(decision).pipe(
976 Effect.ensuring(
977 Ref.update(pendingApprovalsRef, (current) => {
978 const next = new Map(current);
979 next.delete(requestId);
980 return next;
981 }),
982 ),
983 );
984 return {
985 decision: resolved,
986 } satisfies EffectCodexSchema.CommandExecutionRequestApprovalResponse;
987 }),
988 );
989​
990 yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) =>
991 Effect.gen(function* () {
992 const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
993 const turnId = TurnId.make(payload.turnId);
994 const itemId = ProviderItemId.make(payload.itemId);
995 const decision = yield* Deferred.make<ProviderApprovalDecision>();
996​
997 yield* Ref.update(pendingApprovalsRef, (current) => {
998 const next = new Map(current);
999 next.set(requestId, {
1000 requestId,
1001 jsonRpcId: payload.itemId,
1002 requestKind: "file-change",
1003 turnId,
1004 itemId,
1005 decision,
1006 });
1007 return next;
1008 });
1009 yield* Ref.update(approvalCorrelationsRef, (current) => {
1010 const next = new Map(current);
1011 next.set(payload.itemId, {
1012 requestId,
1013 requestKind: "file-change",
1014 turnId,
1015 itemId,
1016 });
1017 return next;
1018 });
1019​
1020 yield* emitEvent({
1021 kind: "request",
1022 threadId: options.threadId,
1023 method: "item/fileChange/requestApproval",
1024 requestId,
1025 requestKind: "file-change",
1026 ...(turnId ? { turnId } : {}),
1027 ...(itemId ? { itemId } : {}),
1028 payload,
1029 });
1030​
1031 const resolved = yield* Deferred.await(decision).pipe(
1032 Effect.ensuring(
1033 Ref.update(pendingApprovalsRef, (current) => {
1034 const next = new Map(current);
1035 next.delete(requestId);
1036 return next;
1037 }),
1038 ),
1039 );
1040 return {
1041 decision: resolved,
1042 } satisfies EffectCodexSchema.FileChangeRequestApprovalResponse;
1043 }),
1044 );
1045​
1046 yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
1047 Effect.gen(function* () {
1048 const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
1049 const turnId = TurnId.make(payload.turnId);
1050 const itemId = ProviderItemId.make(payload.itemId);
1051 const answers = yield* Deferred.make<ProviderUserInputAnswers>();
1052​
1053 yield* Ref.update(pendingUserInputsRef, (current) => {
1054 const next = new Map(current);
1055 next.set(requestId, {
1056 requestId,
1057 turnId,
1058 itemId,
1059 answers,
1060 });
1061 return next;
1062 });
1063​
1064 yield* emitEvent({
1065 kind: "request",
1066 threadId: options.threadId,
1067 method: "item/tool/requestUserInput",
1068 requestId,
1069 ...(turnId ? { turnId } : {}),
1070 ...(itemId ? { itemId } : {}),
1071 payload,
1072 });
1073​
1074 const resolvedAnswers = yield* Deferred.await(answers).pipe(
1075 Effect.ensuring(
1076 Ref.update(pendingUserInputsRef, (current) => {
1077 const next = new Map(current);
1078 next.delete(requestId);
1079 return next;
1080 }),
1081 ),
1082 );
1083​
1084 return {
1085 answers: yield* toCodexUserInputAnswers(resolvedAnswers).pipe(
1086 Effect.mapError((error) =>
1087 CodexErrors.CodexAppServerRequestError.invalidParams(error.message, {
1088 questionId: error.questionId,
1089 }),
1090 ),
1091 ),
1092 } satisfies EffectCodexSchema.ToolRequestUserInputResponse;
1093 }),
1094 );
1095​
1096 yield* client.handleUnknownServerRequest((method) =>
1097 Effect.fail(CodexErrors.CodexAppServerRequestError.methodNotFound(method)),
1098 );
1099​
1100 const registerServerNotification = <M extends CodexRpc.ServerNotificationMethod>(method: M) =>
1101 client.handleServerNotification(method, (params) =>
1102 Queue.offer(serverNotifications, makeCodexServerNotification(method, params)).pipe(
1103 Effect.asVoid,
1104 ),
1105 );
1106​
1107 yield* Effect.forEach(
1108 Object.values(
1109 CodexRpc.SERVER_NOTIFICATION_METHODS,
1110 ) as ReadonlyArray<CodexRpc.ServerNotificationMethod>,
1111 registerServerNotification,
1112 { concurrency: 1, discard: true },
1113 );
1114​
1115 yield* Stream.fromQueue(serverNotifications).pipe(
1116 Stream.runForEach(handleRawNotification),
1117 Effect.forkIn(runtimeScope),
1118 );
1119​
1120 const stderrRemainderRef = yield* Ref.make("");
1121 yield* child.stderr.pipe(
1122 Stream.decodeText(),
1123 Stream.runForEach((chunk) =>
1124 Ref.modify(stderrRemainderRef, (current) => {
1125 const combined = current + chunk;
1126 const lines = combined.split("\n");
1127 const remainder = lines.pop() ?? "";
1128 return [lines.map((line) => line.replace(/\r$/, "")), remainder] as const;
1129 }).pipe(
1130 Effect.flatMap((lines) =>
1131 Effect.forEach(
1132 lines,
1133 (line) => {
1134 const classified = classifyCodexStderrLine(line);
1135 if (!classified) {
1136 return Effect.void;
1138 return emitEvent({
1139 kind: "notification",
1140 threadId: options.threadId,
1141 method: "process/stderr",
1142 message: classified.message,
1143 });
1144 },
1145 { discard: true },
1146 ),
1147 ),
1148 ),
1149 ),
1150 Effect.forkIn(runtimeScope),
1151 );
1152​
1153 yield* child.exitCode.pipe(
1154 Effect.flatMap((exitCode) =>
1155 Ref.get(closedRef).pipe(
1156 Effect.flatMap((closed) => {
1157 if (closed) {
1158 return Effect.void;
1160 const nextStatus = exitCode === 0 ? "closed" : "error";
1161 return updateSession(sessionRef, {
1162 status: nextStatus,
1163 activeTurnId: undefined,
1164 }).pipe(
1165 Effect.andThen(
1166 emitSessionEvent(
1167 "session/exited",
1168 exitCode === 0
1169 ? "Codex App Server exited."
1170 : `Codex App Server exited with code ${exitCode}.`,
1171 ),
1172 ),
1173 );
1174 }),
1175 ),
1176 ),
1177 Effect.forkIn(runtimeScope),
1178 );
1179​
1180 const start = Effect.fn("CodexSessionRuntime.start")(function* () {
1181 yield* emitSessionEvent("session/connecting", "Starting Codex App Server session.");
1182 yield* client.request("initialize", buildCodexInitializeParams());
1183 yield* client.notify("initialized", undefined);
1184​
1185 const requestedModel = normalizeCodexModelSlug(options.model);
1186​
1187 const opened = yield* openCodexThread({
1188 client,
1189 threadId: options.threadId,
1190 runtimeMode: options.runtimeMode,
1191 cwd: options.cwd,
1192 requestedModel,
1193 serviceTier: options.serviceTier,
1194 resumeThreadId: readResumeCursorThreadId(options.resumeCursor),
1195 });
1196​
1197 const providerThreadId = opened.thread.id;
1198 const session = {
1199 ...(yield* Ref.get(sessionRef)),
1200 status: "ready",
1201 cwd: opened.cwd,
1202 model: opened.model,
1203 resumeCursor: { threadId: providerThreadId },
1204 updatedAt: yield* nowIso,
1205 } satisfies ProviderSession;
1206 yield* Ref.set(sessionRef, session);
1207 yield* emitSessionEvent("session/ready", "Codex App Server session ready.");
1208 return session;
1209 });
1210​
1211 const readProviderThreadId = Effect.gen(function* () {
1212 const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
1213 if (!providerThreadId) {
1214 return yield* new CodexSessionRuntimeThreadIdMissingError({
1215 threadId: options.threadId,
1216 });
1218 return providerThreadId;
1219 });
1220​
1221 const close = Effect.gen(function* () {
1222 const alreadyClosed = yield* Ref.getAndSet(closedRef, true);
1223 if (alreadyClosed) {
1224 return;
1226 yield* settlePendingApprovals("cancel");
1227 yield* settlePendingUserInputs({});
1228 yield* updateSession(sessionRef, {
1229 status: "closed",
1230 activeTurnId: undefined,
1231 });
1232 yield* emitSessionEvent("session/closed", "Session stopped");
1233 yield* Scope.close(runtimeScope, Exit.void);
1234 yield* Queue.shutdown(serverNotifications);
1235 yield* Queue.shutdown(events);
1236 });
1237​
1238 return {
1239 start,
1240 getSession: Ref.get(sessionRef),
1241 sendTurn: (input) =>
1242 Effect.gen(function* () {
1243 const providerThreadId = yield* readProviderThreadId;
1244 const normalizedModel = normalizeCodexModelSlug(
1245 input.model ?? (yield* Ref.get(sessionRef)).model,
1246 );
1247 const params = yield* buildTurnStartParams({
1248 threadId: providerThreadId,
1249 runtimeMode: options.runtimeMode,
1250 ...(input.input ? { prompt: input.input } : {}),
1251 ...(input.attachments ? { attachments: input.attachments } : {}),
1252 ...(normalizedModel ? { model: normalizedModel } : {}),
1253 ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),
1254 ...(input.effort ? { effort: input.effort } : {}),
1255 ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
1256 });
1257 const rawResponse = yield* client.raw.request("turn/start", params);
1258 const response = yield* decodeV2TurnStartResponse(rawResponse).pipe(
1259 Effect.mapError((error) =>
1260 toProtocolParseError("Invalid turn/start response payload", error),
1261 ),
1262 );
1263 const turnId = TurnId.make(response.turn.id);
1264 yield* updateSession(sessionRef, {
1265 status: "running",
1266 activeTurnId: turnId,
1267 ...(normalizedModel ? { model: normalizedModel } : {}),
1268 });
1269 const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
1270 return {
1271 threadId: options.threadId,
1272 turnId,
1273 ...(resumedProviderThreadId
1274 ? { resumeCursor: { threadId: resumedProviderThreadId } }
1275 : {}),
1276 } satisfies ProviderTurnStartResult;
1277 }),
1278 interruptTurn: (turnId) =>
1279 Effect.gen(function* () {
1280 const providerThreadId = yield* readProviderThreadId;
1281 const session = yield* Ref.get(sessionRef);
1282 const effectiveTurnId = turnId ?? session.activeTurnId;
1283 if (!effectiveTurnId) {
1284 return;
1286 yield* client.request("turn/interrupt", {
1287 threadId: providerThreadId,
1288 turnId: effectiveTurnId,
1289 });
1290 }),
1291 readThread: Effect.gen(function* () {
1292 const providerThreadId = yield* readProviderThreadId;
1293 const response = yield* client.request("thread/read", {
1294 threadId: providerThreadId,
1295 includeTurns: true,
1296 });
1297 return parseThreadSnapshot(response);
1298 }),
1299 rollbackThread: (numTurns) =>
1300 Effect.gen(function* () {
1301 const providerThreadId = yield* readProviderThreadId;
1302 const response = yield* client.request("thread/rollback", {
1303 threadId: providerThreadId,
1304 numTurns,
1305 });
1306 yield* updateSession(sessionRef, {
1307 status: "ready",
1308 activeTurnId: undefined,
1309 });
1310 return parseThreadSnapshot(response);
1311 }),
1312 respondToRequest: (requestId, decision) =>
1313 Effect.gen(function* () {
1314 const pending = (yield* Ref.get(pendingApprovalsRef)).get(requestId);
1315 if (!pending) {
1316 return yield* new CodexSessionRuntimePendingApprovalNotFoundError({
1317 requestId,
1318 });
1320 yield* Ref.update(pendingApprovalsRef, (current) => {
1321 const next = new Map(current);
1322 next.delete(requestId);
1323 return next;
1324 });
1325 yield* Deferred.succeed(pending.decision, decision);
1326 yield* emitEvent({
1327 kind: "notification",
1328 threadId: options.threadId,
1329 method: "item/requestApproval/decision",
1330 requestId: pending.requestId,
1331 requestKind: pending.requestKind,
1332 ...(pending.turnId ? { turnId: pending.turnId } : {}),
1333 ...(pending.itemId ? { itemId: pending.itemId } : {}),
1334 payload: {
1335 requestId: pending.requestId,
1336 requestKind: pending.requestKind,
1337 decision,
1338 },
1339 });
1340 }),
1341 respondToUserInput: (requestId, answers) =>
1342 Effect.gen(function* () {
1343 const pending = (yield* Ref.get(pendingUserInputsRef)).get(requestId);
1344 if (!pending) {
1345 return yield* new CodexSessionRuntimePendingUserInputNotFoundError({
1346 requestId,
1347 });
1349 const codexAnswers = yield* toCodexUserInputAnswers(answers);
1350 yield* Ref.update(pendingUserInputsRef, (current) => {
1351 const next = new Map(current);
1352 next.delete(requestId);
1353 return next;
1354 });
1355 yield* Deferred.succeed(pending.answers, answers);
1356 yield* emitEvent({
1357 kind: "notification",
1358 threadId: options.threadId,
1359 method: "item/tool/requestUserInput/answered",
1360 requestId: pending.requestId,
1361 ...(pending.turnId ? { turnId: pending.turnId } : {}),
1362 ...(pending.itemId ? { itemId: pending.itemId } : {}),
1363 payload: {
1364 answers: codexAnswers,
1365 },
1366 });
1367 }),
1368 events: Stream.fromQueue(events),
1369 close,
1370 } satisfies CodexSessionRuntimeShape;
1371 });