-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathCodexEventHandler.ts
More file actions
222 lines (209 loc) · 7.99 KB
/
Copy pathCodexEventHandler.ts
File metadata and controls
222 lines (209 loc) · 7.99 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
import type {ServerNotification} from "./app-server";
import type {SessionState} from "./CodexAcpServer";
import * as acp from "@agentclientprotocol/sdk";
import {type PlanEntry, type ToolCallContent} from "@agentclientprotocol/sdk";
import {applyPatch} from "diff";
import {ACPSessionConnection, type UpdateSessionEvent} from "./ACPSessionConnection";
import type {
AgentMessageDeltaNotification,
CommandAction,
FileUpdateChange,
ItemCompletedNotification,
ItemStartedNotification,
ThreadItem,
TurnPlanUpdatedNotification
} from "./app-server/v2";
import {readFile} from "node:fs/promises";
export class CodexEventHandler {
private readonly connection: acp.AgentSideConnection;
private readonly sessionState: SessionState;
constructor(connection: acp.AgentSideConnection, sessionState: SessionState) {
this.connection = connection;
this.sessionState = sessionState;
}
async handleNotification(notification: ServerNotification) {
const session = new ACPSessionConnection(this.connection, this.sessionState.sessionMetadata.sessionId);
const updateEvent = await this.createUpdateEvent(notification);
if (updateEvent) {
await session.update(updateEvent);
}
}
private async createUpdateEvent(notification: ServerNotification): Promise<UpdateSessionEvent | null> {
/*
TODO split UpdateSessionEvent to improve completion
createUpdateEvent({
sessionUpdate: "" , <- completion of UpdateSessionEvent["sessionUpdate"]
params: {}, <- quickfix to generate required fields (rest of)
});
*/
switch (notification.method) {
case "item/agentMessage/delta":
return await this.createTextEvent(notification.params);
case "item/started":
return await this.createItemEvent(notification.params);
case "item/completed":
return await this.completeItemEvent(notification.params);
case "turn/plan/updated":
return await this.updatePlan(notification.params);
case "item/reasoning/summaryTextDelta": //TODO streaming reasoning?
case "item/reasoning/summaryPartAdded":
//skipped events
case "item/reasoning/textDelta": //for raw output
case "turn/started":
case "turn/completed":
case "turn/diff/updated":
case "item/commandExecution/outputDelta":
case "item/fileChange/outputDelta":
case "error":
case "thread/tokenUsage/updated":
case "item/mcpToolCall/progress":
case "account/updated":
case "account/rateLimits/updated":
case "thread/compacted":
case "windows/worldWritableWarning":
case "account/login/completed":
case "authStatusChange":
case "loginChatGptComplete":
case "sessionConfigured":
case "thread/started":
return null;
}
}
private async createTextEvent(event: AgentMessageDeltaNotification): Promise<UpdateSessionEvent> {
return {
sessionUpdate: "agent_message_chunk",
content: {
type: "text",
text: event.delta
}
}
}
private async createItemEvent(event: ItemStartedNotification): Promise<UpdateSessionEvent | null> {
switch (event.item.type) {
case "fileChange":
return await this.createFileChangeEvent(event.item)
case "commandExecution":
return await this.createCommandEvent(event.item)
case "userMessage":
case "agentMessage":
case "reasoning":
case "mcpToolCall":
case "webSearch":
case "imageView":
case "enteredReviewMode":
case "exitedReviewMode":
return null;
}
}
private async completeItemEvent(event: ItemCompletedNotification): Promise<UpdateSessionEvent | null> {
switch (event.item.type) {
case "fileChange":
case "commandExecution":
return {
sessionUpdate: "tool_call_update",
toolCallId: event.item.id,
status: event.item.status === "completed" ? "completed" : "failed"
}
case "reasoning":
const summary = event.item.summary[0];
if (!summary) return null;
return {
sessionUpdate: "agent_thought_chunk",
content: {
type: "text",
text: summary
}
}
case "userMessage":
case "agentMessage":
case "mcpToolCall":
case "webSearch":
case "imageView":
case "enteredReviewMode":
case "exitedReviewMode":
return null;
}
}
private async createFileChangeEvent(item: ThreadItem & { "type": "fileChange" }): Promise<UpdateSessionEvent | null> {
const patches: ToolCallContent[] = [];
for (const change of item.changes) {
const content = await this.createPatchContent(change);
if (content) patches.push(content);
//TODO handle errors (nulls)
}
return {
sessionUpdate: "tool_call",
toolCallId: item.id,
title: "Editing files",
kind: "edit",
status: "completed",
content: patches,
};
}
private async createPatchContent(change: FileUpdateChange): Promise<ToolCallContent | null> {
const oldContent = await readFile(change.path, { encoding: "utf8" });
const newContent = applyPatch(oldContent, change.diff);
if (!newContent) {
return null
}
return {
type: "diff",
oldText: oldContent,
newText: newContent,
path: change.path,
}
}
private async createCommandEvent(item: ThreadItem & { "type": "commandExecution" }): Promise<UpdateSessionEvent> {
const commandAction = item.commandActions.length === 1 ? item.commandActions[0] : undefined;
if (commandAction) {
return this.createCommandActionEvent(item.id, commandAction);
}
const command = item.command.replace(/^(?:\/bin\/)?bash\s+/, "");
return {
sessionUpdate: "tool_call",
toolCallId: item.id,
kind: "execute",
title: command,
status: "in_progress"
}
}
private createCommandActionEvent(id: string, commandAction: CommandAction): UpdateSessionEvent {
if (commandAction.type === "read") {
return {
sessionUpdate: "tool_call",
toolCallId: id,
status: "in_progress",
kind: "read",
title: "Read file",
locations: [{path: commandAction.path}],
};
} else if (commandAction.type === "search" && commandAction.query) {
return {
sessionUpdate: "tool_call",
toolCallId: id,
status: "in_progress",
kind: "search",
title: `Search '${commandAction.query}'`,
}
}
return {
sessionUpdate: "tool_call",
toolCallId: id,
status: "in_progress",
kind: "execute",
title: commandAction.command,
}
}
private async updatePlan(event: TurnPlanUpdatedNotification): Promise<UpdateSessionEvent> {
const plan: PlanEntry[] = event.plan.map(value => ({
status: value.status == "inProgress" ? "in_progress" : value.status,
content: value.step,
priority: "medium"
})
);
return {
sessionUpdate: "plan",
entries: plan,
}
}
}