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

adapter.ts

304 lines12.1 KB

1import {
2 normalizeDevinSessionUpdate,
3 normalizeDevinToolCall,
4 extractDevinSubagentUpdate,
5} from "./devinAcp.ts";
6import { defaultInstanceIdForDriver, ProviderDriverKind } from "@t3tools/contracts";
7import { AcpRegistrySettings } from "../settings.ts";
8import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
9import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime";
10import * as Crypto from "effect/Crypto";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Path from "effect/Path";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17import type * as Scope from "effect/Scope";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19import * as EffectAcpErrors from "effect-acp/errors";
20​
21import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
22import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
23import {
24 normalizeAcpRegistryCommands,
25 normalizeAcpRegistryLiveConfiguration,
26 normalizeAcpRegistryWebUrl,
27} from "./probe.ts";
28import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
29import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
30import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
31import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
32import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
33import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
34import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
35import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
36import {
37 ProviderAdapterDriverCreateError,
38 type ProviderAdapterDriver,
39 type ProviderAdapterDriverCreateInput,
40} from "@t3tools/provider-core/server/adapterDriver";
41import {
42 AcpProviderCapabilitiesV2,
43 makeAcpAdapterV2,
44 type AcpAdapterV2ExtensionContext,
45 type AcpAdapterV2Flavor,
46 type AcpAdapterV2RuntimeInput,
47} from "@t3tools/provider-acp/server/adapter";
48​
49export const ACP_REGISTRY_PROVIDER = ProviderDriverKind.make("acpRegistry");
50export const ACP_REGISTRY_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(ACP_REGISTRY_PROVIDER);
51​
52const DEFAULT_ACP_REGISTRY_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({});
53const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);
54​
55export interface AcpRegistryAdapterV2Options {
56 readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
57 readonly settings: AcpRegistrySettings;
58 readonly environment: NodeJS.ProcessEnv;
59 readonly selfInvocation: SelfInvocation;
60 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
61 readonly makeRuntime?: (
62 input: AcpAdapterV2RuntimeInput,
63 ) => Effect.Effect<
64 AcpSessionRuntime.AcpSessionRuntime["Service"],
65 EffectAcpErrors.AcpError,
66 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
67 >;
68 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
70​
71// ─── Per-agent exceptions ────────────────────────────────────────────────────
72// This adapter serves every ACP registry agent through the plain ACP spec.
73// Agent-specific behavior does not belong here: an agent that needs it gets a
74// dedicated driver (as Grok and Antigravity have). The few exceptions below
75// predate that rule and are small presentation hooks, not permission or tool
76// behavior.
77//
78// Agents changing this file: do NOT add another `agentId === "..."` branch,
79// agent table, or agent-specific hook without explicit approval from the
80// maintainer in the conversation. Propose a dedicated driver instead.
81​
82// Mistral Vibe: its application error code for rate limits (not an ACP code).
83const MISTRAL_VIBE_RATE_LIMITED = -31001;
84​
85const MistralVibeSessionRetrying = Schema.Struct({
86 sessionId: Schema.String,
87 category: Schema.Literals(["rate_limited", "server_error", "timed_out", "connection", "unknown"]),
88 detail: Schema.String,
89});
90​
91/** Mistral Vibe (v2.25.5) reports SDK backoff through this ACP extension. */
92export function registerMistralVibeAcpExtensions(context: AcpAdapterV2ExtensionContext) {
93 return context.runtime.handleExtNotification(
94 "_session/retrying",
95 MistralVibeSessionRetrying,
96 (notice) =>
97 context.reportProviderRetry({
98 sessionId: notice.sessionId,
99 failure: makeProviderFailure({
100 message: notice.detail,
101 class:
102 notice.category === "rate_limited"
103 ? "usage_limit"
104 : notice.category === "unknown"
105 ? "provider_error"
106 : "transport_error",
107 retryable: true,
108 }),
109 }),
110 );
112// ─── End per-agent exceptions (Devin's gates are marked in makeAcpRegistryAdapterV2) ───
113​
114export function acpRegistryPromptFailure(agentId: string, cause: unknown) {
115 return makeProviderFailure({
116 cause,
117 ...(isAcpRequestError(cause)
118 ? {
119 message: cause.errorMessage,
120 code: String(cause.code),
121 class:
122 // Per-agent exception: see the note above registerMistralVibeAcpExtensions.
123 agentId === "mistral-vibe" && cause.code === MISTRAL_VIBE_RATE_LIMITED
124 ? ("usage_limit" as const)
125 : ("provider_error" as const),
126 }
127 : { class: "provider_error" as const }),
128 });
130​
131function makeAcpRegistryRuntime(
132 options: AcpRegistryAdapterV2Options,
133 catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"],
134) {
135 return (
136 input: AcpAdapterV2RuntimeInput,
137 ): Effect.Effect<
138 AcpSessionRuntime.AcpSessionRuntime["Service"],
139 EffectAcpErrors.AcpError,
140 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
141 > =>
142 Effect.gen(function* () {
143 const { processEnvironment, ...runtimeInput } = input;
144 const resolved = yield* catalog
145 .resolve(options.settings, input.cwd, options.environment)
146 .pipe(
147 Effect.mapError(
148 (cause) =>
149 new EffectAcpErrors.AcpSpawnError({
150 command: options.settings.agentId || ACP_REGISTRY_PROVIDER,
151 cause,
152 }),
153 ),
154 );
155 const context = yield* Layer.build(
156 AcpSessionRuntime.layer({
157 ...runtimeInput,
158 spawn:
159 processEnvironment === undefined
160 ? resolved.spawn
161 : {
162 ...resolved.spawn,
163 env: { ...resolved.spawn.env, ...processEnvironment },
164 },
165 ...(options.settings.authMethodId ? { authMethodId: options.settings.authMethodId } : {}),
166 }),
167 );
168 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
169 Effect.provide(context),
170 );
171 });
173​
174export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(function* (
175 options: AcpRegistryAdapterV2Options,
176) {
177 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
178 const runtimeCoordinator = Option.getOrUndefined(
179 yield* Effect.serviceOption(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator),
180 );
181 const registryAgentId = options.settings.source === "local" ? "" : options.settings.agentId;
182 const startupKey =
183 options.settings.source === "local" ? `local:${options.instanceId}` : registryAgentId;
184 const isDevin = registryAgentId === "devin";
185 const flavor: AcpAdapterV2Flavor = {
186 driver: ACP_REGISTRY_PROVIDER,
187 capabilities: AcpProviderCapabilitiesV2,
188 promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause),
189 // Per-agent exceptions (Mistral Vibe, Devin): see the note above
190 // registerMistralVibeAcpExtensions before adding any more.
191 ...(registryAgentId === "mistral-vibe"
192 ? { registerExtensions: registerMistralVibeAcpExtensions }
193 : {}),
194 ...(isDevin
195 ? {
196 clientCapabilitiesMeta: {
197 "cognition.ai/subagentSupport": true,
198 "cognition.ai/messageGrouping": true,
199 },
200 normalizeSessionUpdate: normalizeDevinSessionUpdate,
201 normalizeToolCall: normalizeDevinToolCall,
202 extractSubagentUpdate: extractDevinSubagentUpdate,
203 }
204 : {}),
205 makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(options, catalog),
206 ...(runtimeCoordinator === undefined
207 ? {}
208 : {
209 onAvailableCommandsUpdate: (commands) =>
210 runtimeCoordinator.publishAvailableCommands(
211 options.instanceId,
212 normalizeAcpRegistryCommands(commands),
213 ),
214 onSessionConfigurationUpdate: (configOptions, modeState) =>
215 runtimeCoordinator.publishLiveConfiguration(
216 options.instanceId,
217 normalizeAcpRegistryLiveConfiguration(configOptions, modeState),
218 ),
219 onUrlElicitation: ({ elicitationId, url, message }) => {
220 const normalizedUrl = normalizeAcpRegistryWebUrl(url);
221 if (normalizedUrl === undefined || elicitationId.trim().length === 0) {
222 return Effect.succeed(false);
223 }
224 return runtimeCoordinator.requestUrlAuthentication(options.instanceId, {
225 elicitationId: elicitationId.trim().slice(0, 256),
226 url: normalizedUrl,
227 message: message.trim().slice(0, 1_024),
228 });
229 },
230 withRuntimeStartup: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
231 runtimeCoordinator.withForegroundStartup(startupKey, effect),
232 }),
233 ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
234 };
235 return yield* makeAcpAdapterV2({
236 instanceId: options.instanceId,
237 flavor,
238 selfInvocation: options.selfInvocation,
239 // Per-agent exception (see the note above registerMistralVibeAcpExtensions):
240 // Devin runs commands through client terminals and has no ask mode over
241 // ACP to fall back on. Every other registry agent runs its own.
242 ...(isDevin
243 ? {
244 clientTerminals: {
245 environment: options.environment,
246 shellCommands: true,
247 },
248 }
249 : {}),
250 ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
251 });
252});
253​
254export type AcpRegistryAdapterV2DriverEnv =
255 | ChildProcessSpawner.ChildProcessSpawner
256 | Crypto.Crypto
257 | FileSystem.FileSystem
258 | AcpRegistrySupport.AcpRegistryCatalog
259 | IdAllocator.IdAllocatorV2
260 | Path.Path
261 | McpProviderSessions.McpProviderSessions
262 | ProviderEventLoggers.ProviderEventLoggers
263 | ProviderHost.ProviderHost;
264​
265export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
266 AcpRegistrySettings,
267 AcpRegistryAdapterV2DriverEnv
268> = {
269 driverKind: ACP_REGISTRY_PROVIDER,
270 configSchema: AcpRegistrySettings,
271 defaultConfig: (): AcpRegistrySettings => DEFAULT_ACP_REGISTRY_SETTINGS,
272 create: Effect.fn("AcpRegistryAdapterV2Driver.create")(
273 function* (input: ProviderAdapterDriverCreateInput<AcpRegistrySettings>) {
274 const hostEnvironment = yield* HostProcessEnvironment;
275 const selfInvocation = yield* resolveSelfInvocation();
276 const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
277 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
278 return yield* makeAcpRegistryAdapterV2({
279 instanceId: input.instanceId,
280 settings: { ...input.config, enabled: input.enabled },
281 environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
282 selfInvocation,
283 nativeLogging: (threadId) =>
284 makeNativeLogger({
285 nativeEventLogger: providerEventLoggers.native,
286 provider: ACP_REGISTRY_PROVIDER,
287 threadId,
288 }),
289 });
290 },
291 (effect, input) =>
292 effect.pipe(
293 Effect.mapError(
294 (cause) =>
295 new ProviderAdapterDriverCreateError({
296 driver: ACP_REGISTRY_PROVIDER,
297 instanceId: input.instanceId,
298 detail: "Failed to create ACP Registry adapter.",
299 cause,
300 }),
301 ),
302 ),
303 ),
304};