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

PiTextGeneration.ts

245 lines8.6 KB

1import { TextGenerationError, type ModelSelection, type PiSettings } from "@t3tools/contracts";
2import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
3import { tokenizeCliArgs } from "@t3tools/shared/cliArgs";
4import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
5import { extractJsonObject } from "@t3tools/shared/schemaJson";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
11​
12import { splitPiModelSlug } from "../provider/Layers/PiProvider.ts";
13import {
14 makePiRpcTransport,
15 type PiRpcResponse,
16} from "../orchestration-v2/Adapters/PiRpcTransport.ts";
17import {
18 buildBranchNamePrompt,
19 buildCommitMessagePrompt,
20 buildPrContentPrompt,
21 buildThreadTitlePrompt,
22} from "./TextGenerationPrompts.ts";
23import * as TextGeneration from "./TextGeneration.ts";
24import {
25 sanitizeCommitSubject,
26 sanitizePrTitle,
27 sanitizeThreadTitle,
28} from "./TextGenerationUtils.ts";
29​
30type PiTextGenerationOperation =
31 | "generateCommitMessage"
32 | "generatePrContent"
33 | "generateBranchName"
34 | "generateThreadTitle";
35​
36const isTextGenerationError = Schema.is(TextGenerationError);
37​
38function responseData(response: PiRpcResponse | undefined): Record<string, unknown> | undefined {
39 if (response?.["success"] !== true) return undefined;
40 const data = response["data"];
41 return typeof data === "object" && data !== null && !Array.isArray(data)
42 ? (data as Record<string, unknown>)
43 : undefined;
45​
46function thinkingLevel(selection: ModelSelection): string | undefined {
47 return (
48 getModelSelectionStringOptionValue(selection, "thinking") ??
49 getModelSelectionStringOptionValue(selection, "reasoningEffort")
50 );
52​
53export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (
54 settings: PiSettings,
55 environment: NodeJS.ProcessEnv,
56) {
57 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
58​
59 const runPiJson = Effect.fn("PiTextGeneration.runPiJson")(function* <
60 S extends Schema.Top,
61 >(input: {
62 readonly operation: PiTextGenerationOperation;
63 readonly cwd: string;
64 readonly prompt: string;
65 readonly outputSchema: S;
66 readonly modelSelection: ModelSelection;
67 }) {
68 const model = splitPiModelSlug(input.modelSelection.model);
69 if (model === undefined) {
70 return yield* new TextGenerationError({
71 operation: input.operation,
72 detail: "Pi model selection must use the 'provider/model' format.",
73 });
74 }
75​
76 const rawText = yield* Effect.scoped(
77 Effect.gen(function* () {
78 const transport = yield* makePiRpcTransport({
79 command: settings.binaryPath || "pi",
80 args: [
81 "--mode",
82 "rpc",
83 "--no-session",
84 "--no-extensions",
85 ...tokenizeCliArgs(settings.launchArgs),
86 ],
87 cwd: input.cwd,
88 env: environment,
89 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
90 const setModel = yield* transport.request(
91 { type: "set_model", provider: model.provider, modelId: model.id },
92 15_000,
93 );
94 if (setModel?.["success"] !== true) {
95 return yield* new TextGenerationError({
96 operation: input.operation,
97 detail: `Pi rejected model ${input.modelSelection.model}.`,
98 });
99 }
100 const thinking = thinkingLevel(input.modelSelection);
101 if (
102 thinking === "off" ||
103 thinking === "minimal" ||
104 thinking === "low" ||
105 thinking === "medium" ||
106 thinking === "high" ||
107 thinking === "xhigh" ||
108 thinking === "max"
109 ) {
110 const setThinking = yield* transport.request(
111 { type: "set_thinking_level", level: thinking },
112 15_000,
113 );
114 if (setThinking?.["success"] !== true) {
115 return yield* new TextGenerationError({
116 operation: input.operation,
117 detail: `Pi rejected thinking level ${thinking}.`,
118 });
119 }
120 }
121​
122 const settled = yield* Stream.fromQueue(transport.messages).pipe(
123 Stream.takeUntil(
124 (message) => message._tag === "event" && message.event["type"] === "agent_settled",
125 ),
126 Stream.runDrain,
127 Effect.forkChild({ startImmediately: true }),
128 );
129 const prompted = yield* transport.request(
130 { type: "prompt", message: input.prompt },
131 15_000,
132 );
133 if (prompted?.["success"] !== true) {
134 return yield* new TextGenerationError({
135 operation: input.operation,
136 detail: "Pi rejected the text-generation prompt.",
137 });
138 }
139 yield* Fiber.join(settled).pipe(Effect.timeout("2 minutes"));
140 const response = yield* transport.request({ type: "get_last_assistant_text" }, 15_000);
141 const text = responseData(response)?.["text"];
142 if (typeof text !== "string" || text.trim().length === 0) {
143 return yield* new TextGenerationError({
144 operation: input.operation,
145 detail: "Pi returned no assistant text.",
146 });
147 }
148 return text.trim();
149 }),
150 ).pipe(
151 Effect.mapError((cause) =>
152 isTextGenerationError(cause)
153 ? cause
154 : new TextGenerationError({
155 operation: input.operation,
156 detail: "Pi RPC text generation failed.",
157 cause,
158 }),
159 ),
160 );
161​
162 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchema));
163 return yield* decodeOutput(extractJsonObject(rawText)).pipe(
164 Effect.mapError(
165 (cause) =>
166 new TextGenerationError({
167 operation: input.operation,
168 detail: "Pi returned invalid structured output.",
169 cause,
170 }),
171 ),
172 );
173 });
174​
175 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
176 Effect.fn("PiTextGeneration.generateCommitMessage")(function* (input) {
177 const { prompt, outputSchema } = buildCommitMessagePrompt({
178 branch: input.branch,
179 stagedSummary: input.stagedSummary,
180 stagedPatch: input.stagedPatch,
181 includeBranch: input.includeBranch === true,
182 policy: input.policy,
183 });
184 const generated = yield* runPiJson({
185 operation: "generateCommitMessage",
186 cwd: input.cwd,
187 prompt,
188 outputSchema,
189 modelSelection: input.modelSelection,
190 });
191 return {
192 subject: sanitizeCommitSubject(generated.subject),
193 body: generated.body.trim(),
194 ...("branch" in generated && typeof generated.branch === "string"
195 ? { branch: sanitizeFeatureBranchName(generated.branch) }
196 : {}),
197 };
198 });
199​
200 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
201 Effect.fn("PiTextGeneration.generatePrContent")(function* (input) {
202 const { prompt, outputSchema } = buildPrContentPrompt(input);
203 const generated = yield* runPiJson({
204 operation: "generatePrContent",
205 cwd: input.cwd,
206 prompt,
207 outputSchema,
208 modelSelection: input.modelSelection,
209 });
210 return { title: sanitizePrTitle(generated.title), body: generated.body.trim() };
211 });
212​
213 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
214 Effect.fn("PiTextGeneration.generateBranchName")(function* (input) {
215 const { prompt, outputSchema } = buildBranchNamePrompt(input);
216 const generated = yield* runPiJson({
217 operation: "generateBranchName",
218 cwd: input.cwd,
219 prompt,
220 outputSchema,
221 modelSelection: input.modelSelection,
222 });
223 return { branch: sanitizeBranchFragment(generated.branch) };
224 });
225​
226 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
227 Effect.fn("PiTextGeneration.generateThreadTitle")(function* (input) {
228 const { prompt, outputSchema } = buildThreadTitlePrompt(input);
229 const generated = yield* runPiJson({
230 operation: "generateThreadTitle",
231 cwd: input.cwd,
232 prompt,
233 outputSchema,
234 modelSelection: input.modelSelection,
235 });
236 return { title: sanitizeThreadTitle(generated.title) };
237 });
238​
239 return {
240 generateCommitMessage,
241 generatePrContent,
242 generateBranchName,
243 generateThreadTitle,
244 } satisfies TextGeneration.TextGeneration["Service"];
245});