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

textGeneration.ts

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