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

DevinAcpSupport.ts

204 lines8.1 KB

1import { type DevinSettings, type ProviderOptionSelection } from "@t3tools/contracts";
2import * as Crypto from "effect/Crypto";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Scope from "effect/Scope";
6import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
7import type * as EffectAcpErrors from "effect-acp/errors";
8import type * as EffectAcpSchema from "effect-acp/schema";
9​
10import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
11import { devinModelGroupKey, parseDevinModelUid } from "../Layers/DevinProvider.ts";
12​
13export { inferDevinContextWindowTokens } from "../Layers/DevinProvider.ts";
14​
15const LOWER_SPEED_SUFFIX = /-(fast|priority)$/;
16const UPPER_SPEED_SUFFIX = /_(FAST|PRIORITY)$/;
17​
18function stripTrailingSpeed(slug: string): { base: string; speed: string } | undefined {
19 const lower = slug.match(LOWER_SPEED_SUFFIX);
20 if (lower) {
21 return { base: slug.slice(0, slug.length - lower[0].length), speed: lower[1]! };
22 }
23 const upper = slug.match(UPPER_SPEED_SUFFIX);
24 if (upper) {
25 return { base: slug.slice(0, slug.length - upper[0].length), speed: upper[1]!.toLowerCase() };
26 }
27 return undefined;
29​
30type DevinAcpRuntimeSettings = Pick<DevinSettings, "binaryPath">;
31​
32export const DEVIN_ACP_CLIENT_CAPABILITIES = {
33 _meta: {
34 "cognition.ai/requestDiagnostics": true,
35 },
36} satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
37​
38export interface DevinAcpRuntimeInput extends Omit<
39 AcpSessionRuntime.AcpSessionRuntimeOptions,
40 "authMethodId" | "clientCapabilities" | "spawn"
41> {
42 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
43 readonly devinSettings: DevinAcpRuntimeSettings | null | undefined;
44 readonly environment?: NodeJS.ProcessEnv;
46​
47export function buildDevinAcpSpawnInput(
48 devinSettings: DevinAcpRuntimeSettings | null | undefined,
49 cwd: string,
50 environment?: NodeJS.ProcessEnv,
51): AcpSessionRuntime.AcpSpawnInput {
52 return {
53 command: devinSettings?.binaryPath || "devin",
54 args: ["acp"],
55 cwd,
56 ...(environment ? { env: environment } : {}),
57 };
59​
60export const makeDevinAcpRuntime = (
61 input: DevinAcpRuntimeInput,
62): Effect.Effect<
63 AcpSessionRuntime.AcpSessionRuntime["Service"],
64 EffectAcpErrors.AcpError,
65 Crypto.Crypto | Scope.Scope
66> =>
67 Effect.gen(function* () {
68 const acpContext = yield* Layer.build(
69 AcpSessionRuntime.layer({
70 ...input,
71 spawn: buildDevinAcpSpawnInput(input.devinSettings, input.cwd, input.environment),
72 clientCapabilities: DEVIN_ACP_CLIENT_CAPABILITIES,
73 }).pipe(
74 Layer.provide(
75 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
76 ),
77 ),
78 );
79 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
80 Effect.provide(acpContext),
81 );
82 });
83​
84export interface DevinAcpModelSelectionErrorContext {
85 readonly cause: EffectAcpErrors.AcpError;
86 readonly step: "set-config-option";
87 readonly configId: "model";
89​
90export function applyDevinAcpModelSelection<E>(input: {
91 readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setModel">;
92 readonly model: string | null | undefined;
93 readonly selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
94 readonly mapError: (context: DevinAcpModelSelectionErrorContext) => E;
95}): Effect.Effect<void, E> {
96 const model = resolveDevinModelUid(input.model, input.selections);
97 const reasoning = input.selections?.find((option) => option.id === "reasoning")?.value;
98 const context = input.selections?.find((option) => option.id === "contextWindow")?.value;
99 const speed = input.selections?.find((option) => option.id === "speed")?.value;
100 const base = resolveDevinAcpBaseModelId(input.model);
101 const isUpper = base.includes("_") && /[A-Z]/.test(base);
102 const separator = isUpper ? "_" : "-";
103 const contextSuffix =
104 typeof context === "string" && context.trim()
105 ? `${separator}${isUpper ? context.toUpperCase() : context.toLowerCase()}`
106 : "";
107 const fallbackCandidates =
108 reasoning === "none" && (speed === undefined || speed === "standard")
109 ? [contextSuffix.length > 0 ? `${base}${contextSuffix}` : null, base].filter(
110 (candidate): candidate is string => candidate !== null && candidate !== model,
111 )
112 : [];
113 const setModel = input.runtime.setModel(model).pipe(
114 Effect.catch((cause) => {
115 const fallback = fallbackCandidates[0];
116 return fallback === undefined
117 ? Effect.fail(cause)
118 : input.runtime.setModel(fallback).pipe(
119 Effect.catch((fallbackCause) => {
120 const secondFallback = fallbackCandidates[1];
121 return secondFallback === undefined
122 ? Effect.fail(fallbackCause)
123 : input.runtime.setModel(secondFallback);
124 }),
125 );
126 }),
127 );
128 return setModel.pipe(
129 Effect.mapError((cause) =>
130 input.mapError({
131 cause,
132 step: "set-config-option",
133 configId: "model",
134 }),
135 ),
136 );
138​
139/**
140 * Returns the base model slug (the group key, with no reasoning level) used
141 * to decide whether a model change requires an ACP session restart. Changing
142 * only the reasoning level is a config-option tweak, not a model swap.
143 */
144export function resolveDevinAcpBaseModelId(model: string | null | undefined): string {
145 const trimmed = model?.trim();
146 if (!trimmed) return "adaptive";
147 return devinModelGroupKey(parseDevinModelUid(trimmed));
149​
150/**
151 * Recombines a base model slug with its `reasoning` option selection to form
152 * the full model UID Devin's ACP backend expects.
153 *
154 * The base slug is the group key (e.g. `claude-opus-5` or
155 * `claude-opus-5-fast`); the reasoning choice is inserted before any speed
156 * tier so `claude-opus-5-fast` + `medium` → `claude-opus-5-medium-fast`.
157 * Uppercase enum-style UIDs recombine with `_` separators and uppercased
158 * suffixes: `MODEL_GPT_5_2` + `low` → `MODEL_GPT_5_2_LOW`.
159 */
160export function resolveDevinModelUid(
161 model: string | null | undefined,
162 options?: ReadonlyArray<ProviderOptionSelection> | null,
163): string {
164 const groupSlug = resolveDevinAcpBaseModelId(model);
165 const reasoning = options?.find((option) => option.id === "reasoning")?.value;
166 if (typeof reasoning !== "string" || !reasoning.trim()) {
167 return groupSlug;
168 }
169 if (reasoning.startsWith("__uid:")) {
170 const concreteUid = reasoning.slice("__uid:".length).trim();
171 if (concreteUid.length > 0) return concreteUid;
172 }
173 // The group slug is `base + sep + speed` (or just base). Split the speed
174 // tier off so the reasoning level can be inserted before it.
175 const speedParts = stripTrailingSpeed(groupSlug);
176 const base = speedParts?.base ?? groupSlug;
177 const selectedSpeed = options?.find((option) => option.id === "speed")?.value;
178 const speed =
179 typeof selectedSpeed === "string" && selectedSpeed !== "standard"
180 ? selectedSpeed
181 : speedParts?.speed;
182 const isUpper = base.includes("_") && /[A-Z]/.test(base);
183 const sep = isUpper ? "_" : "-";
184 const reasoningSuffix = isUpper ? reasoning.toUpperCase() : reasoning;
185 const speedSuffix = speed ? (isUpper ? `_${speed.toUpperCase()}` : `-${speed}`) : "";
186 const context = options?.find((option) => option.id === "contextWindow")?.value;
187 // Devin's GLM family uses the unsuffixed UID for the 200K variants and
188 // appends only the context suffix for 1M variants. The reasoning level is
189 // encoded for None/Max, while High is the family default (`glm-5-2`).
190 // It is never `glm-5-2-high-200k` (or another `-200k` UID).
191 const isGlm52 = base.toLowerCase() === "glm-5-2";
192 if (isGlm52 && (reasoning ?? "").toLowerCase() === "high") {
193 return context === "1m" ? "glm-5-2-1m" : "glm-5-2";
194 }
195 if (isGlm52 && !speed && ["none", "max"].includes((reasoning ?? "").toLowerCase())) {
196 const glmContextSuffix = context === "1m" ? "-1m" : "";
197 return `glm-5-2-${reasoning!.toLowerCase()}${glmContextSuffix}`;
198 }
199 const contextSuffix =
200 typeof context === "string" && context.trim()
201 ? `${sep}${isUpper ? context.toUpperCase() : context.toLowerCase()}`
202 : "";
203 return `${base}${sep}${reasoningSuffix}${speedSuffix}${contextSuffix}`;