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