-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathCodexAcpServer.ts
More file actions
197 lines (165 loc) · 7 KB
/
Copy pathCodexAcpServer.ts
File metadata and controls
197 lines (165 loc) · 7 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
import * as acp from "@agentclientprotocol/sdk";
import {CodexEventHandler} from "./CodexEventHandler";
import {CodexAuthMethods, type CodexAuthRequest} from "./CodexAuthMethod";
import {type ModelInfo, RequestError, type SessionModelState} from "@agentclientprotocol/sdk";
import {CodexAcpClient, type SessionMetadata} from "./CodexAcpClient";
import type {Model} from "./app-server/v2";
import type {ReasoningEffort} from "./app-server";
import {ModelId} from "./ModelId";
export interface SessionState {
sessionMetadata: SessionMetadata;
pendingPrompt: AbortController | null;
}
export class CodexAcpServer implements acp.Agent {
private readonly codexAcpClient: CodexAcpClient;
private readonly connection: acp.AgentSideConnection;
private readonly defaultAuthRequest: CodexAuthRequest | null;
private readonly getExitCode: () => number | null;
private readonly sessions: Map<string, SessionState>;
constructor(
connection: acp.AgentSideConnection,
codexAcpClient: CodexAcpClient,
defaultAuthRequest?: CodexAuthRequest,
getExitCode?: () => number | null,
) {
this.sessions = new Map();
this.connection = connection;
this.codexAcpClient = codexAcpClient;
this.defaultAuthRequest = defaultAuthRequest ?? null;
this.getExitCode = getExitCode ?? (() => null);
}
async initialize(
_params: acp.InitializeRequest,
): Promise<acp.InitializeResponse> {
await this.runWithProcessCheck(() => this.codexAcpClient.initialize(_params));
return {
protocolVersion: acp.PROTOCOL_VERSION,
agentCapabilities: {
loadSession: false,
},
authMethods: CodexAuthMethods,
};
}
async newSession(
_params: acp.NewSessionRequest,
): Promise<acp.NewSessionResponse> {
if (await this.runWithProcessCheck(() => this.codexAcpClient.authRequired())) {
if (this.defaultAuthRequest) {
await this.authenticate(this.defaultAuthRequest)
} else {
throw RequestError.authRequired();
}
}
const sessionMetadata = await this.runWithProcessCheck(() => this.codexAcpClient.newSession(_params));
const {sessionId, currentModelId, models} = sessionMetadata;
this.sessions.set(sessionId, {
sessionMetadata: sessionMetadata,
pendingPrompt: null
});
const availableModels = this.buildAvailableModels(models);
const sessionModelState: SessionModelState = {
availableModels: availableModels,
currentModelId: currentModelId,
}
return {
sessionId: sessionId,
models: sessionModelState,
};
}
async authenticate(
_params: acp.AuthenticateRequest,
): Promise<acp.AuthenticateResponse> {
const isAuthenticated = await this.runWithProcessCheck(() => this.codexAcpClient.authenticate(_params));
if (!isAuthenticated) {
throw RequestError.invalidParams();
}
return { };
}
async setSessionMode(
_params: acp.SetSessionModeRequest,
): Promise<acp.SetSessionModeResponse> {
//TODO
return {};
}
async setSessionModel(params: acp.SetSessionModelRequest): Promise<acp.SetSessionModelResponse> {
const sessionState = this.sessions.get(params.sessionId);
if (!sessionState) throw new Error(`Session ${params.sessionId} not found`);
const requestedModelId= ModelId.fromString(params.modelId);
const requestedModelName = requestedModelId.model;
const requestedEffort = requestedModelId.effort;
const model = sessionState.sessionMetadata.models.find(m => m.id === requestedModelName);
if (!model) throw new Error(`Unknown model ${params.modelId}`);
const requestedEffortValue = requestedEffort as ReasoningEffort | undefined;
let reasoningEffort: ReasoningEffort;
if (requestedEffortValue) {
const matchedEffort = model.supportedReasoningEfforts.find(
(option) => option.reasoningEffort === requestedEffortValue
)?.reasoningEffort;
if (!matchedEffort) {
throw new Error(`Unsupported reasoning effort ${requestedEffortValue} for model ${requestedModelName}`);
}
reasoningEffort = matchedEffort;
} else {
reasoningEffort = model.defaultReasoningEffort;
}
await this.runWithProcessCheck(() => this.codexAcpClient.setModel({
model: model.model,
reasoningEffort,
}));
sessionState.sessionMetadata.currentModelId = ModelId.fromComponents(model, reasoningEffort).toString();
return {};
}
private buildAvailableModels(models: Model[]): ModelInfo[] {
return models.flatMap((model) =>
model.supportedReasoningEfforts.map((effort) => ({
modelId: ModelId.fromComponents(model, effort.reasoningEffort).toString(),
name: `${model.displayName} (${effort.reasoningEffort})`,
description: `${model.description} ${effort.description}`,
}))
);
}
getSessionState(sessionId: string): SessionState {
const sessionState = this.sessions.get(sessionId);
if (!sessionState) {
throw new Error(`Session ${sessionId} not found`);
}
return sessionState;
}
async prompt(params: acp.PromptRequest): Promise<acp.PromptResponse> {
const sessionState = this.getSessionState(params.sessionId);
sessionState.pendingPrompt?.abort();
sessionState.pendingPrompt = new AbortController();
try {
const messageHandler = new CodexEventHandler(this.connection, sessionState);
await this.runWithProcessCheck(() => this.codexAcpClient.sendPrompt(params, (event) => messageHandler.handleNotification(event)));
} catch (err) {
if (sessionState.pendingPrompt.signal.aborted) {
return {stopReason: "cancelled"};
}
throw err;
}
sessionState.pendingPrompt = null;
return {
stopReason: "end_turn",
};
}
private async runWithProcessCheck<T>(operation: () => Promise<T>): Promise<T> {
try {
return await operation();
} catch (err) {
const exitCode = this.getExitCode();
const requestErrorCode = 1001 // Just some magic number
if (exitCode == 3221225781) {
throw new RequestError(requestErrorCode, `VC++ redistributable should be installed`);
}
if (exitCode !== null) {
throw new RequestError(requestErrorCode, `Codex process has exited with code ${exitCode}`);
}
throw err;
}
}
async cancel(params: acp.CancelNotification): Promise<void> {
//TODO not supported yet
this.sessions.get(params.sessionId)?.pendingPrompt?.abort();
}
}