Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6import * as Scope from "effect/Scope";
7import * as Stream from "effect/Stream";
8import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
9
10import { type CodexSettings, type ModelSelection } from "@piku/contracts";
11import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@piku/shared/git";
12
13import { resolveAttachmentPath } from "../attachmentStore.ts";
14import * as ServerConfig from "../config.ts";
15import { expandHomePath } from "../pathExpansion.ts";
16import { codexExecLaunchArgs, resolveCodexLaunchArgs } from "../provider/Layers/codexLaunchArgs.ts";
17import { TextGenerationError } from "@piku/contracts";
18import * as TextGeneration from "./TextGeneration.ts";
19import {
20 buildBranchNamePrompt,
21 buildCommitMessagePrompt,
22 buildPrContentPrompt,
23 buildThreadTitlePrompt,
24} from "./TextGenerationPrompts.ts";
25import {
26 normalizeCliError,
27 sanitizeCommitSubject,
28 sanitizePrTitle,
29 sanitizeThreadTitle,
30 toJsonSchemaObject,
31} from "./TextGenerationUtils.ts";
32import { getModelSelectionStringOptionValue } from "@piku/shared/model";
33import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
34
35const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
36const CODEX_TIMEOUT_MS = 180_000;
37const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
38/**
39 * Build a Codex text-generation closure bound to a specific `CodexSettings`
40 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
41 */
42export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* (
43 codexConfig: CodexSettings,
44 environment?: NodeJS.ProcessEnv,
45) {
46 const fileSystem = yield* FileSystem.FileSystem;
47 const path = yield* Path.Path;
48 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
49 const serverConfig = yield* Effect.service(ServerConfig.ServerConfig);
50 const resolvedEnvironment = environment ?? process.env;
51
52 type MaterializedImageAttachments = {
53 readonly imagePaths: ReadonlyArray<string>;
54 };
55
56 const readStreamAsString = <E>(
57 operation: string,
58 stream: Stream.Stream<Uint8Array, E>,
59 ): Effect.Effect<string, TextGenerationError> =>
60 stream.pipe(
61 Stream.decodeText(),
62 Stream.runFold(
63 () => "",
64 (acc, chunk) => acc + chunk,
65 ),
66 Effect.mapError((cause) =>
67 normalizeCliError("codex", operation, cause, "Failed to collect process output"),
68 ),
69 );
70
71 const writeTempFile = (
72 operation: string,
73 prefix: string,
74 content: string,
75 ): Effect.Effect<string, TextGenerationError, Scope.Scope> =>
76 fileSystem
77 .makeTempFileScoped({
78 prefix: `pikucode-${prefix}-${process.pid}-`,
79 })
80 .pipe(
81 Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
82 Effect.mapError(
83 (cause) =>
84 new TextGenerationError({
85 operation,
86 detail: `Failed to write temp file`,
87 cause,
88 }),
89 ),
90 );
91
92 const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
93 fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
94
95 const encodeJsonForOperation = (
96 operation:
97 | "generateCommitMessage"
98 | "generatePrContent"
99 | "generateBranchName"
100 | "generateThreadTitle",
101 value: unknown,
102 ): Effect.Effect<string, TextGenerationError> =>
103 encodeJsonString(value).pipe(
104 Effect.mapError(
105 (cause) =>
106 new TextGenerationError({
107 operation,
108 detail: "Failed to encode structured output schema.",
109 cause,
110 }),
111 ),
112 );
113
114 const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
115 _operation:
116 | "generateCommitMessage"
117 | "generatePrContent"
118 | "generateBranchName"
119 | "generateThreadTitle",
120 attachments: TextGeneration.BranchNameGenerationInput["attachments"],
121 ): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
122 if (!attachments || attachments.length === 0) {
123 return { imagePaths: [] };
124 }
125
126 const imagePaths: string[] = [];
127 for (const attachment of attachments) {
128 if (attachment.type !== "image") {
129 continue;
130 }
131
132 const resolvedPath = resolveAttachmentPath({
133 attachmentsDir: serverConfig.attachmentsDir,
134 attachment,
135 });
136 if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
137 continue;
138 }
139 const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));
140 if (!fileInfo || fileInfo.type !== "File") {
141 continue;
142 }
143 imagePaths.push(resolvedPath);
144 }
145 return { imagePaths };
146 });
147
148 const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
149 operation,
150 cwd,
151 prompt,
152 outputSchemaJson,
153 imagePaths = [],
154 cleanupPaths = [],
155 modelSelection,
156 }: {
157 operation:
158 | "generateCommitMessage"
159 | "generatePrContent"
160 | "generateBranchName"
161 | "generateThreadTitle";
162 cwd: string;
163 prompt: string;
164 outputSchemaJson: S;
165 imagePaths?: ReadonlyArray<string>;
166 cleanupPaths?: ReadonlyArray<string>;
167 modelSelection: ModelSelection;
168 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
169 const schemaJson = yield* encodeJsonForOperation(
170 operation,
171 toJsonSchemaObject(outputSchemaJson),
172 );
173 const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
174 const outputPath = yield* writeTempFile(operation, "codex-output", "");
175
176 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
177 const launchArgs = resolveCodexLaunchArgs(codexConfig.launchArgs, resolvedEnvironment);
178 const reasoningEffort =
179 getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
180 CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
181 const serviceTier = getCodexServiceTierOptionValue(modelSelection);
182 const command = ChildProcess.make(
183 codexConfig.binaryPath || "codex",
184 [
185 "exec",
186 ...codexExecLaunchArgs(launchArgs),
187 "--ephemeral",
188 "--skip-git-repo-check",
189 "-s",
190 "read-only",
191 "--model",
192 modelSelection.model,
193 "--config",
194 `model_reasoning_effort="${reasoningEffort}"`,
195 ...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
196 "--output-schema",
197 schemaPath,
198 "--output-last-message",
199 outputPath,
200 ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
201 "-",
202 ],
203 {
204 env: {
205 ...resolvedEnvironment,
206 ...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}),
207 },
208 cwd,
209 stdin: {
210 stream: Stream.encodeText(Stream.make(prompt)),
211 },
212 },
213 );
214
215 const child = yield* commandSpawner
216 .spawn(command)
217 .pipe(
218 Effect.mapError((cause) =>
219 normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
220 ),
221 );
222
223 const [stdout, stderr, exitCode] = yield* Effect.all(
224 [
225 readStreamAsString(operation, child.stdout),
226 readStreamAsString(operation, child.stderr),
227 child.exitCode.pipe(
228 Effect.mapError((cause) =>
229 normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
230 ),
231 ),
232 ],
233 { concurrency: "unbounded" },
234 );
235
236 if (exitCode !== 0) {
237 const stderrDetail = stderr.trim();
238 const stdoutDetail = stdout.trim();
239 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
240 return yield* new TextGenerationError({
241 operation,
242 detail:
243 detail.length > 0
244 ? `Codex CLI command failed: ${detail}`
245 : `Codex CLI command failed with code ${exitCode}.`,
246 });
247 }
248 });
249
250 const cleanup = Effect.all(
251 [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
252 {
253 concurrency: "unbounded",
254 },
255 ).pipe(Effect.asVoid);
256
257 return yield* Effect.gen(function* () {
258 yield* runCodexCommand().pipe(
259 Effect.scoped,
260 Effect.timeoutOption(CODEX_TIMEOUT_MS),
261 Effect.flatMap(
262 Option.match({
263 onNone: () =>
264 Effect.fail(
265 new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
266 ),
267 onSome: () => Effect.void,
268 }),
269 ),
270 );
271
272 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
273
274 return yield* fileSystem.readFileString(outputPath).pipe(
275 Effect.mapError(
276 (cause) =>
277 new TextGenerationError({
278 operation,
279 detail: "Failed to read Codex output file.",
280 cause,
281 }),
282 ),
283 Effect.flatMap(decodeOutput),
284 Effect.catchTags({
285 SchemaError: (cause) =>
286 Effect.fail(
287 new TextGenerationError({
288 operation,
289 detail: "Codex returned invalid structured output.",
290 cause,
291 }),
292 ),
293 }),
294 );
295 }).pipe(Effect.ensuring(cleanup));
296 });
297
298 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
299 Effect.fn("CodexTextGeneration.generateCommitMessage")(function* (input) {
300 const { prompt, outputSchema } = buildCommitMessagePrompt({
301 branch: input.branch,
302 stagedSummary: input.stagedSummary,
303 stagedPatch: input.stagedPatch,
304 includeBranch: input.includeBranch === true,
305 policy: input.policy,
306 });
307
308 const generated = yield* runCodexJson({
309 operation: "generateCommitMessage",
310 cwd: input.cwd,
311 prompt,
312 outputSchemaJson: outputSchema,
313 modelSelection: input.modelSelection,
314 });
315
316 return {
317 subject: sanitizeCommitSubject(generated.subject),
318 body: generated.body.trim(),
319 ...("branch" in generated && typeof generated.branch === "string"
320 ? { branch: sanitizeFeatureBranchName(generated.branch) }
321 : {}),
322 };
323 });
324
325 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
326 Effect.fn("CodexTextGeneration.generatePrContent")(function* (input) {
327 const { prompt, outputSchema } = buildPrContentPrompt({
328 baseBranch: input.baseBranch,
329 headBranch: input.headBranch,
330 commitSummary: input.commitSummary,
331 diffSummary: input.diffSummary,
332 diffPatch: input.diffPatch,
333 policy: input.policy,
334 changeRequestTemplate: input.changeRequestTemplate,
335 });
336
337 const generated = yield* runCodexJson({
338 operation: "generatePrContent",
339 cwd: input.cwd,
340 prompt,
341 outputSchemaJson: outputSchema,
342 modelSelection: input.modelSelection,
343 });
344
345 return {
346 title: sanitizePrTitle(generated.title),
347 body: generated.body.trim(),
348 };
349 });
350
351 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
352 Effect.fn("CodexTextGeneration.generateBranchName")(function* (input) {
353 const { imagePaths } = yield* materializeImageAttachments(
354 "generateBranchName",
355 input.attachments,
356 );
357 const { prompt, outputSchema } = buildBranchNamePrompt({
358 message: input.message,
359 attachments: input.attachments,
360 });
361
362 const generated = yield* runCodexJson({
363 operation: "generateBranchName",
364 cwd: input.cwd,
365 prompt,
366 outputSchemaJson: outputSchema,
367 imagePaths,
368 modelSelection: input.modelSelection,
369 });
370
371 return {
372 branch: sanitizeBranchFragment(generated.branch),
373 };
374 });
375
376 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
377 Effect.fn("CodexTextGeneration.generateThreadTitle")(function* (input) {
378 const { imagePaths } = yield* materializeImageAttachments(
379 "generateThreadTitle",
380 input.attachments,
381 );
382 const { prompt, outputSchema } = buildThreadTitlePrompt({
383 message: input.message,
384 previousTitle: input.previousTitle,
385 attachments: input.attachments,
386 });
387
388 const generated = yield* runCodexJson({
389 operation: "generateThreadTitle",
390 cwd: input.cwd,
391 prompt,
392 outputSchemaJson: outputSchema,
393 imagePaths,
394 modelSelection: input.modelSelection,
395 });
396
397 return {
398 title: sanitizeThreadTitle(generated.title),
399 } satisfies TextGeneration.ThreadTitleGenerationResult;
400 });
401
402 return {
403 generateCommitMessage,
404 generatePrContent,
405 generateBranchName,
406 generateThreadTitle,
407 } satisfies TextGeneration.TextGeneration["Service"];
408});