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

textGeneration.ts

132 lines4.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 } 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​
18export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (
19 piSettings: PiSettings,
20 environment: NodeJS.ProcessEnv = process.env,
21) {
22 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
23​
24 const runPiJson: TextGenerationOperations.Runner = Effect.fn("PiTextGeneration.runPiJson")(
25 function* (request) {
26 const { operation, cwd, prompt, modelSelection } = request;
27​
28 const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
29 if (!resolvedLaunchArgs.ok) {
30 return yield* new TextGenerationError({
31 operation,
32 detail: resolvedLaunchArgs.message,
33 });
34 }
35 const launch = buildPiRpcLaunch({
36 launchArgs: resolvedLaunchArgs.args,
37 environment,
38 mcpSession: undefined,
39 extensionPath: undefined,
40 ephemeral: true,
41 disableExtensions: true,
42 // Background naming/content helpers must never mutate the workspace.
43 disableTools: true,
44 });
45 const connection = yield* makePiRpcConnection({
46 command: piSettings.binaryPath || "pi",
47 args: launch.args,
48 cwd,
49 env: launch.env,
50 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
51​
52 if (modelSelection.model !== "default") {
53 // Reject unusable custom slugs; silently using Pi's default would misreport the requested model.
54 const parsed = parsePiModelSlug(modelSelection.model);
55 if (parsed === null) {
56 return yield* new TextGenerationError({
57 operation,
58 detail: `Pi model '${modelSelection.model}' must use provider/model format.`,
59 });
60 }
61 yield* connection
62 .request({ type: "set_model", provider: parsed.provider, modelId: parsed.modelId })
63 .pipe(
64 // Model discovery loads extensions that this background helper disables.
65 Effect.mapError((error) =>
66 error._tag === "PiRpcError" && error.operation === "set_model"
67 ? new TextGenerationError({
68 operation,
69 detail:
70 `Pi rejected model '${modelSelection.model}': ${error.detail ?? "unknown error"}. ` +
71 "If the model comes from a Pi extension or package, text generation cannot use it " +
72 "because it runs Pi with --no-extensions. Pick a built-in Pi model or one defined " +
73 "in Pi's models.json.",
74 cause: error,
75 })
76 : error,
77 ),
78 );
79 }
80​
81 yield* connection.request({ type: "prompt", message: prompt });
82 yield* Effect.gen(function* () {
83 while (true) {
84 const event = yield* Queue.take(connection.events);
85 if (event["type"] === "agent_settled") return;
86 }
87 });
88 const data = yield* connection.request({ type: "get_last_assistant_text" });
89 const text =
90 typeof data === "object" &&
91 data !== null &&
92 typeof (data as { text?: unknown }).text === "string"
93 ? (data as { text: string }).text.trim()
94 : "";
95 if (!text) {
96 return yield* new TextGenerationError({
97 operation,
98 detail: "Pi returned empty output.",
99 });
100 }
101 return yield* TextGenerationOperations.decodeJsonReply(request, "Pi", text);
102 },
103 (effect, request) => {
104 const { operation } = request;
105 return effect.pipe(
106 Effect.timeoutOption(PI_TIMEOUT_MS),
107 Effect.flatMap(
108 Option.match({
109 onNone: () =>
110 Effect.fail(new TextGenerationError({ operation, detail: "Pi request timed out." })),
111 onSome: (value) => Effect.succeed(value),
112 }),
113 ),
114 Effect.mapError((cause) =>
115 isTextGenerationError(cause)
116 ? cause
117 : new TextGenerationError({
118 operation,
119 detail: "Pi text generation failed.",
120 cause,
121 }),
122 ),
123 Effect.scoped,
124 );
125 },
126 );
127​
128 return TextGenerationOperations.fromRunner(
129 "PiTextGeneration",
130 TextGenerationOperations.withoutInvestigation("Pi", runPiJson),
131 );
132});