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

codexAppServer.ts

241 lines7.0 KB

1import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
2import readline from "node:readline";
3import type { ServerProviderSkill } from "@workbench/contracts";
4import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount.ts";
5​
6interface JsonRpcProbeResponse {
7 readonly id?: unknown;
8 readonly result?: unknown;
9 readonly error?: {
10 readonly message?: unknown;
11 };
13​
14export interface CodexDiscoverySnapshot {
15 readonly account: CodexAccountSnapshot;
16 readonly skills: ReadonlyArray<ServerProviderSkill>;
18​
19function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
20 return typeof response.error?.message === "string" ? response.error.message : undefined;
22​
23function readObject(value: unknown): Record<string, unknown> | undefined {
24 return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
26​
27function readArray(value: unknown): ReadonlyArray<unknown> | undefined {
28 return Array.isArray(value) ? value : undefined;
30​
31function readString(value: unknown): string | undefined {
32 return typeof value === "string" ? value : undefined;
34​
35function nonEmptyTrimmed(value: unknown): string | undefined {
36 const candidate = readString(value)?.trim();
37 return candidate ? candidate : undefined;
39​
40function parseCodexSkillsResult(result: unknown, cwd: string): ReadonlyArray<ServerProviderSkill> {
41 const resultRecord = readObject(result);
42 const dataBuckets = readArray(resultRecord?.data) ?? [];
43 const matchingBucket = dataBuckets.find(
44 (value) => nonEmptyTrimmed(readObject(value)?.cwd) === cwd,
45 );
46 const rawSkills =
47 readArray(readObject(matchingBucket)?.skills) ?? readArray(resultRecord?.skills) ?? [];
48​
49 return rawSkills.flatMap((value) => {
50 const skill = readObject(value);
51 const display = readObject(skill?.interface);
52 const name = nonEmptyTrimmed(skill?.name);
53 const path = nonEmptyTrimmed(skill?.path);
54 if (!name || !path) {
55 return [];
56 }
57​
58 return [
59 {
60 name,
61 path,
62 enabled: skill?.enabled !== false,
63 ...(nonEmptyTrimmed(skill?.description)
64 ? { description: nonEmptyTrimmed(skill?.description) }
65 : {}),
66 ...(nonEmptyTrimmed(skill?.scope) ? { scope: nonEmptyTrimmed(skill?.scope) } : {}),
67 ...(nonEmptyTrimmed(display?.displayName)
68 ? { displayName: nonEmptyTrimmed(display?.displayName) }
69 : {}),
70 ...(nonEmptyTrimmed(skill?.shortDescription) || nonEmptyTrimmed(display?.shortDescription)
71 ? {
72 shortDescription:
73 nonEmptyTrimmed(skill?.shortDescription) ??
74 nonEmptyTrimmed(display?.shortDescription),
75 }
76 : {}),
77 } satisfies ServerProviderSkill,
78 ];
79 });
81​
82export function buildCodexInitializeParams() {
83 return {
84 clientInfo: {
85 name: "t3code_desktop",
86 title: "Workbench Desktop",
87 version: "0.1.0",
88 },
89 capabilities: {
90 experimentalApi: true,
91 },
92 } as const;
94​
95export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
96 if (process.platform === "win32" && child.pid !== undefined) {
97 try {
98 spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
99 return;
100 } catch {
101 // Fall through to direct kill when taskkill is unavailable.
102 }
103 }
104​
105 child.kill();
107​
108export async function probeCodexDiscovery(input: {
109 readonly binaryPath: string;
110 readonly homePath?: string;
111 readonly cwd: string;
112 readonly signal?: AbortSignal;
113}): Promise<CodexDiscoverySnapshot> {
114 return await new Promise((resolve, reject) => {
115 const child = spawn(input.binaryPath, ["app-server"], {
116 env: {
117 ...process.env,
118 ...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
119 },
120 stdio: ["pipe", "pipe", "pipe"],
121 shell: process.platform === "win32",
122 });
123 const output = readline.createInterface({ input: child.stdout });
124​
125 let completed = false;
126 let account: CodexAccountSnapshot | undefined;
127 let skills: ReadonlyArray<ServerProviderSkill> | undefined;
128​
129 const cleanup = () => {
130 output.removeAllListeners();
131 output.close();
132 child.removeAllListeners();
133 if (!child.killed) {
134 killCodexChildProcess(child);
135 }
136 };
137​
138 const finish = (callback: () => void) => {
139 if (completed) return;
140 completed = true;
141 cleanup();
142 callback();
143 };
144​
145 const fail = (error: unknown) =>
146 finish(() =>
147 reject(
148 error instanceof Error
149 ? error
150 : new Error(`Codex discovery probe failed: ${String(error)}.`),
151 ),
152 );
153​
154 const maybeResolve = () => {
155 if (account && skills !== undefined) {
156 const resolvedAccount = account;
157 const resolvedSkills = skills;
158 finish(() => resolve({ account: resolvedAccount, skills: resolvedSkills }));
159 }
160 };
161​
162 if (input.signal?.aborted) {
163 fail(new Error("Codex discovery probe aborted."));
164 return;
165 }
166 input.signal?.addEventListener("abort", () =>
167 fail(new Error("Codex discovery probe aborted.")),
168 );
169​
170 const writeMessage = (message: unknown) => {
171 if (!child.stdin.writable) {
172 fail(new Error("Cannot write to codex app-server stdin."));
173 return;
174 }
175​
176 child.stdin.write(`${JSON.stringify(message)}\n`);
177 };
178​
179 output.on("line", (line) => {
180 let parsed: unknown;
181 try {
182 parsed = JSON.parse(line);
183 } catch {
184 fail(new Error("Received invalid JSON from codex app-server during discovery probe."));
185 return;
186 }
187​
188 if (!parsed || typeof parsed !== "object") {
189 return;
190 }
191​
192 const response = parsed as JsonRpcProbeResponse;
193 if (response.id === 1) {
194 const errorMessage = readErrorMessage(response);
195 if (errorMessage) {
196 fail(new Error(`initialize failed: ${errorMessage}`));
197 return;
198 }
199​
200 writeMessage({ method: "initialized" });
201 writeMessage({ id: 2, method: "skills/list", params: { cwds: [input.cwd] } });
202 writeMessage({ id: 3, method: "account/read", params: {} });
203 return;
204 }
205​
206 if (response.id === 2) {
207 const errorMessage = readErrorMessage(response);
208 skills = errorMessage ? [] : parseCodexSkillsResult(response.result, input.cwd);
209 maybeResolve();
210 return;
211 }
212​
213 if (response.id === 3) {
214 const errorMessage = readErrorMessage(response);
215 if (errorMessage) {
216 fail(new Error(`account/read failed: ${errorMessage}`));
217 return;
218 }
219​
220 account = readCodexAccountSnapshot(response.result);
221 maybeResolve();
222 }
223 });
224​
225 child.once("error", fail);
226 child.once("exit", (code, signal) => {
227 if (completed) return;
228 fail(
229 new Error(
230 `codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
231 ),
232 );
233 });
234​
235 writeMessage({
236 id: 1,
237 method: "initialize",
238 params: buildCodexInitializeParams(),
239 });
240 });