Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Schema from "effect/Schema";
3import type * as AcpSchema from "effect-acp/compat";
4import * as AcpErrors from "effect-acp/errors";
5import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
6import 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
13const COPILOT_META_KEY = "github.com/copilot";
14const COPILOT_SESSION_EVENT = "github.com/copilot/sessionEvent";
15
16export 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
32const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError);
33
34/** Copilot keeps failing every prompt with these until its process is replaced. */
35const 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
40export 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
52const 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
59function 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
65const 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.
68type CopilotToolIdentity =
69 | { readonly kind: "mcp"; readonly server: string; readonly tool: string }
70 | { readonly kind: "search" };
71
72const COPILOT_SEARCH_TOOLS = new Set(["glob", "grep"]);
73
74interface 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
80function 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
89export 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 const task = typeof data.parentToolCallId === "string" ? data.parentToolCallId : undefined;
113 switch (event.type) {
114 case "assistant.message_delta":
115 case "assistant.reasoning_delta": {
116 if (typeof data.deltaContent !== "string") return Effect.void;
117 session(event.sessionId).delta = {
118 kind: event.type,
119 text: data.deltaContent,
120 ...(task === undefined ? {} : { task }),
121 };
122 return Effect.void;
123 }
124 case "subagent.started": {
125 if (event.agentId !== undefined && typeof data.toolCallId === "string") {
126 session(event.sessionId).taskByAgentId.set(event.agentId, data.toolCallId);
127 }
128 return Effect.void;
129 }
130 case "tool.execution_start": {
131 const identity = copilotToolIdentity(data);
132 if (identity !== undefined && typeof data.toolCallId === "string") {
133 session(event.sessionId).toolIdentityByCallId.set(data.toolCallId, identity);
134 }
135 return Effect.void;
136 }
137 case "subagent.completed":
138 case "subagent.failed": {
139 const current = sessions.get(event.sessionId);
140 if (current !== undefined && event.agentId !== undefined) {
141 current.taskByAgentId.delete(event.agentId);
142 release(event.sessionId, current);
143 }
144 if (typeof data.toolCallId !== "string") return Effect.void;
145 // Background tasks end only here; their tool call settles at launch.
146 return context.finishSubagent({
147 sessionId: event.sessionId,
148 childSessionId: childSessionId(data.toolCallId),
149 status: event.type === "subagent.failed" ? "failed" : "completed",
150 result: typeof data.error === "string" ? data.error : null,
151 });
152 }
153 // Copilot sends no ACP compaction_update; agentId marks a subagent's own compaction.
154 // Older Copilot builds report a successful compaction without `outcome`.
155 case "session.compaction_complete": {
156 if (
157 event.agentId !== undefined ||
158 data.success !== true ||
159 (data.outcome !== undefined && data.outcome !== "applied")
160 ) {
161 return Effect.void;
162 }
163 return context.markSessionCompacted(event.sessionId);
164 }
165 // Copilot holds session/prompt while an attached async shell runs (github/copilot-cli#5293).
166 case "assistant.turn_start":
167 case "assistant.idle": {
168 if (event.agentId !== undefined || data.aborted === true) return Effect.void;
169 return context.reportForegroundWork({
170 sessionId: event.sessionId,
171 state: event.type === "assistant.idle" ? "idle" : "running",
172 });
173 }
174 default:
175 return Effect.void;
176 }
177 });
178
179 const normalizeSessionUpdate = (
180 notification: AcpSchema.SessionNotification,
181 ): AcpSchema.SessionNotification => {
182 const update = notification.update;
183 const current = sessions.get(notification.sessionId);
184 if (current === undefined) return notification;
185 let task: string | undefined;
186 let normalized = notification;
187 if (
188 update.sessionUpdate === "agent_message_chunk" ||
189 update.sessionUpdate === "agent_thought_chunk"
190 ) {
191 const delta = current.delta;
192 current.delta = undefined;
193 release(notification.sessionId, current);
194 const kind =
195 update.sessionUpdate === "agent_message_chunk"
196 ? "assistant.message_delta"
197 : "assistant.reasoning_delta";
198 if (
199 delta?.kind === kind &&
200 update.content.type === "text" &&
201 update.content.text === delta.text
202 ) {
203 task = delta.task;
204 }
205 } else if (
206 update.sessionUpdate === "tool_call" ||
207 update.sessionUpdate === "tool_call_update"
208 ) {
209 const agentId = record(record(update._meta)?.[COPILOT_META_KEY])?.agentId;
210 task = typeof agentId === "string" ? current.taskByAgentId.get(agentId) : undefined;
211 const identity = current.toolIdentityByCallId.get(update.toolCallId);
212 if (identity !== undefined) {
213 if (update.status === "completed" || update.status === "failed") {
214 current.toolIdentityByCallId.delete(update.toolCallId);
215 release(notification.sessionId, current);
216 }
217 normalized = {
218 ...notification,
219 update:
220 identity.kind === "search"
221 ? { ...update, kind: "search" }
222 : {
223 ...update,
224 _meta: { ...update._meta, serverId: identity.server, toolName: identity.tool },
225 },
226 };
227 }
228 }
229 return task === undefined ? normalized : { ...normalized, sessionId: childSessionId(task) };
230 };
231
232 return { registerExtensions, normalizeSessionUpdate };
233}
234
235export function extractCopilotSubagentUpdate(
236 tool: AcpToolCallState,
237): AcpAdapterV2SubagentUpdate | undefined {
238 const input = record(tool.data.rawInput);
239 if (typeof input?.agent_type !== "string" || typeof input.prompt !== "string") return undefined;
240 const output = record(tool.data.rawOutput)?.content;
241 const background = input.mode === "background";
242 const status =
243 tool.status === "failed"
244 ? "failed"
245 : tool.status === "completed" && !background
246 ? "completed"
247 : "running";
248 return {
249 nativeTaskId: tool.toolCallId,
250 childSessionId: childSessionId(tool.toolCallId),
251 prompt: input.prompt,
252 title: typeof input.description === "string" ? input.description : null,
253 model: typeof input.model === "string" ? input.model : null,
254 status,
255 result: status !== "running" && typeof output === "string" ? output : null,
256 };
257}