The best way to control Claude Code, Codex and more from any computer or phone

main
ts 264 lines 10 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as Schema from "effect/Schema";
3 import type * as AcpSchema from "effect-acp/compat";
4 import * as AcpErrors from "effect-acp/errors";
5 import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
6 import type {
7 AcpAdapterV2ExtensionContext,
8 AcpAdapterV2SubagentUpdate,
9 } from "@t3tools/provider-acp/server/adapter";
10
11 // The opt-in raw feed identifies each chunk by the preceding assistant.*_delta task call id.
12
13 const COPILOT_META_KEY = "github.com/copilot";
14 const COPILOT_SESSION_EVENT = "github.com/copilot/sessionEvent";
15
16 export const copilotClientCapabilitiesMeta = {
17 [COPILOT_META_KEY]: {
18 events: [
19 "subagent.started",
20 "subagent.completed",
21 "subagent.failed",
22 "assistant.message_delta",
23 "assistant.reasoning_delta",
24 "session.compaction_complete",
25 "assistant.turn_start",
26 "assistant.idle",
27 "tool.execution_start",
28 ],
29 },
30 };
31
32 const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
33
34 /** Copilot keeps failing every prompt with these until its process is replaced. */
35 const COPILOT_LOST_SESSION_MARKERS = [
36 "session event delivery failed: session not found: ",
37 "session lock unavailable during is_session_generation_current: acquisition timed out",
38 ];
39
40 export function isCopilotLostSessionError(error: unknown): boolean {
41 if (!isAcpRequestError(error) || error.method !== "session/prompt" || error.code !== -32603) {
42 return false;
43 }
44 // Older Copilot reports the cause in data.details; its native ACP layer (1.0.105) in the message.
45 return [error.errorMessage, record(error.data)?.details].some(
46 (text) =>
47 typeof text === "string" &&
48 COPILOT_LOST_SESSION_MARKERS.some((marker) => text.includes(marker)),
49 );
50 }
51
52 const CopilotSessionEvent = Schema.Struct({
53 sessionId: Schema.String,
54 type: Schema.String,
55 agentId: Schema.optionalKey(Schema.String),
56 data: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
57 });
58
59 function record(value: unknown): Record<string, unknown> | undefined {
60 return typeof value === "object" && value !== null && !Array.isArray(value)
61 ? (value as Record<string, unknown>)
62 : undefined;
63 }
64
65 const childSessionId = (taskToolCallId: string) => `copilot-task:${taskToolCallId}`;
66
67 // Copilot's tool_call reports MCP calls and glob/grep as kind "read" under a flattened title.
68 type CopilotToolIdentity =
69 | { readonly kind: "mcp"; readonly server: string; readonly tool: string }
70 | { readonly kind: "search" };
71
72 const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep", "rg"]);
73
74 interface CopilotSessionAttribution {
75 delta: { readonly kind: string; readonly text: string; readonly task?: string } | undefined;
76 readonly taskByAgentId: Map<string, string>;
77 readonly toolIdentityByCallId: Map<string, CopilotToolIdentity>;
78 }
79
80 function copilotToolIdentity(data: Record<string, unknown>): CopilotToolIdentity | undefined {
81 const server = typeof data.mcpServerName === "string" ? data.mcpServerName.trim() : "";
82 const tool = typeof data.mcpToolName === "string" ? data.mcpToolName.trim() : "";
83 if (server.length > 0 && tool.length > 0) return { kind: "mcp", server, tool };
84 return typeof data.toolName === "string" && COPILOT_SEARCH_TOOLS.has(data.toolName)
85 ? { kind: "search" }
86 : undefined;
87 }
88
89 export function makeCopilotSubagentRouting() {
90 const sessions = new Map<string, CopilotSessionAttribution>();
91 const session = (sessionId: string) => {
92 let current = sessions.get(sessionId);
93 if (current === undefined) {
94 current = { delta: undefined, taskByAgentId: new Map(), toolIdentityByCallId: new Map() };
95 sessions.set(sessionId, current);
96 }
97 return current;
98 };
99 const release = (sessionId: string, current: CopilotSessionAttribution) => {
100 if (
101 current.delta === undefined &&
102 current.taskByAgentId.size === 0 &&
103 current.toolIdentityByCallId.size === 0
104 ) {
105 sessions.delete(sessionId);
106 }
107 };
108
109 const registerExtensions = (context: AcpAdapterV2ExtensionContext) =>
110 context.runtime.handleExtNotification(COPILOT_SESSION_EVENT, CopilotSessionEvent, (event) => {
111 const data = event.data ?? {};
112 switch (event.type) {
113 case "assistant.message_delta":
114 case "assistant.reasoning_delta": {
115 if (typeof data.deltaContent !== "string") return Effect.void;
116 const current = session(event.sessionId);
117 // Copilot 1.0.114+ names a subagent's deltas only by agentId, without parentToolCallId.
118 const task =
119 typeof data.parentToolCallId === "string"
120 ? data.parentToolCallId
121 : event.agentId === undefined
122 ? undefined
123 : current.taskByAgentId.get(event.agentId);
124 current.delta = {
125 kind: event.type,
126 text: data.deltaContent,
127 ...(task === undefined ? {} : { task }),
128 };
129 return Effect.void;
130 }
131 case "subagent.started": {
132 if (event.agentId !== undefined && typeof data.toolCallId === "string") {
133 session(event.sessionId).taskByAgentId.set(event.agentId, data.toolCallId);
134 }
135 return Effect.void;
136 }
137 case "tool.execution_start": {
138 const identity = copilotToolIdentity(data);
139 if (identity !== undefined && typeof data.toolCallId === "string") {
140 session(event.sessionId).toolIdentityByCallId.set(data.toolCallId, identity);
141 }
142 return Effect.void;
143 }
144 case "subagent.completed":
145 case "subagent.failed": {
146 const current = sessions.get(event.sessionId);
147 if (current !== undefined && event.agentId !== undefined) {
148 current.taskByAgentId.delete(event.agentId);
149 release(event.sessionId, current);
150 }
151 if (typeof data.toolCallId !== "string") return Effect.void;
152 // Background tasks end only here; their tool call settles at launch.
153 return context.finishSubagent({
154 sessionId: event.sessionId,
155 childSessionId: childSessionId(data.toolCallId),
156 status: event.type === "subagent.failed" ? "failed" : "completed",
157 result: typeof data.error === "string" ? data.error : null,
158 });
159 }
160 // Copilot sends no ACP compaction_update; agentId marks a subagent's own compaction.
161 // Older Copilot builds report a successful compaction without `outcome`.
162 case "session.compaction_complete": {
163 if (
164 event.agentId !== undefined ||
165 data.success !== true ||
166 (data.outcome !== undefined && data.outcome !== "applied")
167 ) {
168 return Effect.void;
169 }
170 return context.markSessionCompacted(event.sessionId);
171 }
172 // Copilot holds session/prompt while an attached async shell runs (github/copilot-cli#5293).
173 case "assistant.turn_start":
174 case "assistant.idle": {
175 if (event.agentId !== undefined || data.aborted === true) return Effect.void;
176 return context.reportForegroundWork({
177 sessionId: event.sessionId,
178 state: event.type === "assistant.idle" ? "idle" : "running",
179 });
180 }
181 default:
182 return Effect.void;
183 }
184 });
185
186 const normalizeSessionUpdate = (
187 notification: AcpSchema.SessionNotification,
188 ): AcpSchema.SessionNotification => {
189 const update = notification.update;
190 const current = sessions.get(notification.sessionId);
191 if (current === undefined) return notification;
192 let task: string | undefined;
193 let normalized = notification;
194 if (
195 update.sessionUpdate === "agent_message_chunk" ||
196 update.sessionUpdate === "agent_thought_chunk"
197 ) {
198 const delta = current.delta;
199 current.delta = undefined;
200 release(notification.sessionId, current);
201 const kind =
202 update.sessionUpdate === "agent_message_chunk"
203 ? "assistant.message_delta"
204 : "assistant.reasoning_delta";
205 if (
206 delta?.kind === kind &&
207 update.content.type === "text" &&
208 update.content.text === delta.text
209 ) {
210 task = delta.task;
211 }
212 } else if (
213 update.sessionUpdate === "tool_call" ||
214 update.sessionUpdate === "tool_call_update"
215 ) {
216 const agentId = record(record(update._meta)?.[COPILOT_META_KEY])?.agentId;
217 task = typeof agentId === "string" ? current.taskByAgentId.get(agentId) : undefined;
218 const identity = current.toolIdentityByCallId.get(update.toolCallId);
219 if (identity !== undefined) {
220 if (update.status === "completed" || update.status === "failed") {
221 current.toolIdentityByCallId.delete(update.toolCallId);
222 release(notification.sessionId, current);
223 }
224 normalized = {
225 ...notification,
226 update:
227 identity.kind === "search"
228 ? { ...update, kind: "search" }
229 : {
230 ...update,
231 _meta: { ...update._meta, serverId: identity.server, toolName: identity.tool },
232 },
233 };
234 }
235 }
236 return task === undefined ? normalized : { ...normalized, sessionId: childSessionId(task) };
237 };
238
239 return { registerExtensions, normalizeSessionUpdate };
240 }
241
242 export function extractCopilotSubagentUpdate(
243 tool: AcpToolCallState,
244 ): AcpAdapterV2SubagentUpdate | undefined {
245 const input = record(tool.data.rawInput);
246 if (typeof input?.agent_type !== "string" || typeof input.prompt !== "string") return undefined;
247 const output = record(tool.data.rawOutput)?.content;
248 const background = input.mode === "background";
249 const status =
250 tool.status === "failed"
251 ? "failed"
252 : tool.status === "completed" && !background
253 ? "completed"
254 : "running";
255 return {
256 nativeTaskId: tool.toolCallId,
257 childSessionId: childSessionId(tool.toolCallId),
258 prompt: input.prompt,
259 title: typeof input.description === "string" ? input.description : null,
260 model: typeof input.model === "string" ? input.model : null,
261 status,
262 result: status !== "running" && typeof output === "string" ? output : null,
263 };
264 }