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

main
ts 342 lines 11.5 KB
Raw
1 import { assert, it } from "@effect/vitest";
2 import * as Cause from "effect/Cause";
3 import * as Deferred from "effect/Deferred";
4 import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6 import * as Queue from "effect/Queue";
7 import * as Scope from "effect/Scope";
8 import * as Sink from "effect/Sink";
9 import * as Stream from "effect/Stream";
10 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11 import * as TestClock from "effect/testing/TestClock";
12 import * as HostProcess from "@t3tools/shared/HostProcess";
13
14 import {
15 applyPreferredCodexDefaultModel,
16 codexCustomEndpoint,
17 codexRoutesSpendNativeQuota,
18 makeCodexSkillsProbe,
19 mapCodexModelCapabilities,
20 } from "./CodexProvider.ts";
21
22 function makeFakeCodexAppServers() {
23 const helpers: Array<{
24 readonly codexHome: unknown;
25 readonly crash: Effect.Effect<void>;
26 readonly requests: Array<unknown>;
27 closed: boolean;
28 }> = [];
29 const spawner = ChildProcessSpawner.make((command) =>
30 Effect.gen(function* () {
31 const output = yield* Queue.unbounded<Uint8Array, Cause.Done>();
32 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
33 const crash = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(1)).pipe(
34 Effect.andThen(Queue.end(output)),
35 Effect.asVoid,
36 );
37 const helper = {
38 codexHome: command._tag === "StandardCommand" ? command.options.env?.CODEX_HOME : undefined,
39 crash,
40 requests: [] as Array<unknown>,
41 closed: false,
42 };
43 helpers.push(helper);
44 yield* Effect.addFinalizer(() => Effect.sync(() => (helper.closed = true)));
45 const respond = (id: unknown, result: unknown) =>
46 Queue.offer(output, new TextEncoder().encode(`${JSON.stringify({ id, result })}\n`));
47 return ChildProcessSpawner.makeHandle({
48 pid: ChildProcessSpawner.ProcessId(900_000_000 + helpers.length),
49 exitCode: Deferred.await(exited),
50 isRunning: Effect.map(Deferred.isDone(exited), (done) => !done),
51 kill: () => crash,
52 unref: Effect.succeed(Effect.void),
53 stdin: Sink.forEach((chunk: string | Uint8Array) =>
54 Effect.forEach(
55 (typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk))
56 .split("\n")
57 .filter(Boolean),
58 (line) => {
59 const frame = JSON.parse(line) as {
60 readonly id?: number;
61 readonly method: string;
62 readonly params?: { readonly cwds: ReadonlyArray<string> };
63 };
64 if (frame.id === undefined) return Effect.void;
65 if (frame.method === "initialize") {
66 return respond(frame.id, {
67 codexHome: "/codex-home",
68 platformFamily: "unix",
69 platformOs: "linux",
70 userAgent: "codex/0.0.0",
71 });
72 }
73 helper.requests.push(frame.params);
74 return respond(frame.id, {
75 data: (frame.params?.cwds ?? []).map((cwd) => ({
76 cwd,
77 errors: [],
78 skills: [
79 {
80 name: `skill-in-${cwd}`,
81 path: `${cwd}/SKILL.md`,
82 enabled: true,
83 description: "",
84 scope: "repo",
85 },
86 ],
87 })),
88 });
89 },
90 { discard: true },
91 ),
92 ),
93 stdout: Stream.fromQueue(output),
94 stderr: Stream.empty,
95 all: Stream.empty,
96 getInputFd: () => Sink.drain,
97 getOutputFd: () => Stream.empty,
98 });
99 }),
100 );
101 return { helpers, spawner };
102 }
103
104 it.effect("reuses one Codex skills helper per launch until it idles out", () =>
105 Effect.gen(function* () {
106 const { helpers, spawner } = makeFakeCodexAppServers();
107 const providerScope = yield* Scope.make();
108 const probe = yield* makeCodexSkillsProbe().pipe(
109 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
110 Scope.provide(providerScope),
111 );
112 const read = (cwd: string, homePath = "/home-a") =>
113 probe({ binaryPath: "codex", homePath, cwd, environment: {} }).pipe(
114 Effect.map((skills) => skills.map((skill) => skill.name)),
115 );
116
117 assert.deepStrictEqual(yield* read("/alpha"), ["skill-in-/alpha"]);
118 assert.deepStrictEqual(yield* read("/beta"), ["skill-in-/beta"]);
119 assert.strictEqual(helpers.length, 1);
120 assert.deepStrictEqual(helpers[0]!.requests, [
121 { cwds: ["/alpha"], forceReload: true },
122 { cwds: ["/beta"], forceReload: true },
123 ]);
124
125 // Another home is another launch identity; the previous helper retires at once.
126 assert.deepStrictEqual(yield* read("/alpha", "/home-b"), ["skill-in-/alpha"]);
127 assert.strictEqual(helpers.length, 2);
128 assert.strictEqual(helpers[0]!.closed, true);
129 assert.strictEqual(helpers[1]!.codexHome, "/home-b");
130
131 // A helper that exits is replaced within the same read.
132 yield* helpers[1]!.crash;
133 assert.deepStrictEqual(yield* read("/beta", "/home-b"), ["skill-in-/beta"]);
134 assert.strictEqual(helpers.length, 3);
135
136 yield* TestClock.adjust("29 seconds");
137 assert.strictEqual(helpers[2]!.closed, false);
138 yield* TestClock.adjust("1 second");
139 assert.strictEqual(helpers[2]!.closed, true);
140 assert.deepStrictEqual(yield* read("/alpha", "/home-b"), ["skill-in-/alpha"]);
141 assert.strictEqual(helpers.length, 4);
142
143 yield* Scope.close(providerScope, Exit.void);
144 assert.strictEqual(helpers[3]!.closed, true);
145 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
146 );
147
148 it("maps current Codex model capability fields", () => {
149 const capabilities = mapCodexModelCapabilities({
150 additionalSpeedTiers: [],
151 defaultReasoningEffort: "super-high",
152 description: "Test model",
153 displayName: "GPT Test",
154 hidden: false,
155 id: "gpt-test",
156 isDefault: true,
157 model: "gpt-test",
158 availableAccessPrograms: { cyber: ["standard", "daybreakBlue"] },
159 defaultServiceTier: "flex",
160 serviceTiers: [
161 {
162 id: "priority",
163 name: "Fast",
164 description: "Lower latency responses.",
165 },
166 {
167 id: "flex",
168 name: "Flex",
169 description: "Lower-cost asynchronous routing.",
170 },
171 ],
172 supportedReasoningEfforts: [
173 {
174 description: "Maximum reasoning",
175 reasoningEffort: "super-high",
176 },
177 ],
178 });
179
180 assert.deepStrictEqual(capabilities.optionDescriptors, [
181 {
182 id: "reasoningEffort",
183 label: "Reasoning",
184 type: "select",
185 options: [{ id: "super-high", label: "super-high", isDefault: true }],
186 currentValue: "super-high",
187 },
188 {
189 id: "serviceTier",
190 label: "Service Tier",
191 type: "select",
192 options: [
193 { id: "default", label: "Standard" },
194 {
195 id: "priority",
196 label: "Fast",
197 description: "Lower latency responses.",
198 },
199 {
200 id: "flex",
201 label: "Flex",
202 description: "Lower-cost asynchronous routing.",
203 isDefault: true,
204 },
205 ],
206 currentValue: "flex",
207 },
208 {
209 id: "cyberAccessProgram",
210 label: "Cyber Access",
211 type: "select",
212 options: [
213 { id: "standard", label: "Standard", isDefault: true },
214 { id: "daybreakBlue", label: "Daybreak Blue" },
215 ],
216 currentValue: "standard",
217 },
218 ]);
219 });
220
221 it("uses standard routing when the catalog has no default service tier", () => {
222 const capabilities = mapCodexModelCapabilities({
223 additionalSpeedTiers: ["fast"],
224 defaultReasoningEffort: "medium",
225 defaultServiceTier: null,
226 description: "Test model",
227 displayName: "GPT Test",
228 hidden: false,
229 id: "gpt-test",
230 isDefault: true,
231 model: "gpt-test",
232 serviceTiers: [
233 {
234 id: "priority",
235 name: "Fast",
236 description: "1.5x speed, increased usage",
237 },
238 {
239 id: "ultrafast",
240 name: "Ultrafast",
241 description: "The fastest available responses for latency-sensitive work.",
242 },
243 ],
244 supportedReasoningEfforts: [],
245 });
246
247 assert.deepStrictEqual(capabilities.optionDescriptors, [
248 {
249 id: "serviceTier",
250 label: "Service Tier",
251 type: "select",
252 options: [
253 { id: "default", label: "Standard", isDefault: true },
254 {
255 id: "priority",
256 label: "Fast",
257 description: "1.5x speed, increased usage",
258 },
259 {
260 id: "ultrafast",
261 label: "Ultrafast",
262 description: "Even faster, more expensive",
263 },
264 ],
265 currentValue: "default",
266 },
267 ]);
268 });
269
270 it("marks the most preferred available model as default", () => {
271 const models = applyPreferredCodexDefaultModel([
272 { slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
273 { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
274 ]);
275
276 assert.deepStrictEqual(
277 models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
278 [
279 { slug: "gpt-5.6-terra", isDefault: true },
280 { slug: "gpt-5.4", isDefault: undefined },
281 ],
282 );
283 });
284
285 it("ranks qualified Codex models while preserving their wire ids", () => {
286 const models = applyPreferredCodexDefaultModel([
287 {
288 slug: "openai.gpt-5.6-luna",
289 name: "Luna",
290 isCustom: false,
291 isDefault: true,
292 capabilities: null,
293 },
294 { slug: "openai.gpt-5.6-sol", name: "Sol", isCustom: false, capabilities: null },
295 ]);
296 assert.deepStrictEqual(
297 models.filter((model) => model.isDefault).map((model) => model.slug),
298 ["openai.gpt-5.6-sol"],
299 );
300 });
301
302 it("ignores custom models that shadow a preferred slug", () => {
303 const models = applyPreferredCodexDefaultModel([
304 { slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
305 { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
306 ]);
307
308 assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
309 });
310
311 it("reports native quota only for an OpenAI login on a native route", () => {
312 const chatgpt = { type: "chatgpt", email: "a@example.com", planType: "pro" } as const;
313 const hub = {
314 model_provider: "hub",
315 model_providers: { hub: { base_url: "https://hub.example.com/v1" } },
316 };
317 const cases = [
318 ["default route", chatgpt, true, {}, true],
319 ["openai base url", chatgpt, true, { openai_base_url: "https://chatgpt.com/x" }, true],
320 ["openai proxy url", chatgpt, true, { openai_base_url: "https://proxy.example.com" }, false],
321 ["custom provider", chatgpt, true, hub, false],
322 ["unknown provider id", chatgpt, true, { model_provider: "missing" }, false],
323 ["unreadable config", chatgpt, true, null, false],
324 ["login not required", chatgpt, false, {}, false],
325 ["api key", { type: "apiKey" }, true, {}, false],
326 ] as const;
327 for (const [name, account, requiresOpenaiAuth, config, expected] of cases) {
328 assert.strictEqual(
329 codexRoutesSpendNativeQuota({ account, requiresOpenaiAuth }, config),
330 expected,
331 name,
332 );
333 }
334 // The custom endpoint is what a usage-limit hub is matched against.
335 assert.strictEqual(codexCustomEndpoint(hub), "https://hub.example.com");
336 assert.strictEqual(
337 codexCustomEndpoint({ openai_base_url: "http://127.0.0.1:8317/v1" }),
338 "http://127.0.0.1:8317",
339 );
340 assert.strictEqual(codexCustomEndpoint({ openai_base_url: "https://chatgpt.com/x" }), undefined);
341 assert.strictEqual(codexCustomEndpoint({}), undefined);
342 });