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

textGeneration.ts

134 lines5.0 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 // `customModels` accepts arbitrary strings, so an unusable slug is
54 // rejected rather than skipped: running Pi's default model here would
55 // report success for a model the caller never asked for.
56 const parsed = parsePiModelSlug(modelSelection.model);
57 if (parsed === null) {
58 return yield* new TextGenerationError({
59 operation,
60 detail: `Pi model '${modelSelection.model}' must use provider/model format.`,
61 });
62 }
63 yield* connection
64 .request({ type: "set_model", provider: parsed.provider, modelId: parsed.modelId })
65 .pipe(
66 // Model discovery loads extensions that this background helper disables.
67 Effect.mapError((error) =>
68 error._tag === "PiRpcError" && error.operation === "set_model"
69 ? new TextGenerationError({
70 operation,
71 detail:
72 `Pi rejected model '${modelSelection.model}': ${error.detail ?? "unknown error"}. ` +
73 "If the model comes from a Pi extension or package, text generation cannot use it " +
74 "because it runs Pi with --no-extensions. Pick a built-in Pi model or one defined " +
75 "in Pi's models.json.",
76 cause: error,
77 })
78 : error,
79 ),
80 );
81 }
82​
83 yield* connection.request({ type: "prompt", message: prompt });
84 yield* Effect.gen(function* () {
85 while (true) {
86 const event = yield* Queue.take(connection.events);
87 if (event["type"] === "agent_settled") return;
88 }
89 });
90 const data = yield* connection.request({ type: "get_last_assistant_text" });
91 const text =
92 typeof data === "object" &&
93 data !== null &&
94 typeof (data as { text?: unknown }).text === "string"
95 ? (data as { text: string }).text.trim()
96 : "";
97 if (!text) {
98 return yield* new TextGenerationError({
99 operation,
100 detail: "Pi returned empty output.",
101 });
102 }
103 return yield* TextGenerationOperations.decodeJsonReply(request, "Pi", text);
104 },
105 (effect, request) => {
106 const { operation } = request;
107 return effect.pipe(
108 Effect.timeoutOption(PI_TIMEOUT_MS),
109 Effect.flatMap(
110 Option.match({
111 onNone: () =>
112 Effect.fail(new TextGenerationError({ operation, detail: "Pi request timed out." })),
113 onSome: (value) => Effect.succeed(value),
114 }),
115 ),
116 Effect.mapError((cause) =>
117 isTextGenerationError(cause)
118 ? cause
119 : new TextGenerationError({
120 operation,
121 detail: "Pi text generation failed.",
122 cause,
123 }),
124 ),
125 Effect.scoped,
126 );
127 },
128 );
129​
130 return TextGenerationOperations.fromRunner(
131 "PiTextGeneration",
132 TextGenerationOperations.withoutInvestigation("Pi", runPiJson),
133 );
134});