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