Open History to see the last commit
1import * as Crypto from "effect/Crypto";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Ref from "effect/Ref";
5import * as Schema from "effect/Schema";
6import { ChildProcessSpawner } from "effect/unstable/process";
7
8import { type OmpSettings, type ModelSelection } from "@t3tools/contracts";
9import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
10import { extractJsonObject } from "@t3tools/shared/schemaJson";
11
12import { TextGenerationError } from "@t3tools/contracts";
13import * as TextGeneration from "./TextGeneration.ts";
14import {
15 buildBranchNamePrompt,
16 buildCommitMessagePrompt,
17 buildPrContentPrompt,
18 buildThreadTitlePrompt,
19} from "./TextGenerationPrompts.ts";
20import {
21 sanitizeCommitSubject,
22 sanitizePrTitle,
23 sanitizeThreadTitle,
24} from "./TextGenerationUtils.ts";
25import { applyOmpAcpModelSelection, makeOmpAcpRuntime } from "../provider/acp/OmpAcpSupport.ts";
26
27const OMP_TIMEOUT_MS = 180_000;
28
29const isTextGenerationError = Schema.is(TextGenerationError);
30
31/**
32 * Build an Oh My Pi text-generation closure bound to a specific `OmpSettings`
33 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
34 */
35export const makeOmpTextGeneration = Effect.fn("makeOmpTextGeneration")(function* (
36 ompSettings: OmpSettings,
37 environment?: NodeJS.ProcessEnv,
38) {
39 const crypto = yield* Crypto.Crypto;
40 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
41 const resolvedEnvironment = environment ?? process.env;
42
43 const runOmpJson = <S extends Schema.Top>({
44 operation,
45 cwd,
46 prompt,
47 outputSchemaJson,
48 modelSelection,
49 }: {
50 operation:
51 | "generateCommitMessage"
52 | "generatePrContent"
53 | "generateBranchName"
54 | "generateThreadTitle";
55 cwd: string;
56 prompt: string;
57 outputSchemaJson: S;
58 modelSelection: ModelSelection;
59 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
60 Effect.gen(function* () {
61 const outputRef = yield* Ref.make("");
62 const runtime = yield* makeOmpAcpRuntime({
63 ompSettings,
64 environment: resolvedEnvironment,
65 childProcessSpawner: commandSpawner,
66 cwd,
67 // Background text generation is unattended: nobody can answer an
68 // approval prompt, and this path registers no permission/elicitation
69 // handlers. `--auto-approve` keeps omp's wrapper layer and permission
70 // gate from ever pausing the one-shot generation.
71 runtimeMode: "auto",
72 // Without the elicitation capability omp's non-approval select()
73 // resolves immediately with undefined (fast, clear failure) instead
74 // of queueing onto a channel nobody answers until the 180s timeout.
75 enableElicitation: false,
76 clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
77 }).pipe(Effect.provideService(Crypto.Crypto, crypto));
78
79 yield* runtime.handleSessionUpdate((notification) => {
80 const update = notification.update;
81 if (update.sessionUpdate !== "agent_message_chunk") {
82 return Effect.void;
83 }
84 const content = update.content;
85 if (content.type !== "text") {
86 return Effect.void;
87 }
88 return Ref.update(outputRef, (current) => current + content.text);
89 });
90
91 const promptResult = yield* Effect.gen(function* () {
92 yield* runtime.start();
93 // No mode override: omp only has default/plan and the default mode is
94 // the right one for one-shot generation. The requested model passes
95 // through; when none is requested the CLI's current model wins.
96 yield* applyOmpAcpModelSelection({
97 runtime,
98 model: modelSelection.model,
99 selections: modelSelection.options,
100 mapError: ({ cause, configId }) =>
101 new TextGenerationError({
102 operation,
103 detail: `Failed to set Oh My Pi 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(OMP_TIMEOUT_MS),
113 Effect.flatMap(
114 Option.match({
115 onNone: () =>
116 Effect.fail(
117 new TextGenerationError({
118 operation,
119 detail: "Oh My Pi 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: "Oh My Pi 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 ? "Oh My Pi ACP request was cancelled."
143 : "Oh My Pi 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: "Oh My Pi 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: "Oh My Pi ACP text generation failed.",
167 cause,
168 }),
169 ),
170 Effect.scoped,
171 );
172
173 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
174 Effect.fn("OmpTextGeneration.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* runOmpJson({
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("OmpTextGeneration.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* runOmpJson({
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("OmpTextGeneration.generateBranchName")(function* (input) {
228 const { prompt, outputSchema } = buildBranchNamePrompt({
229 message: input.message,
230 attachments: input.attachments,
231 });
232
233 const generated = yield* runOmpJson({
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("OmpTextGeneration.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* runOmpJson({
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});