Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import { DEFAULT_SERVER_SETTINGS, ProviderInstanceId } from "@t3tools/contracts";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Queue from "effect/Queue";
8import * as Schema from "effect/Schema";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import * as HttpClient from "effect/http/HttpClient";
12import * as ChildProcess from "effect/process/ChildProcess";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14
15import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
16import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
17import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
18import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
19import type { PiSettings } from "../settings.ts";
20import { PiDriver } from "./driver.ts";
21
22const layerTest = Layer.mergeAll(
23 TestProviderHost.layer({
24 cwd: "/machine",
25 settings: { ...DEFAULT_SERVER_SETTINGS, enableProviderUpdateChecks: false },
26 runBackgroundWork: false,
27 }),
28 IdAllocator.layer,
29 McpProviderSessions.layer,
30 ProviderLatestVersions.layer,
31 Layer.succeed(
32 HttpClient.HttpClient,
33 HttpClient.make(() => Effect.die("Unexpected HTTP")),
34 ),
35).pipe(Layer.provideMerge(NodeServices.layer));
36
37const decodeRequest = Schema.decodeSync(
38 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
39);
40const encoder = new TextEncoder();
41const personalSkill = {
42 name: "skill:personal",
43 source: "skill",
44 sourceInfo: { scope: "user", path: "/home/.pi/agent/skills/personal/SKILL.md" },
45};
46
47const makePiSpawner = Effect.fnUntraced(function* (
48 discovery: { readonly state?: unknown; readonly models?: ReadonlyArray<unknown> } = {},
49) {
50 const pendingCommand = yield* Deferred.make<void>();
51 const launches: Array<ChildProcess.StandardCommand> = [];
52 const spawner = ChildProcessSpawner.make((command) =>
53 Effect.gen(function* () {
54 assert.isTrue(ChildProcess.isStandardCommand(command));
55 if (!ChildProcess.isStandardCommand(command)) return yield* Effect.die("Unexpected pipeline");
56 launches.push(command);
57 const version = command.args.includes("--version");
58 const stdout = yield* Queue.unbounded<Uint8Array>();
59 const cwd = command.options.cwd;
60 return ChildProcessSpawner.makeHandle({
61 // Outside the valid PID range, so transport cleanup cannot signal a real process.
62 pid: ChildProcessSpawner.ProcessId(999_999_999),
63 exitCode: version ? Effect.succeed(ChildProcessSpawner.ExitCode(0)) : Effect.never,
64 exitStatus: version
65 ? Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) })
66 : Effect.never,
67 isRunning: Effect.succeed(!version),
68 kill: () => Effect.void,
69 unref: Effect.succeed(Effect.void),
70 stdin: Sink.forEach((chunk: Uint8Array) => {
71 const request = decodeRequest(new TextDecoder().decode(chunk).trim());
72 if (cwd === "/pending" && request.type === "get_commands") {
73 return Deferred.succeed(pendingCommand, undefined).pipe(Effect.asVoid);
74 }
75 const failed = cwd === "/failed" && request.type === "get_commands";
76 const data =
77 request.type === "get_commands"
78 ? {
79 commands: [
80 personalSkill,
81 ...(cwd?.endsWith("/pi-status-probe")
82 ? []
83 : [
84 {
85 name: `skill:${cwd?.slice(1)}`,
86 source: "skill",
87 sourceInfo: {
88 scope: "project",
89 path: `${cwd}/.agents/skills/SKILL.md`,
90 },
91 },
92 { name: `prompt-${cwd?.slice(1)}`, source: "prompt" },
93 ]),
94 ],
95 }
96 : request.type === "get_available_models"
97 ? { models: discovery.models ?? [{ provider: "test", id: "model" }] }
98 : request.type === "get_state"
99 ? (discovery.state ?? {})
100 : {};
101 return Queue.offer(
102 stdout,
103 encoder.encode(
104 `${JSON.stringify({ type: "response", id: request.id, success: !failed, data, ...(failed ? { error: "commands unavailable" } : {}) })}\n`,
105 ),
106 ).pipe(Effect.asVoid);
107 }),
108 stdout: version ? Stream.succeed(encoder.encode("pi 1.0.2\n")) : Stream.fromQueue(stdout),
109 stderr: Stream.empty,
110 all: Stream.empty,
111 getInputFd: () => Sink.drain,
112 getOutputFd: () => Stream.empty,
113 });
114 }),
115 );
116 return { spawner, launches, pendingCommand };
117});
118
119const create = (config: Partial<PiSettings> = {}, enabled = true) =>
120 PiDriver.create({
121 instanceId: ProviderInstanceId.make("pi-workspace-test"),
122 displayName: "My Pi",
123 accentColor: "#abcdef",
124 environment: [{ name: "PI_CODING_AGENT_DIR", value: "/isolated-pi", sensitive: false }],
125 enabled,
126 config: { ...PiDriver.defaultConfig(), binaryPath: "custom-pi", ...config },
127 });
128
129it.layer(layerTest)("PiDriver workspace discovery", (it) => {
130 it.effect("keeps each workspace's skills and commands separate from the machine catalog", () =>
131 Effect.gen(function* () {
132 const { spawner, launches } = yield* makePiSpawner();
133 const instance = yield* create({ launchArgs: '--approve --skill "extra skill"' }).pipe(
134 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
135 );
136 yield* instance.snapshot.refresh;
137 assert.isDefined(instance.snapshotForCwd);
138 const [first, second] = yield* Effect.all(
139 [instance.snapshotForCwd!("/first"), instance.snapshotForCwd!("/second")],
140 { concurrency: "unbounded" },
141 );
142 assert.deepEqual(
143 first.skills.map((skill) => skill.name),
144 ["personal", "first"],
145 );
146 assert.deepEqual(
147 second.skills.map((skill) => skill.name),
148 ["personal", "second"],
149 );
150 assert.deepEqual(
151 first.slashCommands.map((command) => command.name),
152 ["compact", "prompt-first"],
153 );
154 const machine = yield* instance.snapshot.getSnapshot;
155 assert.deepEqual(
156 machine.skills.map((skill) => skill.name),
157 ["personal"],
158 );
159 assert.deepEqual(
160 machine.slashCommands.map((command) => command.name),
161 ["compact"],
162 );
163 assert.equal(first.instanceId, instance.instanceId);
164 assert.equal(first.displayName, "My Pi");
165 assert.equal(first.accentColor, "#abcdef");
166 assert.deepEqual(first.models, machine.models);
167 const workspaceLaunch = launches.find((launch) => launch.options.cwd === "/first");
168 assert.isDefined(workspaceLaunch);
169 assert.equal(workspaceLaunch!.command, "custom-pi");
170 assert.includeMembers(
171 [...workspaceLaunch!.args],
172 ["--approve", "--skill", "extra skill", "--no-session"],
173 );
174 assert.equal(workspaceLaunch!.options.env?.PI_CODING_AGENT_DIR, "/isolated-pi");
175 // Discovery processes are stopped as soon as they answer, so neither may start Pi's
176 // network refresh at launch.
177 assert.isFalse(launches.some((launch) => launch.options.cwd === "/machine"));
178 for (const isLaunch of [
179 (cwd: string | undefined) => cwd?.endsWith("/pi-status-probe") === true,
180 (cwd: string | undefined) => cwd === "/first",
181 ]) {
182 const discovery = launches.find(
183 (launch) => isLaunch(launch.options.cwd) && launch.args.includes("--mode"),
184 );
185 assert.deepEqual(
186 discovery?.args.filter((arg) => arg === "--offline"),
187 ["--offline"],
188 );
189 }
190 }),
191 );
192
193 it.effect("does not run a disabled provider's workspace probe", () =>
194 Effect.gen(function* () {
195 const instance = yield* create({}, false).pipe(
196 Effect.provideService(
197 ChildProcessSpawner.ChildProcessSpawner,
198 ChildProcessSpawner.make(() => Effect.die("Disabled Pi must not spawn")),
199 ),
200 );
201 assert.isDefined(instance.snapshotForCwd);
202 const workspace = yield* instance.snapshotForCwd!("/first");
203 assert.isFalse(workspace.enabled);
204 assert.deepEqual(workspace.skills, []);
205 }),
206 );
207
208 it.effect.each([true, false])(
209 "limits discovered thinking defaults to the known active model, known=%s",
210 (known) =>
211 Effect.gen(function* () {
212 const { spawner } = yield* makePiSpawner({
213 state: {
214 thinkingLevel: "high",
215 ...(known ? { model: { provider: "test", id: "model" } } : {}),
216 },
217 models: [
218 { provider: "test", id: "model", reasoning: true },
219 { provider: "other", id: "model", reasoning: true },
220 { provider: "test", id: "other", reasoning: true },
221 ],
222 });
223 const instance = yield* create().pipe(
224 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
225 );
226 yield* instance.snapshot.refresh;
227 const snapshot = yield* instance.snapshot.getSnapshot;
228 assert.deepEqual(
229 snapshot.models.map((model) => [
230 model.slug,
231 (model.capabilities?.optionDescriptors ?? []).flatMap((descriptor) =>
232 descriptor.type === "select"
233 ? descriptor.options.filter((option) => option.isDefault).map((option) => option.id)
234 : [],
235 ),
236 ]),
237 [
238 ["default", []],
239 ["test/model", known ? ["high"] : []],
240 ["other/model", []],
241 ["test/other", []],
242 ],
243 );
244 }),
245 );
246
247 it.effect(
248 "fails command discovery instead of returning an empty successful workspace catalog",
249 () =>
250 Effect.gen(function* () {
251 const { spawner } = yield* makePiSpawner();
252 const instance = yield* create().pipe(
253 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
254 );
255 yield* instance.snapshot.refresh;
256 assert.isDefined(instance.snapshotForCwd);
257 const error = yield* Effect.flip(instance.snapshotForCwd!("/failed"));
258 assert.equal(error._tag, "ProviderDriverError");
259 assert.equal(error.instanceId, instance.instanceId);
260 assert.deepEqual(
261 (yield* instance.snapshot.getSnapshot).skills.map((skill) => skill.name),
262 ["personal"],
263 );
264 }),
265 );
266});