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

PiTextGeneration.ts

247 lines8.0 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 { ChildProcessSpawner } from "effect/unstable/process";
6​
7import { type ModelSelection, type PiSettings, TextGenerationError } from "@t3tools/contracts";
8import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
9import { extractJsonObject } from "@t3tools/shared/schemaJson";
10​
11import {
12 extractLastAssistantText,
13 makePiRpcTransport,
14 resolvePiThinkingLevel,
15} from "../provider/Layers/PiRpcClient.ts";
16import * as TextGeneration from "./TextGeneration.ts";
17import {
18 buildBranchNamePrompt,
19 buildCommitMessagePrompt,
20 buildPrContentPrompt,
21 buildThreadTitlePrompt,
22} from "./TextGenerationPrompts.ts";
23import {
24 sanitizeCommitSubject,
25 sanitizePrTitle,
26 sanitizeThreadTitle,
27 toJsonSchemaObject,
28} from "./TextGenerationUtils.ts";
29​
30const PI_TIMEOUT_MS = 180_000;
31const PI_LAST_TEXT_TIMEOUT_MS = 5_000;
32​
33type TextGenOperation =
34 | "generateCommitMessage"
35 | "generatePrContent"
36 | "generateBranchName"
37 | "generateThreadTitle";
38​
39const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
40const isTextGenerationError = Schema.is(TextGenerationError);
41​
42export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (
43 piSettings: PiSettings,
44 environment: NodeJS.ProcessEnv = process.env,
45) {
46 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
47​
48 const runPiPrompt = (input: {
49 readonly message: string;
50 readonly cwd: string;
51 readonly modelSelection: ModelSelection;
52 readonly operation: TextGenOperation;
53 }): Effect.Effect<string, TextGenerationError> =>
54 Effect.gen(function* () {
55 const transport = yield* makePiRpcTransport({
56 binaryPath: piSettings.binaryPath || "pi",
57 args: [
58 "--mode",
59 "rpc",
60 "--no-session",
61 "--no-tools",
62 "--no-extensions",
63 ...(resolvePiThinkingLevel(input.modelSelection)
64 ? ["--thinking", resolvePiThinkingLevel(input.modelSelection)!]
65 : []),
66 ...(input.modelSelection.model ? ["--model", input.modelSelection.model] : []),
67 ],
68 cwd: input.cwd,
69 env: environment,
70 onExit: Effect.void,
71 });
72 yield* transport.writeCommand({ type: "prompt", message: input.message });
73 yield* Stream.fromQueue(transport.messages).pipe(
74 Stream.takeUntil(
75 (message) =>
76 message._tag === "event" &&
77 message.event.type === "agent_end" &&
78 message.event.willRetry !== true,
79 ),
80 Stream.runDrain,
81 );
82 const response = yield* transport.request(
83 { type: "get_last_assistant_text" },
84 "pi-textgen-last-text",
85 PI_LAST_TEXT_TIMEOUT_MS,
86 );
87 return extractLastAssistantText(response) ?? "";
88 }).pipe(
89 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, commandSpawner),
90 Effect.scoped,
91 Effect.timeoutOption(PI_TIMEOUT_MS),
92 Effect.flatMap(
93 Option.match({
94 onNone: () =>
95 Effect.fail(
96 new TextGenerationError({
97 operation: input.operation,
98 detail: "Pi request timed out.",
99 }),
100 ),
101 onSome: (value) => Effect.succeed(value),
102 }),
103 ),
104 Effect.mapError((cause) =>
105 isTextGenerationError(cause)
106 ? cause
107 : new TextGenerationError({
108 operation: input.operation,
109 detail: "Pi RPC request failed.",
110 cause,
111 }),
112 ),
113 );
114​
115 const runPiJson = Effect.fn("runPiJson")(function* <S extends Schema.Top>({
116 operation,
117 cwd,
118 prompt,
119 outputSchemaJson,
120 modelSelection,
121 }: {
122 operation: TextGenOperation;
123 cwd: string;
124 prompt: string;
125 outputSchemaJson: S;
126 modelSelection: ModelSelection;
127 }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
128 const schemaJson = yield* encodeJsonString(toJsonSchemaObject(outputSchemaJson)).pipe(
129 Effect.mapError(
130 (cause) =>
131 new TextGenerationError({
132 operation,
133 detail: "Failed to encode structured output schema.",
134 cause,
135 }),
136 ),
137 );
138​
139 const rawResult = yield* runPiPrompt({
140 message:
141 `${prompt}\n\nRespond ONLY with minified JSON matching this schema. ` +
142 `No markdown, no code fences, no prose:\n${schemaJson}`,
143 cwd,
144 modelSelection,
145 operation,
146 });
147​
148 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
149 return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
150 Effect.catchTags({
151 SchemaError: (cause) =>
152 Effect.fail(
153 new TextGenerationError({
154 operation,
155 detail: "Pi returned invalid structured output.",
156 cause,
157 }),
158 ),
159 }),
160 );
161 });
162​
163 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
164 Effect.fn("PiTextGeneration.generateCommitMessage")(function* (input) {
165 const { prompt, outputSchema } = buildCommitMessagePrompt({
166 branch: input.branch,
167 stagedSummary: input.stagedSummary,
168 stagedPatch: input.stagedPatch,
169 includeBranch: input.includeBranch === true,
170 });
171 const generated = yield* runPiJson({
172 operation: "generateCommitMessage",
173 cwd: input.cwd,
174 prompt,
175 outputSchemaJson: outputSchema,
176 modelSelection: input.modelSelection,
177 });
178 return {
179 subject: sanitizeCommitSubject(generated.subject),
180 body: generated.body.trim(),
181 ...("branch" in generated && typeof generated.branch === "string"
182 ? { branch: sanitizeFeatureBranchName(generated.branch) }
183 : {}),
184 };
185 });
186​
187 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
188 Effect.fn("PiTextGeneration.generatePrContent")(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 const generated = yield* runPiJson({
197 operation: "generatePrContent",
198 cwd: input.cwd,
199 prompt,
200 outputSchemaJson: outputSchema,
201 modelSelection: input.modelSelection,
202 });
203 return {
204 title: sanitizePrTitle(generated.title),
205 body: generated.body.trim(),
206 };
207 });
208​
209 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
210 Effect.fn("PiTextGeneration.generateBranchName")(function* (input) {
211 const { prompt, outputSchema } = buildBranchNamePrompt({
212 message: input.message,
213 attachments: input.attachments,
214 });
215 const generated = yield* runPiJson({
216 operation: "generateBranchName",
217 cwd: input.cwd,
218 prompt,
219 outputSchemaJson: outputSchema,
220 modelSelection: input.modelSelection,
221 });
222 return { branch: sanitizeBranchFragment(generated.branch) };
223 });
224​
225 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
226 Effect.fn("PiTextGeneration.generateThreadTitle")(function* (input) {
227 const { prompt, outputSchema } = buildThreadTitlePrompt({
228 message: input.message,
229 attachments: input.attachments,
230 });
231 const generated = yield* runPiJson({
232 operation: "generateThreadTitle",
233 cwd: input.cwd,
234 prompt,
235 outputSchemaJson: outputSchema,
236 modelSelection: input.modelSelection,
237 });
238 return { title: sanitizeThreadTitle(generated.title) };
239 });
240​
241 return {
242 generateCommitMessage,
243 generatePrContent,
244 generateBranchName,
245 generateThreadTitle,
246 } satisfies TextGeneration.TextGeneration["Service"];
247});