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 Deferred from "effect/Deferred";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
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";
14import * as TestClock from "effect/testing/TestClock";
15
16import { checkPiProviderStatus, MINIMUM_PI_VERSION } from "./status.ts";
17
18const encoder = new TextEncoder();
19const decodeRpcRequest = Schema.decodeSync(
20 Schema.fromJsonString(Schema.Struct({ id: Schema.String, type: Schema.String })),
21);
22const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
23
24function processHandle(input: {
25 readonly stdout?: string;
26 readonly stderr?: string;
27 readonly exitCode?: number;
28}) {
29 const bytes = (value: string | undefined) =>
30 value === undefined || value.length === 0
31 ? Stream.empty
32 : Stream.succeed(encoder.encode(value));
33 return ChildProcessSpawner.makeHandle({
34 pid: ChildProcessSpawner.ProcessId(900_000_001),
35 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode ?? 0)),
36 isRunning: Effect.succeed(false),
37 kill: () => Effect.void,
38 unref: Effect.succeed(Effect.void),
39 stdin: Sink.drain,
40 stdout: bytes(input.stdout),
41 stderr: bytes(input.stderr),
42 all: Stream.empty,
43 getInputFd: () => Sink.drain,
44 getOutputFd: () => Stream.empty,
45 });
46}
47
48function piProbeSpawner(version: string) {
49 return ChildProcessSpawner.make((command) => {
50 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
51 return Effect.succeed(
52 args.includes("--version")
53 ? processHandle({ stdout: `pi ${version}\n` })
54 : processHandle({ stderr: "RPC startup failed", exitCode: 1 }),
55 );
56 });
57}
58
59const piDiscoverySpawner = (
60 inventory: unknown,
61 slowStartup?: {
62 readonly delay: Duration.Input;
63 readonly getStateReceived: Deferred.Deferred<void>;
64 },
65) =>
66 Effect.gen(function* () {
67 const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
68 let stdinBuffer = "";
69 const stdin = Sink.forEach((chunk: Uint8Array) =>
70 Effect.gen(function* () {
71 stdinBuffer += new TextDecoder().decode(chunk);
72 while (true) {
73 const newline = stdinBuffer.indexOf("\n");
74 if (newline === -1) return;
75 const line = stdinBuffer.slice(0, newline);
76 stdinBuffer = stdinBuffer.slice(newline + 1);
77 if (line.length === 0) continue;
78 const request = decodeRpcRequest(line);
79 if (request.type === "get_state" && slowStartup !== undefined) {
80 yield* Deferred.succeed(slowStartup.getStateReceived, undefined);
81 yield* Effect.sleep(slowStartup.delay);
82 }
83 const data =
84 request.type === "get_available_models"
85 ? inventory
86 : request.type === "get_commands"
87 ? { commands: [] }
88 : {};
89 yield* Queue.offer(
90 stdout,
91 encoder.encode(
92 `${encodeJsonLine({ type: "response", id: request.id, command: request.type, success: true, data })}\n`,
93 ),
94 );
95 }
96 }),
97 );
98 return ChildProcessSpawner.make((command) => {
99 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
100 return Effect.succeed(
101 args.includes("--version")
102 ? processHandle({ stdout: "pi 0.84.3\n" })
103 : ChildProcessSpawner.makeHandle({
104 ...processHandle({}),
105 exitCode: Effect.never,
106 isRunning: Effect.succeed(true),
107 stdin,
108 stdout: Stream.fromQueue(stdout),
109 }),
110 );
111 });
112 });
113
114const settings = {
115 enabled: true,
116 binaryPath: "pi",
117 launchArgs: "",
118 customModels: [],
119} as const;
120
121describe("PiProvider", () => {
122 it.effect("requires the first published Pi version with entries and settlement hooks", () =>
123 Effect.gen(function* () {
124 const snapshot = yield* checkPiProviderStatus(settings).pipe(
125 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.80.3")),
126 );
127 assert.equal(snapshot.status, "error");
128 assert.equal(snapshot.version, "0.80.3");
129 assert.include(snapshot.message ?? "", `Pi ${MINIMUM_PI_VERSION} or newer`);
130 }).pipe(Effect.provide(NodeServices.layer)),
131 );
132
133 it.effect("keeps compatible Pi selectable when optional discovery fails", () =>
134 Effect.gen(function* () {
135 const snapshot = yield* checkPiProviderStatus(settings).pipe(
136 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, piProbeSpawner("0.84.3")),
137 );
138 assert.equal(snapshot.status, "ready");
139 assert.equal(snapshot.auth.status, "unknown");
140 assert.deepEqual(
141 snapshot.models.map((model) => model.slug),
142 ["default"],
143 );
144 assert.include(snapshot.message ?? "", "could not refresh its models and commands");
145 }).pipe(Effect.provide(NodeServices.layer)),
146 );
147
148 it.effect("reports discovered models when Pi startup takes 20 seconds", () =>
149 Effect.gen(function* () {
150 const getStateReceived = yield* Deferred.make<void>();
151 const spawner = yield* piDiscoverySpawner(
152 { models: [{ provider: "anthropic", id: "claude-sonnet-4" }] },
153 { delay: "20 seconds", getStateReceived },
154 );
155 const probe = yield* checkPiProviderStatus(settings).pipe(
156 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
157 Effect.forkChild,
158 );
159 yield* Deferred.await(getStateReceived);
160 yield* TestClock.adjust("20 seconds");
161 const snapshot = yield* Fiber.join(probe);
162 assert.equal(snapshot.status, "ready");
163 assert.equal(snapshot.auth.status, "authenticated");
164 assert.deepEqual(
165 snapshot.models.map((model) => model.slug),
166 ["default", "anthropic/claude-sonnet-4"],
167 );
168 assert.equal(snapshot.models[1]?.subProvider, "anthropic");
169 }).pipe(Effect.provide(NodeServices.layer)),
170 );
171
172 it.effect("keeps compatible Pi selectable when startup outlasts the discovery deadline", () =>
173 Effect.gen(function* () {
174 const getStateReceived = yield* Deferred.make<void>();
175 const spawner = yield* piDiscoverySpawner(
176 { models: [{ provider: "anthropic", id: "claude-sonnet-4" }] },
177 { delay: "1 hour", getStateReceived },
178 );
179 const probe = yield* checkPiProviderStatus(settings).pipe(
180 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
181 Effect.forkChild,
182 );
183 yield* Deferred.await(getStateReceived);
184 yield* TestClock.adjust("30 seconds");
185 const snapshot = yield* Fiber.join(probe);
186 assert.equal(snapshot.status, "ready");
187 assert.equal(snapshot.auth.status, "unknown");
188 assert.deepEqual(
189 snapshot.models.map((model) => model.slug),
190 ["default"],
191 );
192 }).pipe(Effect.provide(NodeServices.layer)),
193 );
194
195 it.effect("reports a known unauthenticated inventory when Pi returns no usable models", () =>
196 Effect.gen(function* () {
197 const spawner = yield* piDiscoverySpawner({ models: [] });
198 const snapshot = yield* checkPiProviderStatus(settings).pipe(
199 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
200 );
201 assert.equal(snapshot.status, "warning");
202 assert.equal(snapshot.auth.status, "unauthenticated");
203 assert.deepEqual(
204 snapshot.models.map((model) => model.slug),
205 ["default"],
206 );
207 }).pipe(Effect.provide(NodeServices.layer)),
208 );
209
210 it.effect.each([
211 ["missing models", {}],
212 ["non-array models", { models: {} }],
213 ["missing model provider", { models: [{ id: "claude-sonnet-4" }] }],
214 ["missing model id", { models: [{ provider: "anthropic" }] }],
215 ["empty model provider", { models: [{ provider: "", id: "claude-sonnet-4" }] }],
216 ["empty model id", { models: [{ provider: "anthropic", id: "" }] }],
217 [
218 "mixed valid and invalid models",
219 { models: [{ provider: "anthropic", id: "claude-sonnet-4" }, { provider: "openrouter" }] },
220 ],
221 ] as const)("reports unknown authentication when Pi discovery returns %s", (_label, inventory) =>
222 Effect.gen(function* () {
223 const spawner = yield* piDiscoverySpawner(inventory);
224 const snapshot = yield* checkPiProviderStatus(settings).pipe(
225 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
226 );
227 assert.equal(snapshot.status, "ready");
228 assert.equal(snapshot.auth.status, "unknown");
229 }).pipe(Effect.provide(NodeServices.layer)),
230 );
231});