Open History to see the last commit
1import {
2 type DevinSettings,
3 type ModelCapabilities,
4 type ModelPricing,
5 type ProviderOptionChoice,
6 type SelectProviderOptionDescriptor,
7 type ServerProviderModel,
8} from "@t3tools/contracts";
9import { createModelCapabilities } from "@t3tools/shared/model";
10import { resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Option from "effect/Option";
15import * as Result from "effect/Result";
16import * as Schema from "effect/Schema";
17import { ChildProcess } from "effect/unstable/process";
18import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
19
20import {
21 buildServerProvider,
22 isCommandMissingCause,
23 parseGenericCliVersion,
24 providerModelsFromSettings,
25 spawnAndCollect,
26 type ServerProviderDraft,
27} from "../providerSnapshot.ts";
28
29/**
30 * Bumped whenever Devin's model inventory representation changes. The
31 * provider registry uses this marker to prevent an older flattened snapshot
32 * from being merged into the parent/family catalog. v3 invalidates snapshots
33 * written by the first grouped implementation so the picker cannot retain
34 * rows such as `Max 1M`, `Fast`, or `Priority` as standalone models.
35 */
36export const DEVIN_MODEL_CATALOG_VERSION = "devin-model-catalog-v3";
37
38const DEVIN_PRESENTATION = {
39 displayName: "Devin",
40 badgeLabel: "Early Access",
41 showInteractionModeToggle: true,
42 requiresNewThreadForModelChange: false,
43 modelCatalogVersion: DEVIN_MODEL_CATALOG_VERSION,
44} as const;
45
46const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({ optionDescriptors: [] });
47const VERSION_PROBE_TIMEOUT_MS = 4_000;
48const MODEL_PROBE_TIMEOUT_MS = 15_000;
49
50/**
51 * Reasoning levels Devin bakes into model UIDs as a trailing suffix, ordered
52 * from least to most effort. Used both to group variants into a single
53 * selectable model and to order the option choices in the picker.
54 */
55const DEVIN_REASONING_LEVELS = [
56 "none",
57 "low",
58 "medium",
59 "high",
60 "xhigh",
61 "max",
62 "thinking",
63] as const;
64
65const DEVIN_REASONING_LABELS: Readonly<Record<string, string>> = {
66 none: "None",
67 low: "Low",
68 medium: "Medium",
69 high: "High",
70 xhigh: "X-High",
71 max: "Max",
72 thinking: "Thinking",
73};
74const DEVIN_SPEED_LABELS: Readonly<Record<string, string>> = {
75 standard: "Standard",
76 fast: "Fast",
77 priority: "Priority",
78};
79const DEVIN_DEFAULT_CONTEXT_WINDOWS: Readonly<Record<string, string>> = {
80 "glm-5-2": "200k",
81};
82
83/**
84 * Fallback context sizes used when an ACP/CLI catalog omits the field. Devin
85 * currently advertises these limits in its model catalog. Keeping this map in
86 * the provider layer means the context meter still has a useful denominator
87 * while a model is streaming its first usage update.
88 */
89const DEVIN_CONTEXT_WINDOWS: Readonly<Record<string, number>> = {
90 "claude-opus-5": 1_000_000,
91 "claude-5-fable": 1_000_000,
92 "claude-sonnet-5": 1_000_000,
93 "gemini-3-7-flash": 1_048_576,
94 "gpt-5-6-sol": 1_000_000,
95 "gpt-5-6-luna": 1_000_000,
96 "glm-5-2": 200_000,
97 "kimi-k3": 1_048_576,
98 "swe-1-7": 262_000,
99 "swe-1-7-lightning": 202_752,
100 adaptive: 1_000_000,
101 "claude-opus-4-7": 1_000_000,
102 "claude-opus-4-8": 1_000_000,
103 "gemini-3-5-flash": 1_048_576,
104 "gemini-3-6-flash": 1_048_576,
105 "gpt-5-6-terra": 1_000_000,
106 "grok-4-5": 500_000,
107 "grok-4-6": 500_000,
108 inkling: 1_048_576,
109 "deepseek-v4-flash": 1_048_576,
110 "claude-opus-4-6": 200_000,
111 "gpt-5-4": 272_000,
112 "gpt-5-5": 272_000,
113 "gpt-5-4-mini": 400_000,
114 "claude-sonnet-4-6": 200_000,
115 "gpt-5-2": 384_000,
116 model_gpt_5_2: 384_000,
117 "claude-opus-4-5": 200_000,
118 "claude-haiku-4-5": 200_000,
119 "claude-sonnet-4-5": 200_000,
120 "gpt-4-1": 1_047_576,
121 "gpt-5-1": 272_000,
122 model_private_12: 272_000,
123 model_private_13: 272_000,
124 model_private_14: 272_000,
125 model_private_15: 272_000,
126 "gpt-5-3-codex": 400_000,
127 "kimi-k2-6": 262_144,
128 "kimi-k2-7": 262_144,
129 "nemotron-3-ultra": 1_000_000,
130 "swe-1-6": 200_000,
131 "swe-1-6-fast": 200_000,
132 "gemini-3-1-pro": 1_048_576,
133 "gemini-3-flash": 1_048_576,
134 "deepseek-v4-pro": 1_048_576,
135};
136
137export function inferDevinContextWindowTokens(
138 modelUid: string | null | undefined,
139): number | undefined {
140 const trimmed = modelUid?.trim();
141 if (!trimmed) return undefined;
142 const parsed = parseDevinModelUid(trimmed);
143 if (parsed.contextWindow) return parseContext(parsed.contextWindow) * 1_000;
144 const normalizedBase = parsed.base.toLowerCase();
145 return (
146 DEVIN_CONTEXT_WINDOWS[normalizedBase] ??
147 DEVIN_CONTEXT_WINDOWS[normalizedBase.replaceAll("_", "-")]
148 );
149}
150
151/**
152 * Speed suffixes that follow the reasoning level in a model UID
153 * (e.g. `claude-opus-5-medium-fast`). Kept separate from reasoning so the
154 * group key can carry the speed while reasoning becomes an option choice.
155 */
156const LOWER_REASONING_SUFFIX = /-(none|low|medium|high|xhigh|max|thinking)$/;
157const LOWER_SPEED_SUFFIX = /-(fast|priority)$/;
158const UPPER_REASONING_SUFFIX = /_(NONE|LOW|MEDIUM|HIGH|XHIGH|MAX|THINKING)$/;
159const UPPER_SPEED_SUFFIX = /_(FAST|PRIORITY)$/;
160const LOWER_CONTEXT_SUFFIX = /-(\d+(?:k|m))$/i;
161const UPPER_CONTEXT_SUFFIX = /_(\d+(?:K|M))$/;
162
163function capitalize(word: string): string {
164 return word.charAt(0).toUpperCase() + word.slice(1);
165}
166
167function parseContext(value: string): number {
168 const match = value.match(/^(\d+)(k|m)$/i);
169 if (!match) return Number.MAX_SAFE_INTEGER;
170 const amount = Number(match[1]);
171 return match[2]!.toLowerCase() === "m" ? amount * 1000 : amount;
172}
173
174function inferReasoningFromLabel(label: string): string {
175 const normalized = label.toLowerCase();
176 if (normalized.includes("no thinking") || normalized.includes("none")) return "none";
177 for (const level of ["xhigh", "high", "medium", "low", "max", "thinking"]) {
178 if (normalized.includes(level)) return level;
179 }
180 return "none";
181}
182
183function labelHasReasoningSignal(label: string): boolean {
184 return /\b(?:no\s+thinking|none|low|medium|high|x[- ]?high|max|thinking)\b/iu.test(label);
185}
186
187/**
188 * Extracts the `{ base, reasoning, speed }` triple from a Devin model UID.
189 *
190 * Devin bakes the reasoning level (and an optional speed tier) into the UID
191 * as a trailing suffix: `claude-opus-5-medium`, `claude-opus-5-medium-fast`.
192 * Uppercase enum-style UIDs use underscore separators: `MODEL_GPT_5_2_LOW`.
193 *
194 * Speed only counts when a reasoning level precedes it — a bare `-fast`
195 * without a reasoning suffix is treated as part of the base so it cannot
196 * collide with a grouped family that happens to share the same speed tier.
197 * Models with no recognizable reasoning suffix are single variants.
198 */
199export function parseDevinModelUid(uid: string): {
200 base: string;
201 reasoning: string | undefined;
202 speed: string | undefined;
203 contextWindow: string | undefined;
204} {
205 const trimmed = uid.trim();
206 const strip = (value: string, re: RegExp): [string, string] | undefined => {
207 const match = value.match(re);
208 if (!match) return undefined;
209 return [value.slice(0, value.length - match[0].length), match[1]!.toLowerCase()];
210 };
211
212 const contextMatch = strip(trimmed, LOWER_CONTEXT_SUFFIX) ?? strip(trimmed, UPPER_CONTEXT_SUFFIX);
213 const withoutContext = contextMatch?.[0] ?? trimmed;
214 const contextWindow = contextMatch?.[1];
215 const speedMatch =
216 strip(withoutContext, LOWER_SPEED_SUFFIX) ?? strip(withoutContext, UPPER_SPEED_SUFFIX);
217 if (speedMatch) {
218 const [afterSpeed, speed] = speedMatch;
219 const reasoningMatch =
220 strip(afterSpeed, LOWER_REASONING_SUFFIX) ?? strip(afterSpeed, UPPER_REASONING_SUFFIX);
221 if (reasoningMatch) {
222 return { base: reasoningMatch[0], reasoning: reasoningMatch[1], speed, contextWindow };
223 }
224 }
225
226 const reasoningMatch =
227 strip(withoutContext, LOWER_REASONING_SUFFIX) ?? strip(withoutContext, UPPER_REASONING_SUFFIX);
228 if (reasoningMatch) {
229 return {
230 base: reasoningMatch[0],
231 reasoning: reasoningMatch[1],
232 speed: undefined,
233 contextWindow,
234 };
235 }
236 return { base: withoutContext, reasoning: undefined, speed: undefined, contextWindow };
237}
238
239/**
240 * Group key for a parsed UID: the family base, with reasoning, speed, and
241 * context-window qualifiers removed. All variants in a Devin family collapse
242 * into one selectable parent model under this key; the qualifiers become
243 * option descriptors on that row.
244 */
245export function devinModelGroupKey(parsed: { base: string; speed?: string | undefined }): string {
246 return parsed.base;
247}
248
249/**
250 * Known per-model input capabilities for Devin models.
251 *
252 * The `devin models list --format json` payload (see `DevinModelsPayload`)
253 * reports model families and variants but does not advertise input
254 * modalities, so we map them here from the model_uid. Devin is an agentic
255 * coding harness: every catalogued model accepts text, pasted/attached
256 * images, and uploaded file context. None of the current models accept
257 * audio input, so `inputAudio` is false across the board. A model_uid that
258 * is absent from this map falls back to the default (all modalities
259 * supported), which keeps newly added Devin models usable until this map
260 * is refreshed.
261 */
262const DEVIN_MODEL_INPUT_CAPABILITIES: Readonly<
263 Record<string, { inputImages?: boolean; inputAudio?: boolean; inputFiles?: boolean }>
264> = {
265 adaptive: { inputAudio: false },
266};
267
268function devinModelCapabilities(slug: string): ModelCapabilities {
269 const overrides = DEVIN_MODEL_INPUT_CAPABILITIES[slug];
270 if (!overrides) {
271 return EMPTY_CAPABILITIES;
272 }
273 return createModelCapabilities({
274 optionDescriptors: [],
275 ...overrides,
276 });
277}
278
279const DEVIN_PRICING_SOURCE = "devin-cli models list";
280
281function finiteNonNegative(value: unknown): number | undefined {
282 return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
283}
284
285function firstFiniteNonNegative(record: Record<string, unknown>, keys: ReadonlyArray<string>) {
286 for (const key of keys) {
287 const value = finiteNonNegative(record[key]);
288 if (value !== undefined) return value;
289 }
290 return undefined;
291}
292
293/** Read either a per-million or per-token rate and normalize it to USD per
294 * million tokens. Devin has used both spellings across CLI releases, and a
295 * nested `pricing` object is used by newer releases. */
296function readNormalizedRate(
297 record: Record<string, unknown>,
298 perMillionKeys: ReadonlyArray<string>,
299 perTokenKeys: ReadonlyArray<string>,
300): number | undefined {
301 const perMillion = firstFiniteNonNegative(record, perMillionKeys);
302 if (perMillion !== undefined) return perMillion;
303 const perToken = firstFiniteNonNegative(record, perTokenKeys);
304 return perToken === undefined ? undefined : perToken * 1_000_000;
305}
306
307function perMillionToPricing(input: {
308 readonly input: number;
309 readonly cachedInput?: number;
310 readonly cacheCreation?: number;
311 readonly output: number;
312 readonly contextWindowTokens?: number;
313}): ModelPricing {
314 return {
315 inputPerMillion: input.input,
316 ...(input.cachedInput !== undefined ? { cachedInputPerMillion: input.cachedInput } : {}),
317 ...(input.cacheCreation !== undefined ? { cacheCreationPerMillion: input.cacheCreation } : {}),
318 outputPerMillion: input.output,
319 ...(input.contextWindowTokens !== undefined
320 ? { contextWindowTokens: input.contextWindowTokens }
321 : {}),
322 currency: "USD",
323 source: DEVIN_PRICING_SOURCE,
324 };
325}
326
327function parseContextWindowTokens(value: unknown): number | undefined {
328 if (typeof value === "number") return finiteNonNegative(value);
329 if (typeof value !== "string") return undefined;
330 const normalized = value.trim().toLowerCase();
331 const match = /^(\d+(?:\.\d+)?)\s*(k|m)?$/.exec(normalized);
332 if (!match) return undefined;
333 const amount = Number(match[1]);
334 if (!Number.isFinite(amount) || amount <= 0) return undefined;
335 const multiplier = match[2] === "m" ? 1_000_000 : match[2] === "k" ? 1_000 : 1;
336 return Math.round(amount * multiplier);
337}
338
339function formatContextWindowOption(tokens: number): string | undefined {
340 if (!Number.isFinite(tokens) || tokens <= 0) return undefined;
341 if (tokens % 1_000_000 === 0) return `${tokens / 1_000_000}m`;
342 if (tokens % 1_000 === 0) return `${tokens / 1_000}k`;
343 return `${tokens}`;
344}
345
346/**
347 * Accepts the JSON shapes used by different Devin CLI releases. Older builds
348 * expose flat `*_per_million` fields, while newer builds nest rates under a
349 * `pricing` object and use per-token values. The normalized result is always
350 * USD per million tokens so it can be persisted in the provider snapshot.
351 */
352function parseDevinVariantPricing(variant: Record<string, unknown>): ModelPricing | undefined {
353 const nested =
354 variant.pricing && typeof variant.pricing === "object" && !Array.isArray(variant.pricing)
355 ? (variant.pricing as Record<string, unknown>)
356 : {};
357 const input =
358 readNormalizedRate(
359 variant,
360 ["input_per_million", "inputPerMillion", "input_cost_per_million", "inputCostPerMillion"],
361 ["input_cost_per_token", "inputCostPerToken"],
362 ) ??
363 readNormalizedRate(
364 nested,
365 ["input_per_million", "inputPerMillion", "input_cost_per_million", "inputCostPerMillion"],
366 ["input_cost_per_token", "inputCostPerToken"],
367 );
368 const output =
369 readNormalizedRate(
370 variant,
371 ["output_per_million", "outputPerMillion", "output_cost_per_million", "outputCostPerMillion"],
372 ["output_cost_per_token", "outputCostPerToken"],
373 ) ??
374 readNormalizedRate(
375 nested,
376 ["output_per_million", "outputPerMillion", "output_cost_per_million", "outputCostPerMillion"],
377 ["output_cost_per_token", "outputCostPerToken"],
378 );
379 if (input === undefined || output === undefined) return undefined;
380
381 const cached =
382 readNormalizedRate(
383 variant,
384 [
385 "cached_input_per_million",
386 "cachedInputPerMillion",
387 "cache_read_cost_per_million",
388 "cacheReadCostPerMillion",
389 ],
390 [
391 "cached_input_cost_per_token",
392 "cachedInputCostPerToken",
393 "cache_read_cost_per_token",
394 "cacheReadCostPerToken",
395 ],
396 ) ??
397 readNormalizedRate(
398 nested,
399 [
400 "cached_input_per_million",
401 "cachedInputPerMillion",
402 "cache_read_cost_per_million",
403 "cacheReadCostPerMillion",
404 ],
405 [
406 "cached_input_cost_per_token",
407 "cachedInputCostPerToken",
408 "cache_read_cost_per_token",
409 "cacheReadCostPerToken",
410 ],
411 );
412 const cacheCreation =
413 readNormalizedRate(
414 variant,
415 [
416 "cache_creation_per_million",
417 "cacheCreationPerMillion",
418 "cache_write_cost_per_million",
419 "cacheWriteCostPerMillion",
420 ],
421 [
422 "cache_creation_cost_per_token",
423 "cacheCreationCostPerToken",
424 "cache_write_cost_per_token",
425 "cacheWriteCostPerToken",
426 ],
427 ) ??
428 readNormalizedRate(
429 nested,
430 [
431 "cache_creation_per_million",
432 "cacheCreationPerMillion",
433 "cache_write_cost_per_million",
434 "cacheWriteCostPerMillion",
435 ],
436 [
437 "cache_creation_cost_per_token",
438 "cacheCreationCostPerToken",
439 "cache_write_cost_per_token",
440 "cacheWriteCostPerToken",
441 ],
442 );
443 const contextWindowTokens =
444 parseContextWindowTokens(variant.context_window ?? variant.contextWindow) ??
445 parseContextWindowTokens(nested.context_window ?? nested.contextWindow);
446 return perMillionToPricing({
447 input,
448 ...(cached !== undefined ? { cachedInput: cached } : {}),
449 ...(cacheCreation !== undefined ? { cacheCreation } : {}),
450 output,
451 ...(contextWindowTokens !== undefined ? { contextWindowTokens } : {}),
452 });
453}
454
455function pricingWithContext(
456 pricing: ModelPricing | undefined,
457 contextWindowTokens: number | undefined,
458): ModelPricing | undefined {
459 if (!pricing) return undefined;
460 if (pricing.contextWindowTokens !== undefined || contextWindowTokens === undefined) {
461 return pricing;
462 }
463 return { ...pricing, contextWindowTokens };
464}
465
466function modelPricingRecord(
467 variants: ReadonlyMap<string, ModelPricing>,
468): Readonly<Record<string, ModelPricing>> | undefined {
469 if (variants.size === 0) return undefined;
470 return Object.fromEntries(variants.entries());
471}
472
473const DevinModelVariant = Schema.Struct({
474 model_uid: Schema.String,
475 label: Schema.String,
476 context_window: Schema.optional(Schema.Union([Schema.Number, Schema.String])),
477 contextWindow: Schema.optional(Schema.Union([Schema.Number, Schema.String])),
478 input_per_million: Schema.optional(Schema.Number),
479 output_per_million: Schema.optional(Schema.Number),
480 cached_input_per_million: Schema.optional(Schema.Number),
481 cache_creation_per_million: Schema.optional(Schema.Number),
482 input_cost_per_million: Schema.optional(Schema.Number),
483 output_cost_per_million: Schema.optional(Schema.Number),
484 cache_read_cost_per_million: Schema.optional(Schema.Number),
485 cache_write_cost_per_million: Schema.optional(Schema.Number),
486 input_cost_per_token: Schema.optional(Schema.Number),
487 output_cost_per_token: Schema.optional(Schema.Number),
488 cached_input_cost_per_token: Schema.optional(Schema.Number),
489 cache_creation_cost_per_token: Schema.optional(Schema.Number),
490 cache_read_cost_per_token: Schema.optional(Schema.Number),
491 cache_write_cost_per_token: Schema.optional(Schema.Number),
492 inputPerMillion: Schema.optional(Schema.Number),
493 outputPerMillion: Schema.optional(Schema.Number),
494 cachedInputPerMillion: Schema.optional(Schema.Number),
495 cacheCreationPerMillion: Schema.optional(Schema.Number),
496 inputCostPerToken: Schema.optional(Schema.Number),
497 outputCostPerToken: Schema.optional(Schema.Number),
498 cachedInputCostPerToken: Schema.optional(Schema.Number),
499 cacheCreationCostPerToken: Schema.optional(Schema.Number),
500 cacheReadCostPerToken: Schema.optional(Schema.Number),
501 cacheWriteCostPerToken: Schema.optional(Schema.Number),
502 cacheReadCostPerMillion: Schema.optional(Schema.Number),
503 cacheWriteCostPerMillion: Schema.optional(Schema.Number),
504 pricing: Schema.optional(Schema.Unknown),
505});
506
507const DevinModelFamily = Schema.Struct({
508 family_label: Schema.String,
509 family_uid: Schema.String,
510 variants: Schema.Array(DevinModelVariant),
511});
512
513const DevinModelsPayload = Schema.Struct({
514 families: Schema.Array(DevinModelFamily),
515});
516
517const decodeDevinModels = Schema.decodeUnknownEffect(Schema.fromJsonString(DevinModelsPayload));
518
519/** Parse the human-readable fallback emitted by older Devin CLIs. */
520export function parseDevinHumanModelList(output: string): typeof DevinModelsPayload.Type | null {
521 const families: Array<{
522 family_label: string;
523 family_uid: string;
524 variants: Array<Record<string, unknown>>;
525 }> = [];
526 let current:
527 | {
528 family_label: string;
529 family_uid: string;
530 variants: Array<Record<string, unknown>>;
531 }
532 | undefined;
533
534 for (const line of output.split(/\r?\n/u)) {
535 const familyMatch = /^\s*([^()\r\n]+?)\s+\(([^()\r\n]+)\)\s*$/u.exec(line);
536 if (familyMatch) {
537 if (familyMatch[1]!.trim().toLowerCase() === "available models") continue;
538 current = {
539 family_label: familyMatch[1]!.trim(),
540 family_uid: familyMatch[2]!.trim(),
541 variants: [],
542 };
543 families.push(current);
544 continue;
545 }
546 if (!current || /^\s*aliases?:/iu.test(line)) continue;
547
548 const variantMatch = /^\s{2,}(\S+)\s+(.+?)(?:\s+\[(.*)\])?\s*$/u.exec(line);
549 if (!variantMatch) continue;
550 const modelUid = variantMatch[1]!.trim();
551 const label = variantMatch[2]!.trim();
552 if (!modelUid || !label || modelUid === "Available") continue;
553
554 const details = variantMatch[3] ?? "";
555 const contextMatch = /(\d+(?:\.\d+)?)\s*(k|m)?\s+context\b/iu.exec(details);
556 const contextWindowTokens = contextMatch
557 ? parseContextWindowTokens(`${contextMatch[1]}${contextMatch[2] ?? ""}`)
558 : undefined;
559 const pricingValues = new Map<string, number>();
560 const pricePattern = /\$\s*(\d+(?:\.\d+)?)\s*\/\s*1M\s*(Input|Cached\s+input|Output)\b/giu;
561 for (const match of details.matchAll(pricePattern)) {
562 const amount = Number(match[1]);
563 const kind = match[2]!.toLowerCase().replaceAll(/\s+/gu, " ");
564 if (Number.isFinite(amount)) pricingValues.set(kind, amount);
565 }
566 if (/\bfree\b/iu.test(details) && pricingValues.size === 0) {
567 pricingValues.set("input", 0);
568 pricingValues.set("output", 0);
569 }
570 current.variants.push({
571 model_uid: modelUid,
572 label,
573 ...(contextWindowTokens !== undefined ? { contextWindow: contextWindowTokens } : {}),
574 ...(pricingValues.size > 0
575 ? {
576 pricing: {
577 inputPerMillion: pricingValues.get("input") ?? 0,
578 cachedInputPerMillion: pricingValues.get("cached input"),
579 outputPerMillion: pricingValues.get("output") ?? 0,
580 },
581 }
582 : {}),
583 });
584 }
585
586 return families.length > 0 ? ({ families } as unknown as typeof DevinModelsPayload.Type) : null;
587}
588
589export function buildInitialDevinProviderSnapshot(
590 settings: DevinSettings,
591): Effect.Effect<ServerProviderDraft> {
592 return Effect.gen(function* () {
593 const checkedAt = DateTime.formatIso(yield* DateTime.now);
594 const models = providerModelsFromSettings([], settings.customModels, EMPTY_CAPABILITIES);
595 return buildServerProvider({
596 presentation: DEVIN_PRESENTATION,
597 enabled: settings.enabled,
598 checkedAt,
599 models,
600 probe: settings.enabled
601 ? {
602 installed: true,
603 version: null,
604 status: "warning",
605 auth: { status: "unknown" },
606 message: "Checking Devin CLI availability...",
607 }
608 : {
609 installed: false,
610 version: null,
611 status: "warning",
612 auth: { status: "unknown" },
613 message: "Devin is disabled in T3 Code settings.",
614 },
615 });
616 });
617}
618
619function runDevinCommand(
620 settings: Pick<DevinSettings, "binaryPath">,
621 args: ReadonlyArray<string>,
622 environment?: NodeJS.ProcessEnv,
623) {
624 return Effect.gen(function* () {
625 const command = settings.binaryPath || "devin";
626 const spawn = yield* resolveSpawnCommand(
627 command,
628 args,
629 environment ? { env: environment } : {},
630 );
631 return yield* spawnAndCollect(
632 command,
633 ChildProcess.make(spawn.command, spawn.args, {
634 ...(environment ? { env: environment } : { extendEnv: true }),
635 shell: spawn.shell,
636 }),
637 );
638 });
639}
640
641export function buildDevinModelsFromPayload(
642 payload: typeof DevinModelsPayload.Type,
643): ReadonlyArray<ServerProviderModel> {
644 const seen = new Set<string>();
645 const models: ServerProviderModel[] = [];
646
647 for (const family of payload.families) {
648 const subProvider = family.family_label.trim() || family.family_uid.trim();
649 const parsedFamilyVariants = family.variants
650 .map((candidate) => ({
651 uid: candidate.model_uid.trim(),
652 label: candidate.label.trim(),
653 parsed: parseDevinModelUid(candidate.model_uid),
654 }))
655 .filter((candidate) => candidate.uid.length > 0 && candidate.label.length > 0);
656 const familyHasReasoningVariants =
657 parsedFamilyVariants.length > 1 &&
658 parsedFamilyVariants.some(
659 (candidate) =>
660 candidate.parsed.reasoning !== undefined || labelHasReasoningSignal(candidate.label),
661 );
662 // A few Devin families use opaque/private UIDs that do not share a common
663 // suffix (for example MODEL_PRIVATE_2 + MODEL_PRIVATE_3 for a
664 // no-thinking/thinking pair). The unsuffixed variant is the best parent
665 // slug when present; otherwise use the first parsed base.
666 const familyGroupBase =
667 parsedFamilyVariants.find((candidate) => candidate.parsed.reasoning === undefined)?.parsed
668 .base ?? parsedFamilyVariants[0]?.parsed.base;
669
670 // Variants that share a base (+ speed tier) but differ only in reasoning
671 // level collapse into one selectable model. Track them here keyed by the
672 // group key, then emit a single ServerProviderModel with a `reasoning`
673 // option descriptor per group.
674 type DevinModelGroup = {
675 base: string;
676 reasoningLevels: Map<string, string>;
677 /** The first reasoning variant reported by Devin, or a reasoning
678 * level inferred from the family's unsuffixed canonical entry. */
679 firstReasoning?: string;
680 defaultReasoning?: string;
681 /** Some families use the unsuffixed UID for their no-thinking variant. */
682 hasCanonicalNoReasoning?: boolean;
683 /** Concrete UIDs for families whose reasoning variants are opaque. */
684 reasoningUids: Map<string, string>;
685 usesExplicitReasoningUids?: boolean;
686 speeds: Set<string>;
687 contexts: Set<string>;
688 defaultContextWindow?: string;
689 pricingByVariant: Map<string, ModelPricing>;
690 };
691 const groups = new Map<string, DevinModelGroup>();
692
693 for (const variant of family.variants) {
694 const uid = variant.model_uid.trim();
695 const label = variant.label.trim();
696 if (!uid || !label) continue;
697
698 const parsed = parseDevinModelUid(uid);
699 const rawVariant = variant as unknown as Record<string, unknown>;
700 const explicitContextTokens =
701 parseContextWindowTokens(rawVariant.context_window ?? rawVariant.contextWindow) ??
702 (parsed.contextWindow ? parseContext(parsed.contextWindow) * 1_000 : undefined);
703 const variantPricing = pricingWithContext(
704 parseDevinVariantPricing(rawVariant),
705 explicitContextTokens,
706 );
707 if (parsed.reasoning === undefined) {
708 if (familyHasReasoningVariants) {
709 const key = familyGroupBase ?? devinModelGroupKey(parsed);
710 const group =
711 groups.get(key) ??
712 (() => {
713 const defaultContext = DEVIN_DEFAULT_CONTEXT_WINDOWS[parsed.base];
714 const created: DevinModelGroup = {
715 base: key,
716 reasoningLevels: new Map<string, string>(),
717 reasoningUids: new Map<string, string>(),
718 speeds: new Set(["standard"]),
719 contexts: new Set<string>(),
720 ...(defaultContext ? { defaultContextWindow: defaultContext } : {}),
721 pricingByVariant: new Map<string, ModelPricing>(),
722 };
723 if (defaultContext) created.contexts.add(defaultContext);
724 if (variantPricing) created.pricingByVariant.set(uid, variantPricing);
725 groups.set(key, created);
726 return created;
727 })();
728 if (variantPricing) group.pricingByVariant.set(uid, variantPricing);
729 const contextOption = formatContextWindowOption(explicitContextTokens ?? 0);
730 if (contextOption) group.contexts.add(contextOption);
731 const inferredReasoning = inferReasoningFromLabel(label);
732 group.reasoningUids.set(inferredReasoning, uid);
733 if (parsed.base !== group.base) group.usesExplicitReasoningUids = true;
734 if (inferredReasoning === "none") {
735 group.hasCanonicalNoReasoning = true;
736 }
737 group.reasoningLevels.set(
738 inferredReasoning,
739 DEVIN_REASONING_LABELS[inferredReasoning] ?? capitalize(inferredReasoning),
740 );
741 // Some families (notably GLM-5.2) use an unsuffixed UID for their
742 // canonical/default reasoning level. Preserve that signal instead
743 // of letting the alphabetically/effort-sorted options choose None.
744 if (
745 inferredReasoning !== "none" &&
746 parsed.base === group.base &&
747 group.defaultReasoning === undefined
748 ) {
749 group.defaultReasoning = inferredReasoning;
750 }
751 if (parsed.contextWindow) group.contexts.add(parsed.contextWindow);
752 if (parsed.contextWindow && group.defaultContextWindow === undefined) {
753 group.defaultContextWindow = parsed.contextWindow;
754 }
755 continue;
756 }
757 // No reasoning suffix — a standalone model, emitted as-is.
758 if (seen.has(uid)) continue;
759 seen.add(uid);
760 const contextWindowTokens =
761 variantPricing?.contextWindowTokens ??
762 explicitContextTokens ??
763 inferDevinContextWindowTokens(uid);
764 models.push({
765 slug: uid,
766 name: label,
767 subProvider,
768 isCustom: false,
769 ...(uid === "adaptive" ? { isDefault: true } : {}),
770 capabilities: devinModelCapabilities(uid),
771 ...(variantPricing ? { pricing: variantPricing } : {}),
772 ...(contextWindowTokens !== undefined ? { contextWindowTokens } : {}),
773 } satisfies ServerProviderModel);
774 continue;
775 }
776
777 const key = familyGroupBase ?? devinModelGroupKey(parsed);
778 const group =
779 groups.get(key) ??
780 (() => {
781 const defaultContext = DEVIN_DEFAULT_CONTEXT_WINDOWS[parsed.base] ?? parsed.contextWindow;
782 const created: DevinModelGroup = {
783 base: key,
784 reasoningLevels: new Map<string, string>(),
785 reasoningUids: new Map<string, string>(),
786 speeds: new Set([parsed.speed ?? "standard"]),
787 contexts: new Set(parsed.contextWindow ? [parsed.contextWindow] : []),
788 ...(defaultContext ? { defaultContextWindow: defaultContext } : {}),
789 pricingByVariant: new Map<string, ModelPricing>(),
790 };
791 if (defaultContext) created.contexts.add(defaultContext);
792 groups.set(key, created);
793 return created;
794 })();
795 if (variantPricing) group.pricingByVariant.set(uid, variantPricing);
796 const contextOption = formatContextWindowOption(explicitContextTokens ?? 0);
797 if (contextOption) group.contexts.add(contextOption);
798 if (parsed.reasoning !== undefined && !group.reasoningLevels.has(parsed.reasoning)) {
799 const reasoning = parsed.reasoning;
800 if (!reasoning) continue;
801 if (group.firstReasoning === undefined) group.firstReasoning = reasoning;
802 group.reasoningLevels.set(
803 reasoning,
804 DEVIN_REASONING_LABELS[reasoning] ?? capitalize(reasoning),
805 );
806 group.reasoningUids.set(reasoning, uid);
807 if (parsed.base !== group.base) group.usesExplicitReasoningUids = true;
808 }
809 group.speeds.add(parsed.speed ?? "standard");
810 if (parsed.contextWindow) group.contexts.add(parsed.contextWindow);
811 if (parsed.contextWindow && group.defaultContextWindow === undefined) {
812 group.defaultContextWindow = parsed.contextWindow;
813 }
814 }
815
816 for (const [key, group] of groups) {
817 if (seen.has(key)) continue;
818 seen.add(key);
819
820 const orderedLevels = DEVIN_REASONING_LEVELS.filter((level) =>
821 group.reasoningLevels.has(level),
822 );
823 const defaultReasoning =
824 group.defaultReasoning ??
825 (group.hasCanonicalNoReasoning
826 ? "none"
827 : orderedLevels.includes("medium")
828 ? "medium"
829 : group.firstReasoning) ??
830 orderedLevels[0];
831 const choices: ProviderOptionChoice[] = orderedLevels.map((level) => {
832 const concreteUid = group.reasoningUids.get(level);
833 const optionId =
834 group.usesExplicitReasoningUids &&
835 concreteUid &&
836 parseDevinModelUid(concreteUid).base !== group.base
837 ? `__uid:${concreteUid}`
838 : level;
839 return {
840 id: optionId,
841 label: group.reasoningLevels.get(level)!,
842 ...(level === defaultReasoning ? { isDefault: true } : {}),
843 };
844 });
845
846 const reasoningDescriptor: SelectProviderOptionDescriptor = {
847 id: "reasoning",
848 label: "Reasoning",
849 type: "select",
850 options: choices,
851 };
852
853 const speedValues = ["standard", "fast", "priority"].filter((value) =>
854 group.speeds.has(value),
855 );
856 const contextValues = [...group.contexts].sort((a, b) => parseContext(a) - parseContext(b));
857 const optionDescriptors: SelectProviderOptionDescriptor[] = [reasoningDescriptor];
858 if (speedValues.length > 1) {
859 optionDescriptors.push({
860 id: "speed",
861 label: "Speed",
862 type: "select",
863 options: speedValues.map((value) => ({
864 id: value,
865 label: DEVIN_SPEED_LABELS[value] ?? capitalize(value),
866 ...(value === "standard" ? { isDefault: true } : {}),
867 })),
868 });
869 }
870 if (contextValues.length > 1) {
871 optionDescriptors.push({
872 id: "contextWindow",
873 label: "Context window",
874 type: "select",
875 options: contextValues.map((value, index) => ({
876 id: value,
877 label: value.toUpperCase(),
878 ...(value === (group.defaultContextWindow ?? contextValues[0] ?? "") ||
879 (group.defaultContextWindow === undefined && index === 0)
880 ? { isDefault: true }
881 : {}),
882 })),
883 });
884 }
885
886 const overrides = DEVIN_MODEL_INPUT_CAPABILITIES[group.base];
887 const pricingEntries = group.pricingByVariant;
888 const defaultPricing =
889 [...pricingEntries.entries()].find(([uid]) => {
890 const parsed = parseDevinModelUid(uid);
891 return (
892 (parsed.reasoning ?? "") === "medium" && (parsed.speed ?? "standard") === "standard"
893 );
894 })?.[1] ?? [...pricingEntries.values()][0];
895 const pricingContextWindowTokens = [...pricingEntries.values()]
896 .map((pricing) => pricing.contextWindowTokens)
897 .filter((value): value is number => value !== undefined)
898 .sort((left, right) => right - left)[0];
899 const contextWindowTokens =
900 (contextValues.length > 0
901 ? parseContext(contextValues[contextValues.length - 1]!) * 1_000
902 : undefined) ??
903 pricingContextWindowTokens ??
904 defaultPricing?.contextWindowTokens ??
905 inferDevinContextWindowTokens(group.base);
906 models.push({
907 slug: key,
908 name: subProvider,
909 subProvider,
910 isCustom: false,
911 ...(key === "adaptive" ? { isDefault: true } : {}),
912 capabilities: createModelCapabilities({
913 optionDescriptors,
914 ...overrides,
915 }),
916 ...(defaultPricing ? { pricing: defaultPricing } : {}),
917 ...(modelPricingRecord(pricingEntries)
918 ? { pricingByVariant: modelPricingRecord(pricingEntries) }
919 : {}),
920 ...(contextWindowTokens !== undefined ? { contextWindowTokens } : {}),
921 } satisfies ServerProviderModel);
922 }
923 }
924
925 return models;
926}
927
928function looksUnauthenticated(output: string): boolean {
929 const normalized = output.toLowerCase();
930 return (
931 normalized.includes("not authenticated") ||
932 normalized.includes("not logged in") ||
933 normalized.includes("log in") ||
934 normalized.includes("login required")
935 );
936}
937
938export const checkDevinProviderStatus = Effect.fn("checkDevinProviderStatus")(function* (
939 settings: DevinSettings,
940 environment?: NodeJS.ProcessEnv,
941): Effect.fn.Return<
942 ServerProviderDraft,
943 never,
944 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
945> {
946 const checkedAt = DateTime.formatIso(yield* DateTime.now);
947 const fallbackModels = providerModelsFromSettings([], settings.customModels, EMPTY_CAPABILITIES);
948
949 if (!settings.enabled) {
950 return yield* buildInitialDevinProviderSnapshot(settings);
951 }
952
953 const versionResult = yield* runDevinCommand(settings, ["--version"], environment).pipe(
954 Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
955 Effect.result,
956 );
957 if (Result.isFailure(versionResult)) {
958 const missing = isCommandMissingCause(versionResult.failure);
959 return buildServerProvider({
960 presentation: DEVIN_PRESENTATION,
961 enabled: true,
962 checkedAt,
963 models: fallbackModels,
964 probe: {
965 installed: !missing,
966 version: null,
967 status: "error",
968 auth: { status: "unknown" },
969 message: missing
970 ? "Devin CLI (`devin`) is not installed or not on PATH."
971 : "Failed to execute the Devin CLI health check.",
972 },
973 });
974 }
975 if (Option.isNone(versionResult.success)) {
976 return buildServerProvider({
977 presentation: DEVIN_PRESENTATION,
978 enabled: true,
979 checkedAt,
980 models: fallbackModels,
981 probe: {
982 installed: true,
983 version: null,
984 status: "error",
985 auth: { status: "unknown" },
986 message: "Devin CLI timed out while checking its version.",
987 },
988 });
989 }
990
991 const versionOutput = versionResult.success.value;
992 const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
993 if (versionOutput.code !== 0) {
994 return buildServerProvider({
995 presentation: DEVIN_PRESENTATION,
996 enabled: true,
997 checkedAt,
998 models: fallbackModels,
999 probe: {
1000 installed: true,
1001 version,
1002 status: "error",
1003 auth: { status: "unknown" },
1004 message: "Devin CLI is installed but failed to run.",
1005 },
1006 });
1007 }
1008
1009 const modelResult = yield* runDevinCommand(
1010 settings,
1011 ["models", "list", "--format", "json"],
1012 environment,
1013 ).pipe(Effect.timeoutOption(MODEL_PROBE_TIMEOUT_MS), Effect.result);
1014
1015 if (Result.isFailure(modelResult) || Option.isNone(modelResult.success)) {
1016 return buildServerProvider({
1017 presentation: DEVIN_PRESENTATION,
1018 enabled: true,
1019 checkedAt,
1020 models: fallbackModels,
1021 probe: {
1022 installed: true,
1023 version,
1024 status: "warning",
1025 auth: { status: "unknown" },
1026 message: "Devin is installed, but model discovery failed or timed out.",
1027 },
1028 });
1029 }
1030
1031 const output = modelResult.success.value;
1032 if (output.code !== 0) {
1033 const unauthenticated = looksUnauthenticated(`${output.stdout}\n${output.stderr}`);
1034 return buildServerProvider({
1035 presentation: DEVIN_PRESENTATION,
1036 enabled: true,
1037 checkedAt,
1038 models: fallbackModels,
1039 probe: {
1040 installed: true,
1041 version,
1042 status: "error",
1043 auth: { status: unauthenticated ? "unauthenticated" : "unknown" },
1044 message: unauthenticated
1045 ? "Devin CLI is not authenticated. Run `devin auth login`."
1046 : "Devin model discovery failed.",
1047 },
1048 });
1049 }
1050
1051 let decoded = yield* decodeDevinModels(output.stdout).pipe(Effect.option);
1052 // `--format json` was added after the first Devin CLI releases. If an older
1053 // binary ignores the flag (or returns a different JSON envelope), retry the
1054 // same probe without it and retain the pricing/context details from the
1055 // human-readable catalog.
1056 if (Option.isNone(decoded)) {
1057 const humanResult = yield* runDevinCommand(settings, ["models", "list"], environment).pipe(
1058 Effect.timeoutOption(MODEL_PROBE_TIMEOUT_MS),
1059 Effect.result,
1060 );
1061 if (Result.isSuccess(humanResult) && Option.isSome(humanResult.success)) {
1062 const humanOutput = humanResult.success.value;
1063 if (humanOutput.code === 0) {
1064 const parsedHuman = parseDevinHumanModelList(humanOutput.stdout);
1065 if (parsedHuman) decoded = Option.some(parsedHuman);
1066 }
1067 }
1068 }
1069 if (Option.isNone(decoded)) {
1070 return buildServerProvider({
1071 presentation: DEVIN_PRESENTATION,
1072 enabled: true,
1073 checkedAt,
1074 models: fallbackModels,
1075 probe: {
1076 installed: true,
1077 version,
1078 status: "warning",
1079 auth: { status: "authenticated" },
1080 message: "Devin returned an unrecognized model catalog.",
1081 },
1082 });
1083 }
1084
1085 return buildServerProvider({
1086 presentation: DEVIN_PRESENTATION,
1087 enabled: true,
1088 checkedAt,
1089 models: providerModelsFromSettings(
1090 buildDevinModelsFromPayload(decoded.value),
1091 settings.customModels,
1092 EMPTY_CAPABILITIES,
1093 ),
1094 probe: {
1095 installed: true,
1096 version,
1097 status: "ready",
1098 auth: { status: "authenticated" },
1099 },
1100 });
1101});