@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 469 lines 19.2 KB
Raw
1 import {
2 extractClaudeSubagentUpdate,
3 extractClaudeSubagentSessionEvent,
4 isClaudeProvisionalSubagentTool,
5 } from "./claudeAcp.ts";
6 import {
7 normalizeDevinSessionUpdate,
8 normalizeDevinToolCall,
9 extractDevinSubagentUpdate,
10 devinAnswerablePermissionOptions,
11 } from "./devinAcp.ts";
12 import { extractDroidElicitationForm } from "./droidAcp.ts";
13 import { makeKimiPromptOutcomeWatch } from "./kimiAcp.ts";
14 import { extractOmpElicitationForm } from "./ompAcp.ts";
15 import { extractOpenCodeElicitationForm } from "./opencodeAcp.ts";
16 import {
17 copilotClientCapabilitiesMeta,
18 extractCopilotSubagentUpdate,
19 isCopilotLostSessionError,
20 makeCopilotSubagentRouting,
21 } from "./copilotAcp.ts";
22 import { prefersHttpMcpTransport } from "./mcpTransport.ts";
23 import { defaultInstanceIdForDriver, ProviderDriverKind } from "@t3tools/contracts";
24 import { readCustomModelEntries } from "@t3tools/shared/model";
25 import { AcpRegistrySettings } from "../settings.ts";
26 import * as HostProcess from "@t3tools/shared/HostProcess";
27 import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime";
28 import * as SecureRandom from "effect/crypto/SecureRandom";
29 import * as Effect from "effect/Effect";
30 import * as FileSystem from "effect/FileSystem";
31 import * as Path from "effect/Path";
32 import * as Layer from "effect/Layer";
33 import * as Option from "effect/Option";
34 import * as Schema from "effect/Schema";
35 import type * as Scope from "effect/Scope";
36 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
37 import type * as EffectAcpSchema from "effect-acp/compat";
38 import * as EffectAcpErrors from "effect-acp/errors";
39
40 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
41 import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
42 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
43 import {
44 normalizeAcpRegistryCommands,
45 normalizeAcpRegistryLiveConfiguration,
46 normalizeAcpRegistryWebUrl,
47 } from "./probe.ts";
48 import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
49 import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
50 import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
51 import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
52 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
53 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
54 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
55 import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
56 import {
57 ProviderAdapterDriverCreateError,
58 type ProviderAdapterDriver,
59 type ProviderAdapterDriverCreateInput,
60 } from "@t3tools/provider-core/server/adapterDriver";
61 import {
62 AcpProviderCapabilitiesV2,
63 makeAcpAdapterV2,
64 type AcpAdapterV2ExtensionContext,
65 type AcpAdapterV2Flavor,
66 type AcpAdapterV2RuntimeInput,
67 } from "@t3tools/provider-acp/server/adapter";
68
69 export const ACP_REGISTRY_PROVIDER = ProviderDriverKind.make("acpRegistry");
70 export const ACP_REGISTRY_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(ACP_REGISTRY_PROVIDER);
71
72 const DEFAULT_ACP_REGISTRY_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({});
73 const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);
74
75 export interface AcpRegistryAdapterV2Options {
76 readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
77 readonly settings: AcpRegistrySettings;
78 readonly environment: NodeJS.ProcessEnv;
79 readonly selfInvocation: SelfInvocation;
80 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
81 readonly makeRuntime?: (
82 input: AcpAdapterV2RuntimeInput,
83 ) => Effect.Effect<
84 AcpSessionRuntime.AcpSessionRuntime["Service"],
85 EffectAcpErrors.AcpError,
86 ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
87 >;
88 readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
89 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
90 }
91
92 // Mistral Vibe's application rate-limit code, outside ACP.
93 const MISTRAL_VIBE_RATE_LIMITED = -31001;
94
95 const MistralVibeSessionRetrying = Schema.Struct({
96 sessionId: Schema.String,
97 category: Schema.Literals(["rate_limited", "server_error", "timed_out", "connection", "unknown"]),
98 detail: Schema.String,
99 });
100
101 /** Mistral Vibe (v2.25.5) reports SDK backoff through this ACP extension. */
102 export function registerMistralVibeAcpExtensions(context: AcpAdapterV2ExtensionContext) {
103 return context.runtime.handleExtNotification(
104 "_session/retrying",
105 MistralVibeSessionRetrying,
106 (notice) =>
107 context.reportProviderRetry({
108 sessionId: notice.sessionId,
109 failure: makeProviderFailure({
110 message: notice.detail,
111 class:
112 notice.category === "rate_limited"
113 ? "usage_limit"
114 : notice.category === "unknown"
115 ? "provider_error"
116 : "transport_error",
117 retryable: true,
118 }),
119 }),
120 );
121 }
122
123 export function acpRegistryPromptFailure(agentId: string, cause: unknown) {
124 return makeProviderFailure({
125 cause,
126 ...(isAcpRequestError(cause)
127 ? {
128 message: cause.errorMessage,
129 code: String(cause.code),
130 class:
131 agentId === "mistral-vibe" && cause.code === MISTRAL_VIBE_RATE_LIMITED
132 ? ("usage_limit" as const)
133 : ("provider_error" as const),
134 }
135 : { class: "provider_error" as const }),
136 });
137 }
138
139 function makeAcpRegistryRuntime(
140 options: AcpRegistryAdapterV2Options,
141 catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"],
142 ) {
143 return (
144 input: AcpAdapterV2RuntimeInput,
145 ): Effect.Effect<
146 AcpSessionRuntime.AcpSessionRuntime["Service"],
147 EffectAcpErrors.AcpError,
148 ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
149 > =>
150 Effect.gen(function* () {
151 const { processEnvironment, ...runtimeInput } = input;
152 const resolved = yield* catalog
153 .resolve(options.settings, input.cwd, options.environment)
154 .pipe(
155 Effect.mapError(
156 (cause) =>
157 new EffectAcpErrors.AcpSpawnError({
158 command: options.settings.agentId || ACP_REGISTRY_PROVIDER,
159 cause,
160 }),
161 ),
162 );
163 const context = yield* Layer.build(
164 AcpSessionRuntime.layer({
165 ...runtimeInput,
166 spawn:
167 processEnvironment === undefined
168 ? resolved.spawn
169 : {
170 ...resolved.spawn,
171 env: { ...resolved.spawn.env, ...processEnvironment },
172 },
173 ...(options.settings.authMethodId ? { authMethodId: options.settings.authMethodId } : {}),
174 customModels: readCustomModelEntries(options.settings.customModels).map(
175 (entry) => entry.slug,
176 ),
177 }),
178 );
179 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
180 Effect.provide(context),
181 );
182 });
183 }
184
185 const isHermes = (
186 initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"],
187 ) => initializeResult.agentInfo?.name === "hermes-agent";
188
189 export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(function* (
190 options: AcpRegistryAdapterV2Options,
191 ) {
192 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
193 const runtimeCoordinator = Option.getOrUndefined(
194 yield* Effect.serviceOption(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator),
195 );
196 const registryAgentId = options.settings.source === "local" ? "" : options.settings.agentId;
197 const startupKey =
198 options.settings.source === "local" ? `local:${options.instanceId}` : registryAgentId;
199 const isDevin = registryAgentId === "devin";
200 const isAntigravityCli =
201 options.settings.source === "local" &&
202 /^agy(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? "");
203 const isOmp =
204 options.settings.source === "local" &&
205 /^omp(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? "");
206 const isOpenCode =
207 registryAgentId === "opencode" ||
208 registryAgentId === "opencode-v2" ||
209 (options.settings.source === "local" &&
210 /^opencode(?:-v2)?(\.exe|\.cmd)?$/i.test(
211 options.settings.commandPath.split(/[\\/]/).pop() ?? "",
212 ));
213 // Local installs launch the `copilot` binary directly with no registry id.
214 const isCopilot =
215 registryAgentId === "github-copilot-cli" ||
216 (options.settings.source === "local" &&
217 /^copilot(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""));
218 const isKimi =
219 registryAgentId === "kimi-code" ||
220 (options.settings.source === "local" &&
221 /^kimi(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""));
222 const isClaude =
223 registryAgentId === "claude-acp" ||
224 (options.settings.source === "local" &&
225 /^claude-agent-acp(\.exe|\.cmd)?$/i.test(
226 options.settings.commandPath.split(/[\\/]/).pop() ?? "",
227 ));
228 const isDroid =
229 registryAgentId === "factory-droid" ||
230 (options.settings.source === "local" &&
231 /^(?:factory-)?droid(\.exe|\.cmd)?$/i.test(
232 options.settings.commandPath.split(/[\\/]/).pop() ?? "",
233 ));
234 const isGlm =
235 registryAgentId === "glm-acp-agent" ||
236 (options.settings.source === "local" &&
237 /^glm(?:-acp-agent)?(\.exe|\.cmd)?$/i.test(
238 options.settings.commandPath.split(/[\\/]/).pop() ?? "",
239 ));
240 const isVibe =
241 registryAgentId === "mistral-vibe" ||
242 (options.settings.source === "local" &&
243 /^(?:mistral-)?vibe(?:-acp)?(\.exe|\.cmd)?$/i.test(
244 options.settings.commandPath.split(/[\\/]/).pop() ?? "",
245 ));
246 const runtimeOptions = isClaude
247 ? {
248 ...options,
249 environment: {
250 ...options.environment,
251 CLAUDE_AGENT_ACP_EXPERIMENTAL_V2:
252 options.environment.CLAUDE_AGENT_ACP_EXPERIMENTAL_V2 ?? "1",
253 },
254 }
255 : options;
256 const watchKimiPromptOutcome = isKimi
257 ? yield* makeKimiPromptOutcomeWatch(options.environment.KIMI_CODE_HOME)
258 : undefined;
259 const copilotRouting = isCopilot ? makeCopilotSubagentRouting() : undefined;
260 // Copilot CLI 1.0.105 rejects stdio MCP servers from the client, and Command Code cannot
261 // start the stdio bridge on Windows (it spawns MCP commands through cmd.exe, which splits
262 // the unquoted "T3 Code (Beta).exe" path). Both take T3's MCP endpoint over ACP HTTP.
263 const useHttpMcpServers =
264 copilotRouting !== undefined || prefersHttpMcpTransport(options.settings);
265 const flavor: AcpAdapterV2Flavor = {
266 driver: ACP_REGISTRY_PROVIDER,
267 // Cancelling a Copilot prompt also kills the background agents it started.
268 capabilities: isCopilot
269 ? {
270 ...AcpProviderCapabilitiesV2,
271 turns: { ...AcpProviderCapabilitiesV2.turns, supportsSteeringByInterruptRestart: false },
272 }
273 : AcpProviderCapabilitiesV2,
274 customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug),
275 compactViaAdvertisedCommand: true,
276 ...(isAntigravityCli ? { wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true } : {}),
277 promptFailure: (cause) =>
278 acpRegistryPromptFailure(isVibe ? "mistral-vibe" : registryAgentId, cause),
279 ...(isDroid
280 ? { extractElicitationForm: extractDroidElicitationForm }
281 : isOmp
282 ? { extractElicitationForm: extractOmpElicitationForm }
283 : isOpenCode
284 ? { extractElicitationForm: extractOpenCodeElicitationForm }
285 : {}),
286 // glm-acp-agent is the one agent whose per-turn usage a live probe has verified.
287 ...(isGlm ? { reportsPerTurnPromptUsage: true } : {}),
288 ...(watchKimiPromptOutcome === undefined
289 ? {}
290 : {
291 watchPromptOutcome: (sessionId: string) =>
292 Effect.map(
293 watchKimiPromptOutcome(sessionId),
294 (check) => (result: EffectAcpSchema.PromptResponse) =>
295 Effect.map(check(result), (failure) =>
296 failure === undefined
297 ? undefined
298 : { failure, threadDisposition: "reusable" as const },
299 ),
300 ),
301 }),
302 ...(isVibe ? { registerExtensions: registerMistralVibeAcpExtensions } : {}),
303 ...(isClaude
304 ? {
305 followAgentWorkState: true,
306 extractSubagentUpdate: extractClaudeSubagentUpdate,
307 isProvisionalSubagentTool: isClaudeProvisionalSubagentTool,
308 extractSubagentSessionEvent: extractClaudeSubagentSessionEvent,
309 }
310 : {}),
311 // Hermes replies on the root session when a background process it started exits; no
312 // prompt response follows, so the continuation ends on the deferred-finalize debounce.
313 // Hermes is not in the public registry and may run through a wrapper, so only its
314 // initialize reply identifies it. agy does the same and is known by its command.
315 enablePostSettleContinuation: (initializeResult) =>
316 isAntigravityCli || isHermes(initializeResult),
317 deferFinalizeForBackgroundWork: (initializeResult) =>
318 isAntigravityCli || isHermes(initializeResult),
319 ...(isDevin
320 ? {
321 clientCapabilitiesMeta: {
322 "cognition.ai/subagentSupport": true,
323 "cognition.ai/messageGrouping": true,
324 },
325 normalizeSessionUpdate: normalizeDevinSessionUpdate,
326 normalizeToolCall: normalizeDevinToolCall,
327 extractSubagentUpdate: extractDevinSubagentUpdate,
328 answerablePermissionOptions: devinAnswerablePermissionOptions,
329 }
330 : {}),
331 ...(copilotRouting === undefined
332 ? {}
333 : {
334 clientCapabilitiesMeta: copilotClientCapabilitiesMeta,
335 deferMcpTools: true,
336 registerExtensions: copilotRouting.registerExtensions,
337 normalizeSessionUpdate: copilotRouting.normalizeSessionUpdate,
338 extractSubagentUpdate: extractCopilotSubagentUpdate,
339 restartRuntimeAfterPromptError: isCopilotLostSessionError,
340 // A finished background agent wakes the root after assistant.idle settled the run.
341 enablePostSettleContinuation: true,
342 // session/new reports a built-in default, not the model Copilot runs (github/copilot-cli#5363).
343 alwaysSetModel: true,
344 }),
345 mcpOverHttp: useHttpMcpServers,
346 makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(runtimeOptions, catalog),
347 ...(runtimeCoordinator === undefined
348 ? {}
349 : {
350 onAvailableCommandsUpdate: (commands) =>
351 runtimeCoordinator.publishAvailableCommands(
352 options.instanceId,
353 normalizeAcpRegistryCommands(commands),
354 ),
355 // A new Copilot session starts at its own effort, not the one the composer shows.
356 ...(isCopilot
357 ? {
358 unsetOptionDefaults: runtimeCoordinator
359 .getLiveConfiguration(options.instanceId)
360 .pipe(
361 Effect.map(
362 Option.match({
363 onNone: () => [],
364 onSome: ({ configOptions }) =>
365 configOptions.flatMap((descriptor) =>
366 descriptor.type === "select" &&
367 descriptor.role === "reasoning" &&
368 descriptor.currentValue !== undefined
369 ? [{ id: descriptor.id, value: descriptor.currentValue }]
370 : [],
371 ),
372 }),
373 ),
374 ),
375 }
376 : {}),
377 onSessionConfigurationUpdate: (configOptions, modeState, modelState) =>
378 runtimeCoordinator.publishLiveConfiguration(
379 options.instanceId,
380 normalizeAcpRegistryLiveConfiguration(configOptions, modeState, modelState),
381 ),
382 onUrlElicitation: ({ elicitationId, url, message }) => {
383 const normalizedUrl = normalizeAcpRegistryWebUrl(url);
384 if (normalizedUrl === undefined || elicitationId.trim().length === 0) {
385 return Effect.succeed(false);
386 }
387 return runtimeCoordinator.requestUrlAuthentication(options.instanceId, {
388 elicitationId: elicitationId.trim().slice(0, 256),
389 url: normalizedUrl,
390 message: message.trim().slice(0, 1_024),
391 });
392 },
393 withRuntimeStartup: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
394 runtimeCoordinator.withForegroundStartup(startupKey, effect),
395 }),
396 ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
397 };
398 return yield* makeAcpAdapterV2({
399 instanceId: options.instanceId,
400 flavor,
401 selfInvocation: options.selfInvocation,
402 ...(options.continuationRequests === undefined
403 ? {}
404 : { continuationRequests: options.continuationRequests }),
405 // Devin runs commands through client terminals and has no ask mode over ACP to fall back on.
406 ...(isDevin
407 ? {
408 clientTerminals: {
409 environment: options.environment,
410 shellCommands: true,
411 },
412 }
413 : {}),
414 ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
415 });
416 });
417
418 export type AcpRegistryAdapterV2DriverEnv =
419 | ChildProcessSpawner.ChildProcessSpawner
420 | SecureRandom.SecureRandom
421 | FileSystem.FileSystem
422 | AcpRegistrySupport.AcpRegistryCatalog
423 | IdAllocator.IdAllocatorV2
424 | Path.Path
425 | McpProviderSessions.McpProviderSessions
426 | ProviderEventLoggers.ProviderEventLoggers
427 | ProviderHost.ProviderHost;
428
429 export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
430 AcpRegistrySettings,
431 AcpRegistryAdapterV2DriverEnv
432 > = {
433 driverKind: ACP_REGISTRY_PROVIDER,
434 configSchema: AcpRegistrySettings,
435 defaultConfig: (): AcpRegistrySettings => DEFAULT_ACP_REGISTRY_SETTINGS,
436 create: Effect.fn("AcpRegistryAdapterV2Driver.create")(
437 function* (input: ProviderAdapterDriverCreateInput<AcpRegistrySettings>) {
438 const hostEnvironment = yield* HostProcess.Environment;
439 const selfInvocation = yield* resolveSelfInvocation();
440 const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
441 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
442 return yield* makeAcpRegistryAdapterV2({
443 instanceId: input.instanceId,
444 settings: { ...input.config, enabled: input.enabled },
445 environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
446 selfInvocation,
447 continuationRequests: yield* ProviderContinuationRequests.ProviderContinuationRequests,
448 nativeLogging: (threadId) =>
449 makeNativeLogger({
450 nativeEventLogger: providerEventLoggers.native,
451 provider: ACP_REGISTRY_PROVIDER,
452 threadId,
453 }),
454 });
455 },
456 (effect, input) =>
457 effect.pipe(
458 Effect.mapError(
459 (cause) =>
460 new ProviderAdapterDriverCreateError({
461 driver: ACP_REGISTRY_PROVIDER,
462 instanceId: input.instanceId,
463 detail: "Failed to create ACP Registry adapter.",
464 cause,
465 }),
466 ),
467 ),
468 ),
469 };