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 Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
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 TestClock from "effect/testing/TestClock";
13import * as HttpClient from "effect/http/HttpClient";
14import * as ChildProcess from "effect/process/ChildProcess";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16
17import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
18import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
19import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
20import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
21import type { PiSettings } from "../settings.ts";
22import { PiDriver } from "./driver.ts";
23
24const layerTest = Layer.mergeAll(
25 TestProviderHost.layer({
26 cwd: "/machine",
27 settings: { ...DEFAULT_SERVER_SETTINGS, enableProviderUpdateChecks: false },
28 runBackgroundWork: false,
29 }),
30 IdAllocator.layer,
31 McpProviderSessions.layer,
32 ProviderLatestVersions.layer,
33 Layer.succeed(
34 HttpClient.HttpClient,
35 HttpClient.make(() => Effect.die("Unexpected HTTP")),
36 ),
37).pipe(Layer.provideMerge(NodeServices.layer));
38
39const decodeRequest = Schema.decodeSync(
40 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
41);
42const encoder = new TextEncoder();
43const personalSkill = {
44 name: "skill:personal",
45 source: "skill",
46 sourceInfo: { scope: "user", path: "/home/.pi/agent/skills/personal/SKILL.md" },
47};
48
49// Respond through the real stdio transport, with a distinct command catalog for each cwd.
50const makePiSpawner = Effect.fnUntraced(function* (
51 discovery: { readonly state?: unknown; readonly models?: ReadonlyArray<unknown> } = {},
52) {
53 const pendingCommand = yield* Deferred.make<void>();
54 const launches: Array<ChildProcess.StandardCommand> = [];
55 const spawner = ChildProcessSpawner.make((command) =>
56 Effect.gen(function* () {
57 assert.isTrue(ChildProcess.isStandardCommand(command));
58 if (!ChildProcess.isStandardCommand(command)) return yield* Effect.die("Unexpected pipeline");
59 launches.push(command);
60 const version = command.args.includes("--version");
61 const stdout = yield* Queue.unbounded<Uint8Array>();
62 const cwd = command.options.cwd;
63 return ChildProcessSpawner.makeHandle({
64 // Outside the valid PID range, so transport cleanup cannot signal a real process.
65 pid: ChildProcessSpawner.ProcessId(999_999_999),
66 exitCode: version ? Effect.succeed(ChildProcessSpawner.ExitCode(0)) : 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 === "/machine"
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 }).pipe(Effect.scoped),
176 );
177
178 it.effect("does not run a disabled provider's workspace probe", () =>
179 Effect.gen(function* () {
180 const instance = yield* create({}, false).pipe(
181 Effect.provideService(
182 ChildProcessSpawner.ChildProcessSpawner,
183 ChildProcessSpawner.make(() => Effect.die("Disabled Pi must not spawn")),
184 ),
185 );
186 assert.isDefined(instance.snapshotForCwd);
187 const workspace = yield* instance.snapshotForCwd!("/first");
188 assert.isFalse(workspace.enabled);
189 assert.deepEqual(workspace.skills, []);
190 }).pipe(Effect.scoped),
191 );
192
193 it.effect.each([true, false])(
194 "limits discovered thinking defaults to the known active model, known=%s",
195 (known) =>
196 Effect.gen(function* () {
197 const { spawner } = yield* makePiSpawner({
198 state: {
199 thinkingLevel: "high",
200 ...(known ? { model: { provider: "test", id: "model" } } : {}),
201 },
202 models: [
203 { provider: "test", id: "model", reasoning: true },
204 { provider: "other", id: "model", reasoning: true },
205 { provider: "test", id: "other", reasoning: true },
206 ],
207 });
208 const instance = yield* create().pipe(
209 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
210 );
211 yield* instance.snapshot.refresh;
212 const snapshot = yield* instance.snapshot.getSnapshot;
213 assert.deepEqual(
214 snapshot.models.map((model) => [
215 model.slug,
216 (model.capabilities?.optionDescriptors ?? []).flatMap((descriptor) =>
217 descriptor.type === "select"
218 ? descriptor.options.filter((option) => option.isDefault).map((option) => option.id)
219 : [],
220 ),
221 ]),
222 [
223 ["default", []],
224 ["test/model", known ? ["high"] : []],
225 ["other/model", []],
226 ["test/other", []],
227 ],
228 );
229 }).pipe(Effect.scoped),
230 );
231
232 it.effect(
233 "fails command discovery instead of returning an empty successful workspace catalog",
234 () =>
235 Effect.gen(function* () {
236 const { spawner } = yield* makePiSpawner();
237 const instance = yield* create().pipe(
238 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
239 );
240 yield* instance.snapshot.refresh;
241 assert.isDefined(instance.snapshotForCwd);
242 const error = yield* Effect.flip(instance.snapshotForCwd!("/failed"));
243 assert.equal(error._tag, "ProviderDriverError");
244 assert.equal(error.instanceId, instance.instanceId);
245 assert.deepEqual(
246 (yield* instance.snapshot.getSnapshot).skills.map((skill) => skill.name),
247 ["personal"],
248 );
249 }).pipe(Effect.scoped),
250 );
251
252 it.effect("times out workspace discovery that needs interactive input", () =>
253 Effect.gen(function* () {
254 const { spawner, pendingCommand } = yield* makePiSpawner();
255 const instance = yield* create().pipe(
256 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
257 );
258 const probe = yield* instance.snapshotForCwd!("/pending").pipe(Effect.flip, Effect.forkChild);
259 yield* Deferred.await(pendingCommand);
260 yield* TestClock.adjust("15 seconds");
261 const error = yield* Fiber.join(probe);
262 assert.equal(error._tag, "ProviderDriverError");
263 assert.include(error.detail, "workspace commands");
264 }).pipe(Effect.scoped),
265 );
266});