-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathCodexAcpClient.ts
More file actions
162 lines (142 loc) · 5.49 KB
/
Copy pathCodexAcpClient.ts
File metadata and controls
162 lines (142 loc) · 5.49 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
import {isCodexAuthRequest} from "./CodexAuthMethod";
import * as acp from "@agentclientprotocol/sdk";
import type {CodexAppServerClient} from "./CodexAppServerClient";
import {RequestError} from "@agentclientprotocol/sdk";
import open from "open";
import type {
ClientInfo,
ServerNotification,
SetDefaultModelParams,
SetDefaultModelResponse
} from "./app-server";
import type {TurnCompletedNotification } from "./app-server/v2";
import type {JsonValue} from "./app-server/serde_json/JsonValue";
import type {Model} from "./app-server/v2";
import {ModelId} from "./ModelId";
/**
* API for accessing the Codex App Server using ACP requests.
* Converts ACP requests into corresponding app-server operations.
*/
export class CodexAcpClient {
private readonly codexClient: CodexAppServerClient;
private readonly config: JsonObject;
private readonly modelProvider: string | null;
constructor(codexClient: CodexAppServerClient, codexConfig?: JsonObject, modelProvider?: string) {
this.codexClient = codexClient;
this.config = codexConfig ?? {};
this.modelProvider = modelProvider ?? null;
}
private readonly defaultClientInfo: ClientInfo = {
name: "codex-acp", title: "Codex ACP", version: "0.0.5"
};
async initialize(request: acp.InitializeRequest): Promise<void> {
await this.codexClient.initialize({
clientInfo: {
name: request.clientInfo?.name ?? this.defaultClientInfo.name,
version: request.clientInfo?.version ?? this.defaultClientInfo.version,
title: request.clientInfo?.title ?? this.defaultClientInfo.title,
}
});
}
async authenticate(authRequest: acp.AuthenticateRequest): Promise<Boolean> {
if (!isCodexAuthRequest(authRequest)) {
throw RequestError.invalidRequest();
}
switch (authRequest.methodId) {
case "api-key":
await this.codexClient.accountLogin({
type: "apiKey",
apiKey: authRequest._meta.apiKey
});
break;
case "chat-gpt":
const loginResponse = await this.codexClient.accountLogin({ type: "chatgpt" });
if (loginResponse.type == "chatgpt") {
await open(loginResponse.authUrl);
}
break;
}
const result = await this.codexClient.awaitLoginCompleted()
return result.success;
}
async logout(): Promise<void> {
await this.codexClient.accountLogout();
await this.codexClient.awaitAccountUpdated();
}
async authRequired(): Promise<Boolean> {
const response = await this.codexClient.accountRead({refreshToken: false})
return response.requiresOpenaiAuth && !response.account;
}
/**
* Returns a new session ID.
*/
async newSession(request: acp.NewSessionRequest): Promise<SessionMetadata> {
const threadStartResponse = await this.codexClient.threadStart({
config: this.config,
modelProvider: this.modelProvider,
model: null,
cwd: request.cwd,
approvalPolicy: "never",
sandbox: null,
baseInstructions: null,
developerInstructions: null,
});
const codexModels = await this.fetchAvailableModels();
if (codexModels.length === 0) {
throw new Error("Codex did not return any models");
}
const currentModelId = ModelId.fromThreadResponse(threadStartResponse).toString();
return {
sessionId: threadStartResponse.thread.id,
currentModelId: currentModelId,
models: codexModels
};
}
async sendPrompt(
request: acp.PromptRequest,
eventHandler: (result: ServerNotification) => void
): Promise<TurnCompletedNotification> {
this.codexClient.onServerNotification(request.sessionId, eventHandler);
const input = request.prompt.filter(b => b.type === "text")
.map(b => b.text)
.join(" ");
await this.codexClient.turnStart({
threadId: request.sessionId,
input: [{type: "text", text: input}],
approvalPolicy: null,
sandboxPolicy: null,
summary: null,
cwd: null,
effort: null,
model: null,
});
// Wait for turn completion
// If turnInterrupt() was called, Codex will send turn/completed event with status "interrupted"
return await this.codexClient.awaitTurnCompleted();
}
async setModel(params: SetDefaultModelParams): Promise<SetDefaultModelResponse> {
return this.codexClient.setModelRequest(params);
}
async turnInterrupt(params: { threadId: string, turnId: string }): Promise<void> {
await this.codexClient.turnInterrupt({
threadId: params.threadId,
turnId: params.turnId
});
}
private async fetchAvailableModels(): Promise<Model[]> {
const models: Model[] = [];
let cursor: string | null = null;
do {
const response = await this.codexClient.listModels({ cursor, limit: null });
models.push(...response.data);
cursor = response.nextCursor;
} while (cursor);
return models;
}
}
export type JsonObject = { [key in string]?: JsonValue }
export type SessionMetadata = {
sessionId: string,
currentModelId: string,
models: Model[]
}