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

textGeneration.ts

185 lines7.7 KB

1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import * as Queue from "effect/Queue";
4import * as Schema from "effect/Schema";
5import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
6​
7import { TextGenerationError } from "@t3tools/contracts";
8import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
9import { compareSemverVersions } from "@t3tools/shared/semver";
10import { parseGenericCliVersion } from "@t3tools/provider-core/server/snapshotProbe";
11import type { PiSettings } from "../settings.ts";
12​
13import { makePiRpcConnection, piRecordField, piRecordString, resolvePiModelSlug } from "./rpc.ts";
14import { buildPiRpcLaunch, resolvePiLaunchArgs } from "./mcpInjection.ts";
15import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
16import { isPiThinkingLevel } from "./modelCapabilities.ts";
17import { MINIMUM_PI_VERSION, runPiVersionCommand } from "./status.ts";
18​
19const PI_TIMEOUT_MS = 180_000;
20​
21const isTextGenerationError = Schema.is(TextGenerationError);
22​
23// Pi's `errorMessage` is the provider's raw response text and can echo
24// credentials, so only a leading HTTP status reaches the error detail.
25const piTurnErrorDetail = (errorMessage: string | undefined) => {
26 const status = errorMessage?.match(/^([45]\d\d)\b/)?.[1];
27 return status === undefined
28 ? "Pi could not generate text: the model provider reported an error."
29 : `Pi could not generate text: the model provider returned HTTP ${status}.`;
30};
31​
32export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (
33 piSettings: PiSettings,
34 environment: NodeJS.ProcessEnv = process.env,
35) {
36 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
37​
38 const runPiJson: TextGenerationOperations.Runner = Effect.fn("PiTextGeneration.runPiJson")(
39 function* (request) {
40 const { operation, cwd, prompt, modelSelection } = request;
41 const thinking = getModelSelectionStringOptionValue(modelSelection, "thinking");
42 if (thinking !== undefined && isPiThinkingLevel(thinking)) {
43 const output = yield* runPiVersionCommand(piSettings, environment, cwd).pipe(
44 Effect.timeoutOption(4_000),
45 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
46 );
47 const version =
48 Option.isSome(output) && output.value.code === 0
49 ? parseGenericCliVersion(`${output.value.stdout}\n${output.value.stderr}`)
50 : null;
51 if (version === null || compareSemverVersions(version, MINIMUM_PI_VERSION) < 0) {
52 return yield* new TextGenerationError({
53 operation,
54 detail: `Pi ${MINIMUM_PI_VERSION} or newer is required for text generation thinking options. Update Pi and try again.`,
55 });
56 }
57 }
58​
59 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
60 if (!resolvedLaunchArgs.ok) {
61 return yield* new TextGenerationError({
62 operation,
63 detail: resolvedLaunchArgs.message,
64 });
65 }
66 const launch = buildPiRpcLaunch({
67 launchArgs: resolvedLaunchArgs.args,
68 environment,
69 mcpSession: undefined,
70 extensionPath: undefined,
71 ephemeral: true,
72 shortLived: true,
73 disableExtensions: true,
74 // Background naming/content helpers must never mutate the workspace.
75 disableTools: true,
76 });
77 const connection = yield* makePiRpcConnection({
78 command: piSettings.binaryPath || "pi",
79 args: launch.args,
80 cwd,
81 env: launch.env,
82 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
83​
84 if (modelSelection.model !== "default") {
85 // Reject unusable custom slugs; silently using Pi's default would misreport the requested model.
86 const inventory = yield* connection
87 .request({ type: "get_available_models" })
88 .pipe(Effect.orElseSucceed(() => undefined));
89 const parsed = resolvePiModelSlug(modelSelection.model, piRecordField(inventory, "models"));
90 if (parsed === null) {
91 return yield* new TextGenerationError({
92 operation,
93 detail: `Pi model '${modelSelection.model}' must use provider/model format.`,
94 });
95 }
96 yield* connection
97 .request({ type: "set_model", provider: parsed.provider, modelId: parsed.modelId })
98 .pipe(
99 // Model discovery loads extensions that this background helper disables.
100 Effect.mapError((error) =>
101 error._tag === "PiRpcError" && error.operation === "set_model"
102 ? new TextGenerationError({
103 operation,
104 detail:
105 `Pi rejected model '${modelSelection.model}': ${error.detail ?? "unknown error"}. ` +
106 "If the model comes from a Pi extension or package, text generation cannot use it " +
107 "because it runs Pi with --no-extensions. Pick a built-in Pi model or one defined " +
108 "in Pi's models.json.",
109 cause: error,
110 })
111 : error,
112 ),
113 );
114 }
115​
116 if (thinking !== undefined && isPiThinkingLevel(thinking)) {
117 // Pi rejects xhigh/max for models without a thinkingLevelMap entry; a stale saved
118 // level falls back to Pi's default instead of failing the whole generation.
119 yield* connection
120 .request({ type: "set_thinking_level", level: thinking })
121 .pipe(Effect.catchTags({ PiRpcError: () => Effect.void }));
122 }
123​
124 yield* connection.request({ type: "prompt", message: prompt });
125 // Provider failures (bad key, rate limit, 5xx) arrive on the assistant
126 // `message_end`. Keep only the latest, since Pi can retry and still answer.
127 let turnError: string | undefined;
128 yield* Effect.gen(function* () {
129 while (true) {
130 const event = yield* Queue.take(connection.events);
131 if (event["type"] === "agent_settled") return;
132 const message = event["message"];
133 if (event["type"] === "message_end" && piRecordString(message, "role") === "assistant") {
134 turnError =
135 piRecordString(message, "stopReason") === "error"
136 ? piTurnErrorDetail(piRecordString(message, "errorMessage"))
137 : undefined;
138 }
139 }
140 });
141 const data = yield* connection.request({ type: "get_last_assistant_text" });
142 const text =
143 typeof data === "object" &&
144 data !== null &&
145 typeof (data as { text?: unknown }).text === "string"
146 ? (data as { text: string }).text.trim()
147 : "";
148 if (!text) {
149 return yield* new TextGenerationError({
150 operation,
151 detail: turnError ?? "Pi returned empty output.",
152 });
153 }
154 return yield* TextGenerationOperations.decodeJsonReply(request, "Pi", text);
155 },
156 (effect, request) => {
157 const { operation } = request;
158 return effect.pipe(
159 Effect.timeoutOption(PI_TIMEOUT_MS),
160 Effect.flatMap(
161 Option.match({
162 onNone: () =>
163 Effect.fail(new TextGenerationError({ operation, detail: "Pi request timed out." })),
164 onSome: (value) => Effect.succeed(value),
165 }),
166 ),
167 Effect.mapError((cause) =>
168 isTextGenerationError(cause)
169 ? cause
170 : new TextGenerationError({
171 operation,
172 detail: "Pi text generation failed.",
173 cause,
174 }),
175 ),
176 Effect.scoped,
177 );
178 },
179 );
180​
181 return TextGenerationOperations.fromRunner(
182 "PiTextGeneration",
183 TextGenerationOperations.withoutInvestigation("Pi", runPiJson),
184 );
185});