@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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