Open History to see the last commit
1import { TextGenerationError, type ModelSelection, type PiSettings } from "@t3tools/contracts";
2import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
3import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
4import { extractJsonObject } from "@t3tools/shared/schemaJson";
5import * as Cause from "effect/Cause";
6import * as Deferred from "effect/Deferred";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Ref from "effect/Ref";
10import * as Schema from "effect/Schema";
11import * as Scope from "effect/Scope";
12import * as Stream from "effect/Stream";
13import { ChildProcessSpawner } from "effect/unstable/process";
14
15import { decodePiModelSlug } from "../provider/pi/PiModel.ts";
16import {
17 makePiRpcClient,
18 type PiRpcClient,
19 type PiRpcError,
20 type PiRpcSpawnOptions,
21} from "../provider/pi/PiRpcClient.ts";
22import { PiThinkingLevel } from "../provider/pi/PiRpcSchema.ts";
23import {
24 buildBranchNamePrompt,
25 buildCommitMessagePrompt,
26 buildPrContentPrompt,
27 buildThreadTitlePrompt,
28} from "./TextGenerationPrompts.ts";
29import * as TextGeneration from "./TextGeneration.ts";
30import {
31 sanitizeCommitSubject,
32 sanitizePrTitle,
33 sanitizeThreadTitle,
34} from "./TextGenerationUtils.ts";
35
36const DETERMINISTIC_ARGS = ["--no-session", "--offline"] as const;
37type PiRpcClientFactory = (
38 options: PiRpcSpawnOptions,
39) => Effect.Effect<PiRpcClient, PiRpcError, ChildProcessSpawner.ChildProcessSpawner | Scope.Scope>;
40const isTextGenerationError = Schema.is(TextGenerationError);
41export const PI_TEXT_GENERATION_TIMEOUT_MS = 120_000;
42
43export interface PiTextGenerationOptions {
44 readonly timeoutMs?: number;
45}
46
47const record = (value: unknown): Record<string, unknown> | undefined =>
48 typeof value === "object" && value !== null ? (value as Record<string, unknown>) : undefined;
49
50const assistantText = (message: Record<string, unknown>): string | undefined => {
51 if (message.role !== "assistant") return undefined;
52 if (typeof message.content === "string") return message.content;
53 if (!Array.isArray(message.content)) return undefined;
54 const text = message.content
55 .map(record)
56 .filter((part) => part?.type === "text" && typeof part.text === "string")
57 .map((part) => part?.text)
58 .join("");
59 return text || undefined;
60};
61
62export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (
63 settings: PiSettings,
64 environment: NodeJS.ProcessEnv = process.env,
65 makeRpcClient: PiRpcClientFactory = makePiRpcClient,
66 options: PiTextGenerationOptions = {},
67) {
68 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
69 const runJson = <S extends Schema.Top>(input: {
70 operation:
71 | "generateCommitMessage"
72 | "generatePrContent"
73 | "generateBranchName"
74 | "generateThreadTitle";
75 cwd: string;
76 prompt: string;
77 outputSchema: S;
78 modelSelection: ModelSelection;
79 }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
80 Effect.scoped(
81 Effect.gen(function* () {
82 const selected = decodePiModelSlug(input.modelSelection.model);
83 if (!selected)
84 return yield* new TextGenerationError({
85 operation: input.operation,
86 detail: "Pi model selection must use the 'provider/model' format.",
87 });
88 const client = yield* makeRpcClient({
89 command: settings.binaryPath,
90 args: DETERMINISTIC_ARGS,
91 cwd: input.cwd,
92 env: environment,
93 }).pipe(
94 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
95 Effect.mapError(
96 (cause) =>
97 new TextGenerationError({
98 operation: input.operation,
99 detail: "Failed to start Pi RPC text generation.",
100 cause: String(cause),
101 }),
102 ),
103 );
104 const output = yield* Ref.make("");
105 const currentDeltas = yield* Ref.make("");
106 const settled = yield* Deferred.make<void, TextGenerationError>();
107 yield* client.events.pipe(
108 Stream.runForEach((native) => {
109 if ("_tag" in native && native._tag === "PiRpcProtocolFailureEvent")
110 return Deferred.fail(
111 settled,
112 new TextGenerationError({
113 operation: input.operation,
114 detail:
115 typeof native.detail === "string" ? native.detail : "Pi RPC protocol failed.",
116 }),
117 ).pipe(Effect.asVoid);
118 const event = native as Record<string, unknown>;
119 if (event.type === "agent_settled")
120 return Deferred.succeed(settled, undefined).pipe(Effect.asVoid);
121 if (event.type === "message_start") return Ref.set(currentDeltas, "");
122 if (event.type === "message_end") {
123 const message = record(event.message);
124 if (!message || message.role !== "assistant") return Effect.void;
125 const stopReason = message.stopReason;
126 if (stopReason === "error" || stopReason === "aborted")
127 return Deferred.fail(
128 settled,
129 new TextGenerationError({
130 operation: input.operation,
131 detail: `Pi assistant stopped with reason '${stopReason}'.`,
132 }),
133 ).pipe(Effect.asVoid);
134 return Effect.gen(function* () {
135 const completed = assistantText(message) ?? (yield* Ref.get(currentDeltas));
136 yield* Ref.set(output, completed);
137 yield* Ref.set(currentDeltas, "");
138 });
139 }
140 const update = event.assistantMessageEvent;
141 if (
142 event.type === "message_update" &&
143 typeof update === "object" &&
144 update !== null &&
145 "type" in update &&
146 update.type === "text_delta" &&
147 "delta" in update &&
148 typeof update.delta === "string"
149 )
150 return Ref.update(currentDeltas, (current) => current + update.delta);
151 return Effect.void;
152 }),
153 Effect.matchCauseEffect({
154 onFailure: (cause) =>
155 Deferred.fail(
156 settled,
157 new TextGenerationError({
158 operation: input.operation,
159 detail: Cause.hasInterruptsOnly(cause)
160 ? "Pi event stream ended before generation settled."
161 : "Pi event stream failed before generation settled.",
162 ...(Cause.hasInterruptsOnly(cause) ? {} : { cause }),
163 }),
164 ),
165 onSuccess: () =>
166 Deferred.fail(
167 settled,
168 new TextGenerationError({
169 operation: input.operation,
170 detail: "Pi event stream ended before generation settled.",
171 }),
172 ),
173 }),
174 Effect.asVoid,
175 Effect.forkScoped,
176 );
177 yield* client.setModel(selected.provider, selected.modelId);
178 const thinking = getModelSelectionStringOptionValue(input.modelSelection, "thinkingLevel");
179 if (thinking !== undefined) {
180 const level = yield* Schema.decodeUnknownEffect(PiThinkingLevel)(thinking);
181 yield* client.setThinkingLevel(level);
182 }
183 yield* client.prompt(input.prompt);
184 yield* Deferred.await(settled);
185 const raw = (yield* Ref.get(output)).trim();
186 if (!raw)
187 return yield* new TextGenerationError({
188 operation: input.operation,
189 detail: "Pi returned empty output.",
190 });
191 return yield* Schema.decodeEffect(Schema.fromJsonString(input.outputSchema))(
192 extractJsonObject(raw),
193 );
194 }).pipe(
195 Effect.mapError((cause) =>
196 isTextGenerationError(cause)
197 ? cause
198 : new TextGenerationError({
199 operation: input.operation,
200 detail: "Pi text generation failed.",
201 cause,
202 }),
203 ),
204 ),
205 ).pipe(
206 Effect.timeout(Duration.millis(options.timeoutMs ?? PI_TEXT_GENERATION_TIMEOUT_MS)),
207 Effect.catchTag(
208 "TimeoutError",
209 () =>
210 new TextGenerationError({
211 operation: input.operation,
212 detail: "Pi text generation timed out.",
213 }),
214 ),
215 );
216
217 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] = (
218 input,
219 ) => {
220 const built = buildCommitMessagePrompt({
221 branch: input.branch,
222 stagedSummary: input.stagedSummary,
223 stagedPatch: input.stagedPatch,
224 includeBranch: input.includeBranch === true,
225 });
226 return runJson({
227 operation: "generateCommitMessage",
228 cwd: input.cwd,
229 prompt: built.prompt,
230 outputSchema: built.outputSchema,
231 modelSelection: input.modelSelection,
232 }).pipe(
233 Effect.map((value) => ({
234 subject: sanitizeCommitSubject(value.subject),
235 body: value.body.trim(),
236 ...("branch" in value && typeof value.branch === "string"
237 ? { branch: sanitizeFeatureBranchName(value.branch) }
238 : {}),
239 })),
240 );
241 };
242 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] = (
243 input,
244 ) => {
245 const built = buildPrContentPrompt(input);
246 return runJson({
247 operation: "generatePrContent",
248 cwd: input.cwd,
249 prompt: built.prompt,
250 outputSchema: built.outputSchema,
251 modelSelection: input.modelSelection,
252 }).pipe(
253 Effect.map((value) => ({ title: sanitizePrTitle(value.title), body: value.body.trim() })),
254 );
255 };
256 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] = (
257 input,
258 ) => {
259 const built = buildBranchNamePrompt(input);
260 return runJson({
261 operation: "generateBranchName",
262 cwd: input.cwd,
263 prompt: built.prompt,
264 outputSchema: built.outputSchema,
265 modelSelection: input.modelSelection,
266 }).pipe(Effect.map((value) => ({ branch: sanitizeBranchFragment(value.branch) })));
267 };
268 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] = (
269 input,
270 ) => {
271 const built = buildThreadTitlePrompt(input);
272 return runJson({
273 operation: "generateThreadTitle",
274 cwd: input.cwd,
275 prompt: built.prompt,
276 outputSchema: built.outputSchema,
277 modelSelection: input.modelSelection,
278 }).pipe(Effect.map((value) => ({ title: sanitizeThreadTitle(value.title) })));
279 };
280 return {
281 generateCommitMessage,
282 generatePrContent,
283 generateBranchName,
284 generateThreadTitle,
285 } satisfies TextGeneration.TextGeneration["Service"];
286});