@kapybara/zerosub 1.5.1 → 1.18.2
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.
- package/README.md +220 -26
- package/client/accounts-surface.tsx +344 -110
- package/client/add-account.tsx +335 -23
- package/client/api-account.tsx +250 -0
- package/client/azure-account.tsx +311 -0
- package/client/commands.ts +44 -8
- package/client/composer-item.tsx +203 -0
- package/client/fork-confirm.tsx +71 -0
- package/client/fork-settings.tsx +148 -0
- package/client/pace.tsx +196 -0
- package/client/pi-accounts.tsx +571 -0
- package/client/pills.ts +63 -25
- package/client/reset-confirm.tsx +12 -3
- package/client/settings-screen.tsx +48 -9
- package/client/store.ts +148 -19
- package/client/switch-row.tsx +28 -8
- package/client/ui.tsx +11 -0
- package/index.client.tsx +4 -1
- package/index.server.ts +53 -10
- package/package.json +5 -2
- package/server/account-identity.ts +11 -0
- package/server/adapter.ts +115 -8
- package/server/api-usage.ts +144 -0
- package/server/azure.ts +346 -0
- package/server/binaries.ts +41 -3
- package/server/claude.ts +276 -21
- package/server/codex-same-conversation.ts +71 -0
- package/server/codex.ts +35 -7
- package/server/continuations.ts +67 -17
- package/server/cursor.ts +222 -0
- package/server/families.ts +105 -8
- package/server/grok.ts +225 -0
- package/server/handoff.ts +211 -29
- package/server/homes.ts +1263 -35
- package/server/json-file.ts +39 -8
- package/server/launchers.ts +319 -0
- package/server/limits.ts +80 -3
- package/server/main-proxy.ts +238 -0
- package/server/modes.ts +20 -4
- package/server/paths.ts +81 -1
- package/server/pi.ts +528 -0
- package/server/placement.ts +133 -0
- package/server/process.ts +18 -1
- package/server/processes.ts +66 -0
- package/server/provider-env.ts +28 -0
- package/server/proxy.ts +282 -0
- package/server/reopen.ts +50 -8
- package/server/routing.ts +337 -30
- package/server/service.ts +4320 -805
- package/server/state.ts +303 -24
- package/server/usage.ts +2 -0
- package/shared/format.ts +170 -2
- package/shared/model.ts +339 -2
- package/shared/preferences.ts +22 -1
- package/shared/rpc.ts +130 -8
- package/shared/timeline.ts +11 -0
package/server/homes.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import { lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
|
|
1
|
+
import { cp, lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
|
-
import { join,
|
|
4
|
-
import {
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
4
|
+
import type { ApiKeyKind, ApiSummary, Family, TrafficSwitches } from "../shared/model";
|
|
5
|
+
import { AZURE_FILE, isAzureHome, syncAzureConfig } from "./azure";
|
|
6
|
+
import { Mutex, readJson } from "./json-file";
|
|
7
|
+
import { NO_PROXY_KEYS, PROXY_KEYS, REQUIRED_NO_PROXY, bypassesProxy, maskProxy, noProxyFromEnv, proxyFromEnv, withClaudeNoProxy, withoutClaudeDomains } from "./proxy";
|
|
8
|
+
import { providerEnv } from "./provider-env";
|
|
9
|
+
import { homesDir, isOwnHome, mainClaudeDir, mainClaudeGlobalConfig, mainCodexHome, mainConfigHome, mainCursorConfigDir, mainGrokHome, mainPiDir } from "./paths";
|
|
5
10
|
|
|
6
11
|
/**
|
|
7
12
|
* A managed account home is a real directory holding that account's own credentials and account
|
|
@@ -19,6 +24,11 @@ interface OverlaySpec {
|
|
|
19
24
|
const SYNC_TTL_MS = 30_000;
|
|
20
25
|
const lastSync = new Map<string, number>();
|
|
21
26
|
|
|
27
|
+
/** Has the next sync of every home run in full: main's files, which theirs are made from, changed. */
|
|
28
|
+
export function forgetSyncs(): void {
|
|
29
|
+
lastSync.clear();
|
|
30
|
+
}
|
|
31
|
+
|
|
22
32
|
async function exists(path: string): Promise<boolean> {
|
|
23
33
|
try {
|
|
24
34
|
await stat(path);
|
|
@@ -28,10 +38,42 @@ async function exists(path: string): Promise<boolean> {
|
|
|
28
38
|
}
|
|
29
39
|
}
|
|
30
40
|
|
|
41
|
+
/** One sync or edit of a home at a time, so a sync never writes back what an edit just replaced, and a move waits for both. */
|
|
42
|
+
const homeLocks = new Map<string, Mutex>();
|
|
43
|
+
|
|
44
|
+
function withHome<T>(home: string, section: () => Promise<T>): Promise<T> {
|
|
45
|
+
const key = resolve(home);
|
|
46
|
+
let lock = homeLocks.get(key);
|
|
47
|
+
if (!lock) homeLocks.set(key, (lock = new Mutex()));
|
|
48
|
+
return lock.run(section);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Asked with the home's lock held, before anything is written: an account removed meanwhile gets no
|
|
53
|
+
* home back.
|
|
54
|
+
*/
|
|
55
|
+
async function stillWanted(wanted: (() => Promise<boolean>) | undefined): Promise<void> {
|
|
56
|
+
if (wanted && !(await wanted())) throw new Error("That account no longer exists.");
|
|
57
|
+
}
|
|
58
|
+
|
|
31
59
|
async function syncOverlay(home: string, spec: OverlaySpec): Promise<void> {
|
|
32
60
|
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
33
61
|
await mkdir(spec.main, { recursive: true, mode: 0o700 });
|
|
34
62
|
for (const directory of spec.shareDirs) await mkdir(join(spec.main, directory), { recursive: true });
|
|
63
|
+
// A home that isn't ZeroSub's own (see `isOwnHome`) is the user's: a link there is only changed or
|
|
64
|
+
// dropped when it points into main, as the ones made here do. One the user made elsewhere stays.
|
|
65
|
+
const own = await isOwnHome(home);
|
|
66
|
+
const mains = [resolve(spec.main), await realpath(spec.main).catch(() => resolve(spec.main))];
|
|
67
|
+
const ours = async (link: string) => {
|
|
68
|
+
if (own) return true;
|
|
69
|
+
const raw = await readlink(link).catch(() => null);
|
|
70
|
+
if (raw === null) return false;
|
|
71
|
+
const pointsAt = resolve(home, raw);
|
|
72
|
+
return mains.some((main) => {
|
|
73
|
+
const inside = relative(main, pointsAt);
|
|
74
|
+
return inside !== "" && !inside.startsWith("..") && !isAbsolute(inside);
|
|
75
|
+
});
|
|
76
|
+
};
|
|
35
77
|
|
|
36
78
|
for (const name of await readdir(spec.main)) {
|
|
37
79
|
if (name === ".DS_Store" || spec.isPrivate(name)) continue;
|
|
@@ -43,7 +85,7 @@ async function syncOverlay(home: string, spec: OverlaySpec): Promise<void> {
|
|
|
43
85
|
const current = await lstat(link).catch(() => null);
|
|
44
86
|
if (current) {
|
|
45
87
|
if (!current.isSymbolicLink()) continue; // Created here by the CLI; leave it alone.
|
|
46
|
-
if ((await readlink(link)) === target) continue;
|
|
88
|
+
if ((await readlink(link)) === target || !(await ours(link))) continue;
|
|
47
89
|
await unlink(link);
|
|
48
90
|
}
|
|
49
91
|
const targetStat = await stat(target).catch(() => null);
|
|
@@ -59,24 +101,95 @@ async function syncOverlay(home: string, spec: OverlaySpec): Promise<void> {
|
|
|
59
101
|
for (const name of await readdir(home)) {
|
|
60
102
|
const link = join(home, name);
|
|
61
103
|
const current = await lstat(link).catch(() => null);
|
|
62
|
-
if (current?.isSymbolicLink() && !(await exists(link))) await unlink(link).catch(() => undefined);
|
|
104
|
+
if (current?.isSymbolicLink() && !(await exists(link)) && (await ours(link))) await unlink(link).catch(() => undefined);
|
|
63
105
|
}
|
|
64
106
|
}
|
|
65
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Whether `home` is a folder ZeroSub made for an account (of `family`, when given): a direct child
|
|
110
|
+
* of `homesDir()`, named `<family>-<id>`, written out in full. A path with `..` in it, or one
|
|
111
|
+
* elsewhere, is not, even if it starts with `homesDir()`.
|
|
112
|
+
*/
|
|
113
|
+
export function isAccountHome(home: string, family?: Family): boolean {
|
|
114
|
+
if (resolve(home) !== home || dirname(home) !== homesDir()) return false;
|
|
115
|
+
return !family || basename(home).startsWith(`${family}-`);
|
|
116
|
+
}
|
|
117
|
+
|
|
66
118
|
/**
|
|
67
119
|
* Deletes a managed home. Its top level holds symlinks into the user's real CLI home, so those are
|
|
68
|
-
* unlinked first; nothing outside ZeroSub's own directory is ever followed or removed
|
|
120
|
+
* unlinked first; nothing outside ZeroSub's own directory is ever followed or removed: only a folder
|
|
121
|
+
* it made for an account (see `isAccountHome`) goes, and a link put in its place is left as it is.
|
|
122
|
+
* It holds the home's lock, so a sync never puts entries back while the home is being deleted.
|
|
123
|
+
*/
|
|
124
|
+
export function removeHome(home: string): Promise<void> {
|
|
125
|
+
return withHome(home, async () => {
|
|
126
|
+
if (!isAccountHome(home) || !(await isOwnHome(home))) return;
|
|
127
|
+
// Checked again right here: a link put in its place is never followed into the folder it points at.
|
|
128
|
+
const entry = await lstat(home).catch(() => null);
|
|
129
|
+
if (!entry?.isDirectory()) return;
|
|
130
|
+
await removeTree(home);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Moves a home's folder from `from` to `to`, which mustn't exist yet, then runs `commit` (saving
|
|
136
|
+
* where its account's home is now) while it still holds both homes' locks: a sync of `from` waiting
|
|
137
|
+
* meanwhile then finds its account gone from there and never makes the folder again. When `commit`
|
|
138
|
+
* fails the folder goes back. Onto another disk the folder is copied, links as they are, and `from`
|
|
139
|
+
* only deleted once `commit` worked.
|
|
69
140
|
*/
|
|
70
|
-
export
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
141
|
+
export function moveHome(from: string, to: string, commit: () => Promise<void>): Promise<void> {
|
|
142
|
+
return withHome(from, () =>
|
|
143
|
+
withHome(to, async () => {
|
|
144
|
+
const entry = await lstat(from).catch(() => null);
|
|
145
|
+
if (!entry?.isDirectory()) throw new Error(`${from} isn't a folder`);
|
|
146
|
+
if (await lstat(to).catch(() => null)) throw new Error(`${to} is already there`);
|
|
147
|
+
await mkdir(dirname(to), { recursive: true, mode: 0o700 });
|
|
148
|
+
const copied = await moveFolder(from, to);
|
|
149
|
+
try {
|
|
150
|
+
await commit();
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (copied) await rm(to, { recursive: true, force: true });
|
|
153
|
+
else await rename(to, from);
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
if (copied) await removeTree(from);
|
|
157
|
+
for (const synced of [lastMcpSync, lastMcpKeys] as Map<string, unknown>[]) {
|
|
158
|
+
if (synced.has(from)) synced.set(to, synced.get(from));
|
|
159
|
+
synced.delete(from);
|
|
160
|
+
}
|
|
161
|
+
lastSync.delete(from);
|
|
162
|
+
}),
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Renames `from` to `to`, or copies it there when that's another disk; says whether it copied. */
|
|
167
|
+
async function moveFolder(from: string, to: string): Promise<boolean> {
|
|
168
|
+
try {
|
|
169
|
+
await rename(from, to);
|
|
170
|
+
return false;
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
await cp(from, to, { recursive: true, verbatimSymlinks: true, preserveTimestamps: true, errorOnExist: true, force: false });
|
|
176
|
+
} catch (error) {
|
|
177
|
+
await rm(to, { recursive: true, force: true });
|
|
178
|
+
throw error;
|
|
76
179
|
}
|
|
77
|
-
|
|
180
|
+
return true;
|
|
78
181
|
}
|
|
79
182
|
|
|
183
|
+
/** Deletes a folder whose top level may link into main: the links go first, never followed. */
|
|
184
|
+
async function removeTree(folder: string): Promise<void> {
|
|
185
|
+
for (const name of await readdir(folder).catch(() => [] as string[])) {
|
|
186
|
+
const path = join(folder, name);
|
|
187
|
+
if ((await lstat(path).catch(() => null))?.isSymbolicLink()) await unlink(path).catch(() => undefined);
|
|
188
|
+
}
|
|
189
|
+
await rm(folder, { recursive: true, force: true });
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
|
|
80
193
|
/** Atomic-write leftovers and scratch files: never worth sharing. */
|
|
81
194
|
function isTemporary(name: string): boolean {
|
|
82
195
|
return name.startsWith("..") || name.startsWith(".tmp") || /\.tmp(?:$|[-.])/.test(name);
|
|
@@ -84,12 +197,25 @@ function isTemporary(name: string): boolean {
|
|
|
84
197
|
|
|
85
198
|
// --------------------------------------------------------------------------- Claude
|
|
86
199
|
|
|
200
|
+
/** The account's own settings, layered over main's `settings.json`. Claude Code never writes it. */
|
|
201
|
+
export const ACCOUNT_SETTINGS = "settings.account.json";
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* The `settings.json` last generated for an account, kept beside it: what differs from it in
|
|
205
|
+
* `settings.json` was saved there since (by Claude Code's `/model`, say; see `foldSavedSettings`).
|
|
206
|
+
*/
|
|
207
|
+
const GENERATED_SETTINGS = ".settings.generated.json";
|
|
208
|
+
|
|
87
209
|
/**
|
|
88
210
|
* Per-account entries, from Claude Code's own split between configuration and state: credentials,
|
|
89
211
|
* the global config (it holds `oauthAccount`), account caches, org policy, telemetry and locks.
|
|
212
|
+
* `settings.json` is generated per account from main's plus the account's own overrides.
|
|
90
213
|
*/
|
|
91
214
|
const CLAUDE_PRIVATE = new Set([
|
|
92
215
|
".credentials.json",
|
|
216
|
+
"settings.json",
|
|
217
|
+
ACCOUNT_SETTINGS,
|
|
218
|
+
GENERATED_SETTINGS,
|
|
93
219
|
".config.json",
|
|
94
220
|
".oauth_refresh.lock",
|
|
95
221
|
".storage-write",
|
|
@@ -214,14 +340,45 @@ async function readJsonObject(path: string): Promise<Record<string, unknown> | n
|
|
|
214
340
|
}
|
|
215
341
|
}
|
|
216
342
|
|
|
343
|
+
/**
|
|
344
|
+
* One of Pi's own files as Pi reads it, so nothing Pi acts on is hidden from ZeroSub: a byte order
|
|
345
|
+
* mark is dropped, and in `models.json` (`comments`) so are `//` comments and trailing commas
|
|
346
|
+
* (`stripJsonComments` in Pi, the same from 1.4.0 to 1.5.2). Undefined without the file; throws when Pi couldn't parse it either.
|
|
347
|
+
*/
|
|
348
|
+
export async function readPiOwnJson(path: string, comments = false): Promise<unknown | undefined> {
|
|
349
|
+
let text: string;
|
|
350
|
+
try {
|
|
351
|
+
text = await readFile(path, "utf8");
|
|
352
|
+
} catch (error) {
|
|
353
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
354
|
+
throw error;
|
|
355
|
+
}
|
|
356
|
+
if (text.startsWith("\uFEFF")) text = text.slice(1);
|
|
357
|
+
if (comments) {
|
|
358
|
+
text = text
|
|
359
|
+
.replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (match) => (match[0] === '"' ? match : ""))
|
|
360
|
+
.replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (match, tail: string | undefined) => tail ?? (match[0] === '"' ? match : ""));
|
|
361
|
+
}
|
|
362
|
+
return JSON.parse(text) as unknown;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** `readPiOwnJson` for a file that should hold an object: null without one, or when it doesn't parse. */
|
|
366
|
+
async function readPiOwnObject(path: string, comments = false): Promise<Record<string, unknown> | null> {
|
|
367
|
+
const value = await readPiOwnJson(path, comments).catch(() => undefined);
|
|
368
|
+
return isObject(value) ? value : null;
|
|
369
|
+
}
|
|
370
|
+
|
|
217
371
|
async function writeJsonAtomically(path: string, value: unknown): Promise<void> {
|
|
218
372
|
const temporary = `${path}.zerosub.${randomBytes(4).toString("hex")}.tmp`;
|
|
219
373
|
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
220
374
|
await rename(temporary, path);
|
|
221
375
|
}
|
|
222
376
|
|
|
223
|
-
/**
|
|
224
|
-
|
|
377
|
+
/**
|
|
378
|
+
* Claude Code guards `.claude.json` writes with a `<file>.lock` directory; take it too. False while
|
|
379
|
+
* someone else holds it, else what `action` returns.
|
|
380
|
+
*/
|
|
381
|
+
async function withClaudeConfigLock(file: string, action: () => Promise<boolean>): Promise<boolean> {
|
|
225
382
|
const lock = `${file}.lock`;
|
|
226
383
|
try {
|
|
227
384
|
await mkdir(lock);
|
|
@@ -236,8 +393,7 @@ async function withClaudeConfigLock(file: string, action: () => Promise<void>):
|
|
|
236
393
|
}
|
|
237
394
|
}
|
|
238
395
|
try {
|
|
239
|
-
await action();
|
|
240
|
-
return true;
|
|
396
|
+
return await action();
|
|
241
397
|
} finally {
|
|
242
398
|
await rmdir(lock).catch(() => undefined);
|
|
243
399
|
}
|
|
@@ -246,6 +402,8 @@ async function withClaudeConfigLock(file: string, action: () => Promise<void>):
|
|
|
246
402
|
const lastMcpSync = new Map<string, number>();
|
|
247
403
|
/** MCP server names each home last received from main, so removals in main propagate. */
|
|
248
404
|
const lastMcpKeys = new Map<string, Set<string>>();
|
|
405
|
+
/** Homes whose `.claude.json` didn't read at their last sync, so that's logged once. */
|
|
406
|
+
const unreadableConfigs = new Set<string>();
|
|
249
407
|
|
|
250
408
|
async function syncClaudeGlobalConfig(home: string): Promise<void> {
|
|
251
409
|
const source = mainClaudeGlobalConfig();
|
|
@@ -268,7 +426,15 @@ async function syncClaudeGlobalConfig(home: string): Promise<void> {
|
|
|
268
426
|
|
|
269
427
|
const mainServers = isObject(main.mcpServers) ? main.mcpServers : {};
|
|
270
428
|
const synced = await withClaudeConfigLock(target, async () => {
|
|
271
|
-
const current =
|
|
429
|
+
const current = await readJsonObject(target);
|
|
430
|
+
if (!current) {
|
|
431
|
+
// The account's identity lives in this file, so one that doesn't read (half written, damaged,
|
|
432
|
+
// unreadable) is never replaced by just what's shared. The next sync tries again.
|
|
433
|
+
if (!unreadableConfigs.has(home)) console.warn(`[ZeroSub] left ${target} alone: it doesn't read as a JSON object`);
|
|
434
|
+
unreadableConfigs.add(home);
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
unreadableConfigs.delete(home);
|
|
272
438
|
const next: Json = { ...current };
|
|
273
439
|
next.mcpServers = mergeShared(current.mcpServers, mainServers, lastMcpKeys.get(home));
|
|
274
440
|
const projects: Json = isObject(current.projects) ? { ...current.projects } : {};
|
|
@@ -280,6 +446,7 @@ async function syncClaudeGlobalConfig(home: string): Promise<void> {
|
|
|
280
446
|
}
|
|
281
447
|
next.projects = projects;
|
|
282
448
|
await writeJsonAtomically(target, next);
|
|
449
|
+
return true;
|
|
283
450
|
});
|
|
284
451
|
if (synced) {
|
|
285
452
|
lastMcpSync.set(home, sourceStat.mtimeMs);
|
|
@@ -287,16 +454,481 @@ async function syncClaudeGlobalConfig(home: string): Promise<void> {
|
|
|
287
454
|
}
|
|
288
455
|
}
|
|
289
456
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
457
|
+
/** Settings whose lists Claude Code joins across settings files rather than letting one replace another. */
|
|
458
|
+
const JOINED_LISTS = new Set(["permissions", "hooks"]);
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Account overrides win; object values (`env`, `permissions`, …) merge one level deep. Lists in
|
|
462
|
+
* `permissions` (`allow`, `deny`, …) and each `hooks` event's list are joined, main's entries first
|
|
463
|
+
* and each entry once, the way Claude Code merges them across its own settings files.
|
|
464
|
+
*/
|
|
465
|
+
export function mergeSettings(main: Json, account: Json): Json {
|
|
466
|
+
const merged: Json = { ...main };
|
|
467
|
+
for (const [key, value] of Object.entries(account)) {
|
|
468
|
+
const base = main[key];
|
|
469
|
+
if (!isObject(value) || !isObject(base)) {
|
|
470
|
+
merged[key] = value;
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
473
|
+
const next: Json = { ...base, ...value };
|
|
474
|
+
if (JOINED_LISTS.has(key)) {
|
|
475
|
+
for (const [name, entries] of Object.entries(value)) {
|
|
476
|
+
const inherited = base[name];
|
|
477
|
+
if (Array.isArray(entries) && Array.isArray(inherited)) next[name] = joinLists(inherited, entries);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
merged[key] = next;
|
|
481
|
+
}
|
|
482
|
+
return merged;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function joinLists(first: readonly unknown[], second: readonly unknown[]): unknown[] {
|
|
486
|
+
const joined: unknown[] = [];
|
|
487
|
+
for (const entry of [...first, ...second]) {
|
|
488
|
+
if (!joined.some((existing) => sameJson(existing, entry))) joined.push(entry);
|
|
489
|
+
}
|
|
490
|
+
return joined;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** Whether two JSON values are the same, whatever order their keys are in, as Claude Code compares hooks. */
|
|
494
|
+
function sameJson(a: unknown, b: unknown): boolean {
|
|
495
|
+
return canonicalJson(a) === canonicalJson(b);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function canonicalJson(value: unknown): string {
|
|
499
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
500
|
+
if (isObject(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
|
|
501
|
+
return JSON.stringify(value) ?? "null";
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
async function readSettings(path: string): Promise<Json | null> {
|
|
505
|
+
const value = await readJson(path);
|
|
506
|
+
if (value === undefined) return null;
|
|
507
|
+
if (!isObject(value)) throw new Error(`${path} is not a JSON object`);
|
|
508
|
+
return value;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Writes the account's `settings.json` as main's settings with the account's overrides on top, so
|
|
513
|
+
* each account can carry its own `env` (a proxy, say) while everything else stays shared.
|
|
514
|
+
*
|
|
515
|
+
* `settings.account.json` marks a file as ZeroSub's, so a home gets one (empty) at its first sync,
|
|
516
|
+
* whether or not main has settings, before Claude Code can write a `settings.json` of its own there
|
|
517
|
+
* (for `/model`, say). A plain `settings.json` without one was made by hand and is left alone, except
|
|
518
|
+
* in a home of ZeroSub's own (see `isOwnHome`): there it's what Claude Code wrote into a home made
|
|
519
|
+
* before the marker was, so it becomes the account's overrides, and main's settings apply under it
|
|
520
|
+
* again. A link the user made (see `userSettingsLink`) is left alone too. A file that doesn't parse
|
|
521
|
+
* stops the sync and keeps the previous one: dropping the account's overrides would quietly send it
|
|
522
|
+
* out without them. What Claude Code saved in the generated file since the last sync is kept (see
|
|
523
|
+
* `foldSavedSettings`).
|
|
524
|
+
*/
|
|
525
|
+
async function syncClaudeSettings(home: string): Promise<void> {
|
|
526
|
+
const target = join(home, "settings.json");
|
|
527
|
+
const overrides = join(home, ACCOUNT_SETTINGS);
|
|
528
|
+
const current = await lstat(target).catch(() => null);
|
|
529
|
+
if (current?.isSymbolicLink() && (await userSettingsLink(home))) return;
|
|
530
|
+
let account = await readSettings(overrides);
|
|
531
|
+
if (!account && current && !current.isSymbolicLink()) {
|
|
532
|
+
if (!current.isFile() || !(await isOwnHome(home))) return;
|
|
533
|
+
account = (await readSettings(target)) ?? {};
|
|
534
|
+
await writeJsonAtomically(overrides, account);
|
|
535
|
+
console.log(`[ZeroSub] kept ${target}, which had no ${ACCOUNT_SETTINGS}, as that account's own settings; main's settings apply under it again`);
|
|
536
|
+
}
|
|
537
|
+
if (!account) {
|
|
538
|
+
account = {};
|
|
539
|
+
await writeJsonAtomically(overrides, account);
|
|
540
|
+
}
|
|
541
|
+
// Read before folding: it tells main's entries in a saved list from the account's own.
|
|
542
|
+
const main = (await readSettings(join(mainClaudeDir(), "settings.json"))) ?? {};
|
|
543
|
+
if (current?.isFile()) {
|
|
544
|
+
const folded = await foldSavedSettings(home, account, main);
|
|
545
|
+
if (folded) {
|
|
546
|
+
account = folded;
|
|
547
|
+
await writeJsonAtomically(overrides, account);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// Homes from earlier versions link to main's file; replace the link, never write through it.
|
|
552
|
+
if (current?.isSymbolicLink()) await unlink(target);
|
|
553
|
+
const inherited = { ...process.env, ...providerEnv("claude") };
|
|
554
|
+
const next = `${JSON.stringify(accountSettings(main, account, inherited), null, 2)}\n`;
|
|
555
|
+
const generated = join(home, GENERATED_SETTINGS);
|
|
556
|
+
if (current?.isFile() && (await readFile(target, "utf8").catch(() => null)) === next) {
|
|
557
|
+
if ((await readFile(generated, "utf8").catch(() => null)) !== next) await writeJsonAtomically(generated, JSON.parse(next));
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
await writeJsonAtomically(generated, JSON.parse(next));
|
|
561
|
+
await writeJsonAtomically(target, JSON.parse(next));
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* `account` with what was saved in the home's `settings.json` since it was last generated folded
|
|
566
|
+
* in, so the next generated file keeps it: Claude Code saves `/model`, a plugin turned on and the
|
|
567
|
+
* like there, and regenerating would otherwise take it back out. A setting that changed or was
|
|
568
|
+
* added becomes the account's own (only the keys that changed, for one holding an object such as
|
|
569
|
+
* `enabledPlugins`, so main's others still come through); one taken out leaves the account's own
|
|
570
|
+
* settings, though main's still applies underneath. A list Claude Code joins across its settings
|
|
571
|
+
* files (see `JOINED_LISTS`) keeps only the account's own entries (see `ownEntries`), never `main`'s,
|
|
572
|
+
* so one taken out of main or changed there is taken out or changed for the account too. Null when
|
|
573
|
+
* nothing was saved, or when there's no copy of the last generated file to tell by (a home from an
|
|
574
|
+
* earlier version: it gets one now).
|
|
575
|
+
*/
|
|
576
|
+
async function foldSavedSettings(home: string, account: Json, main: Json): Promise<Json | null> {
|
|
577
|
+
const before = await readSettings(join(home, GENERATED_SETTINGS)).catch(() => null);
|
|
578
|
+
const now = await readSettings(join(home, "settings.json")).catch(() => null);
|
|
579
|
+
if (!before || !now) return null;
|
|
580
|
+
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
|
|
581
|
+
const next: Json = { ...account };
|
|
582
|
+
let changed = false;
|
|
583
|
+
for (const key of new Set([...Object.keys(before), ...Object.keys(now)])) {
|
|
584
|
+
const was = before[key];
|
|
585
|
+
const is = now[key];
|
|
586
|
+
if (same(was, is)) continue;
|
|
587
|
+
changed = true;
|
|
588
|
+
if (is === undefined) {
|
|
589
|
+
delete next[key];
|
|
590
|
+
} else if (isObject(is) && isObject(was)) {
|
|
591
|
+
const own: Json = isObject(next[key]) ? { ...next[key] } : {};
|
|
592
|
+
const inherited = isObject(main[key]) ? main[key] : {};
|
|
593
|
+
for (const name of new Set([...Object.keys(was), ...Object.keys(is)])) {
|
|
594
|
+
if (same(was[name], is[name])) continue;
|
|
595
|
+
const saved = is[name];
|
|
596
|
+
// Main's entries: those in its settings now, and those of the generated file this was saved over.
|
|
597
|
+
const value = JOINED_LISTS.has(key) && Array.isArray(saved) ? ownEntries(saved, [inherited[name], was[name]], own[name]) : saved;
|
|
598
|
+
if (value === undefined) delete own[name];
|
|
599
|
+
else own[name] = value;
|
|
600
|
+
}
|
|
601
|
+
if (Object.keys(own).length > 0) next[key] = own;
|
|
602
|
+
else delete next[key];
|
|
603
|
+
} else {
|
|
604
|
+
next[key] = is;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return changed ? next : null;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* The entries of `list`, a joined list as saved in an account's `settings.json`, that are the
|
|
612
|
+
* account's own: those in `own`, its list so far, and any that none of the `inherited` lists (main's)
|
|
613
|
+
* has. A hook group keeps just the hooks that are, since Claude Code adds a hook to the group already
|
|
614
|
+
* there for its matcher, main's included. Entries are compared whatever order their keys are in.
|
|
615
|
+
* Undefined when none are.
|
|
616
|
+
*/
|
|
617
|
+
function ownEntries(list: readonly unknown[], inherited: readonly unknown[], own: unknown): unknown[] | undefined {
|
|
618
|
+
const theirs = inherited.flatMap((entries) => (Array.isArray(entries) ? entries : []));
|
|
619
|
+
const ours = Array.isArray(own) ? own : [];
|
|
620
|
+
const isOwn = (entry: unknown, mains: readonly unknown[], owns: readonly unknown[]) =>
|
|
621
|
+
owns.some((other) => sameJson(other, entry)) || !mains.some((other) => sameJson(other, entry));
|
|
622
|
+
const kept: unknown[] = [];
|
|
623
|
+
for (const entry of list) {
|
|
624
|
+
if (!isHookGroup(entry)) {
|
|
625
|
+
if (isOwn(entry, theirs, ours)) kept.push(entry);
|
|
626
|
+
continue;
|
|
627
|
+
}
|
|
628
|
+
const mainHooks = hooksFor(theirs, entry);
|
|
629
|
+
const ownHooks = hooksFor(ours, entry);
|
|
630
|
+
const hooks = entry.hooks.filter((hook) => isOwn(hook, mainHooks, ownHooks));
|
|
631
|
+
if (hooks.length > 0) kept.push(hooks.length === entry.hooks.length ? entry : { ...entry, hooks });
|
|
632
|
+
}
|
|
633
|
+
return kept.length > 0 ? kept : undefined;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** An entry of a `hooks` event's list: the hooks to run, and what they match (none is the same as ""). */
|
|
637
|
+
interface HookGroup {
|
|
638
|
+
matcher?: unknown;
|
|
639
|
+
hooks: unknown[];
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function isHookGroup(value: unknown): value is HookGroup {
|
|
643
|
+
return isObject(value) && Array.isArray(value.hooks);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** The hooks of the groups in `groups` with `group`'s matcher. */
|
|
647
|
+
function hooksFor(groups: readonly unknown[], group: HookGroup): unknown[] {
|
|
648
|
+
return groups.flatMap((other) => (isHookGroup(other) && sameJson(other.matcher ?? "", group.matcher ?? "") ? other.hooks : []));
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* An account's generated settings: main's with the account's overrides on top (see `mergeSettings`).
|
|
653
|
+
* An API account (overrides holding a key) uses exactly what was entered for it: `API_ACCOUNT_ENV`
|
|
654
|
+
* goes under its own `env`, and main's `apiKeyHelper` is left out, since Claude Code would send the
|
|
655
|
+
* helper's answer along with the key or in its place. Each sync so also corrects a file generated
|
|
656
|
+
* before they were pinned.
|
|
657
|
+
*
|
|
658
|
+
* An account with a proxy of its own also gets `no_proxy` and `NO_PROXY`, both set to the no-proxy
|
|
659
|
+
* list it would otherwise have (from `inherited`, the environment Paseo starts it with, then the
|
|
660
|
+
* merged `env`) without the entries that would send Anthropic or Claude traffic past the proxy,
|
|
661
|
+
* plus localhost, 127.0.0.1 and `downloads.claude.ai`. Claude Code applies them over what it
|
|
662
|
+
* inherits, so a `NO_PROXY` in main's settings, the daemon or a shell can't send the account out
|
|
663
|
+
* directly while ZeroSub's own calls for it go through the proxy. Any other account gets the
|
|
664
|
+
* plain merge.
|
|
665
|
+
*/
|
|
666
|
+
export function accountSettings(main: Json, account: Json, inherited: Readonly<Record<string, string | undefined>> = {}): Json {
|
|
667
|
+
const merged = mergeSettings(main, account);
|
|
668
|
+
if (keyKindOf(stringEnv(account))) {
|
|
669
|
+
const env: Json = { ...(isObject(main.env) ? main.env : {}), ...API_ACCOUNT_ENV, ...(isObject(account.env) ? account.env : {}) };
|
|
670
|
+
if (typeof env.ANTHROPIC_BASE_URL !== "string" || !env.ANTHROPIC_BASE_URL.trim()) env.ANTHROPIC_BASE_URL = ANTHROPIC_API;
|
|
671
|
+
merged.env = env;
|
|
672
|
+
if (!("apiKeyHelper" in account)) delete merged.apiKeyHelper;
|
|
673
|
+
}
|
|
674
|
+
if (proxyFromEnv(stringEnv(account))) {
|
|
675
|
+
const env: Json = isObject(merged.env) ? { ...merged.env } : {};
|
|
676
|
+
const noProxy = withClaudeNoProxy(withoutClaudeDomains(noProxyFromEnv({ ...inherited, ...stringEnv({ env }) })));
|
|
677
|
+
for (const key of NO_PROXY_KEYS) env[key] = noProxy;
|
|
678
|
+
merged.env = env;
|
|
679
|
+
}
|
|
680
|
+
return merged;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function stringEnv(settings: Json | null): Record<string, string> {
|
|
684
|
+
const env = isObject(settings?.env) ? settings.env : {};
|
|
685
|
+
const strings: Record<string, string> = {};
|
|
686
|
+
for (const [key, value] of Object.entries(env)) if (typeof value === "string") strings[key] = value;
|
|
687
|
+
return strings;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** The proxy set in the account's own settings, or null when it uses whatever it inherits. */
|
|
691
|
+
export async function readAccountProxy(home: string): Promise<string | null> {
|
|
692
|
+
return proxyFromEnv(stringEnv(await readSettings(join(home, ACCOUNT_SETTINGS)).catch(() => null)));
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* Where `home`'s `settings.json` links to when the link is the user's: in a home that isn't
|
|
697
|
+
* ZeroSub's own (see `isOwnHome`), a link to anything but main's settings, which homes of earlier
|
|
698
|
+
* versions link to. Such a link is left as it is.
|
|
699
|
+
*/
|
|
700
|
+
async function userSettingsLink(home: string): Promise<string | null> {
|
|
701
|
+
const target = join(home, "settings.json");
|
|
702
|
+
const to = await readlink(target).catch(() => null);
|
|
703
|
+
if (to === null || (await isOwnHome(home))) return null;
|
|
704
|
+
const main = join(mainClaudeDir(), "settings.json");
|
|
705
|
+
if (resolve(home, to) === resolve(main)) return null;
|
|
706
|
+
const [real, mainReal] = await Promise.all([realpath(target).catch(() => null), realpath(main).catch(() => null)]);
|
|
707
|
+
return real !== null && real === mainReal ? null : to;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/** The account's overrides; a hand-made `settings.json` becomes them, so taking the home over loses nothing. */
|
|
711
|
+
async function readOverrides(home: string): Promise<Json> {
|
|
712
|
+
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
713
|
+
const link = await userSettingsLink(home);
|
|
714
|
+
// Overrides written here would never reach Claude Code, which reads the linked file.
|
|
715
|
+
if (link) throw new Error(`${join(home, "settings.json")} links to ${link}, which ZeroSub leaves as it is: set this there instead`);
|
|
716
|
+
const account = await readSettings(join(home, ACCOUNT_SETTINGS));
|
|
717
|
+
if (account) return account;
|
|
718
|
+
const target = join(home, "settings.json");
|
|
719
|
+
const current = await lstat(target).catch(() => null);
|
|
720
|
+
return current?.isFile() ? ((await readSettings(target)) ?? {}) : {};
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* Writes the account's overrides with `edit` applied to their `env`, then regenerates `settings.json`.
|
|
725
|
+
* Nothing is written while main's settings don't parse: the account couldn't be regenerated, so its
|
|
726
|
+
* overrides would show a proxy it doesn't use.
|
|
727
|
+
*/
|
|
728
|
+
async function editOverridesEnv(home: string, edit: (env: Json) => void): Promise<void> {
|
|
729
|
+
const account = await readOverrides(home);
|
|
730
|
+
const env: Json = isObject(account.env) ? { ...account.env } : {};
|
|
731
|
+
edit(env);
|
|
732
|
+
const next: Json = { ...account, env };
|
|
733
|
+
if (Object.keys(env).length === 0) delete next.env;
|
|
734
|
+
await readSettings(join(mainClaudeDir(), "settings.json"));
|
|
735
|
+
await writeJsonAtomically(join(home, ACCOUNT_SETTINGS), next);
|
|
736
|
+
await syncClaudeSettings(home);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* Sets (or clears, with `null`) the account's proxy and regenerates its `settings.json` at once.
|
|
741
|
+
* All four proxy variables get the same value, so nothing Claude Code inherits (a lower-case
|
|
742
|
+
* `https_proxy` in the shell, say) can outrank it, and the generated file pins the no-proxy list
|
|
743
|
+
* too (see `accountSettings`). `wanted` as for `stillWanted`.
|
|
744
|
+
*/
|
|
745
|
+
export function writeAccountProxy(home: string, proxy: string | null, wanted?: () => Promise<boolean>): Promise<void> {
|
|
746
|
+
return withHome(home, async () => {
|
|
747
|
+
await stillWanted(wanted);
|
|
748
|
+
await editOverridesEnv(home, (env) => {
|
|
749
|
+
for (const key of PROXY_KEYS) {
|
|
750
|
+
if (proxy) env[key] = proxy;
|
|
751
|
+
else delete env[key];
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
});
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// --------------------------------------------------------------------------- API accounts
|
|
758
|
+
|
|
759
|
+
const KEY_VARIABLE: Record<ApiKeyKind, string> = { api_key: "ANTHROPIC_API_KEY", auth_token: "ANTHROPIC_AUTH_TOKEN" };
|
|
760
|
+
const TRAFFIC_VARIABLE: Record<keyof TrafficSwitches, string> = {
|
|
761
|
+
disableTelemetry: "DISABLE_TELEMETRY",
|
|
762
|
+
disableErrorReporting: "DISABLE_ERROR_REPORTING",
|
|
763
|
+
disableNonessentialTraffic: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
|
|
764
|
+
};
|
|
765
|
+
|
|
766
|
+
/** What an API account is stored with. Pi's take the key and base URL only. */
|
|
767
|
+
export interface ApiConfig extends TrafficSwitches {
|
|
768
|
+
keyKind: ApiKeyKind;
|
|
769
|
+
/** `null` keeps the current key. */
|
|
770
|
+
key: string | null;
|
|
771
|
+
/** `null` for Anthropic's own API. */
|
|
772
|
+
baseUrl: string | null;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** Anthropic's own API, where an API account without a base URL sends its key. */
|
|
776
|
+
const ANTHROPIC_API = "https://api.anthropic.com";
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* What an API account's generated `env` holds under its own values: a base URL (Anthropic's unless
|
|
780
|
+
* the account has one) and blanks for every other way Claude Code would pick up a key or token,
|
|
781
|
+
* extra request headers, or another provider (Bedrock, Vertex and the like) instead of the base
|
|
782
|
+
* URL. Claude Code applies `settings.json` `env` over the environment it was started with, so these
|
|
783
|
+
* also beat what the daemon or the shell exports.
|
|
784
|
+
*/
|
|
785
|
+
const API_ACCOUNT_ENV: Readonly<Record<string, string>> = {
|
|
786
|
+
ANTHROPIC_BASE_URL: ANTHROPIC_API,
|
|
787
|
+
ANTHROPIC_API_KEY: "",
|
|
788
|
+
ANTHROPIC_AUTH_TOKEN: "",
|
|
789
|
+
CLAUDE_CODE_OAUTH_TOKEN: "",
|
|
790
|
+
ANTHROPIC_CUSTOM_HEADERS: "",
|
|
791
|
+
CLAUDE_CODE_USE_BEDROCK: "",
|
|
792
|
+
CLAUDE_CODE_USE_VERTEX: "",
|
|
793
|
+
CLAUDE_CODE_USE_FOUNDRY: "",
|
|
794
|
+
CLAUDE_CODE_USE_ANTHROPIC_AWS: "",
|
|
795
|
+
CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD: "",
|
|
796
|
+
CLAUDE_CODE_USE_MANTLE: "",
|
|
797
|
+
};
|
|
798
|
+
|
|
799
|
+
/** Which key the account's own `env` holds, if any: what makes it an API account. */
|
|
800
|
+
function keyKindOf(env: Record<string, string>): ApiKeyKind | null {
|
|
801
|
+
return env.ANTHROPIC_AUTH_TOKEN ? "auth_token" : env.ANTHROPIC_API_KEY ? "api_key" : null;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* The proxy an added Claude account's requests to `baseUrl` cross as plain http://, which that proxy
|
|
806
|
+
* can read, key and all; null for https://, or when nothing carries them, or the no-proxy list keeps
|
|
807
|
+
* them direct. Read as Claude Code starts on the home: its generated settings' env over the daemon's
|
|
808
|
+
* (and Paseo's for Claude). `through` asks the same of another proxy (the CLI login's new one, say)
|
|
809
|
+
* with the account's no-proxy list as it is. Any proxy variable counts, http_proxy or https_proxy.
|
|
810
|
+
*/
|
|
811
|
+
export async function claudeClearTextProxy(home: string, baseUrl: string | null, through?: string): Promise<string | null> {
|
|
812
|
+
if (!baseUrl || !plainHttp(baseUrl)) return null;
|
|
813
|
+
const settings = await readSettings(join(home, "settings.json")).catch(() => null);
|
|
814
|
+
const env: Record<string, string | undefined> = { ...process.env, ...providerEnv("claude"), ...stringEnv(settings) };
|
|
815
|
+
const proxy = through ?? proxyFromEnv(env);
|
|
816
|
+
return proxy && !bypassesProxy(noProxyFromEnv(env), baseUrl) ? proxy : null;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* Whether `home` holds a Claude account: signed in (`oauthAccount` in its `.claude.json`, or a
|
|
821
|
+
* `.credentials.json` off macOS), or an API key of its own. A folder made again by a sync has none.
|
|
822
|
+
*/
|
|
823
|
+
export async function claudeHomeHoldsAccount(home: string): Promise<boolean> {
|
|
824
|
+
const config = await readJson(join(home, ".claude.json")).catch(() => undefined);
|
|
825
|
+
if (isObject(config) && isObject(config.oauthAccount)) return true;
|
|
826
|
+
if ((await lstat(join(home, ".credentials.json")).catch(() => null))?.isFile()) return true;
|
|
827
|
+
return (await readAccountApi(home).catch(() => null)) !== null;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* The account's API settings with the key reduced to a hint (its last four characters, or empty for
|
|
832
|
+
* a short key), or null when it has no key of its own.
|
|
833
|
+
*/
|
|
834
|
+
export async function readAccountApi(home: string): Promise<ApiSummary | null> {
|
|
835
|
+
const env = stringEnv(await readSettings(join(home, ACCOUNT_SETTINGS)).catch(() => null));
|
|
836
|
+
const keyKind = keyKindOf(env);
|
|
837
|
+
if (!keyKind) return null;
|
|
838
|
+
const on = (name: string) => Boolean(env[name]) && env[name] !== "0" && env[name]?.toLowerCase() !== "false";
|
|
839
|
+
const key = (env[KEY_VARIABLE[keyKind]] ?? "").trim();
|
|
840
|
+
return {
|
|
841
|
+
keyKind,
|
|
842
|
+
keyHint: key.length >= KEY_HINT_MIN_LENGTH ? key.slice(-4) : "",
|
|
843
|
+
baseUrl: env.ANTHROPIC_BASE_URL || null,
|
|
844
|
+
disableTelemetry: on(TRAFFIC_VARIABLE.disableTelemetry),
|
|
845
|
+
disableErrorReporting: on(TRAFFIC_VARIABLE.disableErrorReporting),
|
|
846
|
+
disableNonessentialTraffic: on(TRAFFIC_VARIABLE.disableNonessentialTraffic),
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Stores an API account's key, base URL and traffic switches in its overrides. No base URL is
|
|
852
|
+
* stored for Anthropic's own API; the generated settings write it out (see `accountSettings`). A
|
|
853
|
+
* switch that's off is left out rather than set to 0, so it's whatever main's settings say. An
|
|
854
|
+
* `x-api-key` key is also approved in the account's `.claude.json`, the way answering Claude
|
|
855
|
+
* Code's "use this API key?" question would, so a session doesn't stop to ask about a key added
|
|
856
|
+
* here. `wanted` as for `stillWanted`.
|
|
857
|
+
*/
|
|
858
|
+
export function writeAccountApi(home: string, config: ApiConfig, wanted?: () => Promise<boolean>): Promise<void> {
|
|
859
|
+
return withHome(home, async () => {
|
|
860
|
+
await stillWanted(wanted);
|
|
861
|
+
await storeAccountApi(home, config);
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
async function storeAccountApi(home: string, config: ApiConfig): Promise<void> {
|
|
866
|
+
const previous = stringEnv(await readOverrides(home));
|
|
867
|
+
const replaced = previous.ANTHROPIC_AUTH_TOKEN || previous.ANTHROPIC_API_KEY || null;
|
|
868
|
+
const key = config.key?.trim() || replaced;
|
|
869
|
+
if (!key) throw new Error("Enter the API key or token");
|
|
870
|
+
const baseUrl = config.baseUrl?.trim() ? normalizeBaseUrl(config.baseUrl) : null;
|
|
871
|
+
// A kept key only goes where it went before: sending it somewhere new takes typing it again.
|
|
872
|
+
if (!config.key?.trim() && (previous.ANTHROPIC_BASE_URL || null) !== baseUrl) {
|
|
873
|
+
throw new Error("Enter the key again to use it with a different base URL");
|
|
874
|
+
}
|
|
875
|
+
if (config.keyKind === "api_key") await approveApiKey(home, key, replaced);
|
|
876
|
+
await editOverridesEnv(home, (env) => {
|
|
877
|
+
for (const name of Object.values(KEY_VARIABLE)) delete env[name];
|
|
878
|
+
env[KEY_VARIABLE[config.keyKind]] = key;
|
|
879
|
+
if (baseUrl) env.ANTHROPIC_BASE_URL = baseUrl;
|
|
880
|
+
else delete env.ANTHROPIC_BASE_URL;
|
|
881
|
+
for (const [field, name] of Object.entries(TRAFFIC_VARIABLE) as [keyof TrafficSwitches, string][]) {
|
|
882
|
+
if (config[field]) env[name] = "1";
|
|
883
|
+
else delete env[name];
|
|
884
|
+
}
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/** Claude Code remembers an approved key by its last 20 characters. */
|
|
889
|
+
function keyFingerprint(key: string): string {
|
|
890
|
+
return key.trim().slice(-20);
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
async function approveApiKey(home: string, key: string, replaced: string | null): Promise<void> {
|
|
894
|
+
const file = join(home, ".claude.json");
|
|
895
|
+
// Seed a new home first, so the account still gets the user's preferences and MCP servers.
|
|
896
|
+
if (!(await exists(file))) await syncClaudeGlobalConfig(home);
|
|
897
|
+
const approve = keyFingerprint(key);
|
|
898
|
+
const retire = replaced ? keyFingerprint(replaced) : null;
|
|
899
|
+
const done = await withClaudeConfigLock(file, async () => {
|
|
900
|
+
const value = await readJson(file);
|
|
901
|
+
const config: Json = isObject(value) ? value : {};
|
|
902
|
+
const responses: Json = isObject(config.customApiKeyResponses) ? config.customApiKeyResponses : {};
|
|
903
|
+
const list = (entry: unknown) => (Array.isArray(entry) ? entry.filter((item): item is string => typeof item === "string") : []);
|
|
904
|
+
const approved = list(responses.approved).filter((item) => item !== retire && item !== approve);
|
|
905
|
+
const rejected = list(responses.rejected).filter((item) => item !== approve);
|
|
906
|
+
await writeJsonAtomically(file, { ...config, customApiKeyResponses: { ...responses, approved: [...approved, approve], rejected } });
|
|
907
|
+
return true;
|
|
908
|
+
});
|
|
909
|
+
if (!done) throw new Error("Claude Code is writing this account's settings right now. Try again in a moment.");
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/**
|
|
913
|
+
* Brings a Claude home in step with main: shared entries, `.claude.json` and generated settings.
|
|
914
|
+
* It holds the home's lock, so a sync never writes back settings an edit just replaced. `wanted`,
|
|
915
|
+
* if given, is asked once the lock is held: a home whose account has gone since the caller looked
|
|
916
|
+
* is left as it is, so it's never written to (or made again) after its account is.
|
|
917
|
+
*/
|
|
918
|
+
export function prepareClaudeHome(home: string, force = false, wanted?: () => Promise<boolean>): Promise<void> {
|
|
919
|
+
return withHome(home, async () => {
|
|
920
|
+
if (wanted && !(await wanted())) return;
|
|
921
|
+
const last = lastSync.get(home);
|
|
922
|
+
if (!force && last && Date.now() - last < SYNC_TTL_MS) return;
|
|
923
|
+
await syncOverlay(home, {
|
|
924
|
+
main: mainClaudeDir(),
|
|
925
|
+
shareDirs: ["projects", "file-history", "todos", "plans", "tasks", "session-env", "shell-snapshots"],
|
|
926
|
+
isPrivate: claudePrivate,
|
|
927
|
+
});
|
|
928
|
+
await syncClaudeGlobalConfig(home);
|
|
929
|
+
await syncClaudeSettings(home);
|
|
930
|
+
lastSync.set(home, Date.now());
|
|
297
931
|
});
|
|
298
|
-
await syncClaudeGlobalConfig(home);
|
|
299
|
-
lastSync.set(home, Date.now());
|
|
300
932
|
}
|
|
301
933
|
|
|
302
934
|
// --------------------------------------------------------------------------- Codex
|
|
@@ -304,6 +936,8 @@ export async function prepareClaudeHome(home: string, force = false): Promise<vo
|
|
|
304
936
|
/** Per-account entries in a Codex home: credentials and caches keyed to the ChatGPT account. */
|
|
305
937
|
const CODEX_PRIVATE = new Set([
|
|
306
938
|
"auth.json",
|
|
939
|
+
// An Azure OpenAI account's endpoint and key: never linked in from `~/.codex`, whatever the home.
|
|
940
|
+
AZURE_FILE,
|
|
307
941
|
"secrets",
|
|
308
942
|
"models_cache.json",
|
|
309
943
|
"cloud-config-bundle-cache.json",
|
|
@@ -331,15 +965,52 @@ function codexPrivate(name: string): boolean {
|
|
|
331
965
|
);
|
|
332
966
|
}
|
|
333
967
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
968
|
+
/**
|
|
969
|
+
* Brings a Codex home's shared entries in step with main; `wanted` as for `prepareClaudeHome`. An
|
|
970
|
+
* Azure OpenAI account's home (see azure.ts) also keeps `config.toml` to itself: it's the shared one
|
|
971
|
+
* with ZeroSub's Azure provider set, remade here and at each session open.
|
|
972
|
+
*/
|
|
973
|
+
export function prepareCodexHome(home: string, force = false, wanted?: () => Promise<boolean>): Promise<void> {
|
|
974
|
+
return withHome(home, async () => {
|
|
975
|
+
if (wanted && !(await wanted())) return;
|
|
976
|
+
const azure = isAzureHome(home);
|
|
977
|
+
const last = lastSync.get(home);
|
|
978
|
+
if (!force && last && Date.now() - last < SYNC_TTL_MS) {
|
|
979
|
+
if (azure) await syncAzureConfig(home);
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
await syncOverlay(home, {
|
|
983
|
+
main: mainCodexHome(),
|
|
984
|
+
shareDirs: ["sessions", "archived_sessions"],
|
|
985
|
+
isPrivate: azure ? (name) => codexPrivate(name) || name === "config.toml" : codexPrivate,
|
|
986
|
+
});
|
|
987
|
+
if (azure) await syncAzureConfig(home);
|
|
988
|
+
lastSync.set(home, Date.now());
|
|
341
989
|
});
|
|
342
|
-
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/**
|
|
993
|
+
* The session directory `home` will read. The CLI login (`null`, or the main Codex home) is the
|
|
994
|
+
* directory itself. Any other home counts only when `sessions` is a symlink or a Windows junction
|
|
995
|
+
* to that directory: a plain folder, including one left behind when a junction fails, is its own
|
|
996
|
+
* copy and must not be treated as shared.
|
|
997
|
+
*/
|
|
998
|
+
export async function codexSessionsRoot(home: string | null): Promise<string | null> {
|
|
999
|
+
const main = mainCodexHome();
|
|
1000
|
+
const homeIsMain = !home || resolve(home) === resolve(main);
|
|
1001
|
+
const sessions = homeIsMain ? join(main, "sessions") : join(home, "sessions");
|
|
1002
|
+
const info = await lstat(sessions).catch(() => null);
|
|
1003
|
+
if (!info) return null;
|
|
1004
|
+
if (!homeIsMain && !info.isSymbolicLink()) return null;
|
|
1005
|
+
if (homeIsMain && !info.isDirectory() && !info.isSymbolicLink()) return null;
|
|
1006
|
+
return realpath(sessions).catch(() => null);
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/** Both homes read one session directory, so one agent can reload the thread on the other account. */
|
|
1010
|
+
export async function codexSessionsShared(destinationHome: string | null, sourceHome: string | null): Promise<boolean> {
|
|
1011
|
+
const destination = await codexSessionsRoot(destinationHome);
|
|
1012
|
+
const source = await codexSessionsRoot(sourceHome);
|
|
1013
|
+
return destination !== null && destination === source;
|
|
343
1014
|
}
|
|
344
1015
|
|
|
345
1016
|
/** Where the main Codex home keeps its SQLite state; managed homes point there so thread metadata is shared. */
|
|
@@ -350,3 +1021,560 @@ export async function codexSqliteHome(): Promise<string | null> {
|
|
|
350
1021
|
if (/^\s*sqlite_home\s*=/m.test(config)) return null;
|
|
351
1022
|
return mainCodexHome();
|
|
352
1023
|
}
|
|
1024
|
+
|
|
1025
|
+
// --------------------------------------------------------------------------- Grok
|
|
1026
|
+
|
|
1027
|
+
/**
|
|
1028
|
+
* Per-account entries in a Grok home: the login (`auth.json`, or a file `GROK_AUTH_PATH` names there),
|
|
1029
|
+
* MCP sign-ins, what Grok fetched for this account (settings, model list, experiments, the team's
|
|
1030
|
+
* managed config and requirements), and the running processes' own state: locks, sockets, the leader,
|
|
1031
|
+
* logs, crash reports and trace uploads (sent with this account's login). The rest, sessions included,
|
|
1032
|
+
* is shared, so an agent reopens on another account with its conversation.
|
|
1033
|
+
*/
|
|
1034
|
+
const GROK_PRIVATE = new Set([
|
|
1035
|
+
"auth.json",
|
|
1036
|
+
"mcp_credentials.json",
|
|
1037
|
+
"settings_cache.json",
|
|
1038
|
+
"models_cache.json",
|
|
1039
|
+
"experiments_remote_opt_out",
|
|
1040
|
+
"managed_config.toml",
|
|
1041
|
+
"managed_config_cache.json",
|
|
1042
|
+
"managed_config.sig.json",
|
|
1043
|
+
"managed_identity.sig.json",
|
|
1044
|
+
"staged",
|
|
1045
|
+
"requirements.toml",
|
|
1046
|
+
"active_sessions.json",
|
|
1047
|
+
"logs",
|
|
1048
|
+
"upload_queue",
|
|
1049
|
+
"memtrace",
|
|
1050
|
+
"crash",
|
|
1051
|
+
".metadata_version",
|
|
1052
|
+
]);
|
|
1053
|
+
|
|
1054
|
+
export function grokPrivate(name: string): boolean {
|
|
1055
|
+
return (
|
|
1056
|
+
GROK_PRIVATE.has(name) ||
|
|
1057
|
+
isTemporary(name) ||
|
|
1058
|
+
/auth|credential|token|secret/i.test(name) ||
|
|
1059
|
+
name.startsWith("leader") ||
|
|
1060
|
+
/\.(?:lock|sock|pid)$/.test(name)
|
|
1061
|
+
);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
export async function prepareGrokHome(home: string, force = false): Promise<void> {
|
|
1065
|
+
const last = lastSync.get(home);
|
|
1066
|
+
if (!force && last && Date.now() - last < SYNC_TTL_MS) return;
|
|
1067
|
+
await syncOverlay(home, { main: mainGrokHome(), shareDirs: ["sessions"], isPrivate: grokPrivate });
|
|
1068
|
+
lastSync.set(home, Date.now());
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// --------------------------------------------------------------------------- Cursor
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* Per-account entries in Cursor's settings folder: the login (`auth.json`), `cli-config.json` (next to
|
|
1075
|
+
* the user's settings it caches who is signed in, the team requests go to and the team's privacy mode,
|
|
1076
|
+
* so an account gets its own copy, seeded from the CLI login's; see `seedCursorSettings`), and
|
|
1077
|
+
* `statsig-cache.json` (the feature flags fetched for the signed-in user, stored with that user's id,
|
|
1078
|
+
* which `cursor-agent` reports to Statsig ahead of the account's own while the cache is there).
|
|
1079
|
+
*/
|
|
1080
|
+
const CURSOR_PRIVATE = new Set(["auth.json", "cli-config.json", "statsig-cache.json"]);
|
|
1081
|
+
|
|
1082
|
+
/** Keys of `cli-config.json` that belong to the account signed in, never copied to another. */
|
|
1083
|
+
function isCursorAccountKey(key: string): boolean {
|
|
1084
|
+
return key === "authInfo" || /privacy|cache|statsig/i.test(key) || /auth|token|secret|credential/i.test(key);
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/** A new account's `cli-config.json`: the CLI login's settings (model, permissions, sandbox, …), without its account's. */
|
|
1088
|
+
async function seedCursorSettings(settings: string): Promise<void> {
|
|
1089
|
+
const target = join(settings, "cli-config.json");
|
|
1090
|
+
if (await lstat(target).catch(() => null)) return;
|
|
1091
|
+
const main = await readJsonObject(join(mainCursorConfigDir(), "cli-config.json"));
|
|
1092
|
+
if (!main) return;
|
|
1093
|
+
const seed: Json = {};
|
|
1094
|
+
for (const [key, value] of Object.entries(main)) if (!isCursorAccountKey(key)) seed[key] = value;
|
|
1095
|
+
await writeJsonAtomically(target, seed);
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* Creates or refreshes an added Cursor account's home, which is its agents' `XDG_CONFIG_HOME`. Their
|
|
1100
|
+
* tools (git, gh, …) get that variable too, so it mirrors the daemon's own (`mainConfigHome`): every
|
|
1101
|
+
* entry links back except `cursor/`, where `cursor-agent` keeps its login. With `XDG_CONFIG_HOME` set,
|
|
1102
|
+
* `cursor-agent` keeps its settings in `cursor/` too, instead of `~/.cursor`, so `cursor/` in turn
|
|
1103
|
+
* mirrors Cursor's settings folder (`mainCursorConfigDir`), keeping only `CURSOR_PRIVATE` per account.
|
|
1104
|
+
* Chats and ACP sessions are kept there too (`chats/`, `acp-sessions/`), so those folders are shared up
|
|
1105
|
+
* front, as other families' sessions are, and Paseo reopens a session where it was saved; projects are
|
|
1106
|
+
* in `~/.cursor` (`CURSOR_DATA_DIR`), which neither variable moves.
|
|
1107
|
+
*/
|
|
1108
|
+
export async function prepareCursorHome(home: string, force = false): Promise<void> {
|
|
1109
|
+
const last = lastSync.get(home);
|
|
1110
|
+
if (!force && last && Date.now() - last < SYNC_TTL_MS) return;
|
|
1111
|
+
await syncOverlay(home, { main: mainConfigHome(), shareDirs: [], isPrivate: (name) => name === "cursor" || isTemporary(name) });
|
|
1112
|
+
const settings = join(home, "cursor");
|
|
1113
|
+
await syncOverlay(settings, { main: mainCursorConfigDir(), shareDirs: ["acp-sessions", "chats"], isPrivate: (name) => CURSOR_PRIVATE.has(name) || isTemporary(name) });
|
|
1114
|
+
await seedCursorSettings(settings);
|
|
1115
|
+
lastSync.set(home, Date.now());
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
// --------------------------------------------------------------------------- Pi
|
|
1119
|
+
|
|
1120
|
+
/** Checks a base URL typed by the user: http(s), no query or fragment, no trailing slash. */
|
|
1121
|
+
export function normalizeBaseUrl(input: string): string {
|
|
1122
|
+
let url: URL;
|
|
1123
|
+
try {
|
|
1124
|
+
url = new URL(input.trim());
|
|
1125
|
+
} catch {
|
|
1126
|
+
throw new Error("Enter the base URL as a URL, like https://api.example.com");
|
|
1127
|
+
}
|
|
1128
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("The base URL must start with http:// or https://");
|
|
1129
|
+
if (url.username || url.password) throw new Error("Put credentials in the key field, not in the base URL");
|
|
1130
|
+
if (url.search || url.hash) throw new Error("The base URL can't have a query or fragment");
|
|
1131
|
+
return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, "")}`;
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
/** Keys shorter than this get no hint: their last four characters would give away too much of them. */
|
|
1135
|
+
const KEY_HINT_MIN_LENGTH = 12;
|
|
1136
|
+
|
|
1137
|
+
/**
|
|
1138
|
+
* An added Pi account's own settings, kept by ZeroSub in its home (mode 600): the Anthropic API key
|
|
1139
|
+
* and base URL it uses, and its proxy. Pi never reads it; `auth.json` and `models.json` are made
|
|
1140
|
+
* from it (see `preparePiHome`), and the proxy goes to the account's sessions as environment
|
|
1141
|
+
* variables (see `PiAdapter.env`).
|
|
1142
|
+
*/
|
|
1143
|
+
export const PI_ACCOUNT_FILE = "zerosub.json";
|
|
1144
|
+
|
|
1145
|
+
/** Whether `home` holds a Pi account: its key, base URL and proxy are in its account file. */
|
|
1146
|
+
export async function piHomeHoldsAccount(home: string): Promise<boolean> {
|
|
1147
|
+
return (await lstat(join(home, PI_ACCOUNT_FILE)).catch(() => null))?.isFile() === true;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
export interface PiAccount {
|
|
1151
|
+
key: string | null;
|
|
1152
|
+
baseUrl: string | null;
|
|
1153
|
+
proxy: string | null;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
/**
|
|
1157
|
+
* Entries of Pi's agent directory an added account keeps to itself: its sign-ins (`auth.json`) and
|
|
1158
|
+
* where its Anthropic requests go (`models.json`), both made here, Pi's model catalog cache, which
|
|
1159
|
+
* it fills from the providers it can reach with its own key, ZeroSub's own file, and locks and
|
|
1160
|
+
* scratch files. Settings, sessions, extensions, skills, prompts and the rest are shared.
|
|
1161
|
+
*/
|
|
1162
|
+
function piPrivate(name: string): boolean {
|
|
1163
|
+
return (
|
|
1164
|
+
name === PI_ACCOUNT_FILE ||
|
|
1165
|
+
name === "zerosub.env" ||
|
|
1166
|
+
name.startsWith("auth.json") ||
|
|
1167
|
+
name.startsWith("models.json") ||
|
|
1168
|
+
name.startsWith("models-store.json") ||
|
|
1169
|
+
name.endsWith(".lock") ||
|
|
1170
|
+
isTemporary(name)
|
|
1171
|
+
);
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
function stringOrNull(value: unknown): string | null {
|
|
1175
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
/** The account's own settings; empty ones for a home without the file (or one that doesn't parse). */
|
|
1179
|
+
export async function readPiAccount(home: string): Promise<PiAccount> {
|
|
1180
|
+
return piAccountFrom(await readJsonObject(join(home, PI_ACCOUNT_FILE)));
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
/**
|
|
1184
|
+
* The account's settings to start an agent with. Unlike `readPiAccount`, a folder without a readable
|
|
1185
|
+
* `zerosub.json` throws instead of reading as empty: the folder is being moved (renamed away while
|
|
1186
|
+
* Pi's processes are checked) or is gone, and an agent started from empty settings would run without
|
|
1187
|
+
* the account's proxy, and keep running that way.
|
|
1188
|
+
*/
|
|
1189
|
+
export async function readPiAccountForAgents(home: string): Promise<PiAccount> {
|
|
1190
|
+
const value = await readJsonObject(join(home, PI_ACCOUNT_FILE));
|
|
1191
|
+
if (!value) throw new Error(`${home} has no readable ${PI_ACCOUNT_FILE} (it may be moving)`);
|
|
1192
|
+
return piAccountFrom(value);
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
function piAccountFrom(value: Record<string, unknown> | null): PiAccount {
|
|
1196
|
+
return { key: stringOrNull(value?.key), baseUrl: stringOrNull(value?.baseUrl), proxy: stringOrNull(value?.proxy) };
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
async function writePiAccount(home: string, account: PiAccount): Promise<void> {
|
|
1200
|
+
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
1201
|
+
const value: Json = {};
|
|
1202
|
+
if (account.key) value.key = account.key;
|
|
1203
|
+
if (account.baseUrl) value.baseUrl = account.baseUrl;
|
|
1204
|
+
if (account.proxy) value.proxy = account.proxy;
|
|
1205
|
+
await writeJsonAtomically(join(home, PI_ACCOUNT_FILE), value);
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
/**
|
|
1209
|
+
* The account's `auth.json`: the API keys the CLI login keeps for other providers (OpenRouter's,
|
|
1210
|
+
* say), which are safe to copy, and the account's own Anthropic key in place of any the CLI login
|
|
1211
|
+
* has. Subscription sign-ins (OAuth) aren't copied: each copy would refresh its token on its own,
|
|
1212
|
+
* and the first refresh would leave the other with a spent one. Pi uses a stored key before any in
|
|
1213
|
+
* the environment, so the daemon's `ANTHROPIC_API_KEY` can't take this one's place; the key is
|
|
1214
|
+
* stored escaped (see `piLiteral`) so Pi reads it as it was typed.
|
|
1215
|
+
*/
|
|
1216
|
+
export function piAuth(main: unknown, key: string | null): Json {
|
|
1217
|
+
const auth: Json = {};
|
|
1218
|
+
if (isObject(main)) {
|
|
1219
|
+
for (const [provider, entry] of Object.entries(main)) {
|
|
1220
|
+
if (provider !== "anthropic" && isObject(entry) && entry.type === "api_key") auth[provider] = entry;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
if (key) auth.anthropic = { type: "api_key", key: piLiteral(key) };
|
|
1224
|
+
return auth;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
/**
|
|
1228
|
+
* `value` written so Pi reads it back unchanged. Pi resolves a stored key as config: one starting
|
|
1229
|
+
* with `!` is run as a shell command, and `$NAME` or `${NAME}` is filled in from the environment, so
|
|
1230
|
+
* a key containing either would be run or changed (and one that came out empty would fall back to
|
|
1231
|
+
* the environment's key). In Pi's syntax `$$` stands for `$`, and `$!` for `!`.
|
|
1232
|
+
*/
|
|
1233
|
+
export function piLiteral(value: string): string {
|
|
1234
|
+
const escaped = value.split("$").join("$$");
|
|
1235
|
+
return escaped.startsWith("!") ? `$${escaped}` : escaped;
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/**
|
|
1239
|
+
* What else in a `models.json` provider entry would send another key or token along, or in its
|
|
1240
|
+
* place, or send the requests elsewhere (`oauth` takes each model's own base URL).
|
|
1241
|
+
*/
|
|
1242
|
+
const PI_OVERRIDING_AUTH = ["apiKey", "headers", "authHeader", "oauth"];
|
|
1243
|
+
|
|
1244
|
+
/** A model entry (`models[]`) or override (`modelOverrides`) with `keys` taken out. */
|
|
1245
|
+
function without(entry: unknown, keys: readonly string[]): unknown {
|
|
1246
|
+
if (!isObject(entry)) return entry;
|
|
1247
|
+
const copy: Json = { ...entry };
|
|
1248
|
+
for (const key of keys) delete copy[key];
|
|
1249
|
+
return copy;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
/**
|
|
1253
|
+
* The account's `models.json`: the CLI login's, with Anthropic's requests sent to the account's base
|
|
1254
|
+
* URL (Pi's built-in one, `https://api.anthropic.com`, when it has none) and nothing in Anthropic's
|
|
1255
|
+
* entry that would send another key or extra headers, or send a model's requests elsewhere. In Pi a
|
|
1256
|
+
* model's own `baseUrl` and `headers` (`models[]`) outrank the provider's, and an override's
|
|
1257
|
+
* `headers` (`modelOverrides`) are added to its requests, so those are taken out of Anthropic's
|
|
1258
|
+
* models too: otherwise that model would carry the account's key to wherever the CLI login sends
|
|
1259
|
+
* it. Everything else (other providers, the rest of each model) stays as it is.
|
|
1260
|
+
*/
|
|
1261
|
+
export function piModels(main: unknown, baseUrl: string | null): Json {
|
|
1262
|
+
const models: Json = isObject(main) ? { ...main } : {};
|
|
1263
|
+
const providers: Json = isObject(models.providers) ? { ...models.providers } : {};
|
|
1264
|
+
const anthropic: Json = isObject(providers.anthropic) ? { ...providers.anthropic } : {};
|
|
1265
|
+
for (const key of [...PI_OVERRIDING_AUTH, "baseUrl"]) delete anthropic[key];
|
|
1266
|
+
if (Array.isArray(anthropic.models)) anthropic.models = anthropic.models.map((model) => without(model, ["baseUrl", "headers"]));
|
|
1267
|
+
if (isObject(anthropic.modelOverrides)) {
|
|
1268
|
+
anthropic.modelOverrides = Object.fromEntries(Object.entries(anthropic.modelOverrides).map(([id, entry]) => [id, without(entry, ["headers"])]));
|
|
1269
|
+
}
|
|
1270
|
+
if (baseUrl) anthropic.baseUrl = baseUrl;
|
|
1271
|
+
if (Object.keys(anthropic).length > 0) providers.anthropic = anthropic;
|
|
1272
|
+
else delete providers.anthropic;
|
|
1273
|
+
if (Object.keys(providers).length > 0) models.providers = providers;
|
|
1274
|
+
else delete models.providers;
|
|
1275
|
+
return models;
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/** Main's `models.json` files that didn't parse, so each is only logged once. */
|
|
1279
|
+
const unreadablePiModels = new Set<string>();
|
|
1280
|
+
|
|
1281
|
+
/** Writes `value` to `path` unless it already holds exactly that. */
|
|
1282
|
+
async function writeIfChanged(path: string, value: unknown): Promise<void> {
|
|
1283
|
+
const next = `${JSON.stringify(value, null, 2)}\n`;
|
|
1284
|
+
const current = await lstat(path).catch(() => null);
|
|
1285
|
+
if (current?.isFile() && (await readFile(path, "utf8").catch(() => null)) === next) return;
|
|
1286
|
+
await writeJsonAtomically(path, value);
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
async function syncPiFiles(home: string): Promise<void> {
|
|
1290
|
+
const account = await readPiAccount(home);
|
|
1291
|
+
const mainDir = mainPiDir();
|
|
1292
|
+
const mainAuth = await readPiOwnObject(join(mainDir, "auth.json"));
|
|
1293
|
+
await writeIfChanged(join(home, "auth.json"), piAuth(mainAuth, account.key));
|
|
1294
|
+
const modelsPath = join(mainDir, "models.json");
|
|
1295
|
+
let mainModels: unknown = {};
|
|
1296
|
+
try {
|
|
1297
|
+
mainModels = (await readPiOwnJson(modelsPath, true)) ?? {};
|
|
1298
|
+
unreadablePiModels.delete(modelsPath);
|
|
1299
|
+
} catch {
|
|
1300
|
+
// Still written, so the account's key never goes to a base URL it wasn't set up with.
|
|
1301
|
+
if (!unreadablePiModels.has(modelsPath)) console.warn(`[ZeroSub] ${modelsPath} doesn't parse; added Pi accounts don't get its models until it's fixed`);
|
|
1302
|
+
unreadablePiModels.add(modelsPath);
|
|
1303
|
+
}
|
|
1304
|
+
await writeIfChanged(join(home, "models.json"), piModels(mainModels, account.baseUrl));
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
/** Main's `settings.json` files that didn't parse, so each is only logged once. */
|
|
1308
|
+
const unreadablePiSettings = new Set<string>();
|
|
1309
|
+
|
|
1310
|
+
/**
|
|
1311
|
+
* The account's `settings.json`. Without a proxy of its own it's a link to the CLI login's, like
|
|
1312
|
+
* the other shared entries. With one it's the CLI login's settings with `httpProxy` set to the
|
|
1313
|
+
* proxy, so Pi started on the account's folder anywhere else (`PI_CODING_AGENT_DIR=<folder> pi` in
|
|
1314
|
+
* a terminal, say) goes through it too, as long as its environment names no proxy (Pi only fills
|
|
1315
|
+
* the proxy variables in from `httpProxy` when they're unset). It's remade from the CLI login's at
|
|
1316
|
+
* every sync, so what Pi writes to it there doesn't last. A home ZeroSub made is the only kind a
|
|
1317
|
+
* Pi account has, so the generated file is replaced by the link again once the proxy goes; while
|
|
1318
|
+
* the CLI login has no settings to link to, it stays with `httpProxy` taken out.
|
|
1319
|
+
*/
|
|
1320
|
+
async function syncPiSettings(home: string, proxy: string | null): Promise<void> {
|
|
1321
|
+
const target = join(home, "settings.json");
|
|
1322
|
+
const current = await lstat(target).catch(() => null);
|
|
1323
|
+
const mainSettings = join(mainPiDir(), "settings.json");
|
|
1324
|
+
if (proxy) {
|
|
1325
|
+
let main: unknown;
|
|
1326
|
+
try {
|
|
1327
|
+
main = await readPiOwnJson(mainSettings);
|
|
1328
|
+
unreadablePiSettings.delete(mainSettings);
|
|
1329
|
+
} catch {
|
|
1330
|
+
if (!unreadablePiSettings.has(mainSettings)) console.warn(`[ZeroSub] ${mainSettings} isn't valid JSON; added Pi accounts with a proxy keep the rest of their settings as they were until it's fixed`);
|
|
1331
|
+
unreadablePiSettings.add(mainSettings);
|
|
1332
|
+
// The rest stays as it was, but never the proxy: the account's may have changed since.
|
|
1333
|
+
if (current?.isFile()) main = await readJsonObject(target);
|
|
1334
|
+
}
|
|
1335
|
+
// Written over the link, never through it: the CLI login's settings stay as they are.
|
|
1336
|
+
await writeIfChanged(target, { ...(isObject(main) ? main : {}), httpProxy: proxy });
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
if (!current?.isFile()) return;
|
|
1340
|
+
const real = await realpath(mainSettings).catch(() => null);
|
|
1341
|
+
if (!real) {
|
|
1342
|
+
// The CLI login has none to share, so the file stays, without the proxy that was the account's:
|
|
1343
|
+
// Pi started on this folder would otherwise still go through it.
|
|
1344
|
+
const own = await readJsonObject(target);
|
|
1345
|
+
if (own && "httpProxy" in own) {
|
|
1346
|
+
const { httpProxy: _gone, ...rest } = own;
|
|
1347
|
+
await writeIfChanged(target, rest);
|
|
1348
|
+
}
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
await unlink(target);
|
|
1352
|
+
await symlink(real, target);
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
/**
|
|
1356
|
+
* Brings an added Pi account's home in step with the CLI login's agent directory: shared entries
|
|
1357
|
+
* linked, `auth.json` and `models.json` made from it and the account's own settings. `wanted`, if
|
|
1358
|
+
* given, is asked once the home's lock is held: a home whose account has gone since the caller
|
|
1359
|
+
* looked is left as it is.
|
|
1360
|
+
*/
|
|
1361
|
+
export function preparePiHome(home: string, force = false, wanted?: () => Promise<boolean>): Promise<void> {
|
|
1362
|
+
return withHome(home, async () => {
|
|
1363
|
+
if (wanted && !(await wanted())) return;
|
|
1364
|
+
const last = lastSync.get(home);
|
|
1365
|
+
if (!force && last && Date.now() - last < SYNC_TTL_MS) return;
|
|
1366
|
+
const { proxy } = await readPiAccount(home);
|
|
1367
|
+
await syncPiSettings(home, proxy);
|
|
1368
|
+
const isPrivate = (name: string) => piPrivate(name) || (proxy !== null && name === "settings.json");
|
|
1369
|
+
await syncOverlay(home, { main: mainPiDir(), shareDirs: ["sessions"], isPrivate });
|
|
1370
|
+
await syncPiFiles(home);
|
|
1371
|
+
lastSync.set(home, Date.now());
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
/** The account's API settings with the key reduced to a hint (its last four characters, or empty for a short key); null without a key. */
|
|
1376
|
+
export async function readPiAccountApi(home: string): Promise<ApiSummary | null> {
|
|
1377
|
+
const { key, baseUrl } = await readPiAccount(home);
|
|
1378
|
+
if (!key) return null;
|
|
1379
|
+
return { keyHint: key.length >= KEY_HINT_MIN_LENGTH ? key.slice(-4) : "", baseUrl };
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
/**
|
|
1383
|
+
* Stores a Pi account's Anthropic key (`null` keeps the current one) and base URL, then remakes its
|
|
1384
|
+
* `auth.json` and `models.json`. A kept key only goes where it went before: sending it somewhere new
|
|
1385
|
+
* takes typing it again, so nobody can point it at a new address without knowing it. `wanted` as for `stillWanted`.
|
|
1386
|
+
*/
|
|
1387
|
+
export function writePiAccountApi(home: string, config: { key: string | null; baseUrl: string | null }, wanted?: () => Promise<boolean>): Promise<void> {
|
|
1388
|
+
return withHome(home, async () => {
|
|
1389
|
+
await stillWanted(wanted);
|
|
1390
|
+
const previous = await readPiAccount(home);
|
|
1391
|
+
const key = config.key?.trim() || previous.key;
|
|
1392
|
+
if (!key) throw new Error("Enter the API key");
|
|
1393
|
+
const baseUrl = config.baseUrl?.trim() ? normalizeBaseUrl(config.baseUrl) : null;
|
|
1394
|
+
if (!config.key?.trim() && previous.baseUrl !== baseUrl) throw new Error("Enter the key again to use it with a different base URL");
|
|
1395
|
+
await writePiAccount(home, { ...previous, key, baseUrl });
|
|
1396
|
+
await syncPiFiles(home);
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
/**
|
|
1401
|
+
* Sets (or clears, with `null`) a Pi account's proxy, for its sessions started afterwards (see
|
|
1402
|
+
* `PiAdapter.env`). `wanted` as for `stillWanted`. `inherited` says which proxy the account would go
|
|
1403
|
+
* through without one of its own, for a key that clearing it would send there in the clear.
|
|
1404
|
+
*/
|
|
1405
|
+
export function writePiAccountProxy(
|
|
1406
|
+
home: string,
|
|
1407
|
+
proxy: string | null,
|
|
1408
|
+
wanted?: () => Promise<boolean>,
|
|
1409
|
+
inherited?: (baseUrl: string | null) => Promise<{ proxy: string; from: string } | null>,
|
|
1410
|
+
): Promise<void> {
|
|
1411
|
+
return withHome(home, async () => {
|
|
1412
|
+
await stillWanted(wanted);
|
|
1413
|
+
const previous = await readPiAccount(home);
|
|
1414
|
+
// Without its own, the account goes through the proxy it inherits: a plain-http:// key would then
|
|
1415
|
+
// cross that one in the clear, as through a new one of its own, to this machine too (`inherited`
|
|
1416
|
+
// is null where the no-proxy list keeps the base URL direct; see `crossesInheritedProxy`).
|
|
1417
|
+
if (!proxy && previous.proxy && previous.key && plainHttp(previous.baseUrl)) {
|
|
1418
|
+
const next = await inherited?.(previous.baseUrl);
|
|
1419
|
+
if (next) {
|
|
1420
|
+
throw new Error(
|
|
1421
|
+
`This account sends its key over plain http://, and without its own proxy it would go through ${maskProxy(next.proxy)} (${next.from}), which could read it. Switch to an https:// base URL first, or keep this proxy.`,
|
|
1422
|
+
);
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
// As with a new base URL, a key is never sent somewhere new: over plain http:// a proxy reads it.
|
|
1426
|
+
if (proxy && proxy !== previous.proxy) {
|
|
1427
|
+
if (previous.key && sentInTheClear(previous.baseUrl)) {
|
|
1428
|
+
throw new Error(
|
|
1429
|
+
"This account sends its key over plain http://, which a proxy can read. To use a new proxy, remove the account and add it again with its key and the proxy, or switch to an https:// base URL.",
|
|
1430
|
+
);
|
|
1431
|
+
}
|
|
1432
|
+
const exposed = await clearTextProviders(false);
|
|
1433
|
+
if (exposed.length > 0) {
|
|
1434
|
+
throw new Error(
|
|
1435
|
+
`Pi's own models.json sends the API key for ${exposed.join(", ")} over plain http://, and every Pi account gets that key, so a proxy could read it. Use https:// there, or a gateway on this machine, before setting a proxy.`,
|
|
1436
|
+
);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
await writePiAccount(home, { ...previous, proxy });
|
|
1440
|
+
await syncPiSettings(home, proxy);
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
/**
|
|
1445
|
+
* The variables Pi takes each of its own providers' key from when it has none stored
|
|
1446
|
+
* (`getApiKeyEnvVars` in pi-ai): every name any version from 1.4.0 on reads, as a name an older or
|
|
1447
|
+
* newer Pi doesn't read only refuses a proxy it could have allowed. 1.5.1 added
|
|
1448
|
+
* `qwen-token-plan-individual-cn`; the per-plan Qwen variables come after 1.5.2 (on Pi's main
|
|
1449
|
+
* branch, not released yet). Anthropic's are in `PI_ANTHROPIC_CREDENTIAL_ENV`.
|
|
1450
|
+
*/
|
|
1451
|
+
const PI_KEY_ENV: Readonly<Record<string, string | readonly string[]>> = {
|
|
1452
|
+
"github-copilot": "COPILOT_GITHUB_TOKEN",
|
|
1453
|
+
"ant-ling": "ANT_LING_API_KEY",
|
|
1454
|
+
"qwen-token-plan": ["QWEN_TOKEN_PLAN_TEAM_API_KEY", "QWEN_TOKEN_PLAN_API_KEY"],
|
|
1455
|
+
"qwen-token-plan-cn": ["QWEN_TOKEN_PLAN_TEAM_CN_API_KEY", "QWEN_TOKEN_PLAN_CN_API_KEY"],
|
|
1456
|
+
"qwen-token-plan-individual": ["QWEN_TOKEN_PLAN_INDIVIDUAL_API_KEY", "QWEN_TOKEN_PLAN_API_KEY"],
|
|
1457
|
+
"qwen-token-plan-individual-cn": ["QWEN_TOKEN_PLAN_INDIVIDUAL_CN_API_KEY", "QWEN_TOKEN_PLAN_CN_API_KEY"],
|
|
1458
|
+
openai: "OPENAI_API_KEY",
|
|
1459
|
+
azure: "AZURE_OPENAI_API_KEY",
|
|
1460
|
+
nvidia: "NVIDIA_API_KEY",
|
|
1461
|
+
deepseek: "DEEPSEEK_API_KEY",
|
|
1462
|
+
google: "GEMINI_API_KEY",
|
|
1463
|
+
"google-vertex": "GOOGLE_CLOUD_API_KEY",
|
|
1464
|
+
groq: "GROQ_API_KEY",
|
|
1465
|
+
cerebras: "CEREBRAS_API_KEY",
|
|
1466
|
+
xai: "XAI_API_KEY",
|
|
1467
|
+
typesafe: "TYPESAFE_API_KEY",
|
|
1468
|
+
radius: "RADIUS_API_KEY",
|
|
1469
|
+
openrouter: "OPENROUTER_API_KEY",
|
|
1470
|
+
"vercel-ai-gateway": "AI_GATEWAY_API_KEY",
|
|
1471
|
+
zai: "ZAI_API_KEY",
|
|
1472
|
+
"zai-coding-cn": "ZAI_CODING_CN_API_KEY",
|
|
1473
|
+
mistral: "MISTRAL_API_KEY",
|
|
1474
|
+
minimax: "MINIMAX_API_KEY",
|
|
1475
|
+
"minimax-cn": "MINIMAX_CN_API_KEY",
|
|
1476
|
+
moonshotai: "MOONSHOT_API_KEY",
|
|
1477
|
+
"moonshotai-cn": "MOONSHOT_API_KEY",
|
|
1478
|
+
huggingface: "HF_TOKEN",
|
|
1479
|
+
fireworks: "FIREWORKS_API_KEY",
|
|
1480
|
+
together: "TOGETHER_API_KEY",
|
|
1481
|
+
baseten: "BASETEN_API_KEY",
|
|
1482
|
+
opencode: "OPENCODE_API_KEY",
|
|
1483
|
+
"opencode-go": "OPENCODE_API_KEY",
|
|
1484
|
+
"kimi-coding": "KIMI_API_KEY",
|
|
1485
|
+
meta: "META_API_KEY",
|
|
1486
|
+
"cloudflare-workers-ai": "CLOUDFLARE_API_KEY",
|
|
1487
|
+
"cloudflare-ai-gateway": "CLOUDFLARE_API_KEY",
|
|
1488
|
+
xiaomi: "XIAOMI_API_KEY",
|
|
1489
|
+
"xiaomi-token-plan-cn": "XIAOMI_TOKEN_PLAN_CN_API_KEY",
|
|
1490
|
+
"xiaomi-token-plan-ams": "XIAOMI_TOKEN_PLAN_AMS_API_KEY",
|
|
1491
|
+
"xiaomi-token-plan-sgp": "XIAOMI_TOKEN_PLAN_SGP_API_KEY",
|
|
1492
|
+
};
|
|
1493
|
+
|
|
1494
|
+
/**
|
|
1495
|
+
* The variables that give Pi's own login something of Anthropic's to send: a key or token, headers
|
|
1496
|
+
* the SDK adds to every request, or the federation rule Pi gets a token for when it has no key.
|
|
1497
|
+
*/
|
|
1498
|
+
const PI_ANTHROPIC_CREDENTIAL_ENV = ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_CUSTOM_HEADERS", "ANTHROPIC_FEDERATION_RULE_ID"];
|
|
1499
|
+
|
|
1500
|
+
/**
|
|
1501
|
+
* Providers that Pi's own `models.json` sends over plain http:// through the proxy (to another
|
|
1502
|
+
* machine for an added account's, see `sentInTheClear`; for the login's, anywhere the no-proxy list
|
|
1503
|
+
* doesn't keep direct, see `crossesInheritedProxy`), for the provider or any of its models, along
|
|
1504
|
+
* with a credential a proxy could then read: an entry in the CLI login's `auth.json`, an `apiKey`,
|
|
1505
|
+
* `headers` or `authHeader` in its `models.json` (for the provider, a model or an override), or a key
|
|
1506
|
+
* in the environment Pi starts with (the daemon's, under the Pi provider's `env` in Paseo's config).
|
|
1507
|
+
*
|
|
1508
|
+
* For an added account's proxy these are the credentials every account gets from the CLI login: its
|
|
1509
|
+
* `auth.json` API keys (see `piAuth`; its sign-ins aren't copied) and everything but Anthropic's, which
|
|
1510
|
+
* the account has its own of (see `piModels`). For the proxy of Pi's own login (`login`) it's whatever
|
|
1511
|
+
* that login sends: Anthropic's too, and its sign-ins. There a `models.json` that doesn't parse is
|
|
1512
|
+
* refused, as nothing can be told from it; an added account gets none of it (see `syncPiFiles`).
|
|
1513
|
+
*/
|
|
1514
|
+
export async function clearTextProviders(login: boolean): Promise<string[]> {
|
|
1515
|
+
const auth = (await readPiOwnObject(join(mainPiDir(), "auth.json"))) ?? {};
|
|
1516
|
+
const modelsPath = join(mainPiDir(), "models.json");
|
|
1517
|
+
let models: unknown;
|
|
1518
|
+
try {
|
|
1519
|
+
models = await readPiOwnJson(modelsPath, true);
|
|
1520
|
+
} catch {
|
|
1521
|
+
if (login) throw new Error(`${modelsPath} doesn't parse, so ZeroSub can't tell whether a key there would cross the proxy over plain http://. Fix it before setting a proxy.`);
|
|
1522
|
+
}
|
|
1523
|
+
const providers = isObject(models) && isObject(models.providers) ? models.providers : {};
|
|
1524
|
+
const env: Record<string, string | undefined> = { ...process.env, ...providerEnv("pi") };
|
|
1525
|
+
const inEnv = (name: string) => (name === "anthropic" ? PI_ANTHROPIC_CREDENTIAL_ENV : [PI_KEY_ENV[name] ?? []].flat()).some((key) => env[key]?.trim());
|
|
1526
|
+
const clear = (value: unknown) => typeof value === "string" && (login ? crossesInheritedProxy(value, env) : sentInTheClear(value));
|
|
1527
|
+
// Set to something: an empty key or header list, or `authHeader: false`, sends nothing.
|
|
1528
|
+
const set = (value: unknown) => (isObject(value) ? Object.keys(value).length > 0 : value !== undefined && value !== null && value !== false && value !== "");
|
|
1529
|
+
const carries = (entry: unknown) => isObject(entry) && ["apiKey", "headers", "authHeader"].some((key) => set(entry[key]));
|
|
1530
|
+
return Object.entries(providers)
|
|
1531
|
+
.filter(([name, config]) => {
|
|
1532
|
+
if ((name === "anthropic" && !login) || !isObject(config)) return false;
|
|
1533
|
+
const list = Array.isArray(config.models) ? config.models.filter(isObject) : [];
|
|
1534
|
+
const overrides = isObject(config.modelOverrides) ? Object.values(config.modelOverrides) : [];
|
|
1535
|
+
const entry = auth[name];
|
|
1536
|
+
const stored = isObject(entry) && (login || entry.type === "api_key");
|
|
1537
|
+
const shared = stored || inEnv(name) || carries(config) || overrides.some(carries);
|
|
1538
|
+
// A model sends what the provider carries, plus its own headers, to its own base URL or the provider's.
|
|
1539
|
+
return list.some((model) => clear(model.baseUrl ?? config.baseUrl) && (shared || carries(model))) || (clear(config.baseUrl) && shared);
|
|
1540
|
+
})
|
|
1541
|
+
.map(([name]) => name);
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
/**
|
|
1545
|
+
* Whether requests to `baseUrl` would cross a proxy ZeroSub gives an added account unencrypted:
|
|
1546
|
+
* plain http:// to anywhere but the hosts that always stay direct (`REQUIRED_NO_PROXY`, which
|
|
1547
|
+
* ZeroSub puts in that account's no-proxy list; see `proxyVariables`). For a proxy Pi takes itself,
|
|
1548
|
+
* see `crossesInheritedProxy`.
|
|
1549
|
+
*/
|
|
1550
|
+
export function sentInTheClear(baseUrl: string | null): boolean {
|
|
1551
|
+
if (!baseUrl) return false;
|
|
1552
|
+
try {
|
|
1553
|
+
const url = new URL(baseUrl);
|
|
1554
|
+
const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
1555
|
+
return url.protocol === "http:" && !(REQUIRED_NO_PROXY as readonly string[]).includes(host);
|
|
1556
|
+
} catch {
|
|
1557
|
+
return false;
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
/** Whether `baseUrl` is plain http://, which any proxy it goes through can read. */
|
|
1562
|
+
export function plainHttp(baseUrl: string | null): boolean {
|
|
1563
|
+
if (!baseUrl) return false;
|
|
1564
|
+
try {
|
|
1565
|
+
return new URL(baseUrl).protocol === "http:";
|
|
1566
|
+
} catch {
|
|
1567
|
+
return false;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
/**
|
|
1572
|
+
* Whether requests to `baseUrl` would cross a proxy Pi takes from `httpProxy` or the environment
|
|
1573
|
+
* (`env`, the one Pi starts with) unencrypted: plain http:// that the no-proxy list doesn't keep
|
|
1574
|
+
* direct. Pi adds nothing to that list, and undici, which Pi sends its requests with, keeps no host
|
|
1575
|
+
* direct without it, this machine included. The list is read as undici reads it: `no_proxy` wherever
|
|
1576
|
+
* it's set, even empty, else `NO_PROXY`.
|
|
1577
|
+
*/
|
|
1578
|
+
export function crossesInheritedProxy(baseUrl: string | null, env: Record<string, string | undefined> = { ...process.env, ...providerEnv("pi") }): boolean {
|
|
1579
|
+
return baseUrl !== null && plainHttp(baseUrl) && !bypassesProxy(env.no_proxy ?? env.NO_PROXY ?? null, baseUrl);
|
|
1580
|
+
}
|