@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/pi.ts
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
import type { ApiSummary, LoginMethod } from "../shared/model";
|
|
5
|
+
import type { EnvPatch, FamilyAdapter, Identity, LoginHandle, ProxyState, RedeemReply, TurnEvent, UsageRead } from "./adapter";
|
|
6
|
+
import { providerCommand } from "./binaries";
|
|
7
|
+
import { clearTextProviders, forgetSyncs, normalizeBaseUrl, piHomeHoldsAccount, piLiteral, preparePiHome, readPiAccount, readPiOwnJson, readPiAccountApi, readPiAccountForAgents, writePiAccountApi, writePiAccountProxy } from "./homes";
|
|
8
|
+
import { PI_LAUNCH_ENV } from "./launchers";
|
|
9
|
+
import { Mutex, readJson, writeJsonAtomic } from "./json-file";
|
|
10
|
+
import { eachProcessEnvironment, homesInEnvironment, parseTrace } from "./processes";
|
|
11
|
+
import { detectPiSignOut } from "./limits";
|
|
12
|
+
import { dataDir, mainPiDir, shownPath } from "./paths";
|
|
13
|
+
import { run } from "./process";
|
|
14
|
+
import { providerEnv } from "./provider-env";
|
|
15
|
+
import { NO_PROXY_KEYS, PROXY_KEYS, bypassesProxy, noProxyFromEnv, proxiedFetch, proxyFromEnv, withRequiredNoProxy, withoutDomains } from "./proxy";
|
|
16
|
+
|
|
17
|
+
const ANTHROPIC_API = "https://api.anthropic.com";
|
|
18
|
+
/** Anthropic's edge answers this with the address it sees the request come from (see `PiAdapter.egress`). */
|
|
19
|
+
const TRACE = `${ANTHROPIC_API}/cdn-cgi/trace`;
|
|
20
|
+
/** Where Anthropic's API and sign-in live; a proxy set here must not be gone around for them. */
|
|
21
|
+
const ANTHROPIC_DOMAINS = ["anthropic.com", "claude.ai", "claude.com"];
|
|
22
|
+
|
|
23
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
24
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function hostOf(url: string | null): string | null {
|
|
28
|
+
if (!url) return null;
|
|
29
|
+
try {
|
|
30
|
+
return new URL(url).hostname.toLowerCase();
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function mainSettingsPath(): string {
|
|
37
|
+
return join(mainPiDir(), "settings.json");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* `httpProxy` in Pi's own `settings.json`, which Pi applies when the environment names no proxy. Only
|
|
42
|
+
* written when the user sets the CLI login's proxy from its card (see `writePiMainProxy`).
|
|
43
|
+
*/
|
|
44
|
+
async function settingsProxy(): Promise<string | null> {
|
|
45
|
+
const settings = await readPiOwnJson(mainSettingsPath()).catch(() => undefined);
|
|
46
|
+
return isObject(settings) && typeof settings.httpProxy === "string" && settings.httpProxy.trim() ? settings.httpProxy.trim() : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The folder Pi keeps the CLI login's sessions for `cwd` in: `sessions/--<cwd with / as ->--` in its
|
|
51
|
+
* agent directory, as Pi names it (`getDefaultSessionDirPath`, 1.4.0 to 1.5.2). Pi names it after its
|
|
52
|
+
* `process.cwd()`, which is the folder's real path (`/private/tmp/x` for `/tmp/x` on macOS).
|
|
53
|
+
*/
|
|
54
|
+
export async function piSessionDir(cwd: string): Promise<string> {
|
|
55
|
+
const real = await realpath(cwd).catch(() => resolve(cwd));
|
|
56
|
+
const safe = `--${real.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
|
|
57
|
+
return join(mainPiDir(), "sessions", safe);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Whether Pi's sessions directory is set somewhere other than its default under the agent directory. */
|
|
61
|
+
async function sessionDirConfigured(): Promise<boolean> {
|
|
62
|
+
if (process.env.PI_CODING_AGENT_SESSION_DIR?.trim() || providerEnv("pi").PI_CODING_AGENT_SESSION_DIR?.trim()) return true;
|
|
63
|
+
const settings = await readPiOwnJson(mainSettingsPath()).catch(() => undefined);
|
|
64
|
+
return isObject(settings) && typeof settings.sessionDir === "string" && settings.sessionDir.trim() !== "";
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The variables that send a Pi process through `proxy`: all four proxy variables, so nothing it
|
|
69
|
+
* inherits outranks it, and both no-proxy variables (Pi reads the lower-case one first), set to the
|
|
70
|
+
* list it would otherwise have without the entries that would send Anthropic's traffic, or the
|
|
71
|
+
* account's base URL's, past the proxy, plus localhost and 127.0.0.1 so a gateway on this machine
|
|
72
|
+
* stays direct.
|
|
73
|
+
*/
|
|
74
|
+
function proxyVariables(proxy: string, baseUrl: string | null): Record<string, string> {
|
|
75
|
+
const inherited = { ...process.env, ...providerEnv("pi") };
|
|
76
|
+
const base = hostOf(baseUrl);
|
|
77
|
+
const noProxy = withRequiredNoProxy(withoutDomains(noProxyFromEnv(inherited), base ? [...ANTHROPIC_DOMAINS, base] : ANTHROPIC_DOMAINS));
|
|
78
|
+
const env: Record<string, string> = {};
|
|
79
|
+
for (const key of PROXY_KEYS) env[key] = proxy;
|
|
80
|
+
for (const key of NO_PROXY_KEYS) env[key] = noProxy;
|
|
81
|
+
return env;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The proxy an added account's Pi goes through without one of its own, and where that's set: the Pi
|
|
86
|
+
* provider's `env` in Paseo's config over the daemon's environment, else `httpProxy` in Pi's own
|
|
87
|
+
* settings, which the account shares. Null when it goes direct, or the no-proxy list sends `target`
|
|
88
|
+
* past it.
|
|
89
|
+
*/
|
|
90
|
+
export async function inheritedPiProxy(target = ANTHROPIC_API): Promise<{ proxy: string; from: string } | null> {
|
|
91
|
+
const provider = providerEnv("pi");
|
|
92
|
+
const env: Record<string, string | undefined> = { ...process.env, ...provider };
|
|
93
|
+
if (bypassesProxy(env.no_proxy ?? env.NO_PROXY ?? null, target)) return null;
|
|
94
|
+
const key = PROXY_KEYS.find((name) => env[name]?.trim());
|
|
95
|
+
if (key) return { proxy: env[key]!.trim(), from: key in provider ? "the Pi provider's env in Paseo's config" : "the daemon's environment" };
|
|
96
|
+
const own = await settingsProxy();
|
|
97
|
+
return own ? { proxy: own, from: `httpProxy in ${shownPath(mainSettingsPath())}` } : null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The proxy a Pi process reaches `target` through, from the environment it starts with, else Pi's
|
|
102
|
+
* `httpProxy` setting, then the no-proxy list; null when it goes direct.
|
|
103
|
+
*/
|
|
104
|
+
async function piProxyFor(env: Record<string, string | undefined>, target: string): Promise<string | null> {
|
|
105
|
+
const proxy = proxyFromEnv(env) ?? (await settingsProxy());
|
|
106
|
+
return proxy && !bypassesProxy(env.no_proxy ?? env.NO_PROXY ?? null, target) ? proxy : null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// --------------------------------------------------------------------------- the CLI login's files
|
|
110
|
+
//
|
|
111
|
+
// Only ever written when the user changes the CLI login's key, base URL or proxy from its card:
|
|
112
|
+
// nothing else in ZeroSub writes Pi's own files.
|
|
113
|
+
|
|
114
|
+
function mainAuthPath(): string {
|
|
115
|
+
return join(mainPiDir(), "auth.json");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function mainModelsPath(): string {
|
|
119
|
+
return join(mainPiDir(), "models.json");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The base URL the CLI login's `models.json` sends Anthropic's requests to, if it sets one. */
|
|
123
|
+
async function mainAnthropicBaseUrl(): Promise<string | null> {
|
|
124
|
+
const models = await readPiOwnJson(mainModelsPath(), true).catch(() => undefined);
|
|
125
|
+
const providers = isObject(models) && isObject(models.providers) ? models.providers : {};
|
|
126
|
+
const anthropic = isObject(providers.anthropic) ? providers.anthropic : {};
|
|
127
|
+
return typeof anthropic.baseUrl === "string" && anthropic.baseUrl.trim() ? anthropic.baseUrl.trim() : null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Keys shorter than this get no hint, as for Claude API accounts. */
|
|
131
|
+
const KEY_HINT_MIN_LENGTH = 12;
|
|
132
|
+
|
|
133
|
+
/** The Anthropic API key Pi's own login keeps in its `auth.json`; null when it has none (or signs in to Anthropic with OAuth). */
|
|
134
|
+
async function mainAnthropicKey(): Promise<string | null> {
|
|
135
|
+
const auth = await readPiOwnJson(mainAuthPath()).catch(() => undefined);
|
|
136
|
+
const entry = isObject(auth) ? auth.anthropic : undefined;
|
|
137
|
+
return isObject(entry) && entry.type === "api_key" && typeof entry.key === "string" && entry.key.trim() ? entry.key.trim() : null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Pi's own login's Anthropic key (reduced to a hint) and base URL; null without an Anthropic API key. */
|
|
141
|
+
async function readMainPiApi(): Promise<ApiSummary | null> {
|
|
142
|
+
const key = await mainAnthropicKey();
|
|
143
|
+
if (!key) return null;
|
|
144
|
+
return { keyHint: key.length >= KEY_HINT_MIN_LENGTH ? key.slice(-4) : "", baseUrl: await mainAnthropicBaseUrl() };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const PI_BACKUPS = 5;
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Keeps a copy of one of Pi's own files as it was before ZeroSub changes it, in ZeroSub's
|
|
151
|
+
* `backups/` (readable only by you), the last five of each.
|
|
152
|
+
*/
|
|
153
|
+
async function backUp(kind: "auth" | "models" | "settings", value: unknown): Promise<void> {
|
|
154
|
+
const backups = join(dataDir(), "backups");
|
|
155
|
+
await writeJsonAtomic(join(backups, `pi-${kind}-${new Date().toISOString().replace(/[:.]/g, "-")}.json`), value);
|
|
156
|
+
const pattern = new RegExp(`^pi-${kind}-\\d{4}-\\d{2}-\\d{2}T[\\d-]+Z\\.json$`);
|
|
157
|
+
const kept = (await readdir(backups)).filter((name) => pattern.test(name)).sort();
|
|
158
|
+
for (const name of kept.slice(0, -PI_BACKUPS)) await rm(join(backups, name), { force: true });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* How long Pi's lock on one of its files may go untouched before it's taken for one a crash left.
|
|
163
|
+
* Pi's own async lock on `auth.json` (refreshing a sign-in) counts as stale after 30 s and is only
|
|
164
|
+
* touched every 15 s, so anything shorter could take a live one.
|
|
165
|
+
*/
|
|
166
|
+
const PI_LOCK_STALE_MS = 30_000;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Runs `action` holding the lock Pi takes on `file` (`auth.json`, `settings.json`: proper-lockfile's
|
|
170
|
+
* `<file>.lock` folder), so a Pi process writing it meanwhile doesn't write over the change, or the
|
|
171
|
+
* other way round. For a file that's a link, Pi takes the lock beside the link (`auth.json` to
|
|
172
|
+
* 1.5.0, `settings.json` still in 1.5.2) or beside the file it points to (`auth.json` from 1.5.1),
|
|
173
|
+
* so both are held: whichever Pi runs is kept out.
|
|
174
|
+
*/
|
|
175
|
+
async function withPiLock<T>(file: string, action: () => Promise<T>): Promise<T> {
|
|
176
|
+
// Both named through the real folder, so a folder reached through a link isn't taken for two.
|
|
177
|
+
const beside = join(await realpath(dirname(file)).catch(() => dirname(file)), basename(file));
|
|
178
|
+
const real = await realpath(file).catch(() => beside);
|
|
179
|
+
const locks = [...new Set([`${beside}.lock`, `${real}.lock`])];
|
|
180
|
+
const held: string[] = [];
|
|
181
|
+
try {
|
|
182
|
+
for (const lock of locks) {
|
|
183
|
+
try {
|
|
184
|
+
await mkdir(lock);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
187
|
+
const age = Date.now() - ((await stat(lock).catch(() => null))?.mtimeMs ?? 0);
|
|
188
|
+
if (age < PI_LOCK_STALE_MS) throw new Error(`Pi is writing ${shownPath(file)} right now. Try again in a moment.`);
|
|
189
|
+
await rmdir(lock).catch(() => undefined);
|
|
190
|
+
await mkdir(lock);
|
|
191
|
+
}
|
|
192
|
+
held.push(lock);
|
|
193
|
+
}
|
|
194
|
+
return await action();
|
|
195
|
+
} finally {
|
|
196
|
+
for (const lock of held.reverse()) await rmdir(lock).catch(() => undefined);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Writes one of Pi's own files where it really is (a link to it, from a dotfiles repository say, is
|
|
202
|
+
* followed rather than replaced). It keeps its permissions, except that a file holding a secret (a
|
|
203
|
+
* key, or a proxy with a password) is never left readable by others: it's written 0600 or stricter.
|
|
204
|
+
*/
|
|
205
|
+
async function writePiFile(path: string, value: unknown, secret: boolean): Promise<void> {
|
|
206
|
+
const real = await realpath(path).catch(() => path);
|
|
207
|
+
const mode = (await stat(real).catch(() => null))?.mode;
|
|
208
|
+
const kept = mode === undefined ? 0o600 : mode & 0o777;
|
|
209
|
+
await writeJsonAtomic(real, value, { mode: secret ? kept & 0o600 : kept });
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Whether a proxy URL holds a password (or a user name, which may be one). */
|
|
213
|
+
function hasCredentials(proxy: string): boolean {
|
|
214
|
+
try {
|
|
215
|
+
const url = new URL(proxy);
|
|
216
|
+
return url.username !== "" || url.password !== "";
|
|
217
|
+
} catch {
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const mainWrites = new Mutex();
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Sets (or clears, with `null`) Pi's own login's proxy as `httpProxy` in its `settings.json`, which
|
|
226
|
+
* Pi applies wherever it runs on that login while its environment names no proxy, and which added
|
|
227
|
+
* accounts without a proxy of their own share. ZeroSub gives Pi agents nothing for it: Pi reads it
|
|
228
|
+
* itself. Like an added account's, a new proxy is refused while a key or sign-in it would carry goes
|
|
229
|
+
* over plain http://, wherever Pi takes it from (see `clearTextProviders`): to this machine too,
|
|
230
|
+
* unless the no-proxy list keeps it direct, since Pi adds nothing to that list. The file is backed
|
|
231
|
+
* up first and written under Pi's own lock.
|
|
232
|
+
*/
|
|
233
|
+
async function writePiMainProxy(proxy: string | null): Promise<void> {
|
|
234
|
+
await mainWrites.run(async () => {
|
|
235
|
+
if (proxy && proxy !== (await settingsProxy())) {
|
|
236
|
+
const exposed = await clearTextProviders(true);
|
|
237
|
+
if (exposed.includes("anthropic")) {
|
|
238
|
+
throw new Error(
|
|
239
|
+
"Pi's own login sends its Anthropic key or sign-in over plain http://, which a proxy can read (Pi sends even this machine's addresses through it unless NO_PROXY lists them). Use an https:// base URL for Anthropic and its models (in Pi's models.json), or list that host in NO_PROXY, before setting a proxy.",
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
if (exposed.length > 0) {
|
|
243
|
+
throw new Error(
|
|
244
|
+
`Pi's own models.json sends the key or sign-in for ${exposed.join(", ")} over plain http://, so a proxy could read it (Pi sends even this machine's addresses through it unless NO_PROXY lists them). Use https:// there, or list those hosts in NO_PROXY, before setting a proxy.`,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
await withPiLock(mainSettingsPath(), async () => {
|
|
249
|
+
const settings = await readPiOwnJson(await realpath(mainSettingsPath()).catch(() => mainSettingsPath()));
|
|
250
|
+
if (settings !== undefined && !isObject(settings)) throw new Error(`${shownPath(mainSettingsPath())} isn't a JSON object`);
|
|
251
|
+
if (settings === undefined && !proxy) return;
|
|
252
|
+
const next: Record<string, unknown> = { ...(settings ?? {}) };
|
|
253
|
+
if (proxy) next.httpProxy = proxy;
|
|
254
|
+
else delete next.httpProxy;
|
|
255
|
+
if (settings) await backUp("settings", settings);
|
|
256
|
+
await writePiFile(mainSettingsPath(), next, proxy !== null && hasCredentials(proxy));
|
|
257
|
+
});
|
|
258
|
+
// Added accounts with a proxy of their own have settings made from these.
|
|
259
|
+
forgetSyncs();
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Sets the Anthropic API key (`null` keeps the current one) and base URL of Pi's own login, in Pi's
|
|
265
|
+
* own files, which `pi` in a terminal reads too: `anthropic` in `auth.json` (an OAuth sign-in to
|
|
266
|
+
* Anthropic there is replaced by the key) and `providers.anthropic.baseUrl` in `models.json` (taken
|
|
267
|
+
* out for Anthropic's own API). Each is backed up first; `auth.json` is written under Pi's lock and
|
|
268
|
+
* never left readable by others. As for an added account, a kept key only goes where it went before.
|
|
269
|
+
*/
|
|
270
|
+
async function writeMainPiApi(config: { key: string | null; baseUrl: string | null }): Promise<void> {
|
|
271
|
+
await mainWrites.run(async () => {
|
|
272
|
+
const baseUrl = config.baseUrl?.trim() ? normalizeBaseUrl(config.baseUrl) : null;
|
|
273
|
+
const typed = config.key?.trim() || null;
|
|
274
|
+
const previousBase = await mainAnthropicBaseUrl();
|
|
275
|
+
// Read before the key is written, so a models.json that can't take the new base URL leaves the
|
|
276
|
+
// key as it was too: a new key must never go to the old address. Read strictly: it's written
|
|
277
|
+
// back as plain JSON, and the comments Pi allows there would be lost.
|
|
278
|
+
const models =
|
|
279
|
+
previousBase === baseUrl
|
|
280
|
+
? undefined
|
|
281
|
+
: await readJson(await realpath(mainModelsPath()).catch(() => mainModelsPath())).catch(() => {
|
|
282
|
+
throw new Error(`${shownPath(mainModelsPath())} isn't plain JSON (it may have comments), so ZeroSub leaves it as it is. Change the Anthropic base URL there by hand.`);
|
|
283
|
+
});
|
|
284
|
+
if (models !== undefined && !isObject(models)) throw new Error(`${shownPath(mainModelsPath())} isn't a JSON object`);
|
|
285
|
+
await withPiLock(mainAuthPath(), async () => {
|
|
286
|
+
const auth = await readPiOwnJson(await realpath(mainAuthPath()).catch(() => mainAuthPath()));
|
|
287
|
+
if (auth !== undefined && !isObject(auth)) throw new Error(`${shownPath(mainAuthPath())} isn't a JSON object`);
|
|
288
|
+
const current = auth?.anthropic;
|
|
289
|
+
const kept = isObject(current) && current.type === "api_key" && typeof current.key === "string" && current.key.trim() ? current.key.trim() : null;
|
|
290
|
+
const key = typed ?? kept;
|
|
291
|
+
if (!key) throw new Error("Enter the API key");
|
|
292
|
+
if (!typed && previousBase !== baseUrl) throw new Error("Enter the key again to use it with a different base URL");
|
|
293
|
+
// Stored escaped, as an added account's is (see `piLiteral`), so Pi reads it as typed.
|
|
294
|
+
if (typed && piLiteral(typed) !== kept) {
|
|
295
|
+
if (auth) await backUp("auth", auth);
|
|
296
|
+
const entry = isObject(current) && current.type === "api_key" ? { ...current } : {};
|
|
297
|
+
await writePiFile(mainAuthPath(), { ...(auth ?? {}), anthropic: { ...entry, type: "api_key", key: piLiteral(typed) } }, true);
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
if (previousBase !== baseUrl) {
|
|
301
|
+
if (models) await backUp("models", models);
|
|
302
|
+
const next: Record<string, unknown> = { ...(models ?? {}) };
|
|
303
|
+
const providers: Record<string, unknown> = isObject(next.providers) ? { ...next.providers } : {};
|
|
304
|
+
const anthropic: Record<string, unknown> = isObject(providers.anthropic) ? { ...providers.anthropic } : {};
|
|
305
|
+
if (baseUrl) anthropic.baseUrl = baseUrl;
|
|
306
|
+
else delete anthropic.baseUrl;
|
|
307
|
+
if (Object.keys(anthropic).length > 0) providers.anthropic = anthropic;
|
|
308
|
+
else delete providers.anthropic;
|
|
309
|
+
if (Object.keys(providers).length > 0) next.providers = providers;
|
|
310
|
+
else delete next.providers;
|
|
311
|
+
await writePiFile(mainModelsPath(), next, false);
|
|
312
|
+
}
|
|
313
|
+
forgetSyncs();
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// --------------------------------------------------------------------------- the account's script
|
|
318
|
+
|
|
319
|
+
function shellQuote(value: string): string {
|
|
320
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Writes the account's `zerosub.env`, which its `pi-<account>.sh` script reads: the proxy variables
|
|
325
|
+
* its agents get in Paseo (its own proxy), so Pi run from the script goes the same way, whatever the
|
|
326
|
+
* shell exports. Without a proxy it only says so, and the shell's own settings stand, as the
|
|
327
|
+
* daemon's do for its agents. Readable only by you: a proxy can hold a password. Only written when
|
|
328
|
+
* it changes.
|
|
329
|
+
*/
|
|
330
|
+
async function writeLaunchEnv(home: string, variables: Record<string, string>): Promise<void> {
|
|
331
|
+
const lines = ["# Written by ZeroSub: the proxy and environment this account's Pi agents get in Paseo. Don't edit: it's rewritten when that changes."];
|
|
332
|
+
for (const [key, value] of Object.entries(variables)) lines.push(`export ${key}=${shellQuote(value)}`);
|
|
333
|
+
const content = `${lines.join("\n")}\n`;
|
|
334
|
+
const path = join(home, PI_LAUNCH_ENV);
|
|
335
|
+
if ((await readFile(path, "utf8").catch(() => null)) === content) return;
|
|
336
|
+
const temporary = join(home, `.${PI_LAUNCH_ENV}.${randomBytes(4).toString("hex")}.tmp`);
|
|
337
|
+
try {
|
|
338
|
+
await writeFile(temporary, content, { mode: 0o600 });
|
|
339
|
+
await rename(temporary, path);
|
|
340
|
+
} finally {
|
|
341
|
+
await rm(temporary, { force: true });
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// --------------------------------------------------------------------------- adapter
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Pi, which Paseo runs as its built-in `pi` provider. The CLI login is Pi's own agent directory
|
|
349
|
+
* (`~/.pi/agent`) with whatever it's signed in to, and ZeroSub leaves it as it is. An added account
|
|
350
|
+
* is an Anthropic API key, with an optional base URL and proxy, in an agent directory of its own
|
|
351
|
+
* (`PI_CODING_AGENT_DIR`, in ZeroSub's `homes/`) that shares everything else with the CLI login's
|
|
352
|
+
* (see `preparePiHome`). Sessions are kept in the CLI login's sessions folder whichever account
|
|
353
|
+
* opens them, so a conversation moves between accounts and stays where Paseo looks for it after an
|
|
354
|
+
* account is removed.
|
|
355
|
+
*/
|
|
356
|
+
/**
|
|
357
|
+
* The variables that would have an added account's agents send something other than its own key:
|
|
358
|
+
* - the ones Pi reads Anthropic's key or token from (`getApiKeyEnvVars` in pi-ai);
|
|
359
|
+
* - `ANTHROPIC_CUSTOM_HEADERS`, which the Anthropic SDK adds to every request after the key, so an
|
|
360
|
+
* `x-api-key` or `authorization` line there replaces it;
|
|
361
|
+
* - the workload identity federation ones, which Pi uses for Anthropic when no key comes out
|
|
362
|
+
* (`getAnthropicFederation` in pi-ai) and would send the token it gets for them.
|
|
363
|
+
* Blank is unset to both Pi and the SDK.
|
|
364
|
+
*/
|
|
365
|
+
const PI_ANTHROPIC_ENV = [
|
|
366
|
+
"ANTHROPIC_API_KEY",
|
|
367
|
+
"ANTHROPIC_AUTH_TOKEN",
|
|
368
|
+
"ANTHROPIC_OAUTH_TOKEN",
|
|
369
|
+
"ANTHROPIC_CUSTOM_HEADERS",
|
|
370
|
+
"ANTHROPIC_FEDERATION_RULE_ID",
|
|
371
|
+
"ANTHROPIC_ORGANIZATION_ID",
|
|
372
|
+
"ANTHROPIC_IDENTITY_TOKEN_FILE",
|
|
373
|
+
"ANTHROPIC_SERVICE_ACCOUNT_ID",
|
|
374
|
+
"ANTHROPIC_WORKSPACE_ID",
|
|
375
|
+
];
|
|
376
|
+
|
|
377
|
+
export class PiAdapter implements FamilyAdapter {
|
|
378
|
+
readonly family = "pi" as const;
|
|
379
|
+
/** Pi reopens a session from its file, whichever account it runs on. */
|
|
380
|
+
readonly portable = true;
|
|
381
|
+
/** Pi reports no usage; this only keeps the "no usage" note from being asked for often. */
|
|
382
|
+
readonly usageSpacingMs = 60 * 60_000;
|
|
383
|
+
/** Pi's own login's Anthropic key and base URL can be changed from its card. */
|
|
384
|
+
readonly mainApi = true;
|
|
385
|
+
|
|
386
|
+
async env(home: string | null, session?: { cwd: string }): Promise<EnvPatch> {
|
|
387
|
+
// The CLI login runs as Paseo would run it without ZeroSub.
|
|
388
|
+
if (!home) return {};
|
|
389
|
+
// Throws while the folder is being moved: routing then opens the agent on the CLI login rather
|
|
390
|
+
// than on the account without its proxy (see `readPiAccountForAgents`).
|
|
391
|
+
const account = await readPiAccountForAgents(home);
|
|
392
|
+
const patch: EnvPatch = { PI_CODING_AGENT_DIR: home };
|
|
393
|
+
// Pi would send what these give to the account's base URL, in place of or on top of the account's
|
|
394
|
+
// key: an added account's agents only ever use its own key. Always blanked,
|
|
395
|
+
// since they can come from the Pi provider's `env` in Paseo's config as well as the daemon's.
|
|
396
|
+
for (const key of PI_ANTHROPIC_ENV) patch[key] = "";
|
|
397
|
+
// Pi writes a new session in its agent directory's `sessions`, which is the CLI login's linked in,
|
|
398
|
+
// so the file would be named through the account's home: Paseo resumes it by that name, which
|
|
399
|
+
// goes when the account does. Pi is told the folder it would use for the CLI login instead.
|
|
400
|
+
if (session && !(await sessionDirConfigured())) patch.PI_CODING_AGENT_SESSION_DIR = await piSessionDir(session.cwd);
|
|
401
|
+
// Given as variables, so nothing the agent inherits outranks the account's own proxy. Without one,
|
|
402
|
+
// it inherits whatever the daemon and Pi's own settings give it, as Pi does without ZeroSub.
|
|
403
|
+
if (account.proxy) Object.assign(patch, proxyVariables(account.proxy, account.baseUrl));
|
|
404
|
+
return patch;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async available(): Promise<{ ok: boolean; detail: string | null }> {
|
|
408
|
+
const { command, prefix } = await providerCommand("pi");
|
|
409
|
+
const result = await run(command, [...prefix, "--version"], { timeoutMs: 30_000 });
|
|
410
|
+
if (result.code === 0) return { ok: true, detail: null };
|
|
411
|
+
return { ok: false, detail: (result.stderr || result.stdout).trim().split("\n")[0] || `${command} not found` };
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async prepareHome(home: string, wanted?: () => Promise<boolean>): Promise<void> {
|
|
415
|
+
await preparePiHome(home, false, wanted);
|
|
416
|
+
if (wanted && !(await wanted())) return;
|
|
417
|
+
await this.writeLaunchEnv(home);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Brings the account's `zerosub.env` in step with the proxy its agents get, and the Anthropic
|
|
422
|
+
* variables they get blanked (`PI_ANTHROPIC_ENV`), so nothing in a shell's environment stands in for
|
|
423
|
+
* the account's key or goes along with it (see `writeLaunchEnv`).
|
|
424
|
+
*/
|
|
425
|
+
private async writeLaunchEnv(home: string): Promise<void> {
|
|
426
|
+
const patch = await this.env(home);
|
|
427
|
+
const variables: Record<string, string> = {};
|
|
428
|
+
for (const key of [...PI_ANTHROPIC_ENV, ...PROXY_KEYS, ...NO_PROXY_KEYS]) {
|
|
429
|
+
const value = patch[key];
|
|
430
|
+
if (typeof value === "string") variables[key] = value;
|
|
431
|
+
}
|
|
432
|
+
await writeLaunchEnv(home, variables);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Which of `homes` a Pi process runs on right now (started with that `PI_CODING_AGENT_DIR`: by
|
|
437
|
+
* Paseo, or its script in a terminal), so its home isn't moved under it (see `Service.placeHomes`).
|
|
438
|
+
*/
|
|
439
|
+
async homesInUse(homes: readonly string[]): Promise<Set<string>> {
|
|
440
|
+
const found = new Set<string>();
|
|
441
|
+
if (homes.length === 0) return found;
|
|
442
|
+
await eachProcessEnvironment((line) => {
|
|
443
|
+
for (const home of homesInEnvironment(line, homes, ["PI_CODING_AGENT_DIR"])) found.add(home);
|
|
444
|
+
});
|
|
445
|
+
return found;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Everything a Pi account has is in its folder, so only the folder moves; its key says which one it is. */
|
|
449
|
+
holdsAccount(home: string): Promise<boolean> {
|
|
450
|
+
return piHomeHoldsAccount(home);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* The CLI login always counts as signed in: Pi picks a sign-in per model from everything it has.
|
|
455
|
+
* An added account is signed in while it holds a key; a refused key is learned from a failed turn.
|
|
456
|
+
*/
|
|
457
|
+
async identity(home: string | null): Promise<Identity> {
|
|
458
|
+
const signedIn = home ? Boolean((await readPiAccount(home)).key) : true;
|
|
459
|
+
return { signedIn, email: null, plan: null, organization: null, identity: null };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
async usage(): Promise<UsageRead> {
|
|
463
|
+
return { fetchedAt: new Date().toISOString(), windows: [], error: "Pi doesn't report usage.", cached: false, resets: null };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async redeemReset(): Promise<RedeemReply> {
|
|
467
|
+
return { outcome: "none", message: "Pi has no banked resets.", left: null };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
api(home: string | null): Promise<ApiSummary | null> {
|
|
471
|
+
return home ? readPiAccountApi(home) : readMainPiApi();
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
setApi(home: string | null, config: { key: string | null; baseUrl: string | null }, wanted?: () => Promise<boolean>): Promise<void> {
|
|
475
|
+
if (!home) return writeMainPiApi({ key: config.key, baseUrl: config.baseUrl });
|
|
476
|
+
return writePiAccountApi(home, { key: config.key, baseUrl: config.baseUrl }, wanted);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
async proxyState(home: string | null): Promise<ProxyState> {
|
|
480
|
+
if (!home) {
|
|
481
|
+
const own = await settingsProxy();
|
|
482
|
+
return { own, file: own ? shownPath(mainSettingsPath()) : null, inherited: own ? null : await inheritedPiProxy(ANTHROPIC_API) };
|
|
483
|
+
}
|
|
484
|
+
const account = await readPiAccount(home);
|
|
485
|
+
return { own: account.proxy, file: null, inherited: account.proxy ? null : await inheritedPiProxy(account.baseUrl ?? ANTHROPIC_API) };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
async setProxy(home: string | null, proxy: string | null, wanted?: () => Promise<boolean>): Promise<void> {
|
|
489
|
+
if (!home) return writePiMainProxy(proxy);
|
|
490
|
+
await writePiAccountProxy(home, proxy, wanted, (baseUrl) => inheritedPiProxy(baseUrl ?? ANTHROPIC_API));
|
|
491
|
+
await this.writeLaunchEnv(home);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* The address Anthropic sees an added account's requests come from, asked of Anthropic's own host
|
|
496
|
+
* the way the account's Pi reaches it. Null for an account with another base URL (whatever is there
|
|
497
|
+
* reaches Anthropic from its own address), and for the CLI login, which ZeroSub never checks.
|
|
498
|
+
*/
|
|
499
|
+
async egress(home: string | null): Promise<{ ip: string; country: string | null } | null> {
|
|
500
|
+
if (!home) return null;
|
|
501
|
+
const { baseUrl } = await readPiAccount(home);
|
|
502
|
+
if (baseUrl && hostOf(baseUrl) !== hostOf(ANTHROPIC_API)) return null;
|
|
503
|
+
const env: Record<string, string | undefined> = { ...process.env, ...providerEnv("pi") };
|
|
504
|
+
for (const [key, value] of Object.entries(await this.env(home))) if (value !== null) env[key] = value;
|
|
505
|
+
const response = await proxiedFetch(await piProxyFor(env, TRACE), TRACE, { signal: AbortSignal.timeout(10_000) });
|
|
506
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
507
|
+
const seen = parseTrace(await response.text());
|
|
508
|
+
if (!seen) throw new Error("The answer didn't say");
|
|
509
|
+
return seen;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
async login(_home: string | null, _method: LoginMethod): Promise<LoginHandle> {
|
|
513
|
+
throw new Error("Pi accounts use an Anthropic API key: add one with Add account, or change its key from its card.");
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
async logout(_home: string): Promise<void> {
|
|
517
|
+
// The key lives in the home itself, which is deleted next.
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** Pi's accounts are billed per use or are the CLI login, so there's no account to move to on a limit. */
|
|
521
|
+
detectLimit(_event: TurnEvent): null {
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
detectSignOut(event: TurnEvent): string | null {
|
|
526
|
+
return detectPiSignOut(event);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { access, constants, lstat, mkdir, stat } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
4
|
+
import { idSuffix, kindName, slug, type LauncherKind } from "./launchers";
|
|
5
|
+
import { dataDir, homesDir, inHomesDir, launcherDir, mainClaudeDir, mainCodexHome, mainConfigHome, mainCursorConfigDir, mainGrokHome, mainPiDir, piLauncherDir, shownPath } from "./paths";
|
|
6
|
+
import type { Homes, StoredAccount } from "./state";
|
|
7
|
+
|
|
8
|
+
/** The families whose added accounts' homes ZeroSub keeps outside its own folder: Claude's and Pi's. */
|
|
9
|
+
export type PlacedFamily = LauncherKind;
|
|
10
|
+
export const PLACED: readonly PlacedFamily[] = ["claude", "pi"];
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Where `family`'s added accounts' homes are kept: the folder picked in the app, else the script
|
|
14
|
+
* directory (`~/.claude-config`, `~/.pi-config`), beside each account's script. ZeroSub sets new
|
|
15
|
+
* accounts up inside its own `homes/` and moves them here once they're saved (see `Service.placeHomes`).
|
|
16
|
+
*/
|
|
17
|
+
export function homesDirFor(family: PlacedFamily, homes: Homes): string {
|
|
18
|
+
return homes.dir ?? (family === "pi" ? piLauncherDir() : launcherDir());
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Whether `path` is `folder` or inside it. */
|
|
22
|
+
function within(path: string, folder: string): boolean {
|
|
23
|
+
const inside = relative(resolve(folder), resolve(path));
|
|
24
|
+
return inside === "" || (!inside.startsWith("..") && !isAbsolute(inside));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A path typed in the app, as a full path (`~` is the home folder); refused unless it's one, with `example`. */
|
|
28
|
+
function typedPath(typed: string, example: string): string {
|
|
29
|
+
const expanded = typed === "~" ? homedir() : typed.startsWith("~/") ? join(homedir(), typed.slice(2)) : typed;
|
|
30
|
+
if (!isAbsolute(expanded)) throw new Error(`Enter a full path, like ${example}.`);
|
|
31
|
+
return resolve(expanded);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The folder typed in the app for `family`'s added accounts' homes, as a full path (`~` is the home
|
|
36
|
+
* folder), made if it isn't there yet; null for the default (empty, or the default typed out). Refused,
|
|
37
|
+
* saying why: a path that isn't full; the home folder or `/` itself; anywhere in ZeroSub's own
|
|
38
|
+
* folder, where homes it may delete live; in a CLI's own home or an account's; a file; a folder it
|
|
39
|
+
* can't write to.
|
|
40
|
+
*/
|
|
41
|
+
export async function chooseHomesDir(input: string, accounts: readonly StoredAccount[], family: PlacedFamily = "claude"): Promise<string | null> {
|
|
42
|
+
const typed = input.trim();
|
|
43
|
+
if (!typed) return null;
|
|
44
|
+
const dir = typedPath(typed, family === "pi" ? "~/.pi-config or /Volumes/Data/pi-accounts" : "~/.claude-config or /Volumes/Data/claude-accounts");
|
|
45
|
+
if (dir === resolve(homedir()) || dir === resolve("/")) throw new Error(`Pick a folder of their own for the accounts, not ${shownPath(dir)} itself.`);
|
|
46
|
+
if (within(dir, dataDir())) throw new Error(`${shownPath(dir)} is inside ZeroSub's own folder (${shownPath(dataDir())}). Pick one outside it.`);
|
|
47
|
+
// ~/.config and Cursor's folder are mirrored into every Cursor account's home: accounts kept there would be too.
|
|
48
|
+
for (const main of [mainClaudeDir(), mainCodexHome(), mainPiDir(), mainGrokHome(), mainCursorConfigDir(), mainConfigHome()]) {
|
|
49
|
+
if (within(dir, main)) throw new Error(`${shownPath(dir)} is inside ${shownPath(main)}, a CLI's own folder. Pick one outside it.`);
|
|
50
|
+
}
|
|
51
|
+
const holder = accounts.find((account) => account.home && within(dir, account.home));
|
|
52
|
+
if (holder) throw new Error(`${shownPath(dir)} is inside the folder of ${holder.label}. Pick one outside it.`);
|
|
53
|
+
const entry = await stat(dir).catch(() => null);
|
|
54
|
+
if (entry && !entry.isDirectory()) throw new Error(`${shownPath(dir)} is a file, not a folder.`);
|
|
55
|
+
try {
|
|
56
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
57
|
+
await access(dir, constants.W_OK);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
throw new Error(`ZeroSub can't use ${shownPath(dir)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
60
|
+
}
|
|
61
|
+
return dir === resolve(homesDirFor(family, { dir: null, from: [] })) ? null : dir;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The folder typed in the app to add as a Claude account as it is (see `Service.importAccount`), as
|
|
66
|
+
* a full path. Refused, saying why: a path that isn't full, or isn't a folder; the CLI login's own;
|
|
67
|
+
* one already added, inside an added account's folder or holding one; anywhere in ZeroSub's own
|
|
68
|
+
* folder but directly in `homes/`, where a removed account's folder is kept; and one without the
|
|
69
|
+
* `.claude.json` Claude Code keeps in a folder it's started with, so asking Claude Code about a
|
|
70
|
+
* folder typed by mistake (a project, say) never leaves its files there.
|
|
71
|
+
*/
|
|
72
|
+
export async function chooseImportedHome(input: string, accounts: readonly StoredAccount[]): Promise<string> {
|
|
73
|
+
const home = typedPath(input.trim(), "~/.claude-config/claude-work");
|
|
74
|
+
const shown = shownPath(home);
|
|
75
|
+
const notClaudeCode = `${shown} isn't a Claude Code folder`;
|
|
76
|
+
const example = "Enter the folder Claude Code was started with as CLAUDE_CONFIG_DIR.";
|
|
77
|
+
if (home === resolve(homedir()) || home === resolve("/")) throw new Error(`${notClaudeCode}. ${example}`);
|
|
78
|
+
if (home === resolve(mainClaudeDir())) throw new Error(`${shown} is the CLI login's own folder, which ZeroSub has already as the CLI login.`);
|
|
79
|
+
const added = accounts.find((account) => account.home && resolve(account.home) === home);
|
|
80
|
+
if (added) throw new Error(`${shown} is already added, as ${added.label}.`);
|
|
81
|
+
const holder = accounts.find((account) => account.home && within(home, account.home));
|
|
82
|
+
if (holder) throw new Error(`${shown} is inside the folder of ${holder.label}. Enter the account's folder itself.`);
|
|
83
|
+
const held = accounts.find((account) => account.home && within(account.home, home));
|
|
84
|
+
if (held) throw new Error(`${shown} holds the folder of ${held.label}. Enter the folder of the account to add itself.`);
|
|
85
|
+
if (within(home, dataDir()) && dirname(home) !== homesDir()) throw new Error(`${shown} is inside ZeroSub's own folder (${shownPath(dataDir())}).`);
|
|
86
|
+
const entry = await stat(home).catch(() => null);
|
|
87
|
+
if (!entry) throw new Error(`There's no folder at ${shown}.`);
|
|
88
|
+
if (!entry.isDirectory()) throw new Error(`${shown} is a file, not a folder.`);
|
|
89
|
+
if (!(await stat(join(home, ".claude.json")).catch(() => null))?.isFile()) throw new Error(`${notClaudeCode}: there's no .claude.json in it. ${example}`);
|
|
90
|
+
return home;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The folder typed in the app to add back as a Pi account (one ZeroSub set up, kept when its account
|
|
95
|
+
* was removed), as a full path. Refused, saying why: a path that isn't full, or isn't a folder; Pi's
|
|
96
|
+
* own; one already added, inside an added account's folder or holding one; anywhere in ZeroSub's own
|
|
97
|
+
* folder but directly in `homes/`; and a folder without the `zerosub.json` ZeroSub keeps an
|
|
98
|
+
* account's key in.
|
|
99
|
+
*/
|
|
100
|
+
export async function chooseImportedPiHome(input: string, accounts: readonly StoredAccount[]): Promise<string> {
|
|
101
|
+
const home = typedPath(input.trim(), "~/.pi-config/pi-work");
|
|
102
|
+
const shown = shownPath(home);
|
|
103
|
+
if (home === resolve(homedir()) || home === resolve("/") || home === resolve(mainPiDir())) throw new Error(`${shown} isn't a Pi account's folder.`);
|
|
104
|
+
const added = accounts.find((account) => account.home && resolve(account.home) === home);
|
|
105
|
+
if (added) throw new Error(`${shown} is already added, as ${added.label}.`);
|
|
106
|
+
const holder = accounts.find((account) => account.home && (within(home, account.home) || within(account.home, home)));
|
|
107
|
+
if (holder) throw new Error(`${shown} is inside or holds the folder of ${holder.label}. Enter the account's folder itself.`);
|
|
108
|
+
if (within(home, dataDir()) && dirname(home) !== homesDir()) throw new Error(`${shown} is inside ZeroSub's own folder (${shownPath(dataDir())}).`);
|
|
109
|
+
const entry = await stat(home).catch(() => null);
|
|
110
|
+
if (!entry) throw new Error(`There's no folder at ${shown}.`);
|
|
111
|
+
if (!entry.isDirectory()) throw new Error(`${shown} is a file, not a folder.`);
|
|
112
|
+
if (!(await stat(join(home, "zerosub.json")).catch(() => null))?.isFile()) {
|
|
113
|
+
throw new Error(`${shown} isn't a Pi account's folder: there's no zerosub.json in it. Add a new account with its API key instead.`);
|
|
114
|
+
}
|
|
115
|
+
return home;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Where an account's home goes in `dir`. One ZeroSub set up inside `homes/` is named after the
|
|
120
|
+
* account, `claude-<name>` or `pi-<name>` like its script; one from a folder picked before keeps its name. A name
|
|
121
|
+
* already there, or in `taken` (other accounts' homes and places), gets the first six hex digits of
|
|
122
|
+
* the account's ID added, then a number. The name stays when the account is renamed later.
|
|
123
|
+
*/
|
|
124
|
+
export async function placeFor(account: StoredAccount & { home: string }, dir: string, taken: ReadonlySet<string>): Promise<string> {
|
|
125
|
+
const kind: LauncherKind = account.family === "pi" ? "pi" : "claude";
|
|
126
|
+
const suffix = idSuffix(account.id);
|
|
127
|
+
const base = inHomesDir(account.home) ? (slug(account.label) ? kindName(kind, account.label) : `${kind}-${suffix}`) : basename(account.home);
|
|
128
|
+
const free = async (name: string) => !taken.has(resolve(dir, name)) && (await lstat(join(dir, name)).catch(() => null)) === null;
|
|
129
|
+
let name = base;
|
|
130
|
+
if (!(await free(name))) name = `${base}-${suffix}`;
|
|
131
|
+
for (let n = 2; !(await free(name)); n++) name = `${base}-${suffix}-${n}`;
|
|
132
|
+
return join(dir, name);
|
|
133
|
+
}
|