-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathCodexAppServerClient.ts
More file actions
544 lines (479 loc) · 20.2 KB
/
Copy pathCodexAppServerClient.ts
File metadata and controls
544 lines (479 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
import {type MessageConnection, RequestType} from "vscode-jsonrpc/node";
import type {
ClientRequest,
InitializeParams,
InitializeResponse,
ServerNotification
} from "./app-server";
import type {
ConfigReadParams,
ConfigReadResponse,
GetAccountParams,
GetAccountResponse,
ListMcpServerStatusParams,
ListMcpServerStatusResponse,
LoginAccountParams,
LoginAccountResponse,
LogoutAccountResponse,
McpServerElicitationRequestParams,
McpServerElicitationRequestResponse,
McpServerStartupState,
McpServerStatusUpdatedNotification,
ModelListParams,
ModelListResponse,
SkillsExtraRootsSetParams,
SkillsListParams,
SkillsListResponse,
ThreadLoadedListParams,
ThreadLoadedListResponse,
ThreadListParams,
ThreadListResponse,
ThreadReadParams,
ThreadReadResponse,
ThreadResumeParams,
ThreadResumeResponse,
ThreadStartParams,
ThreadStartResponse,
ThreadUnsubscribeParams,
ThreadUnsubscribeResponse,
TurnCompletedNotification,
TurnInterruptParams,
TurnInterruptResponse,
TurnStartParams,
TurnStartResponse,
CommandExecutionRequestApprovalParams,
CommandExecutionRequestApprovalResponse,
FileChangeRequestApprovalParams,
FileChangeRequestApprovalResponse,
} from "./app-server/v2";
export interface ApprovalHandler {
handleCommandExecution(params: CommandExecutionRequestApprovalParams): Promise<CommandExecutionRequestApprovalResponse>;
handleFileChange(params: FileChangeRequestApprovalParams): Promise<FileChangeRequestApprovalResponse>;
}
export interface ElicitationHandler {
handleElicitation(params: McpServerElicitationRequestParams): Promise<McpServerElicitationRequestResponse>;
}
export type McpStartupFailure = {
server: string;
error: string;
};
export type McpStartupResult = {
ready: Array<string>;
failed: Array<McpStartupFailure>;
cancelled: Array<string>;
};
const CommandExecutionApprovalRequest = new RequestType<
CommandExecutionRequestApprovalParams,
CommandExecutionRequestApprovalResponse,
void
>('item/commandExecution/requestApproval');
const FileChangeApprovalRequest = new RequestType<
FileChangeRequestApprovalParams,
FileChangeRequestApprovalResponse,
void
>('item/fileChange/requestApproval');
const McpServerElicitationRequest = new RequestType<
McpServerElicitationRequestParams,
McpServerElicitationRequestResponse,
void
>('mcpServer/elicitation/request');
/**
* A type-safe client over the Codex App Server's JSON-RPC API.
* Maps each request to its expected response and exposes clear, typed methods for supported JSON-RPC operations.
*/
export class CodexAppServerClient {
readonly connection: MessageConnection;
private approvalHandlers = new Map<string, ApprovalHandler>();
private elicitationHandlers = new Map<string, ElicitationHandler>();
private mcpServerStartupVersion = 0;
private readonly mcpServerStartupStates = new Map<string, McpServerStartupSnapshot>();
private readonly mcpServerStartupResolvers: Array<McpServerStartupResolver> = [];
private readonly pendingTurnCompletionResolvers = new Map<string, Map<string, (event: TurnCompletedNotification) => void>>();
private readonly turnCompletionCaptures = new Map<string, Set<(event: TurnCompletedNotification) => void>>();
private readonly staleTurnIds = new Map<string, Set<string>>();
constructor(connection: MessageConnection) {
this.connection = connection;
this.connection.onUnhandledNotification((data) => {
const serverNotification = data as ServerNotification;
if (isMcpServerStatusUpdatedNotification(serverNotification)) {
this.mcpServerStartupVersion += 1;
this.mcpServerStartupStates.set(serverNotification.params.name, {
status: serverNotification.params.status,
error: serverNotification.params.error,
version: this.mcpServerStartupVersion,
});
this.resolveMcpServerStartupResolvers();
}
if (isTurnCompletedNotification(serverNotification)) {
this.recordTurnCompleted(serverNotification.params);
}
const routing = extractTurnRouting(serverNotification);
const staleTurnNotification = this.isStaleTurn(routing.threadId, routing.turnId);
if (staleTurnNotification) {
if (isTurnCompletedNotification(serverNotification) && routing.threadId !== null && routing.turnId !== null) {
this.clearStaleTurn(routing.threadId, routing.turnId);
}
for (const callback of this.codexEventHandlers) {
callback({ eventType: "notification", ...serverNotification });
}
return;
}
this.notify(serverNotification);
for (const callback of this.codexEventHandlers) {
callback({ eventType: "notification", ...serverNotification });
}
});
this.connection.onRequest(CommandExecutionApprovalRequest, async (params) => {
if (this.isStaleTurn(params.threadId, params.turnId)) {
return { decision: "cancel" };
}
const handler = this.approvalHandlers.get(params.threadId);
if (!handler) {
return { decision: "cancel" };
}
return await handler.handleCommandExecution(params);
});
this.connection.onRequest(FileChangeApprovalRequest, async (params) => {
if (this.isStaleTurn(params.threadId, params.turnId)) {
return { decision: "cancel" };
}
const handler = this.approvalHandlers.get(params.threadId);
if (!handler) {
return { decision: "cancel" };
}
return await handler.handleFileChange(params);
});
this.connection.onRequest(McpServerElicitationRequest, async (params) => {
if (this.isStaleTurn(params.threadId, params.turnId)) {
return { action: "cancel", content: null, _meta: null };
}
const handler = this.elicitationHandlers.get(params.threadId);
if (!handler) {
return { action: "cancel", content: null, _meta: null };
}
return await handler.handleElicitation(params);
});
}
onApprovalRequest(threadId: string, handler: ApprovalHandler): void {
this.approvalHandlers.set(threadId, handler);
}
onElicitationRequest(threadId: string, handler: ElicitationHandler): void {
this.elicitationHandlers.set(threadId, handler);
}
clearThreadHandlers(threadId: string): void {
this.notificationHandlers.delete(threadId);
this.approvalHandlers.delete(threadId);
this.elicitationHandlers.delete(threadId);
}
async initialize(params: InitializeParams): Promise<InitializeResponse> {
return await this.sendRequest({ method: "initialize", params: params });
}
async turnStart(params: TurnStartParams): Promise<TurnStartResponse> {
return await this.sendRequest({ method: "turn/start", params: params });
}
async runTurn(params: TurnStartParams, onTurnStarted?: (turnId: string) => void): Promise<TurnCompletedNotification> {
const capturedCompletions: Array<TurnCompletedNotification> = [];
const releaseCapture = this.captureTurnCompletions(params.threadId, (event) => {
capturedCompletions.push(event);
});
try {
const turnStarted = await this.turnStart(params);
onTurnStarted?.(turnStarted.turn.id);
const earlyCompletion = capturedCompletions.find(event => event.turn.id === turnStarted.turn.id);
releaseCapture();
if (earlyCompletion) {
return earlyCompletion;
}
// Wait for turn completion
// If turnInterrupt() was called, Codex will send turn/completed event with status "interrupted"
return await this.awaitTurnCompleted(params.threadId, turnStarted.turn.id);
} finally {
releaseCapture();
}
}
async turnInterrupt(params: TurnInterruptParams): Promise<TurnInterruptResponse> {
return await this.sendRequest({ method: "turn/interrupt", params: params });
}
markTurnStale(threadId: string, turnId: string): void {
const threadStaleTurns = this.staleTurnIds.get(threadId) ?? new Set<string>();
threadStaleTurns.add(turnId);
this.staleTurnIds.set(threadId, threadStaleTurns);
}
async threadStart(params: ThreadStartParams): Promise<ThreadStartResponse> {
return await this.sendRequest({ method: "thread/start", params: params });
}
async threadResume(params: ThreadResumeParams): Promise<ThreadResumeResponse> {
return await this.sendRequest({ method: "thread/resume", params: params });
}
async threadList(params: ThreadListParams): Promise<ThreadListResponse> {
return await this.sendRequest({ method: "thread/list", params: params });
}
async threadLoadedList(params: ThreadLoadedListParams): Promise<ThreadLoadedListResponse> {
return await this.sendRequest({ method: "thread/loaded/list", params: params });
}
async threadRead(params: ThreadReadParams): Promise<ThreadReadResponse> {
return await this.sendRequest({ method: "thread/read", params: params });
}
async threadUnsubscribe(params: ThreadUnsubscribeParams): Promise<ThreadUnsubscribeResponse> {
return await this.sendRequest({ method: "thread/unsubscribe", params: params });
}
async listMcpServerStatus(params: ListMcpServerStatusParams): Promise<ListMcpServerStatusResponse> {
return await this.sendRequest({ method: "mcpServerStatus/list", params });
}
async accountLogin(params: LoginAccountParams): Promise<LoginAccountResponse> {
return await this.sendRequest({ method: "account/login/start", params: params });
}
async accountLogout(): Promise<LogoutAccountResponse> {
return await this.sendRequest({ method: "account/logout", params: undefined });
}
async configRead(params: ConfigReadParams): Promise<ConfigReadResponse> {
return await this.sendRequest({ method: "config/read", params: params });
}
getMcpServerStartupVersion(): number {
return this.mcpServerStartupVersion;
}
async awaitMcpServerStartup(serverNames: Array<string>, afterVersion: number): Promise<McpStartupResult> {
const uniqueServerNames = Array.from(new Set(serverNames.map(serverName => serverName.trim()).filter(serverName => serverName.length > 0)));
if (uniqueServerNames.length === 0) {
return { ready: [], failed: [], cancelled: [] };
}
const result = this.tryBuildMcpStartupResult(uniqueServerNames, afterVersion);
if (result !== null) {
return result;
}
return await new Promise((resolve) => {
this.mcpServerStartupResolvers.push({
serverNames: uniqueServerNames,
afterVersion,
resolve,
});
});
}
async accountRead(params: GetAccountParams): Promise<GetAccountResponse> {
return await this.sendRequest({ method: "account/read", params: params });
}
//TODO create type-safe helper
async awaitTurnCompleted(threadId: string, turnId: string): Promise<TurnCompletedNotification> {
return await new Promise((resolve) => {
const threadResolvers = this.getOrCreatePendingTurnCompletionResolvers(threadId);
threadResolvers.set(turnId, resolve);
});
}
resolveTurnInterrupted(threadId: string, turnId: string): void {
this.recordTurnCompleted({
threadId,
turn: {
id: turnId,
items: [],
itemsView: "notLoaded",
status: "interrupted",
error: null,
startedAt: null,
completedAt: null,
durationMs: null,
},
});
}
async listModels(params: ModelListParams): Promise<ModelListResponse> {
return await this.sendRequest({ method: "model/list", params });
}
async skillsExtraRootsSet(params: SkillsExtraRootsSetParams): Promise<void> {
return await this.sendRequest({ method: "skills/extraRoots/set", params });
}
async listSkills(params: SkillsListParams): Promise<SkillsListResponse> {
return await this.sendRequest({ method: "skills/list", params });
}
/**
* Registers a notification handler for a specific session.
* Replaces any existing handler for the same session, preventing handler accumulation.
*/
onServerNotification(sessionId: string, callback: (event: ServerNotification) => void) {
this.notificationHandlers.set(sessionId, callback);
}
private codexEventHandlers: Array<(event: CodexConnectionEvent) => void> = [];
onClientTransportEvent(callback: (event: CodexConnectionEvent) => void){
this.codexEventHandlers.push(callback);
}
private notificationHandlers = new Map<string, (event: ServerNotification) => void>();
private notify(notification: ServerNotification) {
const threadId = extractThreadId(notification);
if (threadId !== null) {
const handler = this.notificationHandlers.get(threadId);
if (handler) {
handler(notification);
}
return;
}
for (const notificationHandler of this.notificationHandlers.values()) {
notificationHandler(notification);
}
}
private recordTurnCompleted(event: TurnCompletedNotification): void {
const threadResolvers = this.pendingTurnCompletionResolvers.get(event.threadId);
const resolve = threadResolvers?.get(event.turn.id);
if (resolve) {
threadResolvers!.delete(event.turn.id);
if (threadResolvers!.size === 0) {
this.pendingTurnCompletionResolvers.delete(event.threadId);
}
resolve(event);
return;
}
const captures = this.turnCompletionCaptures.get(event.threadId);
if (!captures) {
return;
}
for (const capture of captures) {
capture(event);
}
}
private isStaleTurn(threadId: string | null, turnId: string | null): boolean {
if (threadId === null || turnId === null) {
return false;
}
return this.staleTurnIds.get(threadId)?.has(turnId) ?? false;
}
private clearStaleTurn(threadId: string, turnId: string): void {
const threadStaleTurns = this.staleTurnIds.get(threadId);
if (!threadStaleTurns) {
return;
}
threadStaleTurns.delete(turnId);
if (threadStaleTurns.size === 0) {
this.staleTurnIds.delete(threadId);
}
}
private getOrCreatePendingTurnCompletionResolvers(threadId: string): Map<string, (event: TurnCompletedNotification) => void> {
const existing = this.pendingTurnCompletionResolvers.get(threadId);
if (existing) {
return existing;
}
const created = new Map<string, (event: TurnCompletedNotification) => void>();
this.pendingTurnCompletionResolvers.set(threadId, created);
return created;
}
private captureTurnCompletions(threadId: string, capture: (event: TurnCompletedNotification) => void): () => void {
const captures = this.turnCompletionCaptures.get(threadId) ?? new Set<(event: TurnCompletedNotification) => void>();
captures.add(capture);
this.turnCompletionCaptures.set(threadId, captures);
let released = false;
return () => {
if (released) {
return;
}
released = true;
captures.delete(capture);
if (captures.size === 0) {
this.turnCompletionCaptures.delete(threadId);
}
};
}
private resolveMcpServerStartupResolvers(): void {
const pendingResolvers: Array<McpServerStartupResolver> = [];
for (const resolver of this.mcpServerStartupResolvers) {
const result = this.tryBuildMcpStartupResult(resolver.serverNames, resolver.afterVersion);
if (result !== null) {
resolver.resolve(result);
} else {
pendingResolvers.push(resolver);
}
}
this.mcpServerStartupResolvers.splice(0, this.mcpServerStartupResolvers.length, ...pendingResolvers);
}
private tryBuildMcpStartupResult(serverNames: Array<string>, afterVersion: number): McpStartupResult | null {
const ready: Array<string> = [];
const failed: Array<McpStartupFailure> = [];
const cancelled: Array<string> = [];
for (const serverName of serverNames) {
const state = this.mcpServerStartupStates.get(serverName);
if (!state || state.version <= afterVersion) {
return null;
}
switch (state.status) {
case "starting":
return null;
case "ready":
ready.push(serverName);
break;
case "failed":
failed.push({
server: serverName,
error: state.error ?? "unknown MCP startup error",
});
break;
case "cancelled":
cancelled.push(serverName);
break;
}
}
return { ready, failed, cancelled };
}
private async sendRequest<R>(request: CodexRequest): Promise<R> {
for (const callback of this.codexEventHandlers) {
callback({ eventType: "request", ...request});
}
let result: any;
if (request.params) {
result = await this.connection.sendRequest<R>(request.method, request.params)
}
else {
result = await this.connection.sendRequest<R>(request.method);
}
for (const callback of this.codexEventHandlers) {
callback({ eventType: "response", ...result});
}
return result;
}
}
export type CodexConnectionEvent =
| ({ eventType: "request" } & CodexRequest)
| ({ eventType: "response" } & unknown)
| ({ eventType: "notification" } & ServerNotification);
type CodexRequest = DistributiveOmit<ClientRequest, "id">
type DistributiveOmit<T, K extends keyof any> = T extends any
? Omit<T, K>
: never;
type McpServerStartupSnapshot = {
status: McpServerStartupState;
error: string | null;
version: number;
};
type McpServerStartupResolver = {
serverNames: Array<string>;
afterVersion: number;
resolve: (result: McpStartupResult) => void;
};
function isMcpServerStatusUpdatedNotification(notification: ServerNotification): notification is {
method: "mcpServer/startupStatus/updated";
params: McpServerStatusUpdatedNotification;
} {
return notification.method === "mcpServer/startupStatus/updated";
}
function isTurnCompletedNotification(notification: ServerNotification): notification is {
method: "turn/completed";
params: TurnCompletedNotification;
} {
return notification.method === "turn/completed";
}
function extractThreadId(notification: ServerNotification): string | null {
const params = notification.params as { threadId?: unknown } | undefined;
if (params && typeof params.threadId === "string") {
return params.threadId;
}
return null;
}
function extractTurnRouting(notification: ServerNotification): { threadId: string | null, turnId: string | null } {
const params = notification.params as {
threadId?: unknown,
turnId?: unknown,
turn?: { id?: unknown },
} | undefined;
const threadId = extractThreadId(notification);
if (params && typeof params.turnId === "string") {
return {threadId, turnId: params.turnId};
}
if (params && typeof params.turn?.id === "string") {
return {threadId, turnId: params.turn.id};
}
return {threadId, turnId: null};
}