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

codexAppServerManager.ts

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