-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathCodexAppServerClient.ts
More file actions
241 lines (206 loc) · 9.22 KB
/
Copy pathCodexAppServerClient.ts
File metadata and controls
241 lines (206 loc) · 9.22 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
import {type MessageConnection, RequestType} from "vscode-jsonrpc/node";
import type {
ClientRequest, ConversationId,
InitializeParams,
InitializeResponse, McpStartupCompleteEvent,
ServerNotification
} from "./app-server";
import type {
AccountLoginCompletedNotification, AccountUpdatedNotification,
GetAccountParams,
GetAccountResponse, LoginAccountParams, LoginAccountResponse, LogoutAccountResponse, ModelListParams,
ModelListResponse,
ThreadStartParams,
ThreadStartResponse,
ThreadLoadedListParams,
ThreadLoadedListResponse,
ThreadListParams,
ThreadListResponse,
ThreadReadParams,
ThreadReadResponse,
TurnCompletedNotification,
TurnInterruptParams,
TurnInterruptResponse,
TurnStartParams,
TurnStartResponse,
CommandExecutionRequestApprovalParams,
CommandExecutionRequestApprovalResponse,
FileChangeRequestApprovalParams,
FileChangeRequestApprovalResponse,
ThreadResumeParams,
ThreadResumeResponse,
SkillsListParams,
SkillsListResponse,
ListMcpServerStatusParams,
ListMcpServerStatusResponse, ConfigReadParams, ConfigReadResponse,
} from "./app-server/v2";
export interface ApprovalHandler {
handleCommandExecution(params: CommandExecutionRequestApprovalParams): Promise<CommandExecutionRequestApprovalResponse>;
handleFileChange(params: FileChangeRequestApprovalParams): Promise<FileChangeRequestApprovalResponse>;
}
const CommandExecutionApprovalRequest = new RequestType<
CommandExecutionRequestApprovalParams,
CommandExecutionRequestApprovalResponse,
void
>('item/commandExecution/requestApproval');
const FileChangeApprovalRequest = new RequestType<
FileChangeRequestApprovalParams,
FileChangeRequestApprovalResponse,
void
>('item/fileChange/requestApproval');
/**
* Poorly supported/deprecated event types
*/
export type McpStartupCompleteNotification = { method: "codex/event/mcp_startup_complete", params: { id?: string, msg: McpStartupCompleteEvent & { type:"mcp_startup_complete" }, conversationId?: ConversationId } }
/**
* 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>();
constructor(connection: MessageConnection) {
this.connection = connection;
this.connection.onUnhandledNotification((data) => {
const serverNotification = data as ServerNotification ?? null;
if (serverNotification) {
this.notify(serverNotification);
}
for (const callback of this.codexEventHandlers) {
callback({ eventType: "notification", ...serverNotification});
}
});
this.connection.onRequest(CommandExecutionApprovalRequest, async (params) => {
const handler = this.approvalHandlers.get(params.threadId);
if (!handler) {
return { decision: "cancel" };
}
return await handler.handleCommandExecution(params);
});
this.connection.onRequest(FileChangeApprovalRequest, async (params) => {
const handler = this.approvalHandlers.get(params.threadId);
if (!handler) {
return { decision: "cancel" };
}
return await handler.handleFileChange(params);
});
}
onApprovalRequest(threadId: string, handler: ApprovalHandler): void {
this.approvalHandlers.set(threadId, handler);
}
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 turnInterrupt(params: TurnInterruptParams): Promise<TurnInterruptResponse> {
return await this.sendRequest({ method: "turn/interrupt", params: params });
}
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 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 });
}
async awaitLoginCompleted(loginId: string | null = null): Promise<AccountLoginCompletedNotification> {
return await new Promise((resolve) => {
this.connection.onNotification("account/login/completed", (event: AccountLoginCompletedNotification) => {
if (loginId !== null && event.loginId !== loginId) {
return;
}
resolve(event);
});
});
}
async awaitAccountUpdated(): Promise<AccountUpdatedNotification> {
return await new Promise((resolve) => {
this.connection.onNotification("account/updated", (event: AccountUpdatedNotification) => {
resolve(event);
});
});
}
async awaitMcpStartup(): Promise<McpStartupCompleteEvent> {
return await new Promise((resolve) => {
this.connection.onNotification("codex/event/mcp_startup_complete", (event: McpStartupCompleteNotification["params"]) => {
resolve(event.msg);
});
});
}
async accountRead(params: GetAccountParams): Promise<GetAccountResponse> {
return await this.sendRequest({ method: "account/read", params: params });
}
//TODO create type-safe helper
async awaitTurnCompleted(): Promise<TurnCompletedNotification> {
return await new Promise((resolve) => {
this.connection.onNotification("turn/completed", (event: TurnCompletedNotification) => {
resolve(event);
});
});
}
async listModels(params: ModelListParams = {cursor: null, limit: null}): Promise<ModelListResponse> {
return await this.sendRequest({ method: "model/list", 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) {
for (const notificationHandler of this.notificationHandlers.values()) {
notificationHandler(notification);
}
}
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;