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 Schema from "effect/Schema";
5import * as Stream from "effect/Stream";
6import { ChildProcessSpawner } from "effect/unstable/process";
7
8import {
9 type ChatAttachment,
10 type ModelSelection,
11 type PiSettings,
12 TextGenerationError,
13} from "@t3tools/contracts";
14import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
15import { extractJsonObject } from "@t3tools/shared/schemaJson";
16
17import { resolveAttachmentPath } from "../attachmentStore.ts";
18import * as ServerConfig from "../config.ts";
19import {
20 extractLastAssistantText,
21 makePiRpcTransport,
22 piImageContentFromBytes,
23 type PiImageContent,
24} from "../provider/Layers/PiRpcClient.ts";
25import { type TextGenerationShape } from "./TextGeneration.ts";
26import {
27 buildBranchNamePrompt,
28 buildCommitMessagePrompt,
29 buildPrContentPrompt,
30 buildThreadTitlePrompt,
31} from "./TextGenerationPrompts.ts";
32import {
33 sanitizeCommitSubject,
34 sanitizePrTitle,
35 sanitizeThreadTitle,
36 toJsonSchemaObject,
37} from "./TextGenerationUtils.ts";
38
39const PI_TIMEOUT_MS = 180_000;
40const PI_LAST_TEXT_TIMEOUT_MS = 5_000;
41
42type TextGenOperation =
43 | "generateCommitMessage"
44 | "generatePrContent"
45 | "generateBranchName"
46 | "generateThreadTitle";
47
48const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
49const isTextGenerationError = Schema.is(TextGenerationError);
50
51export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (
52 piSettings: PiSettings,
53 environment: NodeJS.ProcessEnv = process.env,
54) {
55 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
56 const fileSystem = yield* FileSystem.FileSystem;
57 const serverConfig = yield* ServerConfig.ServerConfig;
58
59 const materializePiImages = Effect.fn("materializePiImages")(function* (
60 operation: TextGenOperation,
61 attachments: ReadonlyArray<ChatAttachment> | undefined,
62 ): Effect.fn.Return<ReadonlyArray<PiImageContent>, TextGenerationError> {
63 const images: Array<PiImageContent> = [];
64 for (const attachment of attachments ?? []) {
65 if (attachment.type !== "image") continue;
66
67 const attachmentPath = resolveAttachmentPath({
68 attachmentsDir: serverConfig.attachmentsDir,
69 attachment,
70 });
71 if (!attachmentPath) {
72 return yield* new TextGenerationError({
73 operation,
74 detail: `Invalid attachment id '${attachment.id}'.`,
75 });
76 }
77 const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
78 Effect.mapError(
79 (cause) =>
80 new TextGenerationError({
81 operation,
82 detail: `Failed to read attachment '${attachment.id}'.`,
83 cause,
84 }),
85 ),
86 );
87 images.push(piImageContentFromBytes({ mimeType: attachment.mimeType, bytes }));
88 }
89 return images;
90 });
91
92 const runPiPrompt = (input: {
93 readonly message: string;
94 readonly cwd: string;
95 readonly modelSelection: ModelSelection;
96 readonly operation: TextGenOperation;
97 readonly images?: ReadonlyArray<PiImageContent>;
98 }): Effect.Effect<string, TextGenerationError> =>
99 Effect.gen(function* () {
100 const transport = yield* makePiRpcTransport({
101 binaryPath: piSettings.binaryPath || "pi",
102 args: [
103 "--mode",
104 "rpc",
105 "--no-session",
106 "--no-tools",
107 "--no-extensions",
108 "--thinking",
109 "off",
110 ...(input.modelSelection.model ? ["--model", input.modelSelection.model] : []),
111 ],
112 cwd: input.cwd,
113 env: environment,
114 onExit: Effect.void,
115 });
116 yield* transport.writeCommand({
117 type: "prompt",
118 message: input.message,
119 ...(input.images !== undefined && input.images.length > 0
120 ? { images: [...input.images] }
121 : {}),
122 });
123 yield* Stream.fromQueue(transport.messages).pipe(
124 Stream.takeUntil(
125 (message) =>
126 message._tag === "event" &&
127 message.event.type === "agent_end" &&
128 message.event.willRetry !== true,
129 ),
130 Stream.runDrain,
131 );
132 if (yield* transport.isClosed) {
133 return yield* new TextGenerationError({
134 operation: input.operation,
135 detail: "Pi RPC process exited before completing the request.",
136 });
137 }
138 const response = yield* transport.request(
139 { type: "get_last_assistant_text" },
140 "pi-textgen-last-text",
141 PI_LAST_TEXT_TIMEOUT_MS,
142 );
143 return extractLastAssistantText(response) ?? "";
144 }).pipe(
145 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, commandSpawner),
146 Effect.scoped,
147 Effect.timeoutOption(PI_TIMEOUT_MS),
148 Effect.flatMap(
149 Option.match({
150 onNone: () =>
151 Effect.fail(
152 new TextGenerationError({
153 operation: input.operation,
154 detail: "Pi request timed out.",
155 }),
156 ),
157 onSome: (value) => Effect.succeed(value),
158 }),
159 ),
160 Effect.mapError((cause) =>
161 isTextGenerationError(cause)
162 ? cause
163 : new TextGenerationError({
164 operation: input.operation,
165 detail: "Pi RPC request failed.",
166 cause,
167 }),
168 ),
169 Effect.catchDefect((cause) =>
170 Effect.fail(
171 new TextGenerationError({
172 operation: input.operation,
173 detail: "Pi RPC request failed.",
174 cause,
175 }),
176 ),
177 ),
178 );
179
180 const runPiJson = Effect.fn("runPiJson")(function* <S extends Schema.Top>({
181 operation,
182 cwd,
183 prompt,
184 outputSchemaJson,
185 modelSelection,
186 images,
187 }: {
188 operation: TextGenOperation;
189 cwd: string;
190 prompt: string;
191 outputSchemaJson: S;
192 modelSelection: ModelSelection;
193 images?: ReadonlyArray<PiImageContent>;
194 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
195 const schemaJson = yield* encodeJsonString(toJsonSchemaObject(outputSchemaJson)).pipe(
196 Effect.mapError(
197 (cause) =>
198 new TextGenerationError({
199 operation,
200 detail: "Failed to encode structured output schema.",
201 cause,
202 }),
203 ),
204 );
205
206 const rawResult = yield* runPiPrompt({
207 message:
208 `${prompt}\n\nRespond ONLY with minified JSON matching this schema. ` +
209 `No markdown, no code fences, no prose:\n${schemaJson}`,
210 cwd,
211 modelSelection,
212 operation,
213 ...(images !== undefined ? { images } : {}),
214 });
215
216 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
217 return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
218 Effect.catchTags({
219 SchemaError: (cause) =>
220 Effect.fail(
221 new TextGenerationError({
222 operation,
223 detail: "Pi returned invalid structured output.",
224 cause,
225 }),
226 ),
227 }),
228 );
229 });
230
231 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
232 "PiTextGeneration.generateCommitMessage",
233 )(function* (input) {
234 const { prompt, outputSchema } = buildCommitMessagePrompt({
235 branch: input.branch,
236 stagedSummary: input.stagedSummary,
237 stagedPatch: input.stagedPatch,
238 includeBranch: input.includeBranch === true,
239 });
240 const generated = yield* runPiJson({
241 operation: "generateCommitMessage",
242 cwd: input.cwd,
243 prompt,
244 outputSchemaJson: outputSchema,
245 modelSelection: input.modelSelection,
246 });
247 return {
248 subject: sanitizeCommitSubject(generated.subject),
249 body: generated.body.trim(),
250 ...("branch" in generated && typeof generated.branch === "string"
251 ? { branch: sanitizeFeatureBranchName(generated.branch) }
252 : {}),
253 };
254 });
255
256 const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
257 "PiTextGeneration.generatePrContent",
258 )(function* (input) {
259 const { prompt, outputSchema } = buildPrContentPrompt({
260 baseBranch: input.baseBranch,
261 headBranch: input.headBranch,
262 commitSummary: input.commitSummary,
263 diffSummary: input.diffSummary,
264 diffPatch: input.diffPatch,
265 });
266 const generated = yield* runPiJson({
267 operation: "generatePrContent",
268 cwd: input.cwd,
269 prompt,
270 outputSchemaJson: outputSchema,
271 modelSelection: input.modelSelection,
272 });
273 return {
274 title: sanitizePrTitle(generated.title),
275 body: generated.body.trim(),
276 };
277 });
278
279 const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
280 "PiTextGeneration.generateBranchName",
281 )(function* (input) {
282 const images = yield* materializePiImages("generateBranchName", input.attachments);
283 const { prompt, outputSchema } = buildBranchNamePrompt({
284 message: input.message,
285 attachments: input.attachments,
286 });
287 const generated = yield* runPiJson({
288 operation: "generateBranchName",
289 cwd: input.cwd,
290 prompt,
291 outputSchemaJson: outputSchema,
292 modelSelection: input.modelSelection,
293 images,
294 });
295 return { branch: sanitizeBranchFragment(generated.branch) };
296 });
297
298 const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
299 "PiTextGeneration.generateThreadTitle",
300 )(function* (input) {
301 const images = yield* materializePiImages("generateThreadTitle", input.attachments);
302 const { prompt, outputSchema } = buildThreadTitlePrompt({
303 message: input.message,
304 attachments: input.attachments,
305 });
306 const generated = yield* runPiJson({
307 operation: "generateThreadTitle",
308 cwd: input.cwd,
309 prompt,
310 outputSchemaJson: outputSchema,
311 modelSelection: input.modelSelection,
312 images,
313 });
314 return { title: sanitizeThreadTitle(generated.title) };
315 });
316
317 return {
318 generateCommitMessage,
319 generatePrContent,
320 generateBranchName,
321 generateThreadTitle,
322 } satisfies TextGenerationShape;
323});