TypeScript
fix(pi): explain when Pi's default model has no credentials (#27513)
Wout Stiens6575ce32508b
diff --git a/packages/provider-pi/src/server/status.test.ts b/packages/provider-pi/src/server/status.test.tsindex cee6442fc96..b8559d1ab7d 100644--- a/packages/provider-pi/src/server/status.test.ts+++ b/packages/provider-pi/src/server/status.test.ts@@ -52,7 +52,15 @@ function piProbeSpawner(version: string) {});}-const piDiscoverySpawner = (inventory: unknown) =>+/** Fails the test if status runs `pi auth check` without `authCheck` or with other arguments. */+const piDiscoverySpawner = (+ inventory: unknown,+ options: {+ readonly version?: string;+ readonly state?: unknown;+ readonly authCheck?: string | undefined;+ } = {},+) =>Effect.gen(function* () {const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();let stdinBuffer = "";@@ -71,7 +79,9 @@ const piDiscoverySpawner = (inventory: unknown) =>? inventory: request.type === "get_commands"? { commands: [] }- : {};+ : request.type === "get_state"+ ? (options.state ?? {})+ : {};yield* Queue.offer(stdout,encoder.encode(@@ -83,16 +93,23 @@ const piDiscoverySpawner = (inventory: unknown) =>);return ChildProcessSpawner.make((command) => {const args = ChildProcess.isStandardCommand(command) ? command.args : [];+ if (args.includes("--version")) {+ return Effect.succeed(processHandle({ stdout: `pi ${options.version ?? "0.84.3"}\n` }));+ }+ if (args[0] === "auth") {+ const expected = ["auth", "check", "--provider", "openai", "--json", "--no-refresh"];+ return options.authCheck === undefined || args.join(" ") !== expected.join(" ")+ ? Effect.die(`Unexpected pi ${args.join(" ")}`)+ : Effect.succeed(processHandle({ stdout: options.authCheck, exitCode: 1 }));+ }return Effect.succeed(- args.includes("--version")- ? processHandle({ stdout: "pi 0.84.3\n" })- : ChildProcessSpawner.makeHandle({- ...processHandle({}),- exitCode: Effect.never,- isRunning: Effect.succeed(true),- stdin,- stdout: Stream.fromQueue(stdout),- }),+ ChildProcessSpawner.makeHandle({+ ...processHandle({}),+ exitCode: Effect.never,+ isRunning: Effect.succeed(true),+ stdin,+ stdout: Stream.fromQueue(stdout),+ }),);});});@@ -146,6 +163,72 @@ describe("PiProvider", () => {}).pipe(Effect.provide(NodeServices.layer)),);+ it.effect.each([+ {+ label: "a pinned model without credentials",+ version: "1.4.0",+ activeModel: { provider: "openai", id: "gpt-5" },+ authCheck: '{"status":"not_ready","provider":"openai","reason":"credentials_not_configured"}',+ message: "Pi default (openai/gpt-5) has no credentials configured for openai.",+ },+ {+ label: "a pinned model with a runtime --api-key",+ version: "1.4.0",+ launchArgs: "--provider openai --model gpt-5 --api-key fake-key",+ activeModel: { provider: "openai", id: "gpt-5" },+ authCheck: undefined,+ message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",+ },+ {+ label: "a pinned model whose provider auth check cannot find",+ version: "1.4.0",+ activeModel: { provider: "openai", id: "gpt-5" },+ authCheck: '{"status":"not_ready","provider":"openai","reason":"provider_not_found"}',+ message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",+ },+ {+ label: "a pinned model on Pi without auth check",+ version: MINIMUM_PI_VERSION,+ activeModel: { provider: "openai", id: "gpt-5" },+ authCheck: undefined,+ message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",+ },+ {+ label: "an uncatalogued model id of a provider with credentials",+ version: "1.4.0",+ activeModel: { provider: "anthropic", id: "claude-next" },+ authCheck: undefined,+ message: undefined,+ },+ {+ label: "an extension model Pi lists as available",+ version: "1.4.0",+ activeModel: { provider: "router", id: "auto" },+ authCheck: undefined,+ message: undefined,+ },+ ])("diagnoses Pi's active model readiness for $label", (row) =>+ Effect.gen(function* () {+ const spawner = yield* piDiscoverySpawner(+ {+ models: [+ { provider: "anthropic", id: "claude-sonnet-4" },+ { provider: "router", id: "auto" },+ ],+ },+ { version: row.version, state: { model: row.activeModel }, authCheck: row.authCheck },+ );+ const snapshot = yield* checkPiProviderStatus({+ ...settings,+ launchArgs: row.launchArgs ?? "",+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));+ assert.equal(snapshot.status, "ready");+ assert.equal(snapshot.auth.status, "authenticated");+ if (row.message === undefined) assert.isUndefined(snapshot.message);+ else assert.include(snapshot.message ?? "", row.message);+ }).pipe(Effect.provide(NodeServices.layer)),+ );+// regression: #18498 a malformed model inventory must not restore stale Pi modelsit.effect.each([["missing models", {}],diff --git a/packages/provider-pi/src/server/status.ts b/packages/provider-pi/src/server/status.tsindex eef8bb5be35..a180ab9c41a 100644--- a/packages/provider-pi/src/server/status.ts+++ b/packages/provider-pi/src/server/status.ts@@ -13,6 +13,7 @@ import * as Stream from "effect/Stream";import * as Exit from "effect/Exit";import * as Option from "effect/Option";import * as Result from "effect/Result";+import * as Schema from "effect/Schema";import * as HttpClient from "effect/http/HttpClient";import * as ChildProcess from "effect/process/ChildProcess";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";@@ -62,6 +63,12 @@ const PI_RPC_DISCOVERY_TIMEOUT_MS = 30_000;* Version 0.80.5 was the first published package containing both hooks.*/export const MINIMUM_PI_VERSION = "0.80.5";+/** `pi auth check --json --no-refresh` arrived in 0.84.1. */+const PI_AUTH_CHECK_VERSION = "0.84.1";++const decodePiAuthCheck = Schema.decodeUnknownOption(+ Schema.fromJsonString(Schema.Struct({ reason: Schema.optional(Schema.String) })),+);const PI_DEFAULT_MODEL: ServerProviderModel = {slug: "default",@@ -73,6 +80,8 @@ const PI_DEFAULT_MODEL: ServerProviderModel = {interface PiDiscovery extends PiDiscoveredCommands {readonly models: ReadonlyArray<ServerProviderModel>;readonly authenticated: boolean;+ /** Pi's active model when Pi lists no model of its provider, so it cannot start a turn. */+ readonly unavailableActiveModel: { readonly provider: string; readonly id: string } | undefined;}function piModelsFromSettings(@@ -169,11 +178,22 @@ const discoverPiViaRpc = Effect.fn("PiProviderStatus.discoverPiViaRpc")(function.pipe(Effect.orElseSucceed(() => undefined));const discoveredModels = yield* Effect.fromResult(parseDiscoveredModels(modelsData, stateData));const { slashCommands, skills } = parsePiDiscoveredCommands(commandsData);+ // Pi lists only models of providers it holds credentials for, including extension, virtual and+ // --api-key ones. Turns need only the provider's credentials, so uncatalogued model ids still run.+ const activeModel = recordField(stateData, "model");+ const activeProvider = recordString(activeModel, "provider");+ const activeModelId = recordString(activeModel, "id");return {models: discoveredModels,slashCommands: withPiBuiltinSlashCommands(slashCommands),skills,authenticated: discoveredModels.length > 0,+ unavailableActiveModel:+ activeProvider !== undefined &&+ activeModelId !== undefined &&+ !discoveredModels.some((model) => model.subProvider === activeProvider)+ ? { provider: activeProvider, id: activeModelId }+ : undefined,} satisfies PiDiscovery;}, Effect.scoped);@@ -221,6 +241,56 @@ const runPiVersionCommand = Effect.fn("PiProviderStatus.runPiVersionCommand")(fu);});+/**+ * Explains why Pi's active model cannot start a turn. On Pi versions with `auth check`, asks it+ * whether credentials are missing, without refreshing or printing them. That command cannot see+ * extension providers or a runtime --api-key, so it only refines Pi's own unavailable verdict,+ * and is skipped when launch args supply the key.+ */+const describeUnavailablePiModel = Effect.fn("PiProviderStatus.describeUnavailablePiModel")(+ function* (+ piSettings: PiSettings,+ environment: NodeJS.ProcessEnv,+ version: string,+ launchArgs: ReadonlyArray<string>,+ model: { readonly provider: string; readonly id: string },+ ) {+ const label = `Pi default (${model.provider}/${model.id})`;+ const unavailable = `${label} uses ${model.provider}, which has no available models in Pi. Choose another model, or check that provider's setup and the Pi launch arguments.`;+ if (+ compareSemverVersions(version, PI_AUTH_CHECK_VERSION) < 0 ||+ launchArgs.includes("--api-key")+ ) {+ return unavailable;+ }+ const command = piSettings.binaryPath || "pi";+ const output = yield* resolveSpawnCommand(+ command,+ ["auth", "check", "--provider", model.provider, "--json", "--no-refresh"],+ { env: environment },+ ).pipe(+ Effect.flatMap((spawnCommand) =>+ spawnAndCollect(+ command,+ ChildProcess.make(spawnCommand.command, spawnCommand.args, {+ env: environment,+ shell: spawnCommand.shell,+ }),+ ),+ ),+ Effect.timeout(VERSION_PROBE_TIMEOUT_MS),+ Effect.option,+ );+ const missingCredentials = Option.exists(+ Option.flatMap(output, (result) => decodePiAuthCheck(result.stdout)),+ (check) => check.reason === "credentials_not_configured",+ );+ return missingCredentials+ ? `${label} has no credentials configured for ${model.provider}. Choose another model, or run \`pi\` in a terminal and use /login or configure its API key.`+ : unavailable;+ },+);+export const buildInitialPiProviderSnapshot = Effect.fn("PiProviderStatus.buildInitialPiProviderSnapshot",)(function* (piSettings: PiSettings): Effect.fn.Return<ServerProviderDraft> {@@ -432,6 +502,17 @@ export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(functionconst discovery = discoveryExit.value.value;const models = piModelsFromSettings(piSettings.customModels, discovery.models);+ const message = !discovery.authenticated+ ? "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent."+ : discovery.unavailableActiveModel === undefined+ ? undefined+ : yield* describeUnavailablePiModel(+ piSettings,+ environment,+ version,+ resolvedLaunchArgs.args,+ discovery.unavailableActiveModel,+ );return buildServerProvider({presentation: PI_PRESENTATION,enabled: piSettings.enabled,@@ -442,14 +523,10 @@ export const checkPiProviderStatus = Effect.fn("checkPiProviderStatus")(functionprobe: {installed: true,version,+ // Other Pi models still work when only the default is unavailable, so keep the picker usable.status: discovery.authenticated ? "ready" : "warning",auth: { status: discovery.authenticated ? "authenticated" : "unauthenticated", type: "pi" },- ...(discovery.authenticated- ? {}- : {- message:- "Pi has no usable models. Run `pi` in a terminal and use /login, or configure an API key in ~/.pi/agent.",- }),+ ...(message === undefined ? {} : { message }),},});});