-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathCodexAcpServer.ts
More file actions
908 lines (821 loc) · 34.8 KB
/
Copy pathCodexAcpServer.ts
File metadata and controls
908 lines (821 loc) · 34.8 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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
import * as acp from "@agentclientprotocol/sdk";
import {RequestError, type SessionId, type SessionModelState, type SessionModeState} from "@agentclientprotocol/sdk";
import {CodexEventHandler} from "./CodexEventHandler";
import {CodexApprovalHandler} from "./CodexApprovalHandler";
import {CodexElicitationHandler} from "./CodexElicitationHandler";
import {type CodexAuthRequest, getCodexAuthMethods} from "./CodexAuthMethod";
import {CodexAcpClient, type SessionMetadata, type SessionMetadataWithThread} from "./CodexAcpClient";
import type {McpStartupResult} from "./CodexAppServerClient";
import {ACPSessionConnection, type UpdateSessionEvent} from "./ACPSessionConnection";
import type {InputModality, ReasoningEffort} from "./app-server";
import type {
Account,
CollabAgentToolCallStatus,
Model,
ReasoningEffortOption,
Thread,
ThreadItem,
TurnCompletedNotification,
UserInput
} from "./app-server/v2";
import type {RateLimitsMap} from "./RateLimitsMap";
import {ModelId} from "./ModelId";
import {AgentMode} from "./AgentMode";
import type {TokenCount} from "./TokenCount";
import {toPromptUsage} from "./TokenCount";
import {CodexCommands} from "./CodexCommands";
import type {QuotaMeta} from "./QuotaMeta";
import {logger} from "./Logger";
import {isExtMethodRequest} from "./AcpExtensions";
import {
createCommandExecutionUpdate,
createDynamicToolCallUpdate,
createFileChangeUpdate,
createMcpToolCallUpdate,
} from "./CodexToolCallMapper";
export interface SessionState {
sessionId: string,
currentModelId: string,
supportedReasoningEfforts: Array<ReasoningEffortOption>,
supportedInputModalities: Array<InputModality>,
agentMode: AgentMode,
currentTurnId: string | null;
lastTokenUsage: TokenCount | null;
totalTokenUsage: TokenCount | null;
modelContextWindow: number | null;
rateLimits: RateLimitsMap | null;
account: Account | null;
cwd: string;
sessionMcpServers?: Array<string>;
}
interface PendingMcpStartupSession {
requestedServers: Set<string>;
afterVersion: number;
}
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 availableCommands: CodexCommands;
private readonly sessions: Map<string, SessionState>;
private readonly pendingMcpStartupSessions: Map<string, PendingMcpStartupSession>;
constructor(
connection: acp.AgentSideConnection,
codexAcpClient: CodexAcpClient,
defaultAuthRequest?: CodexAuthRequest,
getExitCode?: () => number | null,
) {
this.sessions = new Map();
this.pendingMcpStartupSessions = new Map();
this.connection = connection;
this.codexAcpClient = codexAcpClient;
this.defaultAuthRequest = defaultAuthRequest ?? null;
this.getExitCode = getExitCode ?? (() => null);
this.availableCommands = new CodexCommands(
connection,
codexAcpClient,
(operation) => this.runWithProcessCheck(operation)
);
}
async initialize(
_params: acp.InitializeRequest,
): Promise<acp.InitializeResponse> {
logger.log("Initialize request received");
await this.runWithProcessCheck(() => this.codexAcpClient.initialize(_params));
return {
protocolVersion: acp.PROTOCOL_VERSION,
agentCapabilities: {
auth: {
logout: {},
},
loadSession: true,
promptCapabilities: {
image: true
},
sessionCapabilities: {
resume: { },
list: { }
},
mcpCapabilities: {
http: true,
sse: false
}
},
authMethods: getCodexAuthMethods(_params.clientCapabilities),
};
}
async extMethod(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {
const methodRequest = { method: method, params: params };
if (!isExtMethodRequest(methodRequest)) {
return {};
}
switch (methodRequest.method) {
case "authentication/status":
return await this.runWithProcessCheck(() => this.codexAcpClient.getAuthenticationStatus());
case "authentication/logout": {
await this.unstable_logout({});
return {};
}
}
}
async checkAuthorization(){
const authNeeded = await this.runWithProcessCheck(() => this.codexAcpClient.authRequired());
logger.log("Auth requirement checked", {authRequired: authNeeded});
if (authNeeded) {
if (this.defaultAuthRequest) {
logger.log("Authenticating with default auth request...", {
authRequest: this.defaultAuthRequest
});
await this.authenticate(this.defaultAuthRequest)
logger.log("Authentication completed");
} else {
logger.log("Authentication required but no default auth request provided, return to IDE");
throw RequestError.authRequired();
}
}
}
async getOrCreateSession(request: acp.NewSessionRequest | acp.ResumeSessionRequest): Promise<[SessionId, SessionModelState, SessionModeState]> {
await this.checkAuthorization();
const requestedMcpServers = request.mcpServers ?? [];
const mcpServerStartupVersion = requestedMcpServers.length > 0
? this.codexAcpClient.getMcpServerStartupVersion()
: null;
let sessionMetadata: SessionMetadata;
if ("sessionId" in request) {
logger.log(`Resume existing session: ${request.sessionId}...`)
sessionMetadata = await this.runWithProcessCheck(() => this.codexAcpClient.resumeSession(request));
} else {
logger.log(`Create new session...`)
sessionMetadata = await this.runWithProcessCheck(() => this.codexAcpClient.newSession(request));
}
const account = await this.getActiveAccount();
const {sessionId, currentModelId, models} = sessionMetadata;
const sessionMcpServers = this.resolveSessionMcpServers(requestedMcpServers, "sessionId" in request);
const currentModel = this.findCurrentModel(models, currentModelId);
const sessionState: SessionState = {
sessionId: sessionId,
currentModelId: currentModelId,
supportedReasoningEfforts: currentModel?.supportedReasoningEfforts ?? [],
supportedInputModalities: currentModel?.inputModalities ?? ["text", "image"],
agentMode: AgentMode.getInitialAgentMode(),
currentTurnId: null,
lastTokenUsage: null,
totalTokenUsage: null,
modelContextWindow: null,
rateLimits: null,
account: account,
cwd: request.cwd,
sessionMcpServers: sessionMcpServers,
}
this.sessions.set(sessionId, sessionState);
if (requestedMcpServers.length > 0 && mcpServerStartupVersion !== null) {
this.pendingMcpStartupSessions.set(sessionId, {
requestedServers: new Set(requestedMcpServers.map(server => server.name)),
afterVersion: mcpServerStartupVersion,
});
this.publishMcpStartupStatusAsync(sessionId);
}
this.publishAvailableCommandsAsync(sessionId);
const sessionModelState: SessionModelState = this.createModelState(models, currentModelId);
const sessionModeState: SessionModeState = sessionState.agentMode.toSessionModeState();
return [sessionId, sessionModelState, sessionModeState];
}
private async getActiveAccount(){
if (this.codexAcpClient.getModelProvider()) {
return null
}
const accountResponse = await this.runWithProcessCheck(() => this.codexAcpClient.getAccount());
return accountResponse.account;
}
async loadSession(params: acp.LoadSessionRequest): Promise<acp.LoadSessionResponse> {
logger.log("Loading session...", {sessionId: params.sessionId});
const {
sessionId,
modelState,
modeState,
thread,
} = await this.getOrCreateSessionWithHistory(params);
await this.streamThreadHistory(sessionId, thread);
logger.log("Session loaded", {
sessionId: sessionId,
modelId: modelState.currentModelId,
availableModelCount: modelState.availableModels.length
});
return {
models: modelState,
modes: modeState
};
}
async resumeSession(params: acp.ResumeSessionRequest): Promise<acp.ResumeSessionResponse> {
logger.log("Resuming session...", {sessionId: params.sessionId});
const [sessionId, modelState, modeState] = await this.getOrCreateSession(params);
logger.log("Session resumed", {
sessionId: sessionId,
modelId: modelState.currentModelId,
availableModelCount: modelState.availableModels.length
});
return {
models: modelState,
modes: modeState
};
}
async listSessions(params: acp.ListSessionsRequest): Promise<acp.ListSessionsResponse> {
logger.log("Listing sessions...", {cwd: params.cwd, cursor: params.cursor});
await this.checkAuthorization();
return await this.runWithProcessCheck(() => this.codexAcpClient.listSessions(params));
}
async newSession(
params: acp.NewSessionRequest,
): Promise<acp.NewSessionResponse> {
logger.log("Starting new session...");
const [sessionId, modelState, modeState] = await this.getOrCreateSession(params);
logger.log("New session created", {
sessionId: sessionId,
modelId: modelState.currentModelId,
availableModelCount: modelState.availableModels.length
});
return {
sessionId: sessionId,
models: modelState,
modes: modeState
};
}
async authenticate(
_params: acp.AuthenticateRequest,
): Promise<acp.AuthenticateResponse> {
logger.log("Authenticate request received");
const isAuthenticated = await this.runWithProcessCheck(() => this.codexAcpClient.authenticate(_params));
if (!isAuthenticated) {
logger.log("Authenticate request failed");
throw RequestError.invalidParams();
}
logger.log("Authenticate request completed");
return { };
}
async unstable_logout(_params: acp.LogoutRequest): Promise<void> {
logger.log("Logout request received");
await this.runWithProcessCheck(() => this.codexAcpClient.logout());
logger.log("Logout request completed");
}
async setSessionMode(
_params: acp.SetSessionModeRequest,
): Promise<acp.SetSessionModeResponse> {
logger.log("Set session mode requested", {
sessionId: _params.sessionId,
modeId: _params.modeId
});
const sessionState = this.sessions.get(_params.sessionId);
if (!sessionState) throw new Error(`Session ${_params.sessionId} not found`);
const newMode = AgentMode.find(_params.modeId);
if (!newMode) {
throw RequestError.invalidParams();
}
sessionState.agentMode = newMode;
return {};
}
async unstable_setSessionModel(params: acp.SetSessionModelRequest): Promise<acp.SetSessionModelResponse | void> {
logger.log("Set session model requested", {
sessionId: params.sessionId,
modelId: params.modelId
});
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 models = await this.codexAcpClient.fetchAvailableModels();
const model = 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;
}
sessionState.currentModelId = ModelId.fromComponents(model, reasoningEffort).toString();
sessionState.supportedReasoningEfforts = model.supportedReasoningEfforts;
sessionState.supportedInputModalities = model.inputModalities;
return {};
}
private publishAvailableCommandsAsync(sessionId: string) {
void this.availableCommands.publish(sessionId);
}
private findCurrentModel(models: Model[], currentModelId: string): Model | undefined {
const modelId = ModelId.fromString(currentModelId);
return models.find(m => m.id === modelId.model);
}
private createModelState(availableModels: Model[], selectedModelId: string): SessionModelState {
const allowedModels = availableModels
.flatMap((model) =>
model.supportedReasoningEfforts.map((effort) => ({
modelId: ModelId.fromComponents(model, effort.reasoningEffort).toString(),
name: `${model.displayName} (${effort.reasoningEffort})`,
description: `${model.description} ${effort.description}`,
}))
);
return {
availableModels: allowedModels,
currentModelId: selectedModelId,
}
}
private async getOrCreateSessionWithHistory(
request: acp.LoadSessionRequest
): Promise<{
sessionId: SessionId;
modelState: SessionModelState;
modeState: SessionModeState;
thread: Thread;
}> {
await this.checkAuthorization();
const requestedMcpServers = request.mcpServers ?? [];
const mcpServerStartupVersion = requestedMcpServers.length > 0
? this.codexAcpClient.getMcpServerStartupVersion()
: null;
logger.log(`Load existing session: ${request.sessionId}...`);
const sessionMetadata: SessionMetadataWithThread = await this.runWithProcessCheck(() =>
this.codexAcpClient.loadSession(request)
);
const account = await this.getActiveAccount();
const {sessionId, currentModelId, models, thread} = sessionMetadata;
const sessionMcpServers = this.resolveSessionMcpServers(requestedMcpServers, true);
const currentModel = this.findCurrentModel(models, currentModelId);
const sessionState: SessionState = {
sessionId: sessionId,
currentModelId: currentModelId,
supportedReasoningEfforts: currentModel?.supportedReasoningEfforts ?? [],
supportedInputModalities: currentModel?.inputModalities ?? ["text", "image"],
agentMode: AgentMode.getInitialAgentMode(),
currentTurnId: null,
lastTokenUsage: null,
totalTokenUsage: null,
modelContextWindow: null,
rateLimits: null,
account: account,
cwd: request.cwd,
sessionMcpServers: sessionMcpServers,
};
this.sessions.set(sessionId, sessionState);
if (requestedMcpServers.length > 0 && mcpServerStartupVersion !== null) {
this.pendingMcpStartupSessions.set(sessionId, {
requestedServers: new Set(requestedMcpServers.map(server => server.name)),
afterVersion: mcpServerStartupVersion,
});
this.publishMcpStartupStatusAsync(sessionId);
}
await this.availableCommands.publish(sessionId);
const sessionModelState: SessionModelState = this.createModelState(models, currentModelId);
const sessionModeState: SessionModeState = sessionState.agentMode.toSessionModeState();
return {
sessionId: sessionId,
modelState: sessionModelState,
modeState: sessionModeState,
thread: thread,
};
}
private async streamThreadHistory(sessionId: string, thread: Thread): Promise<void> {
const session = new ACPSessionConnection(this.connection, sessionId);
for (const turn of thread.turns) {
for (const item of turn.items) {
const updates = await this.createHistoryUpdates(item);
for (const update of updates) {
await session.update(update);
}
}
}
}
private async createHistoryUpdates(item: ThreadItem): Promise<UpdateSessionEvent[]> {
switch (item.type) {
case "userMessage":
return this.createUserMessageUpdates(item);
case "hookPrompt":
return [];
case "agentMessage":
return [{
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: item.text },
}];
case "reasoning":
return this.createReasoningUpdates(item);
case "fileChange":
return [await createFileChangeUpdate(item)];
case "commandExecution":
return [await createCommandExecutionUpdate(item)];
case "mcpToolCall":
return [await createMcpToolCallUpdate(item)];
case "dynamicToolCall":
return [await createDynamicToolCallUpdate(item)];
case "collabAgentToolCall":
return [this.createCollabAgentToolCallUpdate(item)];
case "webSearch":
return [this.createWebSearchUpdate(item)];
case "imageView":
return [this.createImageViewUpdate(item)];
case "imageGeneration":
return [];
case "enteredReviewMode":
return [this.createReviewModeUpdate(item, true)];
case "exitedReviewMode":
return [this.createReviewModeUpdate(item, false)];
case "contextCompaction":
return [this.createContextCompactionUpdate()];
case "plan":
return [this.createPlanUpdate(item)];
}
}
private createUserMessageUpdates(item: ThreadItem & { type: "userMessage" }): UpdateSessionEvent[] {
const updates: UpdateSessionEvent[] = [];
for (const input of item.content) {
const blocks = this.userInputToContentBlocks(input);
for (const block of blocks) {
updates.push({
sessionUpdate: "user_message_chunk",
content: block,
});
}
}
return updates;
}
private createReasoningUpdates(item: ThreadItem & { type: "reasoning" }): UpdateSessionEvent[] {
const parts = item.summary.length > 0 ? item.summary : item.content;
return parts.map((text) => ({
sessionUpdate: "agent_thought_chunk",
content: { type: "text", text: text },
}));
}
private createCollabAgentToolCallUpdate(
item: ThreadItem & { type: "collabAgentToolCall" }
): UpdateSessionEvent {
return {
sessionUpdate: "tool_call",
toolCallId: item.id,
kind: "other",
title: `collab.${item.tool}`,
status: this.toAcpToolCallStatus(item.status),
rawInput: {
prompt: item.prompt,
senderThreadId: item.senderThreadId,
receiverThreadIds: item.receiverThreadIds,
agentsStates: item.agentsStates,
status: item.status,
},
};
}
private createWebSearchUpdate(
item: ThreadItem & { type: "webSearch" }
): UpdateSessionEvent {
return {
sessionUpdate: "tool_call",
toolCallId: item.id,
kind: "search",
title: this.formatWebSearchTitle(item),
status: "completed",
rawInput: {
query: item.query,
action: item.action,
},
};
}
private createImageViewUpdate(
item: ThreadItem & { type: "imageView" }
): UpdateSessionEvent {
return {
sessionUpdate: "tool_call",
toolCallId: item.id,
kind: "read",
title: "View image",
status: "completed",
locations: [{ path: item.path }],
rawInput: {
path: item.path,
},
};
}
private createReviewModeUpdate(
item: ThreadItem & { type: "enteredReviewMode" | "exitedReviewMode" },
entered: boolean
): UpdateSessionEvent {
return {
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: `${entered ? "Entered" : "Exited"} review mode: ${item.review}`,
},
};
}
private createContextCompactionUpdate(): UpdateSessionEvent {
return {
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: "Context compacted.",
},
};
}
private createPlanUpdate(
item: ThreadItem & { type: "plan" }
): UpdateSessionEvent {
return {
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: `Plan:\n${item.text}`,
},
};
}
private formatWebSearchTitle(item: ThreadItem & { type: "webSearch" }): string {
const action = item.action;
if (!action) {
return item.query ? `Web search: ${item.query}` : "Web search";
}
switch (action.type) {
case "search": {
const queries = action.queries?.filter((query) => query && query.length > 0) ?? [];
const query = action.query ?? (queries.length > 0 ? queries.join(", ") : null) ?? item.query;
return query ? `Web search: ${query}` : "Web search";
}
case "openPage":
return action.url ? `Open page: ${action.url}` : "Open page";
case "findInPage": {
const pattern = action.pattern ? ` for '${action.pattern}'` : "";
const url = action.url ? ` in ${action.url}` : "";
return `Find in page${pattern}${url}`.trim();
}
case "other":
return "Web search";
}
}
private toAcpToolCallStatus(status: CollabAgentToolCallStatus): "in_progress" | "completed" | "failed" {
switch (status) {
case "inProgress":
return "in_progress";
case "completed":
return "completed";
case "failed":
return "failed";
}
}
private userInputToContentBlocks(input: UserInput): acp.ContentBlock[] {
switch (input.type) {
case "text":
return input.text.length > 0 ? [{ type: "text", text: input.text }] : [];
case "image":
return [{ type: "text", text: this.formatUriAsLink("image", input.url) }];
case "localImage": {
const uri = input.path.startsWith("file://") ? input.path : `file://${input.path}`;
return [{ type: "text", text: this.formatUriAsLink(null, uri) }];
}
case "skill":
return [{ type: "text", text: `skill:${input.name} (${input.path})` }];
}
return [];
}
private formatUriAsLink(name: string | null, uri: string): string {
if (name && name.length > 0) {
return `[@${name}](${uri})`;
}
if (uri.startsWith("file://")) {
const path = uri.replace("file://", "");
const fileName = path.split("/").pop() ?? path;
return `[@${fileName}](${uri})`;
}
return uri;
}
getSessionState(sessionId: string): SessionState {
const sessionState = this.sessions.get(sessionId);
if (!sessionState) {
throw new Error(`Session ${sessionId} not found`);
}
return sessionState;
}
private resolveSessionMcpServers(
mcpServers: Array<acp.McpServer>,
recoverFromStartup: boolean,
): Array<string> {
// Explicit MCP servers from the request are the primary source of truth for the session.
const requestedServerNames = getRequestedMcpServerNames(mcpServers);
if (requestedServerNames.length > 0) {
return requestedServerNames;
}
// Fresh sessions without MCP config should not inherit any session MCP state.
if (!recoverFromStartup) {
return [];
}
// Without a thread-scoped startup completion event, loadSession/resumeSession can no longer
// recover omitted session MCP server names. Treat the session set as unknown unless ACP
// explicitly provided mcpServers in the request.
logger.log("Skipping MCP server recovery for load/resume without explicit mcpServers");
return [];
}
private publishMcpStartupStatusAsync(sessionId: string): void {
void this.doPublishMcpStartupStatus(sessionId);
}
private async doPublishMcpStartupStatus(sessionId: string): Promise<void> {
const pendingStartup = this.pendingMcpStartupSessions.get(sessionId);
if (!pendingStartup) {
return;
}
try {
const mcpStartup = await this.runWithProcessCheck(() =>
this.codexAcpClient.awaitMcpServerStartup(
Array.from(pendingStartup.requestedServers),
pendingStartup.afterVersion,
)
);
await this.publishMcpStartupStatus(sessionId, mcpStartup, pendingStartup.requestedServers);
} catch (err) {
logger.error(`Failed to publish MCP startup status for session ${sessionId}`, err);
} finally {
this.pendingMcpStartupSessions.delete(sessionId);
}
}
private async publishMcpStartupStatus(
sessionId: string,
mcpStartup: McpStartupResult,
requestedServers?: Set<string>
): Promise<void> {
const filteredStartup = requestedServers
? {
ready: mcpStartup.ready.filter(server => requestedServers.has(server)),
failed: mcpStartup.failed.filter(server => requestedServers.has(server.server)),
cancelled: mcpStartup.cancelled.filter(server => requestedServers.has(server)),
}
: mcpStartup;
for (const update of CodexEventHandler.createMcpStartupUpdates(filteredStartup)) {
await this.connection.sessionUpdate({
sessionId,
update,
});
}
}
async prompt(params: acp.PromptRequest): Promise<acp.PromptResponse> {
logger.log("Prompt received", {
sessionId: params.sessionId,
prompt: params.prompt,
});
const sessionState = this.getSessionState(params.sessionId);
sessionState.currentTurnId = null;
sessionState.lastTokenUsage = null;
try {
const eventHandler = new CodexEventHandler(this.connection, sessionState);
const approvalHandler = new CodexApprovalHandler(this.connection, sessionState);
const elicitationHandler = new CodexElicitationHandler(this.connection, sessionState);
await this.codexAcpClient.subscribeToSessionEvents(params.sessionId,
(event) => {
elicitationHandler.handleNotification(event);
return eventHandler.handleNotification(event);
},
approvalHandler,
elicitationHandler);
const commandResult = await this.availableCommands.tryHandle(params.prompt, sessionState);
if (commandResult) {
logger.log("Prompt handled by a command");
if (commandResult !== true) {
const interruptedResponse = await this.createInterruptedResponseIfNeeded(params.sessionId, commandResult, sessionState);
if (interruptedResponse) {
return interruptedResponse;
}
}
const error = eventHandler.getFailure();
if (error) {
throw error;
}
return this.createPromptResponse("end_turn", sessionState);
}
const modelId = ModelId.fromString(sessionState.currentModelId);
const modelLacksReasoning = sessionState.supportedReasoningEfforts.length > 0
&& sessionState.supportedReasoningEfforts.every(e => e.reasoningEffort === "none");
const disableSummary = sessionState.account?.type === "apiKey" || modelLacksReasoning;
if (disableSummary) {
logger.log("Disable reasoning.summary", {
sessionId: params.sessionId,
reason: sessionState.account?.type === "apiKey" ? "API key" : "model lacks reasoning"
});
}
if (!sessionState.supportedInputModalities.includes("image") && params.prompt.some(b => b.type === "image")) {
throw RequestError.invalidRequest("The current model does not support image input");
}
const agentMode = sessionState.agentMode;
const turnCompleted = await this.runWithProcessCheck(
() => this.codexAcpClient.sendPrompt(params, agentMode, modelId, disableSummary, sessionState.cwd));
// Check if turn was interrupted (cancelled)
const interruptedResponse = await this.createInterruptedResponseIfNeeded(params.sessionId, turnCompleted, sessionState);
if (interruptedResponse) {
return interruptedResponse;
}
const error = eventHandler.getFailure()
if (error) {
// noinspection ExceptionCaughtLocallyJS
throw error;
}
return this.createPromptResponse("end_turn", sessionState);
} catch (err) {
logger.error(`Prompt for session ${params.sessionId} failed`, err);
throw err;
} finally {
logger.log("Prompt completed", {sessionId: params.sessionId});
sessionState.currentTurnId = null;
}
}
private buildQuotaMeta(sessionState: SessionState): { quota: QuotaMeta } {
const lastTokenUsage = sessionState.lastTokenUsage;
// Remove the "[reasoning-level]" suffix from currentModelId if present
const modelName = sessionState.currentModelId.replace(/\[.*?]$/, '');
// FIXME: currently all tokens are reported for the current model
const modelUsage = (lastTokenUsage != null)
? [{ model: modelName, token_count: lastTokenUsage }]
: [];
return {
quota: {
token_count: sessionState.lastTokenUsage,
model_usage: modelUsage
}
};
}
private buildPromptUsage(lastTokenUsage: TokenCount | null): acp.Usage | null {
if (lastTokenUsage == null) {
return null;
}
return toPromptUsage(lastTokenUsage);
}
private async createInterruptedResponseIfNeeded(
sessionId: string,
turnCompleted: TurnCompletedNotification,
sessionState: SessionState
): Promise<acp.PromptResponse | null> {
if (turnCompleted.turn.status !== "interrupted") {
return null;
}
await this.connection.sessionUpdate({
sessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: "*Conversation interrupted*"
}
}
});
return this.createPromptResponse("cancelled", sessionState);
}
private createPromptResponse(stopReason: acp.PromptResponse["stopReason"], sessionState: SessionState): acp.PromptResponse {
return {
stopReason,
usage: this.buildPromptUsage(sessionState.lastTokenUsage),
_meta: this.buildQuotaMeta(sessionState),
};
}
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> {
const sessionState = this.sessions.get(params.sessionId);
if (!sessionState) {
logger.log("Cancel request rejected: session not found", {sessionId: params.sessionId});
return;
}
if (!sessionState.currentTurnId) {
logger.log("Cancel request rejected: no current turn", {sessionId: params.sessionId});
return;
}
logger.log("Cancel session requested", {
sessionId: params.sessionId,
currentTurnId: sessionState.currentTurnId
});
try {
// After turnInterrupt(), Codex will send turn/completed event, which will naturally complete awaitTurnCompleted()
await this.codexAcpClient.turnInterrupt({
threadId: params.sessionId,
turnId: sessionState.currentTurnId
});
logger.log("Cancel - turnInterrupt succeeded", {
sessionId: params.sessionId,
currentTurnId: sessionState.currentTurnId
});
} catch (err) {
logger.error(`Cancel - turnInterrupt failed`, err);
}
}
}
function getRequestedMcpServerNames(mcpServers: Array<acp.McpServer>): Array<string> {
return Array.from(new Set(mcpServers.map(server => server.name)));
}