TypeScript
fix(pi): show the provider error when Pi text generation fails (#23741)
Victor Vogel26dc3688e2c9
diff --git a/packages/provider-pi/src/server/textGeneration.test.ts b/packages/provider-pi/src/server/textGeneration.test.tsindex f4f9300c731..ba693da1801 100644--- a/packages/provider-pi/src/server/textGeneration.test.ts+++ b/packages/provider-pi/src/server/textGeneration.test.ts@@ -14,7 +14,11 @@ import { makePiTextGeneration } from "./textGeneration.ts";const decodeJsonLine = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));-const makeFakePi = (reply: string, setModelError?: string) =>+const makeFakePi = (+ reply: string,+ setModelError?: string,+ turnEvents: ReadonlyArray<Record<string, unknown>> = [],+) =>Effect.gen(function* () {const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();const received: Array<Record<string, unknown>> = [];@@ -32,6 +36,7 @@ const makeFakePi = (reply: string, setModelError?: string) =>const response = { type: "response", id: record["id"], command: record["type"] };if (record["type"] === "prompt") {yield* emit({ ...response, success: true });+ for (const event of turnEvents) yield* emit(event);yield* emit({ type: "agent_settled" });} else if (record["type"] === "get_last_assistant_text") {yield* emit({ ...response, success: true, data: { text: reply } });@@ -88,3 +93,70 @@ it.effect("names the model and the disabled extensions when Pi cannot load it",assert.isUndefined(pi.received.find((record) => record["type"] === "prompt"));}),);++const failedTurnWith = (errorMessage: string) => ({+ type: "message_end",+ message: { role: "assistant", stopReason: "error", errorMessage },+});++const failedTurn = failedTurnWith(+ '401: {"error":{"message":"Incorrect API key provided: sk-test-SECRET123"}}',+);++const generateCommitMessage = (turnEvents: ReadonlyArray<Record<string, unknown>>, reply = "") =>+ Effect.gen(function* () {+ const pi = yield* makeFakePi(reply, undefined, turnEvents);+ const textGeneration = yield* makePiTextGeneration(+ { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },+ {},+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));+ return yield* textGeneration.generateCommitMessage({+ cwd: process.cwd(),+ branch: "main",+ stagedSummary: "M README.md",+ stagedPatch: "diff --git a/README.md b/README.md",+ modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "default"),+ });+ });++it.effect("reports Pi's turn error when the reply is empty", () =>+ Effect.gen(function* () {+ const error = yield* generateCommitMessage([failedTurn]).pipe(Effect.flip);++ assert.equal(error._tag, "TextGenerationError");+ assert.equal(error.detail, "Pi could not generate text: the model provider returned HTTP 401.");+ }),+);++it.effect("keeps Pi's raw error text out of the error", () =>+ Effect.gen(function* () {+ const error = yield* generateCommitMessage([+ failedTurnWith("Invalid API key sk-test-SECRET123"),+ ]).pipe(Effect.flip);++ assert.equal(error.detail, "Pi could not generate text: the model provider reported an error.");+ assert.notInclude(error.message, "SECRET123");+ }),+);++it.effect("keeps the reply when Pi answers after a failed attempt", () =>+ Effect.gen(function* () {+ const result = yield* generateCommitMessage(+ [failedTurn, { type: "message_end", message: { role: "assistant", stopReason: "stop" } }],+ JSON.stringify({ subject: "Update README", body: "" }),+ );++ assert.equal(result.subject, "Update README");+ }),+);++it.effect("drops an earlier error once a later attempt succeeds", () =>+ Effect.gen(function* () {+ const error = yield* generateCommitMessage([+ failedTurn,+ { type: "message_end", message: { role: "assistant", stopReason: "stop" } },+ ]).pipe(Effect.flip);++ assert.equal(error.detail, "Pi returned empty output.");+ }),+);diff --git a/packages/provider-pi/src/server/textGeneration.ts b/packages/provider-pi/src/server/textGeneration.tsindex 218a6300a35..3fed9963b6c 100644--- a/packages/provider-pi/src/server/textGeneration.ts+++ b/packages/provider-pi/src/server/textGeneration.ts@@ -7,7 +7,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";import { TextGenerationError } from "@t3tools/contracts";import type { PiSettings } from "../settings.ts";-import { makePiRpcConnection, parsePiModelSlug } from "./rpc.ts";+import { makePiRpcConnection, parsePiModelSlug, piRecordString } from "./rpc.ts";import { buildPiRpcLaunch, resolvePiLaunchArgs } from "./mcpInjection.ts";import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";@@ -15,6 +15,15 @@ const PI_TIMEOUT_MS = 180_000;const isTextGenerationError = Schema.is(TextGenerationError);+// Pi's `errorMessage` is the provider's raw response text and can echo+// credentials, so only a leading HTTP status reaches the error detail.+const piTurnErrorDetail = (errorMessage: string | undefined) => {+ const status = errorMessage?.match(/^([45]\d\d)\b/)?.[1];+ return status === undefined+ ? "Pi could not generate text: the model provider reported an error."+ : `Pi could not generate text: the model provider returned HTTP ${status}.`;+};+export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* (piSettings: PiSettings,environment: NodeJS.ProcessEnv = process.env,@@ -79,10 +88,20 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function*}yield* connection.request({ type: "prompt", message: prompt });+ // Provider failures (bad key, rate limit, 5xx) arrive on the assistant+ // `message_end`. Keep only the latest, since Pi can retry and still answer.+ let turnError: string | undefined;yield* Effect.gen(function* () {while (true) {const event = yield* Queue.take(connection.events);if (event["type"] === "agent_settled") return;+ const message = event["message"];+ if (event["type"] === "message_end" && piRecordString(message, "role") === "assistant") {+ turnError =+ piRecordString(message, "stopReason") === "error"+ ? piTurnErrorDetail(piRecordString(message, "errorMessage"))+ : undefined;+ }}});const data = yield* connection.request({ type: "get_last_assistant_text" });@@ -95,7 +114,7 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function*if (!text) {return yield* new TextGenerationError({operation,- detail: "Pi returned empty output.",+ detail: turnError ?? "Pi returned empty output.",});}return yield* TextGenerationOperations.decodeJsonReply(request, "Pi", text);