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";
11
12import { checkPiProviderStatus, MINIMUM_PI_VERSION } from "./status.ts";
13
14const encoder = new TextEncoder();
15const decodeRpcRequest = Schema.decodeSync(
16 Schema.fromJsonString(Schema.Struct({ id: Schema.String, type: Schema.String })),
17);
18const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
19
20function processHandle(input: {
21 readonly stdout?: string;
22 readonly stderr?: string;
23 readonly exitCode?: number;
24}) {
25 const bytes = (value: string | undefined) =>
26 value === undefined || value.length === 0
27 ? Stream.empty
28 : Stream.succeed(encoder.encode(value));
29 return ChildProcessSpawner.makeHandle({
30 pid: ChildProcessSpawner.ProcessId(900_000_001),
31 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
32 isRunning: Effect.succeed(false),
33 kill: () => Effect.void,
34 unref: Effect.succeed(Effect.void),
35 stdin: Sink.drain,
36 stdout: bytes(input.stdout),
37 stderr: bytes(input.stderr),
38 all: Stream.empty,
39 getInputFd: () => Sink.drain,
40 getOutputFd: () => Stream.empty,
41 });
42}
43
44function piProbeSpawner(version: string) {
45 return ChildProcessSpawner.make((command) => {
46 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
47 return Effect.succeed(
48 args.includes("--version")
49 ? processHandle({ stdout: `pi ${version}\n` })
50 : processHandle({ stderr: "RPC startup failed", exitCode: 1 }),
51 );
52 });
53}
54
55/** Fails the test if status runs `pi auth check` without `authCheck` or with other arguments. */
56const piDiscoverySpawner = (
57 inventory: unknown,
58 options: {
59 readonly version?: string;
60 readonly state?: unknown;
61 readonly authCheck?: string | undefined;
62 } = {},
63) =>
64 Effect.gen(function* () {
65 const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
66 let stdinBuffer = "";
67 const stdin = Sink.forEach((chunk: Uint8Array) =>
68 Effect.gen(function* () {
69 stdinBuffer += new TextDecoder().decode(chunk);
70 while (true) {
71 const newline = stdinBuffer.indexOf("\n");
72 if (newline === -1) return;
73 const line = stdinBuffer.slice(0, newline);
74 stdinBuffer = stdinBuffer.slice(newline + 1);
75 if (line.length === 0) continue;
76 const request = decodeRpcRequest(line);
77 const data =
78 request.type === "get_available_models"
79 ? inventory
80 : request.type === "get_commands"
81 ? { commands: [] }
82 : request.type === "get_state"
83 ? (options.state ?? {})
84 : {};
85 yield* Queue.offer(
86 stdout,
87 encoder.encode(
88 `${encodeJsonLine({ type: "response", id: request.id, command: request.type, success: true, data })}\n`,
89 ),
90 );
91 }
92 }),
93 );
94 return ChildProcessSpawner.make((command) => {
95 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
96 if (args.includes("--version")) {
97 return Effect.succeed(processHandle({ stdout: `pi ${options.version ?? "0.84.3"}\n` }));
98 }
99 if (args[0] === "auth") {
100 const expected = ["auth", "check", "--provider", "openai", "--json", "--no-refresh"];
101 return options.authCheck === undefined || args.join(" ") !== expected.join(" ")
102 ? Effect.die(`Unexpected pi ${args.join(" ")}`)
103 : Effect.succeed(processHandle({ stdout: options.authCheck, exitCode: 1 }));
104 }
105 return Effect.succeed(
106 ChildProcessSpawner.makeHandle({
107 ...processHandle({}),
108 exitCode: Effect.never,
109 isRunning: Effect.succeed(true),
110 stdin,
111 stdout: Stream.fromQueue(stdout),
112 }),
113 );
114 });
115 });
116
117const settings = {
118 enabled: true,
119 binaryPath: "pi",
120 launchArgs: "",
121 customModels: [],
122} as const;
123
124describe("PiProvider", () => {
125 it.effect("requires the first published Pi version with entries and settlement hooks", () =>
126 Effect.gen(function* () {
127 const snapshot = yield* checkPiProviderStatus(settings).pipe(
128 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.80.3")),
129 );
130 assert.equal(snapshot.status, "error");
131 assert.equal(snapshot.version, "0.80.3");
132 assert.include(snapshot.message ?? "", `Pi ${MINIMUM_PI_VERSION} or newer`);
133 }).pipe(Effect.provide(NodeServices.layer)),
134 );
135
136 it.effect("keeps compatible Pi selectable when optional discovery fails", () =>
137 Effect.gen(function* () {
138 const snapshot = yield* checkPiProviderStatus(settings).pipe(
139 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.84.3")),
140 );
141 assert.equal(snapshot.status, "ready");
142 assert.equal(snapshot.auth.status, "unknown");
143 assert.deepEqual(
144 snapshot.models.map((model) => model.slug),
145 ["default"],
146 );
147 assert.include(snapshot.message ?? "", "could not refresh its models and commands");
148 }).pipe(Effect.provide(NodeServices.layer)),
149 );
150
151 it.effect("reports a known unauthenticated inventory when Pi returns no usable models", () =>
152 Effect.gen(function* () {
153 const spawner = yield* piDiscoverySpawner({ models: [] });
154 const snapshot = yield* checkPiProviderStatus(settings).pipe(
155 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
156 );
157 assert.equal(snapshot.status, "warning");
158 assert.equal(snapshot.auth.status, "unauthenticated");
159 assert.deepEqual(
160 snapshot.models.map((model) => model.slug),
161 ["default"],
162 );
163 }).pipe(Effect.provide(NodeServices.layer)),
164 );
165
166 it.effect.each([
167 {
168 label: "a pinned model without credentials",
169 version: "1.4.0",
170 activeModel: { provider: "openai", id: "gpt-5" },
171 authCheck: '{"status":"not_ready","provider":"openai","reason":"credentials_not_configured"}',
172 message: "Pi default (openai/gpt-5) has no credentials configured for openai.",
173 },
174 {
175 label: "a pinned model with a runtime --api-key",
176 version: "1.4.0",
177 launchArgs: "--provider openai --model gpt-5 --api-key fake-key",
178 activeModel: { provider: "openai", id: "gpt-5" },
179 authCheck: undefined,
180 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
181 },
182 {
183 label: "a pinned model whose provider auth check cannot find",
184 version: "1.4.0",
185 activeModel: { provider: "openai", id: "gpt-5" },
186 authCheck: '{"status":"not_ready","provider":"openai","reason":"provider_not_found"}',
187 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
188 },
189 {
190 label: "a pinned model on Pi without auth check",
191 version: MINIMUM_PI_VERSION,
192 activeModel: { provider: "openai", id: "gpt-5" },
193 authCheck: undefined,
194 message: "Pi default (openai/gpt-5) uses openai, which has no available models in Pi.",
195 },
196 {
197 label: "an uncatalogued model id of a provider with credentials",
198 version: "1.4.0",
199 activeModel: { provider: "anthropic", id: "claude-next" },
200 authCheck: undefined,
201 message: undefined,
202 },
203 {
204 label: "an extension model Pi lists as available",
205 version: "1.4.0",
206 activeModel: { provider: "router", id: "auto" },
207 authCheck: undefined,
208 message: undefined,
209 },
210 ])("diagnoses Pi's active model readiness for $label", (row) =>
211 Effect.gen(function* () {
212 const spawner = yield* piDiscoverySpawner(
213 {
214 models: [
215 { provider: "anthropic", id: "claude-sonnet-4" },
216 { provider: "router", id: "auto" },
217 ],
218 },
219 { version: row.version, state: { model: row.activeModel }, authCheck: row.authCheck },
220 );
221 const snapshot = yield* checkPiProviderStatus({
222 ...settings,
223 launchArgs: row.launchArgs ?? "",
224 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
225 assert.equal(snapshot.status, "ready");
226 assert.equal(snapshot.auth.status, "authenticated");
227 if (row.message === undefined) assert.isUndefined(snapshot.message);
228 else assert.include(snapshot.message ?? "", row.message);
229 }).pipe(Effect.provide(NodeServices.layer)),
230 );
231
232 // regression: #18498 a malformed model inventory must not restore stale Pi models
233 it.effect.each([
234 ["missing models", {}],
235 ["missing model id", { models: [{ provider: "anthropic" }] }],
236 [
237 "mixed valid and invalid models",
238 { models: [{ provider: "anthropic", id: "claude-sonnet-4" }, { provider: "openrouter" }] },
239 ],
240 ] as const)("reports unknown authentication when Pi discovery returns %s", (_label, inventory) =>
241 Effect.gen(function* () {
242 const spawner = yield* piDiscoverySpawner(inventory);
243 const snapshot = yield* checkPiProviderStatus(settings).pipe(
244 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
245 );
246 assert.equal(snapshot.status, "ready");
247 assert.equal(snapshot.auth.status, "unknown");
248 }).pipe(Effect.provide(NodeServices.layer)),
249 );
250});