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

PiTextGeneration.ts

261 lines9.3 KB

1/**
2 * PiTextGeneration — commit messages, PR content, branch names, and thread
3 * titles generated through an ephemeral `pi --mode rpc --no-session` process.
4 * No session file is written; the user's Pi configuration (default model,
5 * auth, custom providers) still applies.
6 */
7import * as Effect from "effect/Effect";
8import * as Option from "effect/Option";
9import * as Queue from "effect/Queue";
10import * as Schema from "effect/Schema";
11import { ChildProcessSpawner } from "effect/unstable/process";
12​
13import { TextGenerationError, type ModelSelection, type PiSettings } from "@t3tools/contracts";
14import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
15import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
16import { extractJsonObject } from "@t3tools/shared/schemaJson";
17​
18import { isPiThinkingLevel } from "../provider/Layers/piThinkingCapabilities.ts";
19import { makePiRpcConnection, parsePiModelSlug } from "../provider/PiRpc.ts";
20import { buildPiRpcLaunch, resolvePiLaunchArgs } from "../provider/piT3McpInjection.ts";
21import * as TextGeneration from "./TextGeneration.ts";
22import {
23 buildBranchNamePrompt,
24 buildCommitMessagePrompt,
25 buildPrContentPrompt,
26 buildThreadTitlePrompt,
27} from "./TextGenerationPrompts.ts";
28import {
29 sanitizeCommitSubject,
30 sanitizePrTitle,
31 sanitizeThreadTitle,
32} from "./TextGenerationUtils.ts";
33​
34const PI_TIMEOUT_MS = 180_000;
35​
36const isTextGenerationError = Schema.is(TextGenerationError);
37​
38export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (
39 piSettings: PiSettings,
40 environment: NodeJS.ProcessEnv = process.env,
41) {
42 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
43​
44 const runPiJson = <S extends Schema.Top>({
45 operation,
46 cwd,
47 prompt,
48 outputSchemaJson,
49 modelSelection,
50 }: {
51 operation:
52 | "generateCommitMessage"
53 | "generatePrContent"
54 | "generateBranchName"
55 | "generateThreadTitle";
56 cwd: string;
57 prompt: string;
58 outputSchemaJson: S;
59 modelSelection: ModelSelection;
60 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
61 Effect.gen(function* () {
62 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
63 if (!resolvedLaunchArgs.ok) {
64 return yield* new TextGenerationError({
65 operation,
66 detail: resolvedLaunchArgs.message,
67 });
68 }
69 const launch = buildPiRpcLaunch({
70 launchArgs: resolvedLaunchArgs.args,
71 environment,
72 mcpSession: undefined,
73 extensionPath: undefined,
74 ephemeral: true,
75 // No user is present to answer a text-generation extension dialog.
76 disableExtensions: true,
77 // Background naming/content helpers must never mutate the workspace.
78 disableTools: true,
79 });
80 const connection = yield* makePiRpcConnection({
81 command: piSettings.binaryPath || "pi",
82 // Extensions and tools are disabled because no user is present to
83 // answer a dialog and background text generation is read-only. User
84 // model config and auth still apply.
85 args: launch.args,
86 cwd,
87 env: launch.env,
88 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
89​
90 if (modelSelection.model !== "default") {
91 // `customModels` accepts arbitrary strings, so an unusable slug is
92 // rejected rather than skipped: running Pi's default model here would
93 // report success for a model the caller never asked for.
94 const parsed = parsePiModelSlug(modelSelection.model);
95 if (parsed === null) {
96 return yield* new TextGenerationError({
97 operation,
98 detail: `Pi model '${modelSelection.model}' must use provider/model format.`,
99 });
100 }
101 yield* connection.request({
102 type: "set_model",
103 provider: parsed.provider,
104 modelId: parsed.modelId,
105 });
106 }
107 // Pi clamps a level the model lacks, so any known level is safe to send.
108 const thinking = getModelSelectionStringOptionValue(modelSelection, "thinking");
109 if (thinking !== undefined && isPiThinkingLevel(thinking)) {
110 yield* connection.request({ type: "set_thinking_level", level: thinking });
111 }
112​
113 yield* connection.request({ type: "prompt", message: prompt });
114 yield* Effect.gen(function* () {
115 while (true) {
116 const event = yield* Queue.take(connection.events);
117 if (event["type"] === "agent_settled") return;
118 }
119 });
120 const data = yield* connection.request({ type: "get_last_assistant_text" });
121 const text =
122 typeof data === "object" &&
123 data !== null &&
124 typeof (data as { text?: unknown }).text === "string"
125 ? (data as { text: string }).text.trim()
126 : "";
127 if (!text) {
128 return yield* new TextGenerationError({
129 operation,
130 detail: "Pi returned empty output.",
131 });
132 }
133 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
134 return yield* decodeOutput(extractJsonObject(text)).pipe(
135 Effect.catchTags({
136 SchemaError: (cause) =>
137 Effect.fail(
138 new TextGenerationError({
139 operation,
140 detail: "Pi returned invalid structured output.",
141 cause,
142 }),
143 ),
144 }),
145 );
146 }).pipe(
147 Effect.timeoutOption(PI_TIMEOUT_MS),
148 Effect.flatMap(
149 Option.match({
150 onNone: () =>
151 Effect.fail(new TextGenerationError({ operation, detail: "Pi request timed out." })),
152 onSome: (value) => Effect.succeed(value),
153 }),
154 ),
155 Effect.mapError((cause) =>
156 isTextGenerationError(cause)
157 ? cause
158 : new TextGenerationError({
159 operation,
160 detail: "Pi text generation failed.",
161 cause,
162 }),
163 ),
164 Effect.scoped,
165 );
166​
167 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
168 Effect.fn("PiTextGeneration.generateCommitMessage")(function* (input) {
169 const { prompt, outputSchema } = buildCommitMessagePrompt({
170 branch: input.branch,
171 stagedSummary: input.stagedSummary,
172 stagedPatch: input.stagedPatch,
173 includeBranch: input.includeBranch === true,
174 policy: input.policy,
175 });
176 const generated = yield* runPiJson({
177 operation: "generateCommitMessage",
178 cwd: input.cwd,
179 prompt,
180 outputSchemaJson: outputSchema,
181 modelSelection: input.modelSelection,
182 });
183 return {
184 subject: sanitizeCommitSubject(generated.subject),
185 body: generated.body.trim(),
186 ...("branch" in generated && typeof generated.branch === "string"
187 ? { branch: sanitizeFeatureBranchName(generated.branch) }
188 : {}),
189 };
190 });
191​
192 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
193 Effect.fn("PiTextGeneration.generatePrContent")(function* (input) {
194 const { prompt, outputSchema } = buildPrContentPrompt({
195 baseBranch: input.baseBranch,
196 headBranch: input.headBranch,
197 commitSummary: input.commitSummary,
198 diffSummary: input.diffSummary,
199 diffPatch: input.diffPatch,
200 policy: input.policy,
201 changeRequestTemplate: input.changeRequestTemplate,
202 });
203 const generated = yield* runPiJson({
204 operation: "generatePrContent",
205 cwd: input.cwd,
206 prompt,
207 outputSchemaJson: outputSchema,
208 modelSelection: input.modelSelection,
209 });
210 return {
211 title: sanitizePrTitle(generated.title),
212 body: generated.body.trim(),
213 };
214 });
215​
216 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
217 Effect.fn("PiTextGeneration.generateBranchName")(function* (input) {
218 const { prompt, outputSchema } = buildBranchNamePrompt({
219 message: input.message,
220 attachments: input.attachments,
221 });
222 const generated = yield* runPiJson({
223 operation: "generateBranchName",
224 cwd: input.cwd,
225 prompt,
226 outputSchemaJson: outputSchema,
227 modelSelection: input.modelSelection,
228 });
229 return {
230 branch: sanitizeBranchFragment(generated.branch),
231 };
232 });
233​
234 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
235 Effect.fn("PiTextGeneration.generateThreadTitle")(function* (input) {
236 const { prompt, outputSchema } = buildThreadTitlePrompt({
237 message: input.message,
238 previousTitle: input.previousTitle,
239 linkedContext: input.linkedContext,
240 attachments: input.attachments,
241 });
242 const generated = yield* runPiJson({
243 operation: "generateThreadTitle",
244 cwd: input.cwd,
245 prompt,
246 outputSchemaJson: outputSchema,
247 modelSelection: input.modelSelection,
248 });
249 return {
250 title: sanitizeThreadTitle(generated.title),
251 ...(generated.needsRefinement ? { needsRefinement: true } : {}),
252 } satisfies TextGeneration.ThreadTitleGenerationResult;
253 });
254​
255 return {
256 generateCommitMessage,
257 generatePrContent,
258 generateBranchName,
259 generateThreadTitle,
260 } satisfies TextGeneration.TextGeneration["Service"];
261});