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

CodexSessionRuntime.ts

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