Skip to content
TypeScript

fix(server): route Copilot ACP subagent output into subagent threads (#17714)

maria818e2be75e1a
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index 8651890a205..369f1c29a56 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -1,4 +1,6 @@
import {
+ extractCopilotSubagentUpdate,
+ makeCopilotSubagentRouting,
normalizeDevinSessionUpdate,
normalizeDevinToolCall,
extractDevinSubagentUpdate,
@@ -1464,6 +1466,206 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
+ it.effect("routes interleaved Copilot subagent output into subagent threads", () =>
+ Effect.gen(function* () {
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const path = yield* Path.Path;
+ const mockAgentPath = yield* path.fromFileUrl(
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
+ );
+ type Runtime = AcpSessionRuntime.AcpSessionRuntime["Service"];
+ let handler: Parameters<Runtime["handleSessionUpdate"]>[0] | undefined;
+ let sessionEvent:
+ | ((event: unknown) => Effect.Effect<void, EffectAcpErrors.AcpError>)
+ | undefined;
+ const routing = makeCopilotSubagentRouting();
+ const instanceId = ProviderInstanceId.make("copilot-replay");
+ const adapter = yield* makeAcpAdapterV2({
+ instanceId,
+ selfInvocation: yield* resolveSelfInvocation(),
+ flavor: {
+ driver: ACP_TEST_DRIVER,
+ capabilities: AcpProviderCapabilitiesV2,
+ registerExtensions: routing.registerExtensions,
+ normalizeSessionUpdate: routing.normalizeSessionUpdate,
+ extractSubagentUpdate: extractCopilotSubagentUpdate,
+ makeRuntime: makeMockRuntime({
+ childProcessSpawner,
+ mockAgentPath,
+ wrapRuntime: (runtime) => ({
+ ...runtime,
+ handleSessionUpdate: (next) =>
+ Effect.sync(() => {
+ handler = next;
+ }).pipe(Effect.andThen(runtime.handleSessionUpdate(next))),
+ handleExtNotification: (method, payload, next) =>
+ Effect.sync(() => {
+ if (method === "github.com/copilot/sessionEvent") {
+ sessionEvent = next as typeof sessionEvent;
+ }
+ }).pipe(Effect.andThen(runtime.handleExtNotification(method, payload, next))),
+ prompt: () =>
+ Effect.gen(function* () {
+ assert.isDefined(handler);
+ assert.isDefined(sessionEvent);
+ const sessionId = "mock-session-1";
+ const raw = (type: string, data: object, agentId?: string) =>
+ sessionEvent!({ sessionId, type, data, ...(agentId ? { agentId } : {}) });
+ const update = (next: EffectAcpSchema.SessionUpdate) =>
+ handler!({ sessionId, update: next });
+ // Copilot sends each chunk's raw delta just before the chunk.
+ const chunk = (text: string, task?: string) =>
+ raw("assistant.message_delta", {
+ deltaContent: text,
+ ...(task ? { parentToolCallId: task } : {}),
+ }).pipe(
+ Effect.andThen(
+ update({
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text },
+ }),
+ ),
+ );
+ const launch = (toolCallId: string, description: string, mode: string) =>
+ update({
+ sessionUpdate: "tool_call",
+ toolCallId,
+ title: description,
+ kind: "other",
+ status: "pending",
+ rawInput: {
+ description,
+ prompt: `${description}.`,
+ agent_type: "explore",
+ mode,
+ },
+ });
+ // Shapes captured from Copilot CLI 1.0.95 with two sync and one
+ // background subagent launched in one batch.
+ yield* chunk("Launching ");
+ yield* launch("task-a", "Describe a.txt", "sync");
+ yield* launch("task-b", "Describe b.txt", "sync");
+ yield* launch("task-bg", "List directory", "background");
+ yield* raw("subagent.started", { toolCallId: "task-a" }, "agent-a");
+ yield* raw("subagent.started", { toolCallId: "task-b" }, "agent-b");
+ yield* raw("subagent.started", { toolCallId: "task-bg" }, "agent-bg");
+ yield* update({
+ sessionUpdate: "tool_call_update",
+ toolCallId: "task-bg",
+ status: "completed",
+ rawOutput: { content: "Agent started in background with agent_id: agent-bg." },
+ });
+ yield* update({
+ sessionUpdate: "tool_call",
+ toolCallId: "view-a",
+ title: "Viewing a.txt",
+ kind: "read",
+ status: "completed",
+ rawInput: { path: "a.txt" },
+ _meta: { "github.com/copilot": { agentId: "agent-a" } },
+ });
+ yield* chunk("`a.txt` says", "task-a");
+ yield* chunk("`b.txt` has", "task-b");
+ yield* chunk(" hello.", "task-a");
+ yield* chunk("a.txt b.txt", "task-bg");
+ yield* chunk(" three lines.", "task-b");
+ for (const [task, agent, text] of [
+ ["task-a", "agent-a", "`a.txt` says hello."],
+ ["task-b", "agent-b", "`b.txt` has three lines."],
+ ] as const) {
+ yield* update({
+ sessionUpdate: "tool_call_update",
+ toolCallId: task,
+ status: "completed",
+ rawOutput: { content: text },
+ });
+ yield* raw("subagent.completed", { toolCallId: task }, agent);
+ }
+ yield* raw("subagent.completed", { toolCallId: "task-bg" }, "agent-bg");
+ yield* chunk("all done.");
+ return { stopReason: "end_turn" as const };
+ }),
+ }),
+ }),
+ },
+ });
+ const threadId = ThreadId.make("copilot-replay-parent");
+ const modelSelection = { instanceId, model: "default" };
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: process.cwd(),
+ });
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("copilot-replay-session"),
+ modelSelection,
+ runtimePolicy,
+ });
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ });
+ yield* runtime.startTurn(
+ makeTurnInput({
+ threadId,
+ providerThread,
+ instanceId,
+ runtimePolicy,
+ now: yield* DateTime.now,
+ }),
+ );
+ const events = Array.from(
+ yield* runtime.events.pipe(
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
+ Stream.runCollect,
+ ),
+ );
+ const items = events.flatMap((event) =>
+ event.type === "turn_item.updated" ? [event.turnItem] : [],
+ );
+ const lastText = (thread: string | null | undefined) =>
+ new Map(
+ items.flatMap((item) =>
+ item.threadId === thread && item.type === "assistant_message"
+ ? [[item.id, item.text] as const]
+ : [],
+ ),
+ );
+ assert.deepEqual([...lastText(threadId).values()].join(""), "Launching all done.");
+ const tasks = new Map(
+ events.flatMap((event) =>
+ event.type === "subagent.updated"
+ ? [[event.subagent.nativeTaskRef?.nativeId, event.subagent] as const]
+ : [],
+ ),
+ );
+ const outputs = Object.fromEntries(
+ [...tasks].map(([id, task]) => [
+ id,
+ [task.status, [...lastText(task.childThreadId).values()].join("")],
+ ]),
+ );
+ assert.deepEqual(outputs, {
+ "task-a": ["completed", "`a.txt` says hello."],
+ "task-b": ["completed", "`b.txt` has three lines."],
+ "task-bg": ["completed", "a.txt b.txt"],
+ });
+ assert.isTrue(
+ items.some(
+ (item) =>
+ item.threadId === tasks.get("task-a")?.childThreadId &&
+ item.type === "dynamic_tool" &&
+ item.title === "Read a.txt",
+ ),
+ );
+ assert.isFalse(
+ items.some((item) => item.threadId === threadId && item.type === "dynamic_tool"),
+ );
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
+
it.effect("projects ACP v2 fidelity updates into first-class orchestration items", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts
index d5fb3279f40..0fa9a83d05c 100644
--- a/packages/provider-acp-registry/src/server/adapter.ts
+++ b/packages/provider-acp-registry/src/server/adapter.ts
@@ -3,6 +3,11 @@ import {
normalizeDevinToolCall,
extractDevinSubagentUpdate,
} from "./devinAcp.ts";
+import {
+ copilotClientCapabilitiesMeta,
+ extractCopilotSubagentUpdate,
+ makeCopilotSubagentRouting,
+} from "./copilotAcp.ts";
import { defaultInstanceIdForDriver, ProviderDriverKind } from "@t3tools/contracts";
import { AcpRegistrySettings } from "../settings.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -73,7 +78,7 @@ export interface AcpRegistryAdapterV2Options {
// Agent-specific behavior does not belong here: an agent that needs it gets a
// dedicated driver (as Grok and Antigravity have). The few exceptions below
// predate that rule and are small presentation hooks, not permission or tool
-// behavior.
+// behavior. Copilot's subagent routing was approved later on the same terms.
//
// Agents changing this file: do NOT add another `agentId === "..."` branch,
// agent table, or agent-specific hook without explicit approval from the
@@ -182,11 +187,17 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
const startupKey =
options.settings.source === "local" ? `local:${options.instanceId}` : registryAgentId;
const isDevin = registryAgentId === "devin";
+ // Local installs launch the `copilot` binary directly with no registry id.
+ const isCopilot =
+ registryAgentId === "github-copilot-cli" ||
+ (options.settings.source === "local" &&
+ /^copilot(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""));
+ const copilotRouting = isCopilot ? makeCopilotSubagentRouting() : undefined;
const flavor: AcpAdapterV2Flavor = {
driver: ACP_REGISTRY_PROVIDER,
capabilities: AcpProviderCapabilitiesV2,
promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause),
- // Per-agent exceptions (Mistral Vibe, Devin): see the note above
+ // Per-agent exceptions (Mistral Vibe, Devin, Copilot): see the note above
// registerMistralVibeAcpExtensions before adding any more.
...(registryAgentId === "mistral-vibe"
? { registerExtensions: registerMistralVibeAcpExtensions }
@@ -202,6 +213,14 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
extractSubagentUpdate: extractDevinSubagentUpdate,
}
: {}),
+ ...(copilotRouting === undefined
+ ? {}
+ : {
+ clientCapabilitiesMeta: copilotClientCapabilitiesMeta,
+ registerExtensions: copilotRouting.registerExtensions,
+ normalizeSessionUpdate: copilotRouting.normalizeSessionUpdate,
+ extractSubagentUpdate: extractCopilotSubagentUpdate,
+ }),
makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(options, catalog),
...(runtimeCoordinator === undefined
? {}
diff --git a/packages/provider-acp-registry/src/server/copilotAcp.ts b/packages/provider-acp-registry/src/server/copilotAcp.ts
new file mode 100644
index 00000000000..95b216e6a47
--- /dev/null
+++ b/packages/provider-acp-registry/src/server/copilotAcp.ts
@@ -0,0 +1,175 @@
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import type * as AcpSchema from "effect-acp/compat";
+import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
+import type {
+ AcpAdapterV2ExtensionContext,
+ AcpAdapterV2SubagentUpdate,
+} from "@t3tools/provider-acp/server/adapter";
+
+// Copilot CLI streams subagent text as plain `agent_message_chunk`s on the
+// root session. Only its opt-in raw event feed says who wrote a chunk: each
+// chunk is preceded by an `assistant.*_delta` carrying the spawning `task`
+// tool call id. Both arrive inline on the same reader, in wire order, so the
+// delta just before a chunk is that chunk's author.
+
+const COPILOT_META_KEY = "github.com/copilot";
+const COPILOT_SESSION_EVENT = "github.com/copilot/sessionEvent";
+
+/** Subscribes to the raw events subagent routing needs, and nothing else. */
+export const copilotClientCapabilitiesMeta = {
+ [COPILOT_META_KEY]: {
+ events: [
+ "subagent.started",
+ "subagent.completed",
+ "subagent.failed",
+ "assistant.message_delta",
+ "assistant.reasoning_delta",
+ ],
+ },
+};
+
+const CopilotSessionEvent = Schema.Struct({
+ sessionId: Schema.String,
+ type: Schema.String,
+ agentId: Schema.optionalKey(Schema.String),
+ data: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
+});
+
+function record(value: unknown): Record<string, unknown> | undefined {
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : undefined;
+}
+
+const childSessionId = (taskToolCallId: string) => `copilot-task:${taskToolCallId}`;
+
+interface CopilotSessionAttribution {
+ /** The last raw delta, consumed by the chunk that follows it. */
+ delta: { readonly kind: string; readonly text: string; readonly task?: string } | undefined;
+ /** Running subagent id to the `task` tool call that spawned it. */
+ readonly taskByAgentId: Map<string, string>;
+}
+
+/** Per adapter instance; entries are keyed by root session and drop once idle. */
+export function makeCopilotSubagentRouting() {
+ const sessions = new Map<string, CopilotSessionAttribution>();
+ const session = (sessionId: string) => {
+ let current = sessions.get(sessionId);
+ if (current === undefined) {
+ current = { delta: undefined, taskByAgentId: new Map() };
+ sessions.set(sessionId, current);
+ }
+ return current;
+ };
+ const release = (sessionId: string, current: CopilotSessionAttribution) => {
+ if (current.delta === undefined && current.taskByAgentId.size === 0) {
+ sessions.delete(sessionId);
+ }
+ };
+
+ const registerExtensions = (context: AcpAdapterV2ExtensionContext) =>
+ context.runtime.handleExtNotification(COPILOT_SESSION_EVENT, CopilotSessionEvent, (event) => {
+ const data = event.data ?? {};
+ const task = typeof data.parentToolCallId === "string" ? data.parentToolCallId : undefined;
+ switch (event.type) {
+ case "assistant.message_delta":
+ case "assistant.reasoning_delta": {
+ if (typeof data.deltaContent !== "string") return Effect.void;
+ session(event.sessionId).delta = {
+ kind: event.type,
+ text: data.deltaContent,
+ ...(task === undefined ? {} : { task }),
+ };
+ return Effect.void;
+ }
+ case "subagent.started": {
+ if (event.agentId !== undefined && typeof data.toolCallId === "string") {
+ session(event.sessionId).taskByAgentId.set(event.agentId, data.toolCallId);
+ }
+ return Effect.void;
+ }
+ case "subagent.completed":
+ case "subagent.failed": {
+ const current = sessions.get(event.sessionId);
+ if (current !== undefined && event.agentId !== undefined) {
+ current.taskByAgentId.delete(event.agentId);
+ release(event.sessionId, current);
+ }
+ if (typeof data.toolCallId !== "string") return Effect.void;
+ // Background tasks end only here; their tool call settles at launch.
+ return context.finishSubagent({
+ sessionId: event.sessionId,
+ childSessionId: childSessionId(data.toolCallId),
+ status: event.type === "subagent.failed" ? "failed" : "completed",
+ result: typeof data.error === "string" ? data.error : null,
+ });
+ }
+ default:
+ return Effect.void;
+ }
+ });
+
+ /** Moves a subagent's chunks and tool calls onto its own child session. */
+ const normalizeSessionUpdate = (
+ notification: AcpSchema.SessionNotification,
+ ): AcpSchema.SessionNotification => {
+ const update = notification.update;
+ const current = sessions.get(notification.sessionId);
+ if (current === undefined) return notification;
+ let task: string | undefined;
+ if (
+ update.sessionUpdate === "agent_message_chunk" ||
+ update.sessionUpdate === "agent_thought_chunk"
+ ) {
+ const delta = current.delta;
+ current.delta = undefined;
+ release(notification.sessionId, current);
+ const kind =
+ update.sessionUpdate === "agent_message_chunk"
+ ? "assistant.message_delta"
+ : "assistant.reasoning_delta";
+ if (
+ delta?.kind === kind &&
+ update.content.type === "text" &&
+ update.content.text === delta.text
+ ) {
+ task = delta.task;
+ }
+ } else if (
+ update.sessionUpdate === "tool_call" ||
+ update.sessionUpdate === "tool_call_update"
+ ) {
+ const agentId = record(record(update._meta)?.[COPILOT_META_KEY])?.agentId;
+ task = typeof agentId === "string" ? current.taskByAgentId.get(agentId) : undefined;
+ }
+ return task === undefined ? notification : { ...notification, sessionId: childSessionId(task) };
+ };
+
+ return { registerExtensions, normalizeSessionUpdate };
+}
+
+/** Copilot's `task` tool launches a subagent; its id names the child session. */
+export function extractCopilotSubagentUpdate(
+ tool: AcpToolCallState,
+): AcpAdapterV2SubagentUpdate | undefined {
+ const input = record(tool.data.rawInput);
+ if (typeof input?.agent_type !== "string" || typeof input.prompt !== "string") return undefined;
+ const output = record(tool.data.rawOutput)?.content;
+ const background = input.mode === "background";
+ const status =
+ tool.status === "failed"
+ ? "failed"
+ : tool.status === "completed" && !background
+ ? "completed"
+ : "running";
+ return {
+ nativeTaskId: tool.toolCallId,
+ childSessionId: childSessionId(tool.toolCallId),
+ prompt: input.prompt,
+ title: typeof input.description === "string" ? input.description : null,
+ model: typeof input.model === "string" ? input.model : null,
+ status,
+ result: status !== "running" && typeof output === "string" ? output : null,
+ };
+}
diff --git a/packages/provider-acp-registry/src/testing.ts b/packages/provider-acp-registry/src/testing.ts
index f1c64a89c15..83f9ba88808 100644
--- a/packages/provider-acp-registry/src/testing.ts
+++ b/packages/provider-acp-registry/src/testing.ts
@@ -16,6 +16,7 @@ export {
normalizeDevinSessionUpdate,
normalizeDevinToolCall,
} from "./server/devinAcp.ts";
+export { extractCopilotSubagentUpdate, makeCopilotSubagentRouting } from "./server/copilotAcp.ts";
export {
acpRegistryProbeFailure,
acpRegistryProbeResult,
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index bec893b1f47..c1208b49556 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -218,7 +218,9 @@ export interface AcpAdapterV2Flavor {
readonly promptFailure?: (cause: unknown) => OrchestrationV2ProviderFailure;
readonly driver: ProviderDriverKind;
readonly capabilities: OrchestrationV2ProviderCapabilities;
- readonly clientCapabilitiesMeta?: Record<string, boolean>;
+ readonly clientCapabilitiesMeta?: NonNullable<
+ EffectAcpSchema.InitializeRequest["clientCapabilities"]
+ >["_meta"];
readonly normalizeSessionUpdate?: (
notification: EffectAcpSchema.SessionNotification,
) => EffectAcpSchema.SessionNotification;