Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

adapter.ts

362 lines14.2 KB

1import {
2 extractClaudeSubagentUpdate,
3 extractClaudeSubagentSessionEvent,
4 isClaudeProvisionalSubagentTool,
5} from "./claudeAcp.ts";
6import {
7 normalizeDevinSessionUpdate,
8 normalizeDevinToolCall,
9 extractDevinSubagentUpdate,
10} from "./devinAcp.ts";
11import { extractDroidElicitationForm } from "./droidAcp.ts";
12import {
13 copilotClientCapabilitiesMeta,
14 extractCopilotSubagentUpdate,
15 isCopilotLostSessionError,
16 makeCopilotSubagentRouting,
17} from "./copilotAcp.ts";
18import { defaultInstanceIdForDriver, ProviderDriverKind } from "@t3tools/contracts";
19import { readCustomModelEntries } from "@t3tools/shared/model";
20import { AcpRegistrySettings } from "../settings.ts";
21import * as HostProcess from "@t3tools/shared/HostProcess";
22import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime";
23import * as Crypto from "effect/Crypto";
24import * as Effect from "effect/Effect";
25import * as FileSystem from "effect/FileSystem";
26import * as Path from "effect/Path";
27import * as Layer from "effect/Layer";
28import * as Option from "effect/Option";
29import * as Schema from "effect/Schema";
30import type * as Scope from "effect/Scope";
31import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
32import * as EffectAcpErrors from "effect-acp/errors";
33​
34import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
35import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
36import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
37import {
38 normalizeAcpRegistryCommands,
39 normalizeAcpRegistryLiveConfiguration,
40 normalizeAcpRegistryWebUrl,
41} from "./probe.ts";
42import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
43import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
44import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
45import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
46import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
47import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
48import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
49import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
50import {
51 ProviderAdapterDriverCreateError,
52 type ProviderAdapterDriver,
53 type ProviderAdapterDriverCreateInput,
54} from "@t3tools/provider-core/server/adapterDriver";
55import {
56 AcpProviderCapabilitiesV2,
57 makeAcpAdapterV2,
58 type AcpAdapterV2ExtensionContext,
59 type AcpAdapterV2Flavor,
60 type AcpAdapterV2RuntimeInput,
61} from "@t3tools/provider-acp/server/adapter";
62​
63export const ACP_REGISTRY_PROVIDER = ProviderDriverKind.make("acpRegistry");
64export const ACP_REGISTRY_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(ACP_REGISTRY_PROVIDER);
65​
66const DEFAULT_ACP_REGISTRY_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({});
67const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);
68​
69export interface AcpRegistryAdapterV2Options {
70 readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
71 readonly settings: AcpRegistrySettings;
72 readonly environment: NodeJS.ProcessEnv;
73 readonly selfInvocation: SelfInvocation;
74 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
75 readonly makeRuntime?: (
76 input: AcpAdapterV2RuntimeInput,
77 ) => Effect.Effect<
78 AcpSessionRuntime.AcpSessionRuntime["Service"],
79 EffectAcpErrors.AcpError,
80 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
81 >;
82 readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
83 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
85​
86// Mistral Vibe's application rate-limit code, outside ACP.
87const MISTRAL_VIBE_RATE_LIMITED = -31001;
88​
89const MistralVibeSessionRetrying = Schema.Struct({
90 sessionId: Schema.String,
91 category: Schema.Literals(["rate_limited", "server_error", "timed_out", "connection", "unknown"]),
92 detail: Schema.String,
93});
94​
95/** Mistral Vibe (v2.25.5) reports SDK backoff through this ACP extension. */
96export function registerMistralVibeAcpExtensions(context: AcpAdapterV2ExtensionContext) {
97 return context.runtime.handleExtNotification(
98 "_session/retrying",
99 MistralVibeSessionRetrying,
100 (notice) =>
101 context.reportProviderRetry({
102 sessionId: notice.sessionId,
103 failure: makeProviderFailure({
104 message: notice.detail,
105 class:
106 notice.category === "rate_limited"
107 ? "usage_limit"
108 : notice.category === "unknown"
109 ? "provider_error"
110 : "transport_error",
111 retryable: true,
112 }),
113 }),
114 );
116​
117export function acpRegistryPromptFailure(agentId: string, cause: unknown) {
118 return makeProviderFailure({
119 cause,
120 ...(isAcpRequestError(cause)
121 ? {
122 message: cause.errorMessage,
123 code: String(cause.code),
124 class:
125 agentId === "mistral-vibe" && cause.code === MISTRAL_VIBE_RATE_LIMITED
126 ? ("usage_limit" as const)
127 : ("provider_error" as const),
128 }
129 : { class: "provider_error" as const }),
130 });
132​
133function makeAcpRegistryRuntime(
134 options: AcpRegistryAdapterV2Options,
135 catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"],
136) {
137 return (
138 input: AcpAdapterV2RuntimeInput,
139 ): Effect.Effect<
140 AcpSessionRuntime.AcpSessionRuntime["Service"],
141 EffectAcpErrors.AcpError,
142 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
143 > =>
144 Effect.gen(function* () {
145 const { processEnvironment, ...runtimeInput } = input;
146 const resolved = yield* catalog
147 .resolve(options.settings, input.cwd, options.environment)
148 .pipe(
149 Effect.mapError(
150 (cause) =>
151 new EffectAcpErrors.AcpSpawnError({
152 command: options.settings.agentId || ACP_REGISTRY_PROVIDER,
153 cause,
154 }),
155 ),
156 );
157 const context = yield* Layer.build(
158 AcpSessionRuntime.layer({
159 ...runtimeInput,
160 spawn:
161 processEnvironment === undefined
162 ? resolved.spawn
163 : {
164 ...resolved.spawn,
165 env: { ...resolved.spawn.env, ...processEnvironment },
166 },
167 ...(options.settings.authMethodId ? { authMethodId: options.settings.authMethodId } : {}),
168 customModels: readCustomModelEntries(options.settings.customModels).map(
169 (entry) => entry.slug,
170 ),
171 }),
172 );
173 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
174 Effect.provide(context),
175 );
176 });
178​
179export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(function* (
180 options: AcpRegistryAdapterV2Options,
181) {
182 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
183 const runtimeCoordinator = Option.getOrUndefined(
184 yield* Effect.serviceOption(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator),
185 );
186 const registryAgentId = options.settings.source === "local" ? "" : options.settings.agentId;
187 const startupKey =
188 options.settings.source === "local" ? `local:${options.instanceId}` : registryAgentId;
189 const isDevin = registryAgentId === "devin";
190 // Local installs launch the `copilot` binary directly with no registry id.
191 const isCopilot =
192 registryAgentId === "github-copilot-cli" ||
193 (options.settings.source === "local" &&
194 /^copilot(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""));
195 const isClaude =
196 registryAgentId === "claude-acp" ||
197 (options.settings.source === "local" &&
198 /^claude-agent-acp(\.exe|\.cmd)?$/i.test(
199 options.settings.commandPath.split(/[\\/]/).pop() ?? "",
200 ));
201 const runtimeOptions = isClaude
202 ? {
203 ...options,
204 environment: {
205 ...options.environment,
206 CLAUDE_AGENT_ACP_EXPERIMENTAL_V2:
207 options.environment.CLAUDE_AGENT_ACP_EXPERIMENTAL_V2 ?? "1",
208 },
209 }
210 : options;
211 const copilotRouting = isCopilot ? makeCopilotSubagentRouting() : undefined;
212 const flavor: AcpAdapterV2Flavor = {
213 driver: ACP_REGISTRY_PROVIDER,
214 // Cancelling a Copilot prompt also kills the background agents it started.
215 capabilities: isCopilot
216 ? {
217 ...AcpProviderCapabilitiesV2,
218 turns: { ...AcpProviderCapabilitiesV2.turns, supportsSteeringByInterruptRestart: false },
219 }
220 : AcpProviderCapabilitiesV2,
221 customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug),
222 promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause),
223 ...(registryAgentId === "factory-droid"
224 ? { extractElicitationForm: extractDroidElicitationForm }
225 : {}),
226 // glm-acp-agent is the one agent whose per-turn usage a live probe has verified.
227 ...(registryAgentId === "glm-acp-agent" ? { reportsPerTurnPromptUsage: true } : {}),
228 ...(registryAgentId === "mistral-vibe"
229 ? { registerExtensions: registerMistralVibeAcpExtensions }
230 : {}),
231 ...(isClaude
232 ? {
233 followAgentWorkState: true,
234 extractSubagentUpdate: extractClaudeSubagentUpdate,
235 isProvisionalSubagentTool: isClaudeProvisionalSubagentTool,
236 extractSubagentSessionEvent: extractClaudeSubagentSessionEvent,
237 }
238 : {}),
239 ...(isDevin
240 ? {
241 clientCapabilitiesMeta: {
242 "cognition.ai/subagentSupport": true,
243 "cognition.ai/messageGrouping": true,
244 },
245 normalizeSessionUpdate: normalizeDevinSessionUpdate,
246 normalizeToolCall: normalizeDevinToolCall,
247 extractSubagentUpdate: extractDevinSubagentUpdate,
248 }
249 : {}),
250 ...(copilotRouting === undefined
251 ? {}
252 : {
253 clientCapabilitiesMeta: copilotClientCapabilitiesMeta,
254 // Copilot CLI 1.0.105 rejects stdio MCP servers from the client.
255 mcpOverHttp: true,
256 registerExtensions: copilotRouting.registerExtensions,
257 normalizeSessionUpdate: copilotRouting.normalizeSessionUpdate,
258 extractSubagentUpdate: extractCopilotSubagentUpdate,
259 restartRuntimeAfterPromptError: isCopilotLostSessionError,
260 }),
261 makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(runtimeOptions, catalog),
262 ...(runtimeCoordinator === undefined
263 ? {}
264 : {
265 onAvailableCommandsUpdate: (commands) =>
266 runtimeCoordinator.publishAvailableCommands(
267 options.instanceId,
268 normalizeAcpRegistryCommands(commands),
269 ),
270 onSessionConfigurationUpdate: (configOptions, modeState, modelState) =>
271 runtimeCoordinator.publishLiveConfiguration(
272 options.instanceId,
273 normalizeAcpRegistryLiveConfiguration(configOptions, modeState, modelState),
274 ),
275 onUrlElicitation: ({ elicitationId, url, message }) => {
276 const normalizedUrl = normalizeAcpRegistryWebUrl(url);
277 if (normalizedUrl === undefined || elicitationId.trim().length === 0) {
278 return Effect.succeed(false);
279 }
280 return runtimeCoordinator.requestUrlAuthentication(options.instanceId, {
281 elicitationId: elicitationId.trim().slice(0, 256),
282 url: normalizedUrl,
283 message: message.trim().slice(0, 1_024),
284 });
285 },
286 withRuntimeStartup: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
287 runtimeCoordinator.withForegroundStartup(startupKey, effect),
288 }),
289 ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
290 };
291 return yield* makeAcpAdapterV2({
292 instanceId: options.instanceId,
293 flavor,
294 selfInvocation: options.selfInvocation,
295 ...(options.continuationRequests === undefined
296 ? {}
297 : { continuationRequests: options.continuationRequests }),
298 // Devin runs commands through client terminals and has no ask mode over ACP to fall back on.
299 ...(isDevin
300 ? {
301 clientTerminals: {
302 environment: options.environment,
303 shellCommands: true,
304 },
305 }
306 : {}),
307 ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
308 });
309});
310​
311export type AcpRegistryAdapterV2DriverEnv =
312 | ChildProcessSpawner.ChildProcessSpawner
313 | Crypto.Crypto
314 | FileSystem.FileSystem
315 | AcpRegistrySupport.AcpRegistryCatalog
316 | IdAllocator.IdAllocatorV2
317 | Path.Path
318 | McpProviderSessions.McpProviderSessions
319 | ProviderEventLoggers.ProviderEventLoggers
320 | ProviderHost.ProviderHost;
321​
322export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
323 AcpRegistrySettings,
324 AcpRegistryAdapterV2DriverEnv
325> = {
326 driverKind: ACP_REGISTRY_PROVIDER,
327 configSchema: AcpRegistrySettings,
328 defaultConfig: (): AcpRegistrySettings => DEFAULT_ACP_REGISTRY_SETTINGS,
329 create: Effect.fn("AcpRegistryAdapterV2Driver.create")(
330 function* (input: ProviderAdapterDriverCreateInput<AcpRegistrySettings>) {
331 const hostEnvironment = yield* HostProcess.Environment;
332 const selfInvocation = yield* resolveSelfInvocation();
333 const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
334 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
335 return yield* makeAcpRegistryAdapterV2({
336 instanceId: input.instanceId,
337 settings: { ...input.config, enabled: input.enabled },
338 environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
339 selfInvocation,
340 continuationRequests: yield* ProviderContinuationRequests.ProviderContinuationRequests,
341 nativeLogging: (threadId) =>
342 makeNativeLogger({
343 nativeEventLogger: providerEventLoggers.native,
344 provider: ACP_REGISTRY_PROVIDER,
345 threadId,
346 }),
347 });
348 },
349 (effect, input) =>
350 effect.pipe(
351 Effect.mapError(
352 (cause) =>
353 new ProviderAdapterDriverCreateError({
354 driver: ACP_REGISTRY_PROVIDER,
355 instanceId: input.instanceId,
356 detail: "Failed to create ACP Registry adapter.",
357 cause,
358 }),
359 ),
360 ),
361 ),
362};