@kapybara/zerosub 1.5.1 → 1.18.3

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.
Files changed (56) hide show
  1. package/README.md +220 -26
  2. package/client/accounts-surface.tsx +344 -110
  3. package/client/add-account.tsx +335 -23
  4. package/client/api-account.tsx +250 -0
  5. package/client/azure-account.tsx +311 -0
  6. package/client/commands.ts +44 -8
  7. package/client/composer-item.tsx +203 -0
  8. package/client/fork-confirm.tsx +71 -0
  9. package/client/fork-settings.tsx +148 -0
  10. package/client/pace.tsx +196 -0
  11. package/client/pi-accounts.tsx +571 -0
  12. package/client/pills.ts +63 -25
  13. package/client/reset-confirm.tsx +12 -3
  14. package/client/settings-screen.tsx +48 -9
  15. package/client/store.ts +148 -19
  16. package/client/switch-row.tsx +28 -8
  17. package/client/ui.tsx +11 -0
  18. package/index.client.tsx +4 -1
  19. package/index.server.ts +53 -10
  20. package/package.json +5 -2
  21. package/server/account-identity.ts +11 -0
  22. package/server/adapter.ts +115 -8
  23. package/server/api-usage.ts +144 -0
  24. package/server/azure.ts +346 -0
  25. package/server/binaries.ts +41 -3
  26. package/server/claude.ts +276 -21
  27. package/server/codex-same-conversation.ts +71 -0
  28. package/server/codex.ts +35 -7
  29. package/server/continuations.ts +67 -17
  30. package/server/cursor.ts +222 -0
  31. package/server/families.ts +105 -8
  32. package/server/grok.ts +225 -0
  33. package/server/handoff.ts +211 -29
  34. package/server/homes.ts +1263 -35
  35. package/server/json-file.ts +39 -8
  36. package/server/launchers.ts +319 -0
  37. package/server/limits.ts +80 -3
  38. package/server/main-proxy.ts +238 -0
  39. package/server/modes.ts +20 -4
  40. package/server/paths.ts +81 -1
  41. package/server/pi.ts +528 -0
  42. package/server/placement.ts +133 -0
  43. package/server/process.ts +18 -1
  44. package/server/processes.ts +66 -0
  45. package/server/provider-env.ts +28 -0
  46. package/server/proxy.ts +282 -0
  47. package/server/reopen.ts +50 -8
  48. package/server/routing.ts +337 -30
  49. package/server/service.ts +4320 -805
  50. package/server/state.ts +303 -24
  51. package/server/usage.ts +2 -0
  52. package/shared/format.ts +170 -2
  53. package/shared/model.ts +339 -2
  54. package/shared/preferences.ts +22 -1
  55. package/shared/rpc.ts +130 -8
  56. package/shared/timeline.ts +11 -0
@@ -0,0 +1,346 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { lstat, mkdir, open, readdir, readFile, rename, rm, unlink } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import type { ApiMonth, ApiPrice, AzureSummary, TokenCount } from "../shared/model";
6
+ import { cleanPrices } from "./api-usage";
7
+ import { Mutex, readJson, writeJsonAtomic } from "./json-file";
8
+ import { mainCodexHome } from "./paths";
9
+ import { providerEnv } from "./provider-env";
10
+ import { bypassesProxy, proxiedFetch, proxyFromEnv } from "./proxy";
11
+
12
+ /**
13
+ * Azure OpenAI accounts: a ChatGPT (Codex) account that runs Codex on an Azure OpenAI resource with an
14
+ * API key instead of a ChatGPT sign-in. Its home is a Codex home like any added account's, except:
15
+ *
16
+ * - `azure.json` (mode 600) holds the endpoint, the key and the user's price table. The key is never
17
+ * logged, never written to the registry, and never sent to the app (only its last four characters).
18
+ * - `config.toml` isn't a link to `~/.codex/config.toml`: it's that file with `model_provider` set to
19
+ * ZeroSub's Azure provider, whose key Codex reads from `AZURE_KEY_ENV` (set for each session it opens).
20
+ * - There's no `auth.json`: nothing signs in.
21
+ */
22
+
23
+ /** The account's own settings file, in its home. */
24
+ export const AZURE_FILE = "azure.json";
25
+ /** The variable the generated provider reads its key from (`env_key`). */
26
+ export const AZURE_KEY_ENV = "ZEROSUB_AZURE_OPENAI_API_KEY";
27
+ /** The provider's id in the generated `config.toml`. */
28
+ export const AZURE_PROVIDER_ID = "zerosub_azure";
29
+ /** Keys shorter than this get no hint: their last four characters would give away too much. */
30
+ const KEY_HINT_MIN_LENGTH = 12;
31
+
32
+ export interface AzureAccount {
33
+ endpoint: string;
34
+ key: string;
35
+ prices: Record<string, ApiPrice>;
36
+ }
37
+
38
+ /**
39
+ * Whether `home` is an Azure OpenAI account's (it has `azure.json`), for the Codex adapter, which only
40
+ * sees homes. The registry marks the account itself (`provider: "azure"`), and that's what routing and
41
+ * the app go by. No other Codex home can have the file: it's never linked in from `~/.codex`.
42
+ */
43
+ export function isAzureHome(home: string | null | undefined): home is string {
44
+ return Boolean(home) && existsSync(join(home!, AZURE_FILE));
45
+ }
46
+
47
+ /**
48
+ * Checks the endpoint typed by the user: https only, no credentials, query or fragment, and no trailing
49
+ * slash. A bare resource URL gets Azure's v1 API path (`/openai/v1`), and `/openai` gets `/v1`.
50
+ */
51
+ export function normalizeAzureEndpoint(input: string): string {
52
+ let url: URL;
53
+ try {
54
+ url = new URL(input.trim());
55
+ } catch {
56
+ throw new Error("Enter the endpoint as a URL, like https://<resource>.openai.azure.com/openai/v1");
57
+ }
58
+ if (url.protocol !== "https:") throw new Error("The endpoint must start with https://");
59
+ if (url.username || url.password) throw new Error("Put the key in the key field, not in the endpoint URL");
60
+ if (url.search || url.hash) throw new Error("The endpoint can't have a query or fragment (Azure's v1 API needs no api-version)");
61
+ let path = url.pathname.replace(/\/+$/, "");
62
+ if (path === "") path = "/openai/v1";
63
+ else if (/\/openai$/i.test(path)) path = `${path}/v1`;
64
+ return `https://${url.host}${path}`;
65
+ }
66
+
67
+ export function azureKeyHint(key: string): string {
68
+ return key.length >= KEY_HINT_MIN_LENGTH ? key.slice(-4) : "";
69
+ }
70
+
71
+ /** A short hash of the key, to tell two accounts with the same key apart from the registry without storing it. */
72
+ export function azureIdentity(endpoint: string, key: string): string {
73
+ return `azure|${endpoint}|${createHash("sha256").update(key).digest("hex").slice(0, 16)}`;
74
+ }
75
+
76
+ /** The account's settings; throws when the file is missing or has no endpoint or key. */
77
+ export async function readAzureAccount(home: string): Promise<AzureAccount> {
78
+ const raw = await readJson(join(home, AZURE_FILE)).catch(() => undefined);
79
+ const value = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : null;
80
+ const endpoint = typeof value?.endpoint === "string" ? value.endpoint.trim() : "";
81
+ const key = typeof value?.key === "string" ? value.key.trim() : "";
82
+ if (!endpoint || !key) throw new Error(`${home} has no readable ${AZURE_FILE}`);
83
+ return { endpoint, key, prices: cleanPrices(value?.prices) };
84
+ }
85
+
86
+ /** Writes the account's settings, readable only by the user (mode 600, in a folder only they can open). */
87
+ export async function writeAzureAccount(home: string, account: AzureAccount): Promise<void> {
88
+ await mkdir(home, { recursive: true, mode: 0o700 });
89
+ await writeJsonAtomic(join(home, AZURE_FILE), { endpoint: account.endpoint, key: account.key, prices: account.prices }, { mode: 0o600 });
90
+ }
91
+
92
+ /** What the app may see of the account: no key, only its hint. */
93
+ export function azureSummary(account: AzureAccount, usage: ApiMonth | null): AzureSummary {
94
+ let host = account.endpoint;
95
+ try {
96
+ host = new URL(account.endpoint).host;
97
+ } catch {
98
+ // Kept as typed.
99
+ }
100
+ return { endpoint: account.endpoint, host, keyHint: azureKeyHint(account.key), prices: account.prices, usage };
101
+ }
102
+
103
+ // --------------------------------------------------------------------------- config.toml
104
+
105
+ const TABLE_HEADER = /^\s*\[\[?([^[\]#]+)\]\]?\s*(?:#.*)?$/;
106
+
107
+ /** A table header's name with quotes and spaces taken out (`model_providers."x"` → `model_providers.x`). */
108
+ function tableName(raw: string): string {
109
+ return raw.replace(/["'\s]/g, "");
110
+ }
111
+
112
+ /**
113
+ * Walks a TOML line outside strings: how much `[`/`]` nesting it opens or closes, and whether it
114
+ * leaves a multi-line string (`"""` or `'''`) open. Comments end the line.
115
+ */
116
+ function scanLine(line: string, openString: string | null): { depth: number; openString: string | null } {
117
+ let depth = 0;
118
+ let index = 0;
119
+ let quote = openString;
120
+ while (index < line.length) {
121
+ if (quote) {
122
+ if (quote.length === 3) {
123
+ const end = line.indexOf(quote, index);
124
+ if (end < 0) return { depth, openString: quote };
125
+ index = end + 3;
126
+ quote = null;
127
+ continue;
128
+ }
129
+ const char = line[index]!;
130
+ if (quote === '"' && char === "\\") index += 2;
131
+ else {
132
+ if (char === quote) quote = null;
133
+ index += 1;
134
+ }
135
+ continue;
136
+ }
137
+ const rest = line.slice(index);
138
+ if (rest.startsWith('"""') || rest.startsWith("'''")) {
139
+ quote = rest.slice(0, 3);
140
+ index += 3;
141
+ continue;
142
+ }
143
+ const char = line[index]!;
144
+ if (char === "#") break;
145
+ if (char === '"' || char === "'") quote = char;
146
+ else if (char === "[") depth += 1;
147
+ else if (char === "]") depth -= 1;
148
+ index += 1;
149
+ }
150
+ // A single-line string can't stay open past its line.
151
+ return { depth, openString: quote && quote.length === 3 ? quote : null };
152
+ }
153
+
154
+ function tomlString(value: string): string {
155
+ return JSON.stringify(value);
156
+ }
157
+
158
+ /**
159
+ * The Azure home's `config.toml`: the shared one, with Codex's provider set to ZeroSub's Azure
160
+ * provider. Only what that needs changes: a top-level `model_provider` (and a top-level dotted key or
161
+ * table for the `zerosub_azure` provider) is taken out, `model_provider` goes in first (before any
162
+ * table header, so it stays top-level), and the provider's table goes at the end. Everything else,
163
+ * comments, profiles and other providers included, stays as it is. A `profile` that sets its own
164
+ * `model_provider` still wins over this, as it would in Codex.
165
+ */
166
+ export function azureConfigToml(shared: string, endpoint: string): string {
167
+ const out: string[] = [];
168
+ let table: string | null = null;
169
+ let dropTable = false;
170
+ let depth = 0;
171
+ let openString: string | null = null;
172
+ let dropValue = false;
173
+ for (const line of shared.replace(/\r\n/g, "\n").split("\n")) {
174
+ // Inside a value that spans lines (a multi-line string or array): it goes wherever its key went.
175
+ if (openString || depth > 0) {
176
+ const scanned = scanLine(line, openString);
177
+ openString = scanned.openString;
178
+ depth = Math.max(0, depth + scanned.depth);
179
+ if (!dropValue && !dropTable) out.push(line);
180
+ continue;
181
+ }
182
+ const header = TABLE_HEADER.exec(line);
183
+ if (header?.[1]) {
184
+ table = tableName(header[1]);
185
+ dropTable = table === `model_providers.${AZURE_PROVIDER_ID}` || table.startsWith(`model_providers.${AZURE_PROVIDER_ID}.`);
186
+ if (!dropTable) out.push(line);
187
+ continue;
188
+ }
189
+ const scanned = scanLine(line, null);
190
+ openString = scanned.openString;
191
+ depth = Math.max(0, scanned.depth);
192
+ const key = /^\s*([A-Za-z0-9_."'-]+?)\s*=/.exec(line)?.[1];
193
+ const name = key ? tableName(key) : null;
194
+ dropValue =
195
+ table === null &&
196
+ name !== null &&
197
+ (name === "model_provider" || name === `model_providers.${AZURE_PROVIDER_ID}` || name.startsWith(`model_providers.${AZURE_PROVIDER_ID}.`));
198
+ if (!dropValue && !dropTable) out.push(line);
199
+ }
200
+ while (out.length > 0 && out[out.length - 1]!.trim() === "") out.pop();
201
+ return [
202
+ "# Made by ZeroSub for an Azure OpenAI account from ~/.codex/config.toml; it's remade when that changes,",
203
+ "# so edit ~/.codex/config.toml instead. The API key isn't here: Codex reads it from " + AZURE_KEY_ENV + ".",
204
+ `model_provider = ${tomlString(AZURE_PROVIDER_ID)}`,
205
+ "",
206
+ ...(out.length > 0 ? [...out, ""] : []),
207
+ `[model_providers.${AZURE_PROVIDER_ID}]`,
208
+ `name = ${tomlString("Azure OpenAI")}`,
209
+ `base_url = ${tomlString(endpoint)}`,
210
+ `env_key = ${tomlString(AZURE_KEY_ENV)}`,
211
+ `wire_api = ${tomlString("responses")}`,
212
+ "",
213
+ ].join("\n");
214
+ }
215
+
216
+ const configLocks = new Map<string, Mutex>();
217
+
218
+ /**
219
+ * Remakes the Azure home's `config.toml` from the shared one when what it would hold has changed (a
220
+ * read of two small files and a compare, so it runs at every session open). A link to the shared file
221
+ * left by an earlier sync is replaced by the file, never written through.
222
+ */
223
+ export function syncAzureConfig(home: string): Promise<void> {
224
+ let lock = configLocks.get(home);
225
+ if (!lock) configLocks.set(home, (lock = new Mutex()));
226
+ return lock.run(async () => {
227
+ const { endpoint } = await readAzureAccount(home);
228
+ const shared = await readFile(join(mainCodexHome(), "config.toml"), "utf8").catch(() => "");
229
+ const next = azureConfigToml(shared, endpoint);
230
+ const target = join(home, "config.toml");
231
+ const current = await lstat(target).catch(() => null);
232
+ if (current?.isFile() && (await readFile(target, "utf8").catch(() => null)) === next) return;
233
+ if (current?.isSymbolicLink()) await unlink(target);
234
+ const temporary = join(home, `.config.${randomBytes(6).toString("hex")}.tmp`);
235
+ try {
236
+ const file = await open(temporary, "wx", 0o600);
237
+ try {
238
+ await file.writeFile(next);
239
+ } finally {
240
+ await file.close();
241
+ }
242
+ await rename(temporary, target);
243
+ } catch (error) {
244
+ await rm(temporary, { force: true });
245
+ throw error;
246
+ }
247
+ });
248
+ }
249
+
250
+ // --------------------------------------------------------------------------- checking a key
251
+
252
+ export type AzureCheck = { ok: true } | { ok: false; fatal: boolean; message: string };
253
+
254
+ type Fetcher = (url: string, init: { headers: Record<string, string>; signal: AbortSignal }) => Promise<{ status: number }>;
255
+
256
+ const defaultFetcher: Fetcher = (url, init) => {
257
+ const env = { ...process.env, ...providerEnv("codex") };
258
+ const proxy = proxyFromEnv(env);
259
+ const direct = !proxy || bypassesProxy(env.no_proxy ?? env.NO_PROXY ?? null, url);
260
+ return proxiedFetch(direct ? null : proxy, url, init);
261
+ };
262
+
263
+ /**
264
+ * Asks the endpoint for its models with the key (`GET {endpoint}/models`, `api-key` header). A refused
265
+ * key (401/403) is `fatal`; anything else that goes wrong (the network, a timeout, another status) is
266
+ * only a warning, so an account can be saved while Azure can't be reached from here. Error text never
267
+ * includes the key.
268
+ */
269
+ export async function checkAzureKey(endpoint: string, key: string, fetcher: Fetcher = defaultFetcher, timeoutMs = 15_000): Promise<AzureCheck> {
270
+ try {
271
+ const response = await fetcher(`${endpoint}/models`, { headers: { "api-key": key, accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
272
+ if (response.status >= 200 && response.status < 300) return { ok: true };
273
+ if (response.status === 401 || response.status === 403) {
274
+ return { ok: false, fatal: true, message: `Azure refused the key (HTTP ${response.status}). Check the key and that it belongs to this resource.` };
275
+ }
276
+ return {
277
+ ok: false,
278
+ fatal: false,
279
+ message:
280
+ response.status === 404
281
+ ? "The endpoint answered 404 for its model list: check that it ends in /openai/v1."
282
+ : `The endpoint answered HTTP ${response.status} for its model list.`,
283
+ };
284
+ } catch (error) {
285
+ const reason = error instanceof Error ? (error.name === "TimeoutError" ? "it didn't answer in time" : error.message) : String(error);
286
+ return { ok: false, fatal: false, message: `Couldn't reach the endpoint to check the key (${reason.replaceAll(key, "…")}).` };
287
+ }
288
+ }
289
+
290
+ function number(value: unknown): number {
291
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
292
+ }
293
+
294
+ /**
295
+ * A Codex thread's tokens so far, from its rollout file: the last `token_count` event's
296
+ * `total_token_usage`, and the model of its last `turn_context`. Null when the file has neither.
297
+ */
298
+ export function parseRollout(text: string): { model: string | null; total: TokenCount } | null {
299
+ let model: string | null = null;
300
+ let total: TokenCount | null = null;
301
+ for (const line of text.split("\n")) {
302
+ if (!line.includes("token_count") && !line.includes("turn_context")) continue;
303
+ let entry: { type?: unknown; payload?: Record<string, unknown> };
304
+ try {
305
+ entry = JSON.parse(line) as typeof entry;
306
+ } catch {
307
+ continue;
308
+ }
309
+ const payload = entry.payload;
310
+ if (!payload || typeof payload !== "object") continue;
311
+ if (entry.type === "turn_context" && typeof payload.model === "string") model = payload.model;
312
+ if (entry.type === "event_msg" && payload.type === "token_count") {
313
+ const info = payload.info as { total_token_usage?: Record<string, unknown> } | null | undefined;
314
+ const usage = info?.total_token_usage;
315
+ if (usage) total = { input: number(usage.input_tokens), cachedInput: number(usage.cached_input_tokens), cacheWrite: 0, output: number(usage.output_tokens) };
316
+ }
317
+ }
318
+ return total ? { model, total } : null;
319
+ }
320
+
321
+ const rolloutPaths = new Map<string, string>();
322
+ const ROLLOUT_DAYS_SEARCHED = 120;
323
+
324
+ /** Where Codex keeps a thread's rollout: `sessions/YYYY/MM/DD/rollout-<time>-<thread id>.jsonl`, newest days first. */
325
+ export async function findRollout(threadId: string, sessions = join(mainCodexHome(), "sessions")): Promise<string | null> {
326
+ const known = rolloutPaths.get(threadId);
327
+ if (known && existsSync(known)) return known;
328
+ if (!/^[\w-]{8,}$/.test(threadId)) return null;
329
+ const sorted = async (dir: string) => (await readdir(dir).catch(() => [] as string[])).filter((name) => /^\d+$/.test(name)).sort().reverse();
330
+ let days = 0;
331
+ for (const year of await sorted(sessions)) {
332
+ for (const month of await sorted(join(sessions, year))) {
333
+ for (const day of await sorted(join(sessions, year, month))) {
334
+ if (days++ >= ROLLOUT_DAYS_SEARCHED) return null;
335
+ const dir = join(sessions, year, month, day);
336
+ const name = (await readdir(dir).catch(() => [] as string[])).find((entry) => entry.startsWith("rollout-") && entry.endsWith(`${threadId}.jsonl`));
337
+ if (name) {
338
+ const path = join(dir, name);
339
+ rolloutPaths.set(threadId, path);
340
+ return path;
341
+ }
342
+ }
343
+ }
344
+ }
345
+ return null;
346
+ }
@@ -1,5 +1,7 @@
1
1
  import { chmod, mkdir, writeFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { FAMILIES, type Family } from "../shared/model";
4
+ import { acpCommand, familiesFromConfig } from "./families";
3
5
  import { readJson } from "./json-file";
4
6
  import { dataDir, paseoHome } from "./paths";
5
7
 
@@ -13,14 +15,14 @@ const CACHE_MS = 60_000;
13
15
  let cache: { at: number; value: Record<string, Command> } | null = null;
14
16
 
15
17
  /** The CLI Paseo launches for a provider: `agents.providers.<id>.command` when set, else the name on PATH. */
16
- export async function providerCommand(provider: "claude" | "codex"): Promise<Command> {
18
+ export async function providerCommand(provider: Family): Promise<Command> {
17
19
  if (!cache || Date.now() - cache.at > CACHE_MS) {
18
20
  const value: Record<string, Command> = {};
19
21
  try {
20
22
  const config = (await readJson(join(paseoHome(), "config.json"))) as
21
23
  | { agents?: { providers?: Record<string, { command?: unknown }> } }
22
24
  | undefined;
23
- for (const id of ["claude", "codex"]) {
25
+ for (const id of FAMILIES) {
24
26
  const command = config?.agents?.providers?.[id]?.command;
25
27
  if (Array.isArray(command) && typeof command[0] === "string" && command.every((part) => typeof part === "string")) {
26
28
  value[id] = { command: command[0], prefix: command.slice(1) as string[] };
@@ -31,7 +33,43 @@ export async function providerCommand(provider: "claude" | "codex"): Promise<Com
31
33
  }
32
34
  cache = { at: Date.now(), value };
33
35
  }
34
- return cache.value[provider] ?? { command: provider, prefix: [] };
36
+ // Paseo's Pi provider also takes its binary from PI_COMMAND (or the older PI_ACP_PI_COMMAND).
37
+ const fallback = provider === "pi" ? process.env.PI_COMMAND?.trim() || process.env.PI_ACP_PI_COMMAND?.trim() || "pi" : provider;
38
+ return cache.value[provider] ?? { command: fallback, prefix: [] };
39
+ }
40
+
41
+ /**
42
+ * The binary of the Paseo provider that runs Grok Build (see `ACP_COMMANDS` in families.ts), preferring
43
+ * one with the id `grok`, as Paseo's catalog names it; null when no provider runs Grok, or the config
44
+ * can't be read.
45
+ */
46
+ export function grokBinary(): Promise<string | null> {
47
+ return acpBinary("grok");
48
+ }
49
+
50
+ /** The same for Cursor's agent (`cursor-agent acp`), preferring the provider with the id `cursor`. */
51
+ export function cursorBinary(): Promise<string | null> {
52
+ return acpBinary("cursor");
53
+ }
54
+
55
+ /** The binary of a custom ACP provider of `family`, preferring the one whose id is the family's. */
56
+ async function acpBinary(family: Family): Promise<string | null> {
57
+ try {
58
+ const config = (await readJson(join(paseoHome(), "config.json"))) as { agents?: { providers?: Record<string, unknown> } } | undefined;
59
+ const providers = config?.agents?.providers;
60
+ const ids = Object.entries(familiesFromConfig(providers))
61
+ .filter(([, found]) => found === family)
62
+ .map(([id]) => id)
63
+ .sort((a, b) => (a === family ? -1 : b === family ? 1 : 0));
64
+ for (const id of ids) {
65
+ const entry = providers?.[id];
66
+ const binary = acpCommand(family, entry && typeof entry === "object" && !Array.isArray(entry) ? (entry as Record<string, unknown>) : undefined);
67
+ if (binary) return binary;
68
+ }
69
+ } catch {
70
+ // Unreadable config: no provider to go by.
71
+ }
72
+ return null;
35
73
  }
36
74
 
37
75
  let browserShim: Promise<string | null> | null = null;