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

PiTextGeneration.ts

256 lines7.4 KB

1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import * as Ref from "effect/Ref";
4import * as Schema from "effect/Schema";
5import { ChildProcessSpawner } from "effect/unstable/process";
6​
7import { type PiSettings } from "@t3tools/contracts";
8import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
9import { extractJsonObject } from "@t3tools/shared/schemaJson";
10​
11import { TextGenerationError } from "@t3tools/contracts";
12import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
13import {
14 buildBranchNamePrompt,
15 buildCommitMessagePrompt,
16 buildPrContentPrompt,
17 buildThreadTitlePrompt,
18} from "./TextGenerationPrompts.ts";
19import {
20 sanitizeCommitSubject,
21 sanitizePrTitle,
22 sanitizeThreadTitle,
23} from "./TextGenerationUtils.ts";
24import { makePiAcpRuntime } from "../provider/acp/PiAcpSupport.ts";
25​
26const PI_TIMEOUT_MS = 180_000;
27​
28function mapPiAcpError(
29 operation:
30 | "generateCommitMessage"
31 | "generatePrContent"
32 | "generateBranchName"
33 | "generateThreadTitle",
34 detail: string,
35 cause: unknown,
36): TextGenerationError {
37 return new TextGenerationError({
38 operation,
39 detail,
40 ...(cause !== undefined ? { cause } : {}),
41 });
43​
44function isTextGenerationError(error: unknown): error is TextGenerationError {
45 return (
46 typeof error === "object" &&
47 error !== null &&
48 "_tag" in error &&
49 error._tag === "TextGenerationError"
50 );
52​
53/**
54 * Build a Pi text-generation closure bound to a specific `PiSettings`
55 * payload. See `makeCodexAdapter` for the overall per-instance rationale.
56 */
57export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (
58 piSettings: PiSettings,
59 environment: NodeJS.ProcessEnv = process.env,
60) {
61 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
62​
63 const runPiJson = <S extends Schema.Top>({
64 operation,
65 cwd,
66 prompt,
67 outputSchemaJson,
68 }: {
69 operation:
70 | "generateCommitMessage"
71 | "generatePrContent"
72 | "generateBranchName"
73 | "generateThreadTitle";
74 cwd: string;
75 prompt: string;
76 outputSchemaJson: S;
77 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
78 Effect.gen(function* () {
79 const outputRef = yield* Ref.make("");
80 const runtime = yield* makePiAcpRuntime({
81 piSettings,
82 environment,
83 childProcessSpawner: commandSpawner,
84 cwd,
85 clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
86 });
87​
88 yield* runtime.handleSessionUpdate((notification) => {
89 const update = notification.update;
90 if (update.sessionUpdate !== "agent_message_chunk") {
91 return Effect.void;
92 }
93 const content = update.content;
94 if (content.type !== "text") {
95 return Effect.void;
96 }
97 return Ref.update(outputRef, (current) => current + content.text);
98 });
99​
100 const promptResult = yield* Effect.gen(function* () {
101 yield* runtime.start();
102 yield* Effect.ignore(runtime.setMode("ask"));
103​
104 return yield* runtime.prompt({
105 prompt: [{ type: "text", text: prompt }],
106 });
107 }).pipe(
108 Effect.timeoutOption(PI_TIMEOUT_MS),
109 Effect.flatMap(
110 Option.match({
111 onNone: () =>
112 Effect.fail(
113 new TextGenerationError({
114 operation,
115 detail: "Pi Agent request timed out.",
116 }),
117 ),
118 onSome: (value) => Effect.succeed(value),
119 }),
120 ),
121 Effect.mapError((cause) =>
122 isTextGenerationError(cause)
123 ? cause
124 : mapPiAcpError(operation, "Pi ACP request failed.", cause),
125 ),
126 );
127​
128 const rawResult = (yield* Ref.get(outputRef)).trim();
129 if (!rawResult) {
130 return yield* new TextGenerationError({
131 operation,
132 detail:
133 promptResult.stopReason === "cancelled"
134 ? "Pi ACP request was cancelled."
135 : "Pi Agent returned empty output.",
136 });
137 }
138​
139 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
140 return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
141 Effect.catchTag("SchemaError", (cause) =>
142 Effect.fail(
143 new TextGenerationError({
144 operation,
145 detail: "Pi Agent returned invalid structured output.",
146 cause,
147 }),
148 ),
149 ),
150 );
151 }).pipe(
152 Effect.mapError((cause) =>
153 isTextGenerationError(cause)
154 ? cause
155 : mapPiAcpError(operation, "Pi ACP text generation failed.", cause),
156 ),
157 Effect.scoped,
158 );
159​
160 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
161 "PiTextGeneration.generateCommitMessage",
162 )(function* (input) {
163 const { prompt, outputSchema } = buildCommitMessagePrompt({
164 branch: input.branch,
165 stagedSummary: input.stagedSummary,
166 stagedPatch: input.stagedPatch,
167 includeBranch: input.includeBranch === true,
168 });
169​
170 const generated = yield* runPiJson({
171 operation: "generateCommitMessage",
172 cwd: input.cwd,
173 prompt,
174 outputSchemaJson: outputSchema,
175 });
176​
177 return {
178 subject: sanitizeCommitSubject(generated.subject),
179 body: generated.body.trim(),
180 ...("branch" in generated && typeof generated.branch === "string"
181 ? { branch: sanitizeFeatureBranchName(generated.branch) }
182 : {}),
183 };
184 });
185​
186 const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
187 "PiTextGeneration.generatePrContent",
188 )(function* (input) {
189 const { prompt, outputSchema } = buildPrContentPrompt({
190 baseBranch: input.baseBranch,
191 headBranch: input.headBranch,
192 commitSummary: input.commitSummary,
193 diffSummary: input.diffSummary,
194 diffPatch: input.diffPatch,
195 });
196​
197 const generated = yield* runPiJson({
198 operation: "generatePrContent",
199 cwd: input.cwd,
200 prompt,
201 outputSchemaJson: outputSchema,
202 });
203​
204 return {
205 title: sanitizePrTitle(generated.title),
206 body: generated.body.trim(),
207 };
208 });
209​
210 const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
211 "PiTextGeneration.generateBranchName",
212 )(function* (input) {
213 const { prompt, outputSchema } = buildBranchNamePrompt({
214 message: input.message,
215 attachments: input.attachments,
216 });
217​
218 const generated = yield* runPiJson({
219 operation: "generateBranchName",
220 cwd: input.cwd,
221 prompt,
222 outputSchemaJson: outputSchema,
223 });
224​
225 return {
226 branch: sanitizeBranchFragment(generated.branch),
227 };
228 });
229​
230 const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
231 "PiTextGeneration.generateThreadTitle",
232 )(function* (input) {
233 const { prompt, outputSchema } = buildThreadTitlePrompt({
234 message: input.message,
235 attachments: input.attachments,
236 });
237​
238 const generated = yield* runPiJson({
239 operation: "generateThreadTitle",
240 cwd: input.cwd,
241 prompt,
242 outputSchemaJson: outputSchema,
243 });
244​
245 return {
246 title: sanitizeThreadTitle(generated.title),
247 } satisfies ThreadTitleGenerationResult;
248 });
249​
250 return {
251 generateCommitMessage,
252 generatePrContent,
253 generateBranchName,
254 generateThreadTitle,
255 } satisfies TextGenerationShape;
256});