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

OhMyPiTextGeneration.ts

206 lines7.2 KB

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";
7import type * as EffectAcpErrors from "effect-acp/errors";
8​
9import { TextGenerationError, type OhMyPiSettings } from "@t3tools/contracts";
10import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
11import { extractJsonObject } from "@t3tools/shared/schemaJson";
12​
13import { makeOhMyPiAcpRuntime } from "../provider/acp/OhMyPiAcpSupport.ts";
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";
26​
27const TIMEOUT_MS = 180_000;
28const isTextGenerationError = Schema.is(TextGenerationError);
29​
30export const makeOhMyPiTextGeneration = Effect.fn("makeOhMyPiTextGeneration")(function* (
31 settings: OhMyPiSettings,
32 environment: NodeJS.ProcessEnv = process.env,
33) {
34 const crypto = yield* Crypto.Crypto;
35 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
36​
37 const runJson = <S extends Schema.Top>({
38 operation,
39 cwd,
40 prompt,
41 outputSchemaJson,
42 }: {
43 operation:
44 | "generateCommitMessage"
45 | "generatePrContent"
46 | "generateBranchName"
47 | "generateThreadTitle";
48 cwd: string;
49 prompt: string;
50 outputSchemaJson: S;
51 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
52 Effect.gen(function* () {
53 const outputRef = yield* Ref.make("");
54 const runtime = yield* makeOhMyPiAcpRuntime({
55 ohMyPiSettings: settings,
56 environment,
57 childProcessSpawner: spawner,
58 cwd,
59 clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
60 }).pipe(Effect.provideService(Crypto.Crypto, crypto));
61​
62 yield* runtime.handleSessionUpdate((notification) => {
63 const update = notification.update;
64 if (update.sessionUpdate !== "agent_message_chunk" || update.content.type !== "text") {
65 return Effect.void;
66 }
67 return Ref.update(outputRef, (current) => current + update.content.text);
68 });
69​
70 // Deliberately do not call setModel/setSessionModel. OMP chooses the
71 // underlying role/model according to its own configuration.
72 const result = yield* Effect.gen(function* () {
73 yield* runtime.start();
74 return yield* runtime.prompt({ prompt: [{ type: "text", text: prompt }] });
75 }).pipe(
76 Effect.timeoutOption(TIMEOUT_MS),
77 Effect.flatMap(
78 Option.match({
79 onNone: () =>
80 Effect.fail(new TextGenerationError({ operation, detail: "Oh My Pi ACP request timed out." })),
81 onSome: Effect.succeed,
82 }),
83 ),
84 Effect.mapError((cause: EffectAcpErrors.AcpError | TextGenerationError) =>
85 isTextGenerationError(cause)
86 ? cause
87 : new TextGenerationError({ operation, detail: "Oh My Pi ACP request failed.", cause }),
88 ),
89 );
90​
91 const trimmed = (yield* Ref.get(outputRef)).trim();
92 if (!trimmed) {
93 return yield* new TextGenerationError({
94 operation,
95 detail:
96 result.stopReason === "cancelled"
97 ? "Oh My Pi ACP request was cancelled."
98 : "Oh My Pi returned empty output.",
99 });
100 }
101​
102 return yield* Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))(
103 extractJsonObject(trimmed),
104 ).pipe(
105 Effect.catchTags({
106 SchemaError: (cause) =>
107 Effect.fail(
108 new TextGenerationError({
109 operation,
110 detail: "Oh My Pi returned invalid structured output.",
111 cause,
112 }),
113 ),
114 }),
115 );
116 }).pipe(
117 Effect.mapError((cause) =>
118 isTextGenerationError(cause)
119 ? cause
120 : new TextGenerationError({ operation, detail: "Oh My Pi text generation failed.", cause }),
121 ),
122 Effect.scoped,
123 );
124​
125 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
126 Effect.fn("OhMyPiTextGeneration.generateCommitMessage")(function* (input) {
127 const { prompt, outputSchema } = buildCommitMessagePrompt({
128 branch: input.branch,
129 stagedSummary: input.stagedSummary,
130 stagedPatch: input.stagedPatch,
131 includeBranch: input.includeBranch === true,
132 policy: input.policy,
133 });
134 const generated = yield* runJson({
135 operation: "generateCommitMessage",
136 cwd: input.cwd,
137 prompt,
138 outputSchemaJson: outputSchema,
139 });
140 return {
141 subject: sanitizeCommitSubject(generated.subject),
142 body: generated.body.trim(),
143 ...("branch" in generated && typeof generated.branch === "string"
144 ? { branch: sanitizeFeatureBranchName(generated.branch) }
145 : {}),
146 };
147 });
148​
149 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
150 Effect.fn("OhMyPiTextGeneration.generatePrContent")(function* (input) {
151 const { prompt, outputSchema } = buildPrContentPrompt({
152 baseBranch: input.baseBranch,
153 headBranch: input.headBranch,
154 commitSummary: input.commitSummary,
155 diffSummary: input.diffSummary,
156 diffPatch: input.diffPatch,
157 policy: input.policy,
158 changeRequestTemplate: input.changeRequestTemplate,
159 });
160 const generated = yield* runJson({
161 operation: "generatePrContent",
162 cwd: input.cwd,
163 prompt,
164 outputSchemaJson: outputSchema,
165 });
166 return { title: sanitizePrTitle(generated.title), body: generated.body.trim() };
167 });
168​
169 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
170 Effect.fn("OhMyPiTextGeneration.generateBranchName")(function* (input) {
171 const { prompt, outputSchema } = buildBranchNamePrompt({
172 message: input.message,
173 attachments: input.attachments,
174 });
175 const generated = yield* runJson({
176 operation: "generateBranchName",
177 cwd: input.cwd,
178 prompt,
179 outputSchemaJson: outputSchema,
180 });
181 return { branch: sanitizeBranchFragment(generated.branch) };
182 });
183​
184 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
185 Effect.fn("OhMyPiTextGeneration.generateThreadTitle")(function* (input) {
186 const { prompt, outputSchema } = buildThreadTitlePrompt({
187 message: input.message,
188 previousTitle: input.previousTitle,
189 attachments: input.attachments,
190 });
191 const generated = yield* runJson({
192 operation: "generateThreadTitle",
193 cwd: input.cwd,
194 prompt,
195 outputSchemaJson: outputSchema,
196 });
197 return { title: sanitizeThreadTitle(generated.title) };
198 });
199​
200 return {
201 generateCommitMessage,
202 generatePrContent,
203 generateBranchName,
204 generateThreadTitle,
205 } satisfies TextGeneration.TextGeneration["Service"];
206});