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

codexAppServer.ts

154 lines4.1 KB

1import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
2import readline from "node:readline";
3import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
4​
5interface JsonRpcProbeResponse {
6 readonly id?: unknown;
7 readonly result?: unknown;
8 readonly error?: {
9 readonly message?: unknown;
10 };
12​
13function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
14 return typeof response.error?.message === "string" ? response.error.message : undefined;
16​
17export function buildCodexInitializeParams() {
18 return {
19 clientInfo: {
20 name: "t3code_desktop",
21 title: "T3 Code Desktop",
22 version: "0.1.0",
23 },
24 capabilities: {
25 experimentalApi: true,
26 },
27 } as const;
29​
30export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
31 if (process.platform === "win32" && child.pid !== undefined) {
32 try {
33 spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
34 return;
35 } catch {
36 // Fall through to direct kill when taskkill is unavailable.
37 }
38 }
39​
40 child.kill();
42​
43export async function probeCodexAccount(input: {
44 readonly binaryPath: string;
45 readonly homePath?: string;
46 readonly signal?: AbortSignal;
47}): Promise<CodexAccountSnapshot> {
48 return await new Promise((resolve, reject) => {
49 const child = spawn(input.binaryPath, ["app-server"], {
50 env: {
51 ...process.env,
52 ...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
53 },
54 stdio: ["pipe", "pipe", "pipe"],
55 shell: process.platform === "win32",
56 });
57 const output = readline.createInterface({ input: child.stdout });
58​
59 let completed = false;
60​
61 const cleanup = () => {
62 output.removeAllListeners();
63 output.close();
64 child.removeAllListeners();
65 if (!child.killed) {
66 killCodexChildProcess(child);
67 }
68 };
69​
70 const finish = (callback: () => void) => {
71 if (completed) return;
72 completed = true;
73 cleanup();
74 callback();
75 };
76​
77 const fail = (error: unknown) =>
78 finish(() =>
79 reject(
80 error instanceof Error
81 ? error
82 : new Error(`Codex account probe failed: ${String(error)}.`),
83 ),
84 );
85​
86 if (input.signal?.aborted) {
87 fail(new Error("Codex account probe aborted."));
88 return;
89 }
90 input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted.")));
91​
92 const writeMessage = (message: unknown) => {
93 if (!child.stdin.writable) {
94 fail(new Error("Cannot write to codex app-server stdin."));
95 return;
96 }
97​
98 child.stdin.write(`${JSON.stringify(message)}\n`);
99 };
100​
101 output.on("line", (line) => {
102 let parsed: unknown;
103 try {
104 parsed = JSON.parse(line);
105 } catch {
106 fail(new Error("Received invalid JSON from codex app-server during account probe."));
107 return;
108 }
109​
110 if (!parsed || typeof parsed !== "object") {
111 return;
112 }
113​
114 const response = parsed as JsonRpcProbeResponse;
115 if (response.id === 1) {
116 const errorMessage = readErrorMessage(response);
117 if (errorMessage) {
118 fail(new Error(`initialize failed: ${errorMessage}`));
119 return;
120 }
121​
122 writeMessage({ method: "initialized" });
123 writeMessage({ id: 2, method: "account/read", params: {} });
124 return;
125 }
126​
127 if (response.id === 2) {
128 const errorMessage = readErrorMessage(response);
129 if (errorMessage) {
130 fail(new Error(`account/read failed: ${errorMessage}`));
131 return;
132 }
133​
134 finish(() => resolve(readCodexAccountSnapshot(response.result)));
135 }
136 });
137​
138 child.once("error", fail);
139 child.once("exit", (code, signal) => {
140 if (completed) return;
141 fail(
142 new Error(
143 `codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
144 ),
145 );
146 });
147​
148 writeMessage({
149 id: 1,
150 method: "initialize",
151 params: buildCodexInitializeParams(),
152 });
153 });