@kapybara/zerosub 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,459 @@
1
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import type { LoginMethod, ResetOffer, Usage, UsageWindow } from "../shared/model";
4
+ import {
5
+ ProgressEmitter,
6
+ spawnEnv,
7
+ type EnvPatch,
8
+ type FamilyAdapter,
9
+ type Identity,
10
+ type LoginHandle,
11
+ type RedeemReply,
12
+ } from "./adapter";
13
+ import { providerCommand } from "./binaries";
14
+ import { codexSqliteHome, prepareCodexHome } from "./homes";
15
+ import { detectCodexLimit, detectCodexSignOut } from "./limits";
16
+ import { run } from "./process";
17
+
18
+ /** The originator Codex's own CLI logs in with; the sign-in service knows it. */
19
+ const CLIENT_NAME = "codex_cli_rs";
20
+
21
+ type Json = Record<string, unknown>;
22
+
23
+ /** Newline-delimited JSON-RPC with `codex app-server` (no `jsonrpc` field on the wire). */
24
+ class AppServer {
25
+ private nextId = 1;
26
+ private buffer = "";
27
+ private stderr = "";
28
+ private closed = false;
29
+ private ending = false;
30
+ private readonly pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
31
+ private readonly listeners = new Map<string, Set<(params: Json) => void>>();
32
+ readonly exited: Promise<void>;
33
+
34
+ private constructor(private readonly child: ChildProcessWithoutNullStreams) {
35
+ child.stdin.on("error", () => undefined);
36
+ child.stdout.on("data", (chunk: Buffer) => this.receive(chunk.toString("utf8")));
37
+ child.stderr.on("data", (chunk: Buffer) => {
38
+ this.stderr = (this.stderr + chunk.toString("utf8")).slice(-4_000);
39
+ });
40
+ this.exited = new Promise((resolve) => {
41
+ const finish = (error?: Error) => {
42
+ this.closed = true;
43
+ const reason = error ?? new Error(this.stderr.trim().split("\n").pop() || "Codex exited");
44
+ for (const request of this.pending.values()) request.reject(reason);
45
+ this.pending.clear();
46
+ resolve();
47
+ };
48
+ child.on("error", (error) => finish(error));
49
+ child.on("close", () => finish());
50
+ });
51
+ }
52
+
53
+ static async open(env: NodeJS.ProcessEnv): Promise<AppServer> {
54
+ const { command, prefix } = await providerCommand("codex");
55
+ const child = spawn(command, [...prefix, "app-server"], { env, stdio: ["pipe", "pipe", "pipe"] });
56
+ const server = new AppServer(child);
57
+ try {
58
+ await server.request(
59
+ "initialize",
60
+ { clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.0.0" }, capabilities: { experimentalApi: false } },
61
+ 60_000,
62
+ );
63
+ server.send({ method: "initialized" });
64
+ return server;
65
+ } catch (error) {
66
+ server.close();
67
+ throw error;
68
+ }
69
+ }
70
+
71
+ on(method: string, listener: (params: Json) => void): void {
72
+ let set = this.listeners.get(method);
73
+ if (!set) this.listeners.set(method, (set = new Set()));
74
+ set.add(listener);
75
+ }
76
+
77
+ request(method: string, params?: unknown, timeoutMs = 30_000): Promise<unknown> {
78
+ if (this.closed || this.ending) return Promise.reject(new Error("Codex is not running"));
79
+ const id = this.nextId++;
80
+ return new Promise((resolve, reject) => {
81
+ const timer = setTimeout(() => {
82
+ this.pending.delete(id);
83
+ reject(new Error(`Codex did not answer ${method}`));
84
+ }, timeoutMs);
85
+ this.pending.set(id, {
86
+ resolve: (value) => {
87
+ clearTimeout(timer);
88
+ resolve(value);
89
+ },
90
+ reject: (error) => {
91
+ clearTimeout(timer);
92
+ reject(error);
93
+ },
94
+ });
95
+ this.send(params === undefined ? { id, method } : { id, method, params });
96
+ });
97
+ }
98
+
99
+ close(): void {
100
+ if (this.closed || this.ending) return;
101
+ this.ending = true;
102
+ for (const request of this.pending.values()) request.reject(new Error("Codex was stopped"));
103
+ this.pending.clear();
104
+ this.child.stdin.end();
105
+ this.child.kill("SIGTERM");
106
+ setTimeout(() => {
107
+ if (!this.closed) this.child.kill("SIGKILL");
108
+ }, 3_000).unref();
109
+ }
110
+
111
+ private send(message: Json): void {
112
+ if (!this.closed && !this.ending) this.child.stdin.write(`${JSON.stringify(message)}\n`);
113
+ }
114
+
115
+ private receive(text: string): void {
116
+ this.buffer += text;
117
+ let newline = this.buffer.indexOf("\n");
118
+ while (newline >= 0) {
119
+ const line = this.buffer.slice(0, newline).trim();
120
+ this.buffer = this.buffer.slice(newline + 1);
121
+ newline = this.buffer.indexOf("\n");
122
+ if (!line) continue;
123
+ let message: Json;
124
+ try {
125
+ message = JSON.parse(line) as Json;
126
+ } catch {
127
+ continue;
128
+ }
129
+ this.dispatch(message);
130
+ }
131
+ }
132
+
133
+ private dispatch(message: Json): void {
134
+ const id = typeof message.id === "number" ? message.id : null;
135
+ if (id !== null && typeof message.method === "string") {
136
+ // A request from the server (e.g. external token refresh); ZeroSub never uses external auth.
137
+ this.send({ id, error: { code: -32601, message: "Not supported" } });
138
+ return;
139
+ }
140
+ if (id !== null) {
141
+ const request = this.pending.get(id);
142
+ if (!request) return;
143
+ this.pending.delete(id);
144
+ const error = message.error as { message?: unknown } | undefined;
145
+ if (error) request.reject(new Error(typeof error.message === "string" ? error.message : "Codex request failed"));
146
+ else request.resolve(message.result);
147
+ return;
148
+ }
149
+ if (typeof message.method === "string") {
150
+ for (const listener of this.listeners.get(message.method) ?? []) listener((message.params ?? {}) as Json);
151
+ }
152
+ }
153
+ }
154
+
155
+ interface Snapshot {
156
+ identity: Identity;
157
+ usage: Usage;
158
+ }
159
+
160
+ export class CodexAdapter implements FamilyAdapter {
161
+ readonly family = "codex" as const;
162
+ /** ChatGPT accounts can't decrypt each other's reasoning, so threads stay on their account. */
163
+ readonly portable = false;
164
+ readonly usageSpacingMs = 20_000;
165
+ private readonly snapshots = new Map<string, { at: number; value: Promise<Snapshot> }>();
166
+
167
+ async env(home: string | null): Promise<EnvPatch> {
168
+ if (!home) return { CODEX_HOME: null, CODEX_SQLITE_HOME: null };
169
+ const patch: EnvPatch = { CODEX_HOME: home };
170
+ // Share thread metadata with the main home so every account sees the same threads.
171
+ const sqlite = await codexSqliteHome();
172
+ patch.CODEX_SQLITE_HOME = sqlite;
173
+ if (process.env.CODEX_ACCESS_TOKEN) patch.CODEX_ACCESS_TOKEN = "";
174
+ return patch;
175
+ }
176
+
177
+ async available(): Promise<{ ok: boolean; detail: string | null }> {
178
+ const { command, prefix } = await providerCommand("codex");
179
+ const result = await run(command, [...prefix, "--version"], { timeoutMs: 30_000 });
180
+ if (result.code === 0) return { ok: true, detail: null };
181
+ return { ok: false, detail: (result.stderr || result.stdout).trim().split("\n")[0] || `${command} not found` };
182
+ }
183
+
184
+ prepareHome(home: string): Promise<void> {
185
+ return prepareCodexHome(home);
186
+ }
187
+
188
+ async identity(home: string | null): Promise<Identity> {
189
+ return (await this.snapshot(home)).identity;
190
+ }
191
+
192
+ async usage(home: string | null): Promise<Usage> {
193
+ return (await this.snapshot(home, true)).usage;
194
+ }
195
+
196
+ /** One short app-server session answers both "who is this" and "how much is left". */
197
+ private snapshot(home: string | null, fresh = false): Promise<Snapshot> {
198
+ const key = home ?? "";
199
+ const cached = this.snapshots.get(key);
200
+ if (cached && Date.now() - cached.at < (fresh ? 5_000 : 15_000)) return cached.value;
201
+ const value = this.readSnapshot(home);
202
+ this.snapshots.set(key, { at: Date.now(), value });
203
+ value.catch(() => this.snapshots.delete(key));
204
+ return value;
205
+ }
206
+
207
+ private async readSnapshot(home: string | null): Promise<Snapshot> {
208
+ const server = await AppServer.open(spawnEnv(await this.env(home)));
209
+ try {
210
+ const account = ((await server.request("account/read", {})) ?? {}) as Json;
211
+ const details = account.account as { type?: unknown; email?: unknown; planType?: unknown } | null;
212
+ const fetchedAt = new Date().toISOString();
213
+ if (!details || details.type !== "chatgpt") {
214
+ const signedIn = Boolean(details);
215
+ return {
216
+ identity: { signedIn, email: null, plan: signedIn ? "API key" : null, organization: null, identity: null },
217
+ usage: {
218
+ fetchedAt,
219
+ windows: [],
220
+ error: signedIn ? "Signed in with an API key, not a ChatGPT plan." : "Not signed in.",
221
+ cached: false,
222
+ resets: null,
223
+ },
224
+ };
225
+ }
226
+ const email = typeof details.email === "string" ? details.email : null;
227
+ const plan = typeof details.planType === "string" ? details.planType : null;
228
+ let usage: Usage;
229
+ let accountId: string | null = null;
230
+ try {
231
+ // Background reads skip the reset-credit detail lookup; the count still comes back.
232
+ let limits = (await server.request("account/rateLimits/read", { excludeResetCreditDetails: true })) as Json;
233
+ if (resetCount(limits.rateLimitResetCredits) > 0) {
234
+ limits = (await server.request("account/rateLimits/read", {}).catch(() => limits)) as Json;
235
+ }
236
+ accountId = typeof limits.accountId === "string" ? limits.accountId : null;
237
+ usage = {
238
+ fetchedAt,
239
+ windows: parseRateLimits(limits.rateLimits),
240
+ error: null,
241
+ cached: false,
242
+ resets: parseResetCredits(limits.rateLimitResetCredits),
243
+ };
244
+ } catch (error) {
245
+ usage = { fetchedAt, windows: [], error: error instanceof Error ? error.message : String(error), cached: false, resets: null };
246
+ }
247
+ return {
248
+ identity: {
249
+ signedIn: true,
250
+ email,
251
+ plan,
252
+ organization: null,
253
+ // The ChatGPT account (workspace) ID tells a personal plan from a Team workspace on the same
254
+ // email; without it, fall back to email plus plan so those two still stay distinct.
255
+ identity: accountId ? `chatgpt|${accountId}` : email ? `chatgpt-email|${email.toLowerCase()}|${plan ?? "unknown"}` : null,
256
+ },
257
+ usage,
258
+ };
259
+ } finally {
260
+ server.close();
261
+ }
262
+ }
263
+
264
+ async login(home: string | null, method: LoginMethod): Promise<LoginHandle> {
265
+ this.snapshots.delete(home ?? "");
266
+ const server = await AppServer.open(spawnEnv(await this.env(home)));
267
+ return new CodexLogin(server, method, () => this.snapshots.delete(home ?? ""));
268
+ }
269
+
270
+ async logout(home: string): Promise<void> {
271
+ this.snapshots.delete(home);
272
+ const server = await AppServer.open(spawnEnv(await this.env(home)));
273
+ try {
274
+ await server.request("account/logout");
275
+ } finally {
276
+ server.close();
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Codex's own reset-credit API (what `/usage` → reset in the Codex CLI uses). It never spends a
282
+ * credit while nothing is used up (`nothingToReset`), so automatic use needs no extra check.
283
+ */
284
+ async redeemReset(home: string | null): Promise<RedeemReply> {
285
+ this.snapshots.delete(home ?? "");
286
+ const server = await AppServer.open(spawnEnv(await this.env(home)));
287
+ try {
288
+ // One idempotency key per attempt, so a retried request can never spend a second credit.
289
+ const reply = (await server.request(
290
+ "account/rateLimitResetCredit/consume",
291
+ { idempotencyKey: randomUUID() },
292
+ 60_000,
293
+ )) as { outcome?: unknown };
294
+ const after = (await server.request("account/rateLimits/read", { excludeResetCreditDetails: true }).catch(() => null)) as Json | null;
295
+ const left = after ? resetCount(after.rateLimitResetCredits) : null;
296
+ return readConsumeReply(reply?.outcome, left);
297
+ } catch (error) {
298
+ return {
299
+ outcome: "error",
300
+ message: `The reset request didn't finish (${error instanceof Error ? error.message : String(error)}). Refresh usage before trying again.`,
301
+ left: null,
302
+ };
303
+ } finally {
304
+ server.close();
305
+ this.snapshots.delete(home ?? "");
306
+ }
307
+ }
308
+
309
+ detectLimit = detectCodexLimit;
310
+ detectSignOut = detectCodexSignOut;
311
+ }
312
+
313
+ class CodexLogin extends ProgressEmitter implements LoginHandle {
314
+ readonly finished: Promise<{ ok: boolean; message: string | null }>;
315
+ private loginId: string | null = null;
316
+ private settle!: (result: { ok: boolean; message: string | null }) => void;
317
+ private done = false;
318
+
319
+ constructor(
320
+ private readonly server: AppServer,
321
+ method: LoginMethod,
322
+ private readonly onFinished: () => void,
323
+ ) {
324
+ super();
325
+ this.finished = new Promise((resolve) => {
326
+ this.settle = (result) => {
327
+ if (this.done) return;
328
+ this.done = true;
329
+ this.server.close();
330
+ this.onFinished();
331
+ resolve(result);
332
+ };
333
+ });
334
+ server.on("account/login/completed", (params) => {
335
+ if (this.loginId && params.loginId && params.loginId !== this.loginId) return;
336
+ if (params.success === true) this.settle({ ok: true, message: null });
337
+ else this.settle({ ok: false, message: friendlyCodexError(typeof params.error === "string" ? params.error : null) });
338
+ });
339
+ void server.exited.then(() => this.settle({ ok: false, message: "Codex stopped before sign-in finished." }));
340
+ void this.begin(method);
341
+ }
342
+
343
+ private async begin(method: LoginMethod): Promise<void> {
344
+ try {
345
+ const result = (await this.server.request("account/login/start", {
346
+ type: method === "code" ? "chatgptDeviceCode" : "chatgpt",
347
+ })) as Json;
348
+ this.loginId = typeof result.loginId === "string" ? result.loginId : null;
349
+ if (result.type === "chatgptDeviceCode") {
350
+ this.update({
351
+ step: "waiting",
352
+ url: typeof result.verificationUrl === "string" ? result.verificationUrl : null,
353
+ userCode: typeof result.userCode === "string" ? result.userCode : null,
354
+ message:
355
+ "If the page says device codes are off, turn on “device code login” in ChatGPT → Settings → Security, or use the browser option.",
356
+ });
357
+ } else {
358
+ this.update({ step: "waiting", url: typeof result.authUrl === "string" ? result.authUrl : null });
359
+ }
360
+ } catch (error) {
361
+ this.settle({ ok: false, message: friendlyCodexError(error instanceof Error ? error.message : String(error)) });
362
+ }
363
+ }
364
+
365
+ async submitCode(): Promise<void> {
366
+ throw new Error("ChatGPT sign-in doesn't use a pasted code. Finish on the sign-in page.");
367
+ }
368
+
369
+ cancel(): void {
370
+ if (this.done) return;
371
+ const loginId = this.loginId;
372
+ if (loginId) void this.server.request("account/login/cancel", { loginId }, 5_000).catch(() => undefined);
373
+ setTimeout(() => this.settle({ ok: false, message: "Sign-in was canceled." }), 300);
374
+ }
375
+ }
376
+
377
+ function friendlyCodexError(message: string | null): string {
378
+ if (!message) return "Sign-in did not finish.";
379
+ if (/device code login is not enabled/i.test(message)) {
380
+ return "Device-code sign-in is turned off for this ChatGPT account. Turn on “device code login” in ChatGPT → Settings → Security, or sign in with the browser option.";
381
+ }
382
+ if (/not completed|timed out/i.test(message)) return "Sign-in timed out or was closed. Try again.";
383
+ return message;
384
+ }
385
+
386
+ function windowLabel(minutes: number | null): string {
387
+ if (!minutes) return "Usage";
388
+ if (minutes === 10_080) return "Weekly";
389
+ if (minutes % 1_440 === 0) return `${minutes / 1_440}-day`;
390
+ if (minutes % 60 === 0) return `${minutes / 60}-hour`;
391
+ return `${minutes}-minute`;
392
+ }
393
+
394
+ export function parseRateLimits(snapshot: unknown): UsageWindow[] {
395
+ if (!snapshot || typeof snapshot !== "object") return [];
396
+ const record = snapshot as Json;
397
+ const windows: UsageWindow[] = [];
398
+ for (const key of ["primary", "secondary"] as const) {
399
+ const window = record[key] as { usedPercent?: unknown; windowDurationMins?: unknown; resetsAt?: unknown } | null;
400
+ if (!window || typeof window.usedPercent !== "number") continue;
401
+ const minutes = typeof window.windowDurationMins === "number" ? window.windowDurationMins : null;
402
+ windows.push({
403
+ id: key,
404
+ label: windowLabel(minutes),
405
+ usedPercent: window.usedPercent,
406
+ resetsAt: typeof window.resetsAt === "number" ? new Date(window.resetsAt * 1000).toISOString() : null,
407
+ });
408
+ }
409
+ return windows;
410
+ }
411
+
412
+ /** Banked reset credits, from `rateLimitResetCredits` (`availableCount` is a JSON number on the wire). */
413
+ export function resetCount(summary: unknown): number {
414
+ const count = (summary as { availableCount?: unknown } | null)?.availableCount;
415
+ return typeof count === "number" && Number.isFinite(count) && count > 0 ? Math.floor(count) : 0;
416
+ }
417
+
418
+ export function parseResetCredits(summary: unknown): ResetOffer | null {
419
+ const available = resetCount(summary);
420
+ if (available === 0) return null;
421
+ const credits = (summary as { credits?: unknown }).credits;
422
+ const usable = (Array.isArray(credits) ? credits : []).filter(
423
+ (credit): credit is Json => Boolean(credit) && typeof credit === "object" && (credit as Json).status === "available",
424
+ );
425
+ const expiring = usable
426
+ .map((credit) => (typeof credit.expiresAt === "number" ? credit.expiresAt : null))
427
+ .filter((at): at is number => at !== null)
428
+ .sort((a, b) => a - b);
429
+ const title = usable.map((credit) => credit.title).find((value): value is string => typeof value === "string" && value.trim() !== "");
430
+ return {
431
+ available,
432
+ // Codex decides at redeem time (it answers "nothing to reset" when the limits aren't used up).
433
+ usableNow: true,
434
+ blockedReason: null,
435
+ expiresAt: expiring[0] !== undefined ? new Date(expiring[0] * 1000).toISOString() : null,
436
+ refills: ["5-hour", "weekly"],
437
+ label: title?.trim() ?? null,
438
+ };
439
+ }
440
+
441
+ export function readConsumeReply(outcome: unknown, left: number | null): RedeemReply {
442
+ const leftText = left === null ? "" : ` · ${left} left`;
443
+ switch (outcome) {
444
+ case "reset":
445
+ return { outcome: "reset", message: `Codex usage limits reset${leftText}.`, left };
446
+ case "nothingToReset":
447
+ return {
448
+ outcome: "not_limited",
449
+ message: "Nothing to reset: this account's limits aren't used up, so the reset was kept.",
450
+ left,
451
+ };
452
+ case "noCredit":
453
+ return { outcome: "none", message: "No banked resets left on this account.", left: 0 };
454
+ case "alreadyRedeemed":
455
+ return { outcome: "already_used", message: `That reset was already used${leftText}.`, left };
456
+ default:
457
+ return { outcome: "error", message: "Codex sent an unexpected reply. Refresh usage before trying again.", left };
458
+ }
459
+ }
@@ -0,0 +1,78 @@
1
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
2
+ import type { Family } from "../shared/model";
3
+
4
+ type PaseoApi = PluginHandlerContext["paseo"];
5
+
6
+ /**
7
+ * Environment keys that mean a provider entry brings its own credentials or endpoint. Such entries
8
+ * (API keys, Bedrock/Vertex, a proxy, a hand-made config dir) are left exactly as configured.
9
+ */
10
+ const OWN_AUTH_KEYS: Record<Family, readonly string[]> = {
11
+ claude: [
12
+ "ANTHROPIC_API_KEY",
13
+ "ANTHROPIC_AUTH_TOKEN",
14
+ "ANTHROPIC_BASE_URL",
15
+ "CLAUDE_CODE_OAUTH_TOKEN",
16
+ "CLAUDE_CONFIG_DIR",
17
+ "CLAUDE_CODE_USE_BEDROCK",
18
+ "CLAUDE_CODE_USE_VERTEX",
19
+ "CLAUDE_CODE_USE_FOUNDRY",
20
+ ],
21
+ codex: ["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_HOME", "OPENAI_BASE_URL"],
22
+ };
23
+
24
+ export function bringsOwnAuth(family: Family, env: Record<string, unknown> | undefined): boolean {
25
+ if (!env) return false;
26
+ return OWN_AUTH_KEYS[family].some((key) => typeof env[key] === "string" && env[key] !== "");
27
+ }
28
+
29
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
30
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
31
+ }
32
+
33
+ /**
34
+ * Maps Paseo provider IDs to the subscription family they run on: the built-in `claude` and `codex`
35
+ * providers, plus custom profiles that extend them without their own credentials.
36
+ */
37
+ export function familiesFromConfig(providers: Record<string, unknown> | undefined): Record<string, Family> {
38
+ const result: Record<string, Family> = {};
39
+ const entries = providers ?? {};
40
+ for (const family of ["claude", "codex"] as const) {
41
+ const entry = asRecord(entries[family]);
42
+ if (!entry || !bringsOwnAuth(family, asRecord(entry.env))) result[family] = family;
43
+ }
44
+ for (const [id, value] of Object.entries(entries)) {
45
+ if (id === "claude" || id === "codex") continue;
46
+ const entry = asRecord(value);
47
+ const base = entry?.extends;
48
+ if (base !== "claude" && base !== "codex") continue;
49
+ if (bringsOwnAuth(base, asRecord(entry?.env))) continue;
50
+ result[id] = base;
51
+ }
52
+ return result;
53
+ }
54
+
55
+ const CACHE_MS = 30_000;
56
+
57
+ /** Reads provider profiles from the daemon config, cached briefly because session opens are hot. */
58
+ export class FamilyResolver {
59
+ private cache: { at: number; value: Record<string, Family> } | null = null;
60
+
61
+ async resolve(paseo: PaseoApi): Promise<Record<string, Family>> {
62
+ if (this.cache && Date.now() - this.cache.at < CACHE_MS) return this.cache.value;
63
+ let value: Record<string, Family>;
64
+ try {
65
+ const { config } = await paseo.config.get();
66
+ value = familiesFromConfig(asRecord(config.providers));
67
+ } catch (error) {
68
+ console.warn("[ZeroSub] could not read provider config; using built-in providers only", describe(error));
69
+ value = { claude: "claude", codex: "codex" };
70
+ }
71
+ this.cache = { at: Date.now(), value };
72
+ return value;
73
+ }
74
+ }
75
+
76
+ function describe(error: unknown): string {
77
+ return error instanceof Error ? error.message : String(error);
78
+ }