Open History to see the last commit
1import * as Crypto from "effect/Crypto";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Ref from "effect/Ref";
6import * as Schema from "effect/Schema";
7import { ChildProcessSpawner } from "effect/unstable/process";
8
9import { type DevinSettings, type ModelSelection } from "@t3tools/contracts";
10import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
11import { extractJsonObject } from "@t3tools/shared/schemaJson";
12
13import { TextGenerationError } from "@t3tools/contracts";
14import * as TextGeneration from "./TextGeneration.ts";
15import {
16 buildBranchNamePrompt,
17 buildCommitMessagePrompt,
18 buildPrContentPrompt,
19 buildThreadTitlePrompt,
20} from "./TextGenerationPrompts.ts";
21import {
22 sanitizeCommitSubject,
23 sanitizePrTitle,
24 sanitizeThreadTitle,
25} from "./TextGenerationUtils.ts";
26import {
27 applyDevinAcpModelSelection,
28 makeDevinAcpRuntime,
29} from "../provider/acp/DevinAcpSupport.ts";
30
31const DEVIN_TIMEOUT_MS = 180_000;
32
33const isTextGenerationError = Schema.is(TextGenerationError);
34
35export interface DevinTextGenerationOptions {
36 /** Override the ACP request timeout for focused tests and local diagnostics. */
37 readonly timeout?: Duration.Input;
38}
39
40/**
41 * Build a Devin text-generation closure bound to a specific `DevinSettings`
42 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
43 */
44export const makeDevinTextGeneration = Effect.fn("makeDevinTextGeneration")(function* (
45 devinSettings: DevinSettings,
46 environment?: NodeJS.ProcessEnv,
47 options?: DevinTextGenerationOptions,
48) {
49 const crypto = yield* Crypto.Crypto;
50 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
51 const resolvedEnvironment = environment ?? process.env;
52 const requestTimeout = options?.timeout ?? DEVIN_TIMEOUT_MS;
53
54 const runDevinJson = <S extends Schema.Top>({
55 operation,
56 cwd,
57 prompt,
58 outputSchemaJson,
59 modelSelection,
60 }: {
61 operation:
62 | "generateCommitMessage"
63 | "generatePrContent"
64 | "generateBranchName"
65 | "generateThreadTitle";
66 cwd: string;
67 prompt: string;
68 outputSchemaJson: S;
69 modelSelection: ModelSelection;
70 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
71 Effect.gen(function* () {
72 const outputRef = yield* Ref.make("");
73 const runtime = yield* makeDevinAcpRuntime({
74 devinSettings,
75 environment: resolvedEnvironment,
76 childProcessSpawner: commandSpawner,
77 cwd,
78 clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
79 }).pipe(Effect.provideService(Crypto.Crypto, crypto));
80
81 yield* runtime.handleSessionUpdate((notification) => {
82 const update = notification.update;
83 if (update.sessionUpdate !== "agent_message_chunk") {
84 return Effect.void;
85 }
86 const content = update.content;
87 if (content.type !== "text") {
88 return Effect.void;
89 }
90 return Ref.update(outputRef, (current) => current + content.text);
91 });
92
93 const promptResult = yield* Effect.gen(function* () {
94 yield* runtime.start();
95 yield* Effect.ignore(runtime.setMode("ask"));
96 yield* applyDevinAcpModelSelection({
97 runtime,
98 model: modelSelection.model,
99 selections: modelSelection.options,
100 mapError: ({ cause, configId }) =>
101 new TextGenerationError({
102 operation,
103 detail: `Failed to set Devin ACP config option "${configId}" for text generation.`,
104 cause,
105 }),
106 });
107
108 return yield* runtime.prompt({
109 prompt: [{ type: "text", text: prompt }],
110 });
111 }).pipe(
112 Effect.timeoutOption(requestTimeout),
113 Effect.flatMap(
114 Option.match({
115 onNone: () =>
116 Effect.fail(
117 new TextGenerationError({
118 operation,
119 detail: "Devin Agent request timed out.",
120 }),
121 ),
122 onSome: (value) => Effect.succeed(value),
123 }),
124 ),
125 Effect.mapError((cause) =>
126 isTextGenerationError(cause)
127 ? cause
128 : new TextGenerationError({
129 operation,
130 detail: "Devin ACP request failed.",
131 cause,
132 }),
133 ),
134 );
135
136 const rawResult = (yield* Ref.get(outputRef)).trim();
137 if (!rawResult) {
138 return yield* new TextGenerationError({
139 operation,
140 detail:
141 promptResult.stopReason === "cancelled"
142 ? "Devin ACP request was cancelled."
143 : "Devin Agent returned empty output.",
144 });
145 }
146
147 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
148 return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
149 Effect.catchTags({
150 SchemaError: (cause) =>
151 Effect.fail(
152 new TextGenerationError({
153 operation,
154 detail: "Devin Agent returned invalid structured output.",
155 cause,
156 }),
157 ),
158 }),
159 );
160 }).pipe(
161 Effect.mapError((cause) =>
162 isTextGenerationError(cause)
163 ? cause
164 : new TextGenerationError({
165 operation,
166 detail: "Devin ACP text generation failed.",
167 cause,
168 }),
169 ),
170 Effect.scoped,
171 );
172
173 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
174 Effect.fn("DevinTextGeneration.generateCommitMessage")(function* (input) {
175 const { prompt, outputSchema } = buildCommitMessagePrompt({
176 branch: input.branch,
177 stagedSummary: input.stagedSummary,
178 stagedPatch: input.stagedPatch,
179 includeBranch: input.includeBranch === true,
180 policy: input.policy,
181 });
182
183 const generated = yield* runDevinJson({
184 operation: "generateCommitMessage",
185 cwd: input.cwd,
186 prompt,
187 outputSchemaJson: outputSchema,
188 modelSelection: input.modelSelection,
189 });
190
191 return {
192 subject: sanitizeCommitSubject(generated.subject),
193 body: generated.body.trim(),
194 ...("branch" in generated && typeof generated.branch === "string"
195 ? { branch: sanitizeFeatureBranchName(generated.branch) }
196 : {}),
197 };
198 });
199
200 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
201 Effect.fn("DevinTextGeneration.generatePrContent")(function* (input) {
202 const { prompt, outputSchema } = buildPrContentPrompt({
203 baseBranch: input.baseBranch,
204 headBranch: input.headBranch,
205 commitSummary: input.commitSummary,
206 diffSummary: input.diffSummary,
207 diffPatch: input.diffPatch,
208 policy: input.policy,
209 changeRequestTemplate: input.changeRequestTemplate,
210 });
211
212 const generated = yield* runDevinJson({
213 operation: "generatePrContent",
214 cwd: input.cwd,
215 prompt,
216 outputSchemaJson: outputSchema,
217 modelSelection: input.modelSelection,
218 });
219
220 return {
221 title: sanitizePrTitle(generated.title),
222 body: generated.body.trim(),
223 };
224 });
225
226 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
227 Effect.fn("DevinTextGeneration.generateBranchName")(function* (input) {
228 const { prompt, outputSchema } = buildBranchNamePrompt({
229 message: input.message,
230 attachments: input.attachments,
231 });
232
233 const generated = yield* runDevinJson({
234 operation: "generateBranchName",
235 cwd: input.cwd,
236 prompt,
237 outputSchemaJson: outputSchema,
238 modelSelection: input.modelSelection,
239 });
240
241 return {
242 branch: sanitizeBranchFragment(generated.branch),
243 };
244 });
245
246 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
247 Effect.fn("DevinTextGeneration.generateThreadTitle")(function* (input) {
248 const { prompt, outputSchema } = buildThreadTitlePrompt({
249 message: input.message,
250 previousTitle: input.previousTitle,
251 attachments: input.attachments,
252 });
253
254 const generated = yield* runDevinJson({
255 operation: "generateThreadTitle",
256 cwd: input.cwd,
257 prompt,
258 outputSchemaJson: outputSchema,
259 modelSelection: input.modelSelection,
260 });
261
262 return {
263 title: sanitizeThreadTitle(generated.title),
264 } satisfies TextGeneration.ThreadTitleGenerationResult;
265 });
266
267 return {
268 generateCommitMessage,
269 generatePrContent,
270 generateBranchName,
271 generateThreadTitle,
272 } satisfies TextGeneration.TextGeneration["Service"];
273});