Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Queue from "effect/Queue";
6import * as Schema from "effect/Schema";
7import * as Sink from "effect/Sink";
8import * as Stream from "effect/Stream";
9import * as ChildProcess from "effect/process/ChildProcess";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11import * as Fiber from "effect/Fiber";
12import * as TestClock from "effect/testing/TestClock";
13
14import { checkPiProviderStatus, MINIMUM_PI_VERSION } from "./status.ts";
15
16const encoder = new TextEncoder();
17const decodeRpcRequest = Schema.decodeSync(
18 Schema.fromJsonString(Schema.Struct({ id: Schema.String, type: Schema.String })),
19);
20const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
21
22function processHandle(input: {
23 readonly stdout?: string;
24 readonly stderr?: string;
25 readonly exitCode?: number;
26 /** Holds stdout and the exit back until it completes, like a CLI slow to answer. */
27 readonly answered?: Effect.Effect<void>;
28}) {
29 const answered = input.answered ?? Effect.void;
30 const bytes = (value: string | undefined) =>
31 value === undefined || value.length === 0
32 ? Stream.empty
33 : Stream.succeed(encoder.encode(value));
34 return ChildProcessSpawner.makeHandle({
35 pid: ChildProcessSpawner.ProcessId(900_000_001),
36 exitCode: Effect.as(answered, ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
37 isRunning: Effect.succeed(false),
38 kill: () => Effect.void,
39 unref: Effect.succeed(Effect.void),
40 stdin: Sink.drain,
41 stdout: Stream.unwrap(Effect.as(answered, bytes(input.stdout))),
42 stderr: bytes(input.stderr),
43 all: Stream.empty,
44 getInputFd: () => Sink.drain,
45 getOutputFd: () => Stream.empty,
46 });
47}
48
49function piProbeSpawner(version: string) {
50 return ChildProcessSpawner.make((command) => {
51 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
52 return Effect.succeed(
53 args.includes("--version")
54 ? processHandle({ stdout: `pi ${version}\n` })
55 : processHandle({ stderr: "RPC startup failed", exitCode: 1 }),
56 );
57 });
58}
59
60/** Fails the test if status runs `pi auth check` without `authCheck` or with other arguments. */
61const piDiscoverySpawner = (
62 inventory: unknown,
63 options: {
64 readonly version?: string;
65 readonly state?: unknown;
66 readonly authCheck?: string | undefined;
67 } = {},
68) =>
69 Effect.gen(function* () {
70 const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
71 let stdinBuffer = "";
72 const stdin = Sink.forEach((chunk: Uint8Array) =>
73 Effect.gen(function* () {
74 stdinBuffer += new TextDecoder().decode(chunk);
75 while (true) {
76 const newline = stdinBuffer.indexOf("\n");
77 if (newline === -1) return;
78 const line = stdinBuffer.slice(0, newline);
79 stdinBuffer = stdinBuffer.slice(newline + 1);
80 if (line.length === 0) continue;
81 const request = decodeRpcRequest(line);
82 const data =
83 request.type === "get_available_models"
84 ? inventory
85 : request.type === "get_commands"
86 ? { commands: [] }
87 : request.type === "get_state"
88 ? (options.state ?? {})
89 : {};
90 yield* Queue.offer(
91 stdout,
92 encoder.encode(
93 `${encodeJsonLine({ type: "response", id: request.id, command: request.type, success: true, data })}\n`,
94 ),
95 );
96 }
97 }),
98 );
99 return ChildProcessSpawner.make((command) => {
100 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
101 if (args.includes("--version")) {
102 return Effect.succeed(processHandle({ stdout: `pi ${options.version ?? "0.84.3"}\n` }));
103 }
104 if (args[0] === "auth") {
105 const expected = ["auth", "check", "--provider", "openai", "--json", "--no-refresh"];
106 return options.authCheck === undefined || args.join(" ") !== expected.join(" ")
107 ? Effect.die(`Unexpected pi ${args.join(" ")}`)
108 : Effect.succeed(processHandle({ stdout: options.authCheck, exitCode: 1 }));
109 }
110 return Effect.succeed(
111 ChildProcessSpawner.makeHandle({
112 ...processHandle({}),
113 exitCode: Effect.never,
114 isRunning: Effect.succeed(true),
115 stdin,
116 stdout: Stream.fromQueue(stdout),
117 }),
118 );
119 });
120 });
121
122const settings = {
123 enabled: true,
124 binaryPath: "pi",
125 launchArgs: "",
126 customModels: [],
127} as const;
128
129describe("PiProvider", () => {
130 it.effect("requires the first published Pi version with entries and settlement hooks", () =>
131 Effect.gen(function* () {
132 const snapshot = yield* checkPiProviderStatus(settings).pipe(
133 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.80.3")),
134 );
135 assert.equal(snapshot.status, "error");
136 assert.equal(snapshot.version, "0.80.3");
137 assert.include(snapshot.message ?? "", `Pi ${MINIMUM_PI_VERSION} or newer`);
138 }).pipe(Effect.provide(NodeServices.layer)),
139 );
140
141 it.effect("keeps compatible Pi selectable when optional discovery fails", () =>
142 Effect.gen(function* () {
143 const snapshot = yield* checkPiProviderStatus(settings).pipe(
144 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.84.3")),
145 );
146 assert.equal(snapshot.status, "ready");
147 assert.equal(snapshot.auth.status, "unknown");
148 assert.deepEqual(
149 snapshot.models.map((model) => model.slug),
150 ["default"],
151 );
152 assert.include(snapshot.message ?? "", "could not refresh its models and commands");
153 }).pipe(Effect.provide(NodeServices.layer)),
154 );
155
156 it.effect.each([
157 {
158 label: "answers after 6 s",
159 versionDelay: "6 seconds",
160 status: "ready",
161 version: "0.84.3",
162 message: "could not refresh its models and commands",
163 probesAfterVersion: true,
164 },
165 {
166 label: "never answers",
167 versionDelay: "Infinity",
168 status: "error",
169 version: null,
170 message: "Pi CLI is installed but timed out while running `pi --version`.",
171 probesAfterVersion: false,
172 },
173 ] as const)("gives `pi --version` 10 s when it $label", (row) =>
174 Effect.gen(function* () {
175 const spawned: Array<string> = [];
176 const spawner = ChildProcessSpawner.make((command) => {
177 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
178 spawned.push(args.join(" "));
179 return Effect.succeed(
180 args.includes("--version")
181 ? processHandle({ stdout: "pi 0.84.3\n", answered: Effect.sleep(row.versionDelay) })
182 : processHandle({ stderr: "RPC startup failed", exitCode: 1 }),
183 );
184 });
185 const fiber = yield* checkPiProviderStatus(settings).pipe(
186 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
187 Effect.forkChild,
188 );
189 yield* TestClock.adjust("10 seconds");
190 const snapshot = yield* Fiber.join(fiber);
191 assert.equal(snapshot.status, row.status);
192 assert.equal(snapshot.version, row.version);
193 assert.include(snapshot.message ?? "", row.message);
194 assert.equal(spawned.length > 1, row.probesAfterVersion);
195 }).pipe(Effect.provide(NodeServices.layer)),
196 );
197
198 it.effect("reports a known unauthenticated inventory when Pi returns no usable models", () =>
199 Effect.gen(function* () {
200 const spawner = yield* piDiscoverySpawner({ models: [] });
201 const snapshot = yield* checkPiProviderStatus(settings).pipe(
202 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
203 );
204 assert.equal(snapshot.status, "warning");
205 assert.equal(snapshot.auth.status, "unauthenticated");
206 assert.deepEqual(
207 snapshot.models.map((model) => model.slug),
208 ["default"],
209 );
210 }).pipe(Effect.provide(NodeServices.layer)),
211 );
212
213 it.effect.each([
214 {
215 label: "a pinned model without credentials",
216 version: "1.4.0",
217 activeModel: { provider: "openai", id: "gpt-5" },
218 authCheck: '{"status":"not_ready","provider":"openai","reason":"credentials_not_configured"}',
219 message: "Pi default (openai/gpt-5) has no credentials configured for openai.",
220 },
221 {
222 label: "a pinned model with a runtime --api-key",
223 version: "1.4.0",
224 launchArgs: "--provider openai --model gpt-5 --api-key fake-key",
225 activeModel: { provider: "openai", id: "gpt-5" },
226 authCheck: undefined,
227 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
228 },
229 {
230 label: "a pinned model whose provider auth check cannot find",
231 version: "1.4.0",
232 activeModel: { provider: "openai", id: "gpt-5" },
233 authCheck: '{"status":"not_ready","provider":"openai","reason":"provider_not_found"}',
234 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
235 },
236 {
237 label: "a pinned model on Pi without auth check",
238 version: MINIMUM_PI_VERSION,
239 activeModel: { provider: "openai", id: "gpt-5" },
240 authCheck: undefined,
241 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
242 },
243 {
244 label: "an uncatalogued model id of a provider with credentials",
245 version: "1.4.0",
246 activeModel: { provider: "anthropic", id: "claude-next" },
247 authCheck: undefined,
248 message: undefined,
249 },
250 {
251 label: "an extension model Pi lists as available",
252 version: "1.4.0",
253 activeModel: { provider: "router", id: "auto" },
254 authCheck: undefined,
255 message: undefined,
256 },
257 ])("diagnoses Pi's active model readiness for $label", (row) =>
258 Effect.gen(function* () {
259 const spawner = yield* piDiscoverySpawner(
260 {
261 models: [
262 { provider: "anthropic", id: "claude-sonnet-4" },
263 { provider: "router", id: "auto" },
264 ],
265 },
266 { version: row.version, state: { model: row.activeModel }, authCheck: row.authCheck },
267 );
268 const snapshot = yield* checkPiProviderStatus({
269 ...settings,
270 launchArgs: row.launchArgs ?? "",
271 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
272 assert.equal(snapshot.status, "ready");
273 assert.equal(snapshot.auth.status, "authenticated");
274 if (row.message === undefined) assert.isUndefined(snapshot.message);
275 else assert.include(snapshot.message ?? "", row.message);
276 }).pipe(Effect.provide(NodeServices.layer)),
277 );
278
279 it.effect("advertises a model's service tiers beside its thinking levels", () =>
280 Effect.gen(function* () {
281 const spawner = yield* piDiscoverySpawner({
282 models: [
283 {
284 provider: "columbia-codex",
285 id: "gpt-6.1-sol",
286 reasoning: true,
287 serviceTiers: [
288 { id: "priority", name: "Fast", description: "2x speed, increased usage" },
289 { id: "ultrafast", name: "Ultrafast" },
290 ],
291 },
292 { provider: "anthropic", id: "claude-sonnet-4", reasoning: true },
293 ],
294 });
295 const snapshot = yield* checkPiProviderStatus(settings).pipe(
296 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
297 );
298 const descriptors = (slug: string) =>
299 snapshot.models.find((model) => model.slug === slug)?.capabilities?.optionDescriptors ?? [];
300 assert.deepEqual(
301 descriptors("columbia-codex/gpt-6.1-sol").map((descriptor) => descriptor.id),
302 ["thinking", "serviceTier"],
303 );
304 assert.deepEqual(descriptors("columbia-codex/gpt-6.1-sol")[1], {
305 id: "serviceTier",
306 label: "Service Tier",
307 type: "select",
308 options: [
309 { id: "default", label: "Standard", isDefault: true },
310 { id: "priority", label: "Fast", description: "2x speed, increased usage" },
311 { id: "ultrafast", label: "Ultrafast" },
312 ],
313 currentValue: "default",
314 });
315 assert.deepEqual(
316 descriptors("anthropic/claude-sonnet-4").map((descriptor) => descriptor.id),
317 ["thinking"],
318 );
319 }).pipe(Effect.provide(NodeServices.layer)),
320 );
321
322 // regression: #18498 a malformed model inventory must not restore stale Pi models
323 it.effect.each([
324 ["missing models", {}],
325 ["missing model id", { models: [{ provider: "anthropic" }] }],
326 [
327 "mixed valid and invalid models",
328 { models: [{ provider: "anthropic", id: "claude-sonnet-4" }, { provider: "openrouter" }] },
329 ],
330 ] as const)("reports unknown authentication when Pi discovery returns %s", (_label, inventory) =>
331 Effect.gen(function* () {
332 const spawner = yield* piDiscoverySpawner(inventory);
333 const snapshot = yield* checkPiProviderStatus(settings).pipe(
334 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
335 );
336 assert.equal(snapshot.status, "ready");
337 assert.equal(snapshot.auth.status, "unknown");
338 }).pipe(Effect.provide(NodeServices.layer)),
339 );
340});