Open History to see the last commit
1import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
2import { randomUUID } from "node:crypto";
3import { EventEmitter } from "node:events";
4import readline from "node:readline";
5
6import {
7 ApprovalRequestId,
8 EventId,
9 ProviderItemId,
10 ProviderRequestKind,
11 ProviderSessionId,
12 ProviderThreadId,
13 ProviderTurnId,
14 normalizeModelSlug,
15 type ProviderApprovalDecision,
16 type ProviderEvent,
17 type ProviderSession,
18 type ProviderSessionStartInput,
19 type ProviderTurnStartResult,
20} from "@t3tools/contracts";
21
22type PendingRequestKey = string;
23
24interface PendingRequest {
25 method: string;
26 timeout: ReturnType<typeof setTimeout>;
27 resolve: (value: unknown) => void;
28 reject: (error: Error) => void;
29}
30
31interface PendingApprovalRequest {
32 requestId: ApprovalRequestId;
33 jsonRpcId: string | number;
34 method: "item/commandExecution/requestApproval" | "item/fileChange/requestApproval";
35 requestKind: ProviderRequestKind;
36 threadId?: ProviderThreadId;
37 turnId?: ProviderTurnId;
38 itemId?: ProviderItemId;
39}
40
41interface CodexSessionContext {
42 session: ProviderSession;
43 child: ChildProcessWithoutNullStreams;
44 output: readline.Interface;
45 pending: Map<PendingRequestKey, PendingRequest>;
46 pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
47 nextRequestId: number;
48 stopping: boolean;
49}
50
51interface JsonRpcError {
52 code?: number;
53 message?: string;
54}
55
56interface JsonRpcRequest {
57 id: string | number;
58 method: string;
59 params?: unknown;
60}
61
62interface JsonRpcResponse {
63 id: string | number;
64 result?: unknown;
65 error?: JsonRpcError;
66}
67
68interface JsonRpcNotification {
69 method: string;
70 params?: unknown;
71}
72
73export interface CodexAppServerSendTurnInput {
74 readonly sessionId: ProviderSessionId;
75 readonly input?: string;
76 readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
77 readonly model?: string;
78 readonly effort?: string;
79}
80
81export interface CodexThreadTurnSnapshot {
82 id: ProviderTurnId;
83 items: unknown[];
84}
85
86export interface CodexThreadSnapshot {
87 threadId: ProviderThreadId;
88 turns: CodexThreadTurnSnapshot[];
89}
90
91const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
92const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
93const CODEX_STDERR_LOG_REGEX =
94 /^\d{4}-\d{2}-\d{2}T\S+\s+(TRACE|DEBUG|INFO|WARN|ERROR)\s+\S+:\s+(.*)$/;
95const BENIGN_ERROR_LOG_SNIPPETS = [
96 "state db missing rollout path for thread",
97 "state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
98];
99const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
100 "not found",
101 "missing thread",
102 "no such thread",
103 "unknown thread",
104 "does not exist",
105];
106
107export function normalizeCodexModelSlug(
108 model: string | undefined | null,
109 preferredId?: string,
110): string | undefined {
111 const normalized = normalizeModelSlug(model);
112 if (!normalized) {
113 return undefined;
114 }
115
116 if (preferredId?.endsWith("-codex") && preferredId !== normalized) {
117 return preferredId;
118 }
119
120 return normalized;
121}
122
123export function classifyCodexStderrLine(rawLine: string): { message: string } | null {
124 const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim();
125 if (!line) {
126 return null;
127 }
128
129 const match = line.match(CODEX_STDERR_LOG_REGEX);
130 if (match) {
131 const level = match[1];
132 if (level && level !== "ERROR") {
133 return null;
134 }
135
136 const isBenignError = BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet));
137 if (isBenignError) {
138 return null;
139 }
140 }
141
142 return { message: line };
143}
144
145export function isRecoverableThreadResumeError(error: unknown): boolean {
146 const message = (error instanceof Error ? error.message : String(error)).toLowerCase();
147 if (!message.includes("thread/resume")) {
148 return false;
149 }
150
151 return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
152}
153
154export interface CodexAppServerManagerEvents {
155 event: [event: ProviderEvent];
156}
157
158export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
159 private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
160
161 async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
162 const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
163 const now = new Date().toISOString();
164 let context: CodexSessionContext | undefined;
165
166 try {
167 const resolvedCwd = input.cwd ?? process.cwd();
168
169 const session: ProviderSession = {
170 sessionId,
171 provider: "codex",
172 status: "connecting",
173 model: normalizeCodexModelSlug(input.model),
174 cwd: resolvedCwd,
175 createdAt: now,
176 updatedAt: now,
177 };
178
179 const codexBinaryPath = input.codexBinaryPath ?? "codex";
180 const codexHomePath = input.codexHomePath;
181 const child = spawn(codexBinaryPath, ["app-server"], {
182 cwd: resolvedCwd,
183 env: {
184 ...process.env,
185 ...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
186 },
187 stdio: ["pipe", "pipe", "pipe"],
188 });
189 const output = readline.createInterface({ input: child.stdout });
190
191 context = {
192 session,
193 child,
194 output,
195 pending: new Map(),
196 pendingApprovals: new Map(),
197 nextRequestId: 1,
198 stopping: false,
199 };
200
201 this.sessions.set(sessionId, context);
202 this.attachProcessListeners(context);
203
204 this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
205
206 await this.sendRequest(context, "initialize", {
207 clientInfo: {
208 name: "t3code_desktop",
209 title: "T3 Code Desktop",
210 version: "0.1.0",
211 },
212 capabilities: {
213 experimentalApi: false,
214 },
215 });
216
217 this.writeMessage(context, { method: "initialized" });
218
219 const normalizedModel = normalizeCodexModelSlug(input.model);
220 const sessionOverrides = {
221 model: normalizedModel ?? null,
222 cwd: input.cwd ?? null,
223 approvalPolicy: input.approvalPolicy,
224 sandbox: input.sandboxMode,
225 };
226
227 const threadStartParams = {
228 ...sessionOverrides,
229 experimentalRawEvents: false,
230 };
231 const resumeThreadId = readResumeThreadId(input);
232
233 let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start";
234 let threadOpenResponse: unknown;
235 if (resumeThreadId) {
236 try {
237 threadOpenMethod = "thread/resume";
238 threadOpenResponse = await this.sendRequest(context, "thread/resume", {
239 ...sessionOverrides,
240 threadId: resumeThreadId,
241 });
242 } catch (error) {
243 if (!isRecoverableThreadResumeError(error)) {
244 throw error;
245 }
246
247 threadOpenMethod = "thread/start";
248 this.emitLifecycleEvent(
249 context,
250 "session/threadResumeFallback",
251 `Could not resume thread ${resumeThreadId}; started a new thread instead.`,
252 );
253 threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
254 }
255 } else {
256 threadOpenMethod = "thread/start";
257 threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
258 }
259
260 const threadOpenRecord = this.readObject(threadOpenResponse);
261 const threadIdRaw =
262 this.readString(this.readObject(threadOpenRecord, "thread"), "id") ??
263 this.readString(threadOpenRecord, "threadId");
264 if (!threadIdRaw) {
265 throw new Error(`${threadOpenMethod} response did not include a thread id.`);
266 }
267 const threadId = ProviderThreadId.makeUnsafe(threadIdRaw);
268
269 this.updateSession(context, {
270 status: "ready",
271 threadId,
272 resumeCursor: { threadId },
273 });
274 this.emitLifecycleEvent(context, "session/ready", `Connected to thread ${threadId}`);
275 return { ...context.session };
276 } catch (error) {
277 const message = error instanceof Error ? error.message : "Failed to start Codex session.";
278 if (context) {
279 this.updateSession(context, {
280 status: "error",
281 lastError: message,
282 });
283 this.emitErrorEvent(context, "session/startFailed", message);
284 this.stopSession(sessionId);
285 } else {
286 this.emitEvent({
287 id: EventId.makeUnsafe(randomUUID()),
288 kind: "error",
289 provider: "codex",
290 sessionId,
291 createdAt: new Date().toISOString(),
292 method: "session/startFailed",
293 message,
294 });
295 }
296 throw new Error(message, { cause: error });
297 }
298 }
299
300 async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
301 const context = this.requireSession(input.sessionId);
302 if (!context.session.threadId) {
303 throw new Error("Session is missing a thread id.");
304 }
305
306 const turnInput: Array<
307 { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
308 > = [];
309 if (input.input) {
310 turnInput.push({
311 type: "text",
312 text: input.input,
313 text_elements: [],
314 });
315 }
316 for (const attachment of input.attachments ?? []) {
317 if (attachment.type === "image") {
318 turnInput.push({
319 type: "image",
320 url: attachment.url,
321 });
322 }
323 }
324 if (turnInput.length === 0) {
325 throw new Error("Turn input must include text or attachments.");
326 }
327
328 const turnStartParams: {
329 threadId: ProviderThreadId;
330 input: Array<
331 { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
332 >;
333 model?: string;
334 effort?: string;
335 } = {
336 threadId: context.session.threadId,
337 input: turnInput,
338 };
339 const normalizedModel = normalizeCodexModelSlug(input.model);
340 if (normalizedModel) {
341 turnStartParams.model = normalizedModel;
342 }
343 if (input.effort) {
344 turnStartParams.effort = input.effort;
345 }
346
347 const response = await this.sendRequest(context, "turn/start", turnStartParams);
348
349 const turn = this.readObject(this.readObject(response), "turn");
350 const turnIdRaw = this.readString(turn, "id");
351 if (!turnIdRaw) {
352 throw new Error("turn/start response did not include a turn id.");
353 }
354 const turnId = ProviderTurnId.makeUnsafe(turnIdRaw);
355
356 this.updateSession(context, {
357 status: "running",
358 activeTurnId: turnId,
359 resumeCursor: context.session.resumeCursor ?? { threadId: context.session.threadId },
360 });
361
362 return {
363 threadId: context.session.threadId,
364 turnId,
365 resumeCursor: context.session.resumeCursor ?? { threadId: context.session.threadId },
366 };
367 }
368
369 async interruptTurn(sessionId: ProviderSessionId, turnId?: ProviderTurnId): Promise<void> {
370 const context = this.requireSession(sessionId);
371 const effectiveTurnId = turnId ?? context.session.activeTurnId;
372
373 if (!effectiveTurnId || !context.session.threadId) {
374 return;
375 }
376
377 await this.sendRequest(context, "turn/interrupt", {
378 threadId: context.session.threadId,
379 turnId: effectiveTurnId,
380 });
381 }
382
383 async readThread(sessionId: ProviderSessionId): Promise<CodexThreadSnapshot> {
384 const context = this.requireSession(sessionId);
385 const threadId = context.session.threadId;
386 if (!threadId) {
387 throw new Error("Session is missing a thread id.");
388 }
389
390 const response = await this.sendRequest(context, "thread/read", {
391 threadId,
392 includeTurns: true,
393 });
394 return this.parseThreadSnapshot("thread/read", response);
395 }
396
397 async rollbackThread(
398 sessionId: ProviderSessionId,
399 numTurns: number,
400 ): Promise<CodexThreadSnapshot> {
401 const context = this.requireSession(sessionId);
402 const threadId = context.session.threadId;
403 if (!threadId) {
404 throw new Error("Session is missing a thread id.");
405 }
406 if (!Number.isInteger(numTurns) || numTurns < 1) {
407 throw new Error("numTurns must be an integer >= 1.");
408 }
409
410 const response = await this.sendRequest(context, "thread/rollback", {
411 threadId,
412 numTurns,
413 });
414 this.updateSession(context, {
415 status: "ready",
416 activeTurnId: undefined,
417 });
418 return this.parseThreadSnapshot("thread/rollback", response);
419 }
420
421 async respondToRequest(
422 sessionId: ProviderSessionId,
423 requestId: ApprovalRequestId,
424 decision: ProviderApprovalDecision,
425 ): Promise<void> {
426 const context = this.requireSession(sessionId);
427 const pendingRequest = context.pendingApprovals.get(requestId);
428 if (!pendingRequest) {
429 throw new Error(`Unknown pending approval request: ${requestId}`);
430 }
431
432 context.pendingApprovals.delete(requestId);
433 this.writeMessage(context, {
434 id: pendingRequest.jsonRpcId,
435 result: {
436 decision,
437 },
438 });
439
440 this.emitEvent({
441 id: EventId.makeUnsafe(randomUUID()),
442 kind: "notification",
443 provider: "codex",
444 sessionId: context.session.sessionId,
445 createdAt: new Date().toISOString(),
446 method: "item/requestApproval/decision",
447 threadId: pendingRequest.threadId,
448 turnId: pendingRequest.turnId,
449 itemId: pendingRequest.itemId,
450 requestId: pendingRequest.requestId,
451 requestKind: pendingRequest.requestKind,
452 payload: {
453 requestId: pendingRequest.requestId,
454 requestKind: pendingRequest.requestKind,
455 decision,
456 },
457 });
458 }
459
460 stopSession(sessionId: ProviderSessionId): void {
461 const context = this.sessions.get(sessionId);
462 if (!context) {
463 return;
464 }
465
466 context.stopping = true;
467
468 for (const pending of context.pending.values()) {
469 clearTimeout(pending.timeout);
470 pending.reject(new Error("Session stopped before request completed."));
471 }
472 context.pending.clear();
473 context.pendingApprovals.clear();
474
475 context.output.close();
476
477 if (!context.child.killed) {
478 context.child.kill();
479 }
480
481 this.updateSession(context, {
482 status: "closed",
483 activeTurnId: undefined,
484 });
485 this.emitLifecycleEvent(context, "session/closed", "Session stopped");
486 this.sessions.delete(sessionId);
487 }
488
489 listSessions(): ProviderSession[] {
490 return Array.from(this.sessions.values(), ({ session }) => ({
491 ...session,
492 }));
493 }
494
495 hasSession(sessionId: ProviderSessionId): boolean {
496 return this.sessions.has(sessionId);
497 }
498
499 stopAll(): void {
500 for (const sessionId of this.sessions.keys()) {
501 this.stopSession(sessionId);
502 }
503 }
504
505 private requireSession(sessionId: ProviderSessionId): CodexSessionContext {
506 const context = this.sessions.get(sessionId);
507 if (!context) {
508 throw new Error(`Unknown session: ${sessionId}`);
509 }
510
511 if (context.session.status === "closed") {
512 throw new Error(`Session is closed: ${sessionId}`);
513 }
514
515 return context;
516 }
517
518 private attachProcessListeners(context: CodexSessionContext): void {
519 context.output.on("line", (line) => {
520 this.handleStdoutLine(context, line);
521 });
522
523 context.child.stderr.on("data", (chunk: Buffer) => {
524 const raw = chunk.toString();
525 const lines = raw.split(/\r?\n/g);
526 for (const rawLine of lines) {
527 const classified = classifyCodexStderrLine(rawLine);
528 if (!classified) {
529 continue;
530 }
531
532 this.emitErrorEvent(context, "process/stderr", classified.message);
533 }
534 });
535
536 context.child.on("error", (error) => {
537 const message = error.message || "codex app-server process errored.";
538 this.updateSession(context, {
539 status: "error",
540 lastError: message,
541 });
542 this.emitErrorEvent(context, "process/error", message);
543 });
544
545 context.child.on("exit", (code, signal) => {
546 if (context.stopping) {
547 return;
548 }
549
550 const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`;
551 this.updateSession(context, {
552 status: "closed",
553 activeTurnId: undefined,
554 lastError: code === 0 ? context.session.lastError : message,
555 });
556 this.emitLifecycleEvent(context, "session/exited", message);
557 this.sessions.delete(context.session.sessionId);
558 });
559 }
560
561 private handleStdoutLine(context: CodexSessionContext, line: string): void {
562 let parsed: unknown;
563 try {
564 parsed = JSON.parse(line);
565 } catch {
566 this.emitErrorEvent(
567 context,
568 "protocol/parseError",
569 "Received invalid JSON from codex app-server.",
570 );
571 return;
572 }
573
574 if (!parsed || typeof parsed !== "object") {
575 this.emitErrorEvent(
576 context,
577 "protocol/invalidMessage",
578 "Received non-object protocol message.",
579 );
580 return;
581 }
582
583 if (this.isServerRequest(parsed)) {
584 this.handleServerRequest(context, parsed);
585 return;
586 }
587
588 if (this.isServerNotification(parsed)) {
589 this.handleServerNotification(context, parsed);
590 return;
591 }
592
593 if (this.isResponse(parsed)) {
594 this.handleResponse(context, parsed);
595 return;
596 }
597
598 this.emitErrorEvent(
599 context,
600 "protocol/unrecognizedMessage",
601 "Received protocol message in an unknown shape.",
602 );
603 }
604
605 private handleServerNotification(
606 context: CodexSessionContext,
607 notification: JsonRpcNotification,
608 ): void {
609 const route = this.readRouteFields(notification.params);
610 const textDelta =
611 notification.method === "item/agentMessage/delta"
612 ? this.readString(notification.params, "delta")
613 : undefined;
614
615 this.emitEvent({
616 id: EventId.makeUnsafe(randomUUID()),
617 kind: "notification",
618 provider: "codex",
619 sessionId: context.session.sessionId,
620 createdAt: new Date().toISOString(),
621 method: notification.method,
622 threadId: route.threadId,
623 turnId: route.turnId,
624 itemId: route.itemId,
625 textDelta,
626 payload: notification.params,
627 });
628
629 if (notification.method === "thread/started") {
630 const threadId = toProviderThreadId(
631 this.readString(this.readObject(notification.params)?.thread, "id"),
632 );
633 if (threadId) {
634 this.updateSession(context, { threadId });
635 }
636 return;
637 }
638
639 if (notification.method === "turn/started") {
640 const turnId = toProviderTurnId(
641 this.readString(this.readObject(notification.params)?.turn, "id"),
642 );
643 this.updateSession(context, {
644 status: "running",
645 activeTurnId: turnId,
646 });
647 return;
648 }
649
650 if (notification.method === "turn/completed") {
651 const turn = this.readObject(notification.params, "turn");
652 const status = this.readString(turn, "status");
653 const errorMessage = this.readString(this.readObject(turn, "error"), "message");
654 this.updateSession(context, {
655 status: status === "failed" ? "error" : "ready",
656 activeTurnId: undefined,
657 lastError: errorMessage ?? context.session.lastError,
658 });
659 return;
660 }
661
662 if (notification.method === "error") {
663 const message = this.readString(this.readObject(notification.params)?.error, "message");
664 const willRetry = this.readBoolean(notification.params, "willRetry");
665
666 this.updateSession(context, {
667 status: willRetry ? "running" : "error",
668 lastError: message ?? context.session.lastError,
669 });
670 }
671 }
672
673 private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
674 const route = this.readRouteFields(request.params);
675 const requestKind = this.requestKindForMethod(request.method);
676 let requestId: ApprovalRequestId | undefined;
677 if (requestKind) {
678 requestId = ApprovalRequestId.makeUnsafe(randomUUID());
679 const pendingRequest: PendingApprovalRequest = {
680 requestId,
681 jsonRpcId: request.id,
682 method:
683 requestKind === "command"
684 ? "item/commandExecution/requestApproval"
685 : "item/fileChange/requestApproval",
686 requestKind,
687 ...(route.threadId ? { threadId: route.threadId } : {}),
688 ...(route.turnId ? { turnId: route.turnId } : {}),
689 ...(route.itemId ? { itemId: route.itemId } : {}),
690 };
691 context.pendingApprovals.set(requestId, pendingRequest);
692 }
693
694 this.emitEvent({
695 id: EventId.makeUnsafe(randomUUID()),
696 kind: "request",
697 provider: "codex",
698 sessionId: context.session.sessionId,
699 createdAt: new Date().toISOString(),
700 method: request.method,
701 threadId: route.threadId,
702 turnId: route.turnId,
703 itemId: route.itemId,
704 requestId,
705 requestKind,
706 payload: request.params,
707 });
708
709 if (requestKind) {
710 return;
711 }
712
713 if (request.method === "item/tool/requestUserInput") {
714 this.writeMessage(context, {
715 id: request.id,
716 result: { answers: {} },
717 });
718 return;
719 }
720
721 this.writeMessage(context, {
722 id: request.id,
723 error: {
724 code: -32601,
725 message: `Unsupported server request: ${request.method}`,
726 },
727 });
728 }
729
730 private handleResponse(context: CodexSessionContext, response: JsonRpcResponse): void {
731 const key = String(response.id);
732 const pending = context.pending.get(key);
733 if (!pending) {
734 return;
735 }
736
737 clearTimeout(pending.timeout);
738 context.pending.delete(key);
739
740 if (response.error?.message) {
741 pending.reject(new Error(`${pending.method} failed: ${String(response.error.message)}`));
742 return;
743 }
744
745 pending.resolve(response.result);
746 }
747
748 private async sendRequest<TResponse>(
749 context: CodexSessionContext,
750 method: string,
751 params: unknown,
752 timeoutMs = 20_000,
753 ): Promise<TResponse> {
754 const id = context.nextRequestId;
755 context.nextRequestId += 1;
756
757 const result = await new Promise<unknown>((resolve, reject) => {
758 const timeout = setTimeout(() => {
759 context.pending.delete(String(id));
760 reject(new Error(`Timed out waiting for ${method}.`));
761 }, timeoutMs);
762
763 context.pending.set(String(id), {
764 method,
765 timeout,
766 resolve,
767 reject,
768 });
769 this.writeMessage(context, {
770 method,
771 id,
772 params,
773 });
774 });
775
776 return result as TResponse;
777 }
778
779 private writeMessage(context: CodexSessionContext, message: unknown): void {
780 const encoded = JSON.stringify(message);
781 if (!context.child.stdin.writable) {
782 throw new Error("Cannot write to codex app-server stdin.");
783 }
784
785 context.child.stdin.write(`${encoded}\n`);
786 }
787
788 private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
789 this.emitEvent({
790 id: EventId.makeUnsafe(randomUUID()),
791 kind: "session",
792 provider: "codex",
793 sessionId: context.session.sessionId,
794 createdAt: new Date().toISOString(),
795 method,
796 message,
797 });
798 }
799
800 private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
801 this.emitEvent({
802 id: EventId.makeUnsafe(randomUUID()),
803 kind: "error",
804 provider: "codex",
805 sessionId: context.session.sessionId,
806 createdAt: new Date().toISOString(),
807 method,
808 message,
809 });
810 }
811
812 private emitEvent(event: ProviderEvent): void {
813 this.emit("event", event);
814 }
815
816 private updateSession(context: CodexSessionContext, updates: Partial<ProviderSession>): void {
817 context.session = {
818 ...context.session,
819 ...updates,
820 updatedAt: new Date().toISOString(),
821 };
822 }
823
824 private requestKindForMethod(method: string): ProviderRequestKind | undefined {
825 if (method === "item/commandExecution/requestApproval") {
826 return "command";
827 }
828
829 if (method === "item/fileChange/requestApproval") {
830 return "file-change";
831 }
832
833 return undefined;
834 }
835
836 private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
837 const responseRecord = this.readObject(response);
838 const thread = this.readObject(responseRecord, "thread");
839 const threadIdRaw =
840 this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
841 if (!threadIdRaw) {
842 throw new Error(`${method} response did not include a thread id.`);
843 }
844 const threadId = ProviderThreadId.makeUnsafe(threadIdRaw);
845
846 const turnsRaw =
847 this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
848 const turns = turnsRaw.map((turnValue, index) => {
849 const turn = this.readObject(turnValue);
850 const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
851 const turnId = ProviderTurnId.makeUnsafe(turnIdRaw);
852 const items = this.readArray(turn, "items") ?? [];
853 return {
854 id: turnId,
855 items,
856 };
857 });
858
859 return {
860 threadId,
861 turns,
862 };
863 }
864
865 private isServerRequest(value: unknown): value is JsonRpcRequest {
866 if (!value || typeof value !== "object") {
867 return false;
868 }
869
870 const candidate = value as Record<string, unknown>;
871 return (
872 typeof candidate.method === "string" &&
873 (typeof candidate.id === "string" || typeof candidate.id === "number")
874 );
875 }
876
877 private isServerNotification(value: unknown): value is JsonRpcNotification {
878 if (!value || typeof value !== "object") {
879 return false;
880 }
881
882 const candidate = value as Record<string, unknown>;
883 return typeof candidate.method === "string" && !("id" in candidate);
884 }
885
886 private isResponse(value: unknown): value is JsonRpcResponse {
887 if (!value || typeof value !== "object") {
888 return false;
889 }
890
891 const candidate = value as Record<string, unknown>;
892 const hasId = typeof candidate.id === "string" || typeof candidate.id === "number";
893 const hasMethod = typeof candidate.method === "string";
894 return hasId && !hasMethod;
895 }
896
897 private readRouteFields(params: unknown): {
898 threadId?: ProviderThreadId;
899 turnId?: ProviderTurnId;
900 itemId?: ProviderItemId;
901 } {
902 const route: {
903 threadId?: ProviderThreadId;
904 turnId?: ProviderTurnId;
905 itemId?: ProviderItemId;
906 } = {};
907
908 const threadId = toProviderThreadId(
909 this.readString(params, "threadId") ??
910 this.readString(this.readObject(params, "thread"), "id"),
911 );
912 const turnId = toProviderTurnId(
913 this.readString(params, "turnId") ?? this.readString(this.readObject(params, "turn"), "id"),
914 );
915 const itemId = toProviderItemId(
916 this.readString(params, "itemId") ?? this.readString(this.readObject(params, "item"), "id"),
917 );
918
919 if (threadId) {
920 route.threadId = threadId;
921 }
922
923 if (turnId) {
924 route.turnId = turnId;
925 }
926
927 if (itemId) {
928 route.itemId = itemId;
929 }
930
931 return route;
932 }
933
934 private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
935 const target =
936 key === undefined
937 ? value
938 : value && typeof value === "object"
939 ? (value as Record<string, unknown>)[key]
940 : undefined;
941
942 if (!target || typeof target !== "object") {
943 return undefined;
944 }
945
946 return target as Record<string, unknown>;
947 }
948
949 private readArray(value: unknown, key?: string): unknown[] | undefined {
950 const target =
951 key === undefined
952 ? value
953 : value && typeof value === "object"
954 ? (value as Record<string, unknown>)[key]
955 : undefined;
956 return Array.isArray(target) ? target : undefined;
957 }
958
959 private readString(value: unknown, key: string): string | undefined {
960 if (!value || typeof value !== "object") {
961 return undefined;
962 }
963
964 const candidate = (value as Record<string, unknown>)[key];
965 return typeof candidate === "string" ? candidate : undefined;
966 }
967
968 private readBoolean(value: unknown, key: string): boolean | undefined {
969 if (!value || typeof value !== "object") {
970 return undefined;
971 }
972
973 const candidate = (value as Record<string, unknown>)[key];
974 return typeof candidate === "boolean" ? candidate : undefined;
975 }
976}
977
978function brandIfNonEmpty<T extends string>(
979 value: string | undefined,
980 maker: (value: string) => T,
981): T | undefined {
982 const normalized = value?.trim();
983 return normalized?.length ? maker(normalized) : undefined;
984}
985
986function toProviderThreadId(value: string | undefined): ProviderThreadId | undefined {
987 return brandIfNonEmpty(value, ProviderThreadId.makeUnsafe);
988}
989
990function readResumeThreadId(input: ProviderSessionStartInput): ProviderThreadId | undefined {
991 if (
992 !input.resumeCursor ||
993 typeof input.resumeCursor !== "object" ||
994 Array.isArray(input.resumeCursor)
995 ) {
996 return input.resumeThreadId;
997 }
998 const rawThreadId = (input.resumeCursor as Record<string, unknown>).threadId;
999 return typeof rawThreadId === "string" ? toProviderThreadId(rawThreadId) : input.resumeThreadId;
1000}
1001
1002function toProviderTurnId(value: string | undefined): ProviderTurnId | undefined {
1003 return brandIfNonEmpty(value, ProviderTurnId.makeUnsafe);
1004}
1005
1006function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
1007 return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);
1008}