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 Deferred from "effect/Deferred";
6import * as Fiber from "effect/Fiber";
7import * as TestClock from "effect/testing/TestClock";
8import * as Queue from "effect/Queue";
9import * as Schema from "effect/Schema";
10import * as Sink from "effect/Sink";
11import * as Stream from "effect/Stream";
12import * as ChildProcess from "effect/process/ChildProcess";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14
15import { checkPiProviderStatus } from "./status.ts";
16
17const encoder = new TextEncoder();
18const decodeRpcRequest = Schema.decodeSync(
19 Schema.fromJsonString(Schema.Struct({ id: Schema.String, type: Schema.String })),
20);
21const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
22const STARTUP_DIALOG = `${encodeJsonLine({
23 type: "extension_ui_request",
24 id: "ui-1",
25 method: "select",
26 title: "Allow project MCP server “github”?",
27 options: ["Don't allow", "Allow"],
28})}\n`;
29
30function processHandle(input: {
31 readonly stdout?: string;
32 readonly stderr?: string;
33 readonly exitCode?: number;
34 /** Holds stdout and the exit back until it completes, like a CLI slow to answer. */
35 readonly answered?: Effect.Effect<void>;
36}) {
37 const answered = input.answered ?? Effect.void;
38 const bytes = (value: string | undefined) =>
39 value === undefined || value.length === 0
40 ? Stream.empty
41 : Stream.succeed(encoder.encode(value));
42 return ChildProcessSpawner.makeHandle({
43 pid: ChildProcessSpawner.ProcessId(900_000_001),
44 exitCode: Effect.as(answered, ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
45 exitStatus: Effect.as(answered, {
46 _tag: "Exited",
47 code: ChildProcessSpawner.ExitCode(input.exitCode ?? 0),
48 }),
49 isRunning: Effect.succeed(false),
50 kill: () => Effect.void,
51 unref: Effect.succeed(Effect.void),
52 stdin: Sink.drain,
53 stdout: Stream.unwrap(Effect.as(answered, bytes(input.stdout))),
54 stderr: bytes(input.stderr),
55 all: Stream.empty,
56 getInputFd: () => Sink.drain,
57 getOutputFd: () => Stream.empty,
58 });
59}
60
61function piProbeSpawner(version: string) {
62 return ChildProcessSpawner.make((command) => {
63 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
64 return Effect.succeed(
65 args.includes("--version")
66 ? processHandle({ stdout: `pi ${version}\n` })
67 : processHandle({ stderr: "RPC startup failed", exitCode: 1 }),
68 );
69 });
70}
71
72const piRpcProcess = (
73 inventory: unknown,
74 onModelRequest: Effect.Effect<void> = Effect.void,
75 state: unknown = {},
76) =>
77 Effect.gen(function* () {
78 const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
79 let stdinBuffer = "";
80 const stdin = Sink.forEach((chunk: Uint8Array) =>
81 Effect.gen(function* () {
82 stdinBuffer += new TextDecoder().decode(chunk);
83 while (true) {
84 const newline = stdinBuffer.indexOf("\n");
85 if (newline === -1) return;
86 const line = stdinBuffer.slice(0, newline);
87 stdinBuffer = stdinBuffer.slice(newline + 1);
88 if (line.length === 0) continue;
89 const request = decodeRpcRequest(line);
90 if (request.type === "get_available_models") {
91 yield* onModelRequest;
92 if (inventory === null) continue;
93 }
94 const data =
95 request.type === "get_available_models"
96 ? inventory
97 : request.type === "get_commands"
98 ? { commands: [] }
99 : request.type === "get_state"
100 ? state
101 : {};
102 yield* Queue.offer(
103 stdout,
104 encoder.encode(
105 `${encodeJsonLine({ type: "response", id: request.id, command: request.type, success: true, data })}\n`,
106 ),
107 );
108 }
109 }),
110 );
111 return ChildProcessSpawner.makeHandle({
112 ...processHandle({}),
113 exitCode: Effect.never,
114 exitStatus: Effect.never,
115 isRunning: Effect.succeed(true),
116 stdin,
117 stdout: Stream.fromQueue(stdout),
118 });
119 });
120
121/** Makes the extension-free launch exit before answering, like launch args naming an extension provider. */
122const exitsWithoutExtensions = Symbol("exitsWithoutExtensions");
123
124// Text generation lists models with --no-extensions, so its inventory can differ.
125const piDiscoverySpawner = (
126 inventory: unknown,
127 extensionFreeInventory: unknown = inventory,
128 onExtensionFreeModelRequest: Effect.Effect<void> = Effect.void,
129 options: {
130 readonly version?: string;
131 readonly state?: unknown;
132 readonly authCheck?: string | undefined;
133 /** Without `--no-approve`, print a project-trust dialog and exit 0 as Pi 1.x does. */
134 readonly startupDialog?: boolean;
135 /** What `--no-approve` lists once project-local extensions are skipped. */
136 readonly declinedProjectInventory?: unknown;
137 } = {},
138) =>
139 Effect.succeed(
140 ChildProcessSpawner.make((command) => {
141 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
142 if (args.includes("--version")) {
143 return Effect.succeed(processHandle({ stdout: `pi ${options.version ?? "0.84.3"}\n` }));
144 }
145 if (args[0] === "auth") {
146 const expected = ["auth", "check", "--provider", "openai", "--json", "--no-refresh"];
147 return options.authCheck === undefined || args.join(" ") !== expected.join(" ")
148 ? Effect.die(`Unexpected pi ${args.join(" ")}`)
149 : Effect.succeed(processHandle({ stdout: options.authCheck, exitCode: 1 }));
150 }
151 if (
152 options.startupDialog === true &&
153 !args.includes("--no-extensions") &&
154 !args.includes("--no-approve")
155 ) {
156 return Effect.succeed(processHandle({ stdout: STARTUP_DIALOG }));
157 }
158 if (args.includes("--no-extensions") && extensionFreeInventory === exitsWithoutExtensions) {
159 return Effect.succeed(
160 processHandle({ stderr: 'Error: Unknown provider "demo".', exitCode: 1 }),
161 );
162 }
163 return piRpcProcess(
164 args.includes("--no-extensions")
165 ? extensionFreeInventory
166 : args.includes("--no-approve") && options.declinedProjectInventory !== undefined
167 ? options.declinedProjectInventory
168 : inventory,
169 args.includes("--no-extensions") ? onExtensionFreeModelRequest : Effect.void,
170 options.state,
171 );
172 }),
173 );
174
175const settings = {
176 enabled: true,
177 binaryPath: "pi",
178 launchArgs: "",
179 customModels: [],
180} as const;
181
182const BROKEN_ADVISORY = {
183 status: "broken",
184 message: null,
185 recommendedVersion: null,
186 recommendedRange: ">=1.0.0",
187} as const;
188
189describe("PiProvider", () => {
190 it.effect("reports a version the policy rates broken as an error", () =>
191 Effect.gen(function* () {
192 const snapshot = yield* checkPiProviderStatus(settings, undefined, undefined, () =>
193 Effect.succeed(BROKEN_ADVISORY),
194 ).pipe(
195 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.84.2")),
196 );
197 assert.equal(snapshot.status, "error");
198 assert.equal(snapshot.version, "0.84.2");
199 assert.include(snapshot.message ?? "", "Pi 0.84.2 does not work");
200 }).pipe(Effect.provide(NodeServices.layer)),
201 );
202
203 it.effect("keeps compatible Pi selectable when optional discovery fails", () =>
204 Effect.gen(function* () {
205 const snapshot = yield* checkPiProviderStatus(settings).pipe(
206 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.84.3")),
207 );
208 assert.equal(snapshot.status, "ready");
209 assert.equal(snapshot.auth.status, "unknown");
210 assert.deepEqual(
211 snapshot.models.map((model) => model.slug),
212 ["default"],
213 );
214 assert.include(snapshot.message ?? "", "could not refresh its models and commands");
215 }).pipe(Effect.provide(NodeServices.layer)),
216 );
217
218 it.effect.each([
219 {
220 label: "answers after 6 s",
221 versionDelay: "6 seconds",
222 status: "ready",
223 version: "0.84.3",
224 message: "could not refresh its models and commands",
225 probesAfterVersion: true,
226 },
227 {
228 label: "never answers",
229 versionDelay: "Infinity",
230 status: "error",
231 version: null,
232 message: "Pi CLI is installed but timed out while running `pi --version`.",
233 probesAfterVersion: false,
234 },
235 ] as const)("gives `pi --version` 10 s when it $label", (row) =>
236 Effect.gen(function* () {
237 const spawned: Array<string> = [];
238 const spawner = ChildProcessSpawner.make((command) => {
239 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
240 spawned.push(args.join(" "));
241 return Effect.succeed(
242 args.includes("--version")
243 ? processHandle({ stdout: "pi 0.84.3\n", answered: Effect.sleep(row.versionDelay) })
244 : processHandle({ stderr: "RPC startup failed", exitCode: 1 }),
245 );
246 });
247 const fiber = yield* checkPiProviderStatus(settings).pipe(
248 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
249 Effect.forkChild,
250 );
251 yield* TestClock.adjust("10 seconds");
252 const snapshot = yield* Fiber.join(fiber);
253 assert.equal(snapshot.status, row.status);
254 assert.equal(snapshot.version, row.version);
255 assert.include(snapshot.message ?? "", row.message);
256 assert.equal(spawned.length > 1, row.probesAfterVersion);
257 }).pipe(Effect.provide(NodeServices.layer)),
258 );
259
260 it.effect("reports a known unauthenticated inventory when Pi returns no usable models", () =>
261 Effect.gen(function* () {
262 const spawner = yield* piDiscoverySpawner({ models: [] });
263 const snapshot = yield* checkPiProviderStatus(settings).pipe(
264 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
265 );
266 assert.equal(snapshot.status, "warning");
267 assert.equal(snapshot.auth.status, "unauthenticated");
268 assert.deepEqual(
269 snapshot.models.map((model) => model.slug),
270 ["default"],
271 );
272 }).pipe(Effect.provide(NodeServices.layer)),
273 );
274
275 it.effect.each([
276 {
277 label: "a pinned model without credentials",
278 version: "1.4.0",
279 activeModel: { provider: "openai", id: "gpt-5" },
280 authCheck: '{"status":"not_ready","provider":"openai","reason":"credentials_not_configured"}',
281 message: "Pi default (openai/gpt-5) has no credentials configured for openai.",
282 },
283 {
284 label: "a pinned model with a runtime --api-key",
285 version: "1.4.0",
286 launchArgs: "--provider openai --model gpt-5 --api-key fake-key",
287 activeModel: { provider: "openai", id: "gpt-5" },
288 authCheck: undefined,
289 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
290 },
291 {
292 label: "a pinned model whose provider auth check cannot find",
293 version: "1.4.0",
294 activeModel: { provider: "openai", id: "gpt-5" },
295 authCheck: '{"status":"not_ready","provider":"openai","reason":"provider_not_found"}',
296 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
297 },
298 {
299 label: "an uncatalogued model id of a provider with credentials",
300 version: "1.4.0",
301 activeModel: { provider: "anthropic", id: "claude-next" },
302 authCheck: undefined,
303 message: undefined,
304 },
305 {
306 label: "an extension model Pi lists as available",
307 version: "1.4.0",
308 activeModel: { provider: "router", id: "auto" },
309 authCheck: undefined,
310 message: undefined,
311 },
312 ])("diagnoses Pi's active model readiness for $label", (row) =>
313 Effect.gen(function* () {
314 const spawner = yield* piDiscoverySpawner(
315 {
316 models: [
317 { provider: "anthropic", id: "claude-sonnet-4" },
318 { provider: "router", id: "auto" },
319 ],
320 },
321 undefined,
322 Effect.void,
323 { version: row.version, state: { model: row.activeModel }, authCheck: row.authCheck },
324 );
325 const snapshot = yield* checkPiProviderStatus({
326 ...settings,
327 launchArgs: row.launchArgs ?? "",
328 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
329 assert.equal(snapshot.status, "ready");
330 assert.equal(snapshot.auth.status, "authenticated");
331 if (row.message === undefined) assert.isUndefined(snapshot.message);
332 else assert.include(snapshot.message ?? "", row.message);
333 }).pipe(Effect.provide(NodeServices.layer)),
334 );
335
336 it.effect("marks models that only load with Pi extensions as unusable for text generation", () =>
337 Effect.gen(function* () {
338 const spawner = yield* piDiscoverySpawner(
339 {
340 models: [
341 { provider: "anthropic", id: "claude-sonnet-4" },
342 { provider: "demo", id: "demo-model" },
343 ],
344 },
345 { models: [{ provider: "anthropic", id: "claude-sonnet-4" }] },
346 );
347 const snapshot = yield* checkPiProviderStatus(settings).pipe(
348 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
349 );
350 assert.deepEqual(
351 snapshot.models.map((model) => [model.slug, model.supportsTextGeneration]),
352 [
353 ["default", undefined],
354 ["anthropic/claude-sonnet-4", undefined],
355 ["demo/demo-model", false],
356 ],
357 );
358 assert.equal(snapshot.supportsTextGeneration, undefined);
359 }).pipe(Effect.provide(NodeServices.layer)),
360 );
361
362 it.effect.each([
363 { label: "exits before answering", extensionFreeInventory: exitsWithoutExtensions },
364 { label: "lists no models", extensionFreeInventory: { models: [] } },
365 ])("makes Pi unusable for text generation when Pi without extensions $label", (row) =>
366 Effect.gen(function* () {
367 const spawner = yield* piDiscoverySpawner(
368 { models: [{ provider: "demo", id: "extension-model" }] },
369 row.extensionFreeInventory,
370 );
371 const snapshot = yield* checkPiProviderStatus({
372 ...settings,
373 launchArgs: "--provider demo --model extension-model",
374 customModels: ["local/custom-alias"],
375 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
376 assert.equal(snapshot.status, "ready");
377 assert.equal(snapshot.auth.status, "authenticated");
378 // Pi default and custom models still run in chat, so the picker keeps them.
379 assert.deepEqual(
380 snapshot.models.map((model) => model.slug),
381 ["default", "demo/extension-model", "local/custom-alias"],
382 );
383 assert.equal(snapshot.supportsTextGeneration, false);
384 }).pipe(Effect.provide(NodeServices.layer)),
385 );
386
387 it.effect("preserves normal discovery when the extension-free model listing times out", () =>
388 Effect.gen(function* () {
389 const modelRequested = yield* Deferred.make<void>();
390 const spawner = yield* piDiscoverySpawner(
391 { models: [{ provider: "demo", id: "demo-model" }] },
392 null,
393 Deferred.succeed(modelRequested, undefined).pipe(Effect.asVoid),
394 );
395 const fiber = yield* checkPiProviderStatus(settings).pipe(
396 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
397 Effect.forkChild,
398 );
399 yield* Deferred.await(modelRequested);
400 yield* TestClock.adjust("5 seconds");
401 const snapshot = yield* Fiber.join(fiber);
402 assert.equal(snapshot.status, "ready");
403 assert.equal(snapshot.auth.status, "authenticated");
404 assert.deepEqual(
405 snapshot.models.map((model) => [model.slug, model.supportsTextGeneration]),
406 [
407 ["default", undefined],
408 ["demo/demo-model", undefined],
409 ],
410 );
411 assert.equal(snapshot.supportsTextGeneration, undefined);
412 assert.include(
413 snapshot.slashCommands.map((command) => command.name),
414 "compact",
415 );
416 }).pipe(Effect.provide(NodeServices.layer)),
417 );
418
419 it.effect("advertises a model's service tiers beside its thinking levels", () =>
420 Effect.gen(function* () {
421 const spawner = yield* piDiscoverySpawner({
422 models: [
423 {
424 provider: "columbia-codex",
425 id: "gpt-6.1-sol",
426 reasoning: true,
427 serviceTiers: [
428 { id: "priority", name: "Fast", description: "2x speed, increased usage" },
429 { id: "ultrafast", name: "Ultrafast" },
430 ],
431 },
432 { provider: "anthropic", id: "claude-sonnet-4", reasoning: true },
433 ],
434 });
435 const snapshot = yield* checkPiProviderStatus(settings).pipe(
436 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
437 );
438 const descriptors = (slug: string) =>
439 snapshot.models.find((model) => model.slug === slug)?.capabilities?.optionDescriptors ?? [];
440 assert.deepEqual(
441 descriptors("columbia-codex/gpt-6.1-sol").map((descriptor) => descriptor.id),
442 ["thinking", "serviceTier"],
443 );
444 assert.deepEqual(descriptors("columbia-codex/gpt-6.1-sol")[1], {
445 id: "serviceTier",
446 label: "Service Tier",
447 type: "select",
448 options: [
449 { id: "default", label: "Standard", isDefault: true },
450 { id: "priority", label: "Fast", description: "2x speed, increased usage" },
451 { id: "ultrafast", label: "Ultrafast" },
452 ],
453 currentValue: "default",
454 });
455 assert.deepEqual(
456 descriptors("anthropic/claude-sonnet-4").map((descriptor) => descriptor.id),
457 ["thinking"],
458 );
459 }).pipe(Effect.provide(NodeServices.layer)),
460 );
461
462 it.effect.each([
463 { launchArgs: "", startupDialog: true, models: ["default", "anthropic/claude-opus"] },
464 { launchArgs: "--approve", startupDialog: true, models: ["default"] },
465 {
466 launchArgs: "",
467 startupDialog: false,
468 models: ["default", "anthropic/claude-opus", "project/local-model"],
469 },
470 ])(
471 "keeps project trust unless a startup dialog blocks discovery (dialog: $startupDialog, launch args '$launchArgs')",
472 (row) =>
473 Effect.gen(function* () {
474 const spawner = yield* piDiscoverySpawner(
475 {
476 models: [
477 { provider: "anthropic", id: "claude-opus" },
478 { provider: "project", id: "local-model" },
479 ],
480 },
481 undefined,
482 undefined,
483 {
484 startupDialog: row.startupDialog,
485 declinedProjectInventory: { models: [{ provider: "anthropic", id: "claude-opus" }] },
486 },
487 );
488 const snapshot = yield* checkPiProviderStatus({
489 ...settings,
490 launchArgs: row.launchArgs,
491 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
492 assert.deepEqual(
493 snapshot.models.map((model) => model.slug),
494 row.models,
495 );
496 }).pipe(Effect.provide(NodeServices.layer)),
497 );
498
499 // regression: #18498 a malformed model inventory must not restore stale Pi models
500 it.effect.each([
501 ["missing models", {}],
502 ["missing model id", { models: [{ provider: "anthropic" }] }],
503 [
504 "mixed valid and invalid models",
505 { models: [{ provider: "anthropic", id: "claude-sonnet-4" }, { provider: "openrouter" }] },
506 ],
507 ] as const)("reports unknown authentication when Pi discovery returns %s", (_label, inventory) =>
508 Effect.gen(function* () {
509 const spawner = yield* piDiscoverySpawner(inventory);
510 const snapshot = yield* checkPiProviderStatus(settings).pipe(
511 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
512 );
513 assert.equal(snapshot.status, "ready");
514 assert.equal(snapshot.auth.status, "unknown");
515 }).pipe(Effect.provide(NodeServices.layer)),
516 );
517});