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

codexAppServerManager.ts

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