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

codexAppServerManager.ts

1,001 lines28.3 KB

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