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

PiTextGeneration.ts

277 lines8.1 KB

1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4import * as Stream from "effect/Stream";
5import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
6​
7import { type PiSettings, type ModelSelection, TextGenerationError } from "@t3tools/contracts";
8import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
9​
10import { type TextGenerationShape } from "./TextGeneration.ts";
11import {
12 buildBranchNamePrompt,
13 buildCommitMessagePrompt,
14 buildPrContentPrompt,
15 buildThreadTitlePrompt,
16} from "./TextGenerationPrompts.ts";
17import {
18 normalizeCliError,
19 sanitizeCommitSubject,
20 sanitizePrTitle,
21 sanitizeThreadTitle,
22 toJsonSchemaObject,
23} from "./TextGenerationUtils.ts";
24import { makePiEnvironment } from "../provider/Drivers/PiHome.ts";
25​
26const PI_TIMEOUT_MS = 180_000;
27​
28const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
29​
30export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (
31 piSettings: PiSettings,
32 environment: NodeJS.ProcessEnv = process.env,
33) {
34 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
35 const piEnvironment = yield* makePiEnvironment(piSettings, environment);
36​
37 const readStreamAsString = <E>(
38 operation: string,
39 stream: Stream.Stream<Uint8Array, E>,
40 ): Effect.Effect<string, TextGenerationError> =>
41 stream.pipe(
42 Stream.decodeText(),
43 Stream.runFold(
44 () => "",
45 (acc, chunk) => acc + chunk,
46 ),
47 Effect.mapError((cause) =>
48 normalizeCliError("pi", operation, cause, "Failed to collect process output"),
49 ),
50 );
51​
52 const runPiJson = Effect.fn("runPiJson")(function* <S extends Schema.Top>({
53 operation,
54 cwd,
55 prompt,
56 outputSchemaJson,
57 modelSelection,
58 }: {
59 operation:
60 | "generateCommitMessage"
61 | "generatePrContent"
62 | "generateBranchName"
63 | "generateThreadTitle";
64 cwd: string;
65 prompt: string;
66 outputSchemaJson: S;
67 modelSelection: ModelSelection;
68 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
69 const runPiCommand = Effect.fn("runPiJson.runPiCommand")(function* () {
70 const command = ChildProcess.make(
71 piSettings.binaryPath || "pi",
72 [
73 "--print",
74 "--output-format",
75 "json",
76 ...(modelSelection.model ? ["--model", modelSelection.model] : []),
77 ],
78 {
79 env: piEnvironment,
80 cwd,
81 shell: true,
82 stdin: {
83 stream: Stream.encodeText(
84 // @effect-diagnostics-next-line preferSchemaOverJson:off
85 Stream.make(
86 `${prompt}\n\nRespond ONLY with valid JSON matching this schema:\n${JSON.stringify(toJsonSchemaObject(outputSchemaJson))}`,
87 ),
88 ),
89 },
90 },
91 );
92​
93 const child = yield* commandSpawner
94 .spawn(command)
95 .pipe(
96 Effect.mapError((cause) =>
97 normalizeCliError("pi", operation, cause, "Failed to spawn Pi Agent CLI process"),
98 ),
99 );
100​
101 const [stdout, stderr, exitCode] = yield* Effect.all(
102 [
103 readStreamAsString(operation, child.stdout),
104 readStreamAsString(operation, child.stderr),
105 child.exitCode.pipe(
106 Effect.mapError((cause) =>
107 normalizeCliError("pi", operation, cause, "Failed to read Pi Agent CLI exit code"),
108 ),
109 ),
110 ],
111 { concurrency: "unbounded" },
112 );
113​
114 if (exitCode !== 0) {
115 const stderrDetail = stderr.trim();
116 const stdoutDetail = stdout.trim();
117 const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
118 return yield* new TextGenerationError({
119 operation,
120 detail:
121 detail.length > 0
122 ? `Pi Agent CLI command failed: ${detail}`
123 : `Pi Agent CLI command failed with code ${exitCode}.`,
124 });
125 }
126​
127 return stdout;
128 });
129​
130 const rawStdout = yield* runPiCommand().pipe(
131 Effect.scoped,
132 Effect.timeoutOption(PI_TIMEOUT_MS),
133 Effect.flatMap(
134 Option.match({
135 onNone: () =>
136 Effect.fail(
137 new TextGenerationError({ operation, detail: "Pi Agent CLI request timed out." }),
138 ),
139 onSome: (value) => Effect.succeed(value),
140 }),
141 ),
142 );
143​
144 const jsonMatch = rawStdout.match(/\{[\s\S]*\}/);
145 if (!jsonMatch) {
146 return yield* new TextGenerationError({
147 operation,
148 detail: "Pi Agent CLI did not return valid JSON output.",
149 });
150 }
151​
152 // @effect-diagnostics-next-line preferSchemaOverJson:off
153 const parsed = yield* Effect.try({
154 try: () => JSON.parse(jsonMatch[0]),
155 catch: (cause) =>
156 new TextGenerationError({
157 operation,
158 detail: "Pi Agent CLI returned malformed JSON.",
159 cause,
160 }),
161 });
162​
163 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
164 return yield* decodeOutput(parsed).pipe(
165 Effect.catchTag("SchemaError", (cause) =>
166 Effect.fail(
167 new TextGenerationError({
168 operation,
169 detail: "Pi Agent returned invalid structured output.",
170 cause,
171 }),
172 ),
173 ),
174 );
175 });
176​
177 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
178 "PiTextGeneration.generateCommitMessage",
179 )(function* (input) {
180 const { prompt, outputSchema } = buildCommitMessagePrompt({
181 branch: input.branch,
182 stagedSummary: input.stagedSummary,
183 stagedPatch: input.stagedPatch,
184 includeBranch: input.includeBranch === true,
185 });
186​
187 const generated = yield* runPiJson({
188 operation: "generateCommitMessage",
189 cwd: input.cwd,
190 prompt,
191 outputSchemaJson: outputSchema,
192 modelSelection: input.modelSelection,
193 });
194​
195 return {
196 subject: sanitizeCommitSubject(generated.subject),
197 body: generated.body.trim(),
198 ...("branch" in generated && typeof generated.branch === "string"
199 ? { branch: sanitizeFeatureBranchName(generated.branch) }
200 : {}),
201 };
202 });
203​
204 const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
205 "PiTextGeneration.generatePrContent",
206 )(function* (input) {
207 const { prompt, outputSchema } = buildPrContentPrompt({
208 baseBranch: input.baseBranch,
209 headBranch: input.headBranch,
210 commitSummary: input.commitSummary,
211 diffSummary: input.diffSummary,
212 diffPatch: input.diffPatch,
213 });
214​
215 const generated = yield* runPiJson({
216 operation: "generatePrContent",
217 cwd: input.cwd,
218 prompt,
219 outputSchemaJson: outputSchema,
220 modelSelection: input.modelSelection,
221 });
222​
223 return {
224 title: sanitizePrTitle(generated.title),
225 body: generated.body.trim(),
226 };
227 });
228​
229 const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
230 "PiTextGeneration.generateBranchName",
231 )(function* (input) {
232 const { prompt, outputSchema } = buildBranchNamePrompt({
233 message: input.message,
234 attachments: input.attachments,
235 });
236​
237 const generated = yield* runPiJson({
238 operation: "generateBranchName",
239 cwd: input.cwd,
240 prompt,
241 outputSchemaJson: outputSchema,
242 modelSelection: input.modelSelection,
243 });
244​
245 return {
246 branch: sanitizeBranchFragment(generated.branch),
247 };
248 });
249​
250 const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
251 "PiTextGeneration.generateThreadTitle",
252 )(function* (input) {
253 const { prompt, outputSchema } = buildThreadTitlePrompt({
254 message: input.message,
255 attachments: input.attachments,
256 });
257​
258 const generated = yield* runPiJson({
259 operation: "generateThreadTitle",
260 cwd: input.cwd,
261 prompt,
262 outputSchemaJson: outputSchema,
263 modelSelection: input.modelSelection,
264 });
265​
266 return {
267 title: sanitizeThreadTitle(generated.title),
268 };
269 });
270​
271 return {
272 generateCommitMessage,
273 generatePrContent,
274 generateBranchName,
275 generateThreadTitle,
276 } satisfies TextGenerationShape;
277});