@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.
Files changed (56) hide show
  1. package/README.md +220 -26
  2. package/client/accounts-surface.tsx +344 -110
  3. package/client/add-account.tsx +335 -23
  4. package/client/api-account.tsx +250 -0
  5. package/client/azure-account.tsx +311 -0
  6. package/client/commands.ts +44 -8
  7. package/client/composer-item.tsx +203 -0
  8. package/client/fork-confirm.tsx +71 -0
  9. package/client/fork-settings.tsx +148 -0
  10. package/client/pace.tsx +196 -0
  11. package/client/pi-accounts.tsx +571 -0
  12. package/client/pills.ts +63 -25
  13. package/client/reset-confirm.tsx +12 -3
  14. package/client/settings-screen.tsx +48 -9
  15. package/client/store.ts +148 -19
  16. package/client/switch-row.tsx +28 -8
  17. package/client/ui.tsx +11 -0
  18. package/index.client.tsx +4 -1
  19. package/index.server.ts +53 -10
  20. package/package.json +5 -2
  21. package/server/account-identity.ts +11 -0
  22. package/server/adapter.ts +115 -8
  23. package/server/api-usage.ts +144 -0
  24. package/server/azure.ts +346 -0
  25. package/server/binaries.ts +41 -3
  26. package/server/claude.ts +276 -21
  27. package/server/codex-same-conversation.ts +71 -0
  28. package/server/codex.ts +35 -7
  29. package/server/continuations.ts +67 -17
  30. package/server/cursor.ts +222 -0
  31. package/server/families.ts +105 -8
  32. package/server/grok.ts +225 -0
  33. package/server/handoff.ts +211 -29
  34. package/server/homes.ts +1263 -35
  35. package/server/json-file.ts +39 -8
  36. package/server/launchers.ts +319 -0
  37. package/server/limits.ts +80 -3
  38. package/server/main-proxy.ts +238 -0
  39. package/server/modes.ts +20 -4
  40. package/server/paths.ts +81 -1
  41. package/server/pi.ts +528 -0
  42. package/server/placement.ts +133 -0
  43. package/server/process.ts +18 -1
  44. package/server/processes.ts +66 -0
  45. package/server/provider-env.ts +28 -0
  46. package/server/proxy.ts +282 -0
  47. package/server/reopen.ts +50 -8
  48. package/server/routing.ts +337 -30
  49. package/server/service.ts +4320 -805
  50. package/server/state.ts +303 -24
  51. package/server/usage.ts +2 -0
  52. package/shared/format.ts +170 -2
  53. package/shared/model.ts +339 -2
  54. package/shared/preferences.ts +22 -1
  55. package/shared/rpc.ts +130 -8
  56. package/shared/timeline.ts +11 -0
@@ -0,0 +1,571 @@
1
+ import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
2
+ import { copyText, Icon, Modal, TextInput, useToast } from "@getpaseo/plugin/client/react-native";
3
+ import { useCallback, useMemo, useState, type ReactNode } from "react";
4
+ import { Text, View } from "react-native";
5
+ import { egressText } from "../shared/format";
6
+ import { HIDDEN, type AccountView, type StateView } from "../shared/model";
7
+ import { addApiAccount, importPiAccount, setAccountProxy, setClaudeHomesDir, setPiHomesDir, updateApiAccount } from "../shared/rpc";
8
+ import { describe, type ZeroSubStore } from "./store";
9
+ import { Button, IconButton, useText } from "./ui";
10
+
11
+ type Theme = PluginSurfaceProps["theme"];
12
+
13
+ /**
14
+ * Pi accounts: Pi's own login (`~/.pi/agent`), and added accounts, each an Anthropic API key with an
15
+ * optional base URL and proxy in an agent directory of its own. Everything here is only shown for Pi.
16
+ */
17
+
18
+ export function useInputStyle(theme: Theme) {
19
+ return useMemo(
20
+ () => ({
21
+ color: theme.colors.foreground,
22
+ backgroundColor: theme.colors.surface2,
23
+ borderColor: theme.colors.border,
24
+ borderWidth: 1,
25
+ borderRadius: 8,
26
+ paddingHorizontal: 12,
27
+ paddingVertical: 10,
28
+ fontSize: 14,
29
+ }),
30
+ [theme],
31
+ );
32
+ }
33
+
34
+ function Field({ theme, title, children }: { theme: Theme; title: string; children: ReactNode }) {
35
+ const text = useText(theme);
36
+ return (
37
+ <View style={{ gap: 6 }}>
38
+ <Text style={text.strong}>{title}</Text>
39
+ {children}
40
+ </View>
41
+ );
42
+ }
43
+
44
+ /** The card's line about the account: its key and where it goes, its proxy, the address Anthropic sees, its folder and script. */
45
+ export function piCardDetails(account: AccountView): string | null {
46
+ if (account.family !== "pi") return null;
47
+ const api = account.api;
48
+ const parts = [
49
+ api ? `Key${api.keyHint ? ` …${api.keyHint}` : ""} · ${api.baseUrl ?? "Anthropic API"}` : null,
50
+ account.proxy ? `Via ${account.proxy}` : null,
51
+ egressText(account.egress),
52
+ account.kind === "managed" && account.home ? `Folder: ${account.home}` : null,
53
+ account.launcher ? `Terminal: ${account.launcher}` : null,
54
+ ].filter(Boolean);
55
+ return parts.length > 0 ? parts.join(" · ") : null;
56
+ }
57
+
58
+ /** Above the Pi accounts: what they are, what a proxy on them reaches, and the way to run them from a terminal. */
59
+ export function PiSectionNotes({ theme, state, accounts, store }: { theme: Theme; state: StateView; accounts: AccountView[]; store: ZeroSubStore }) {
60
+ const text = useText(theme);
61
+ return (
62
+ <>
63
+ <Text style={text.small}>
64
+ Each added Pi account is an Anthropic API key, with its own base URL and proxy if you like. Its agents use that key for Claude models and
65
+ share Pi's settings, sessions and other API keys; subscription sign-ins (/login) stay on the CLI login, whose files ZeroSub changes only when you edit its key or proxy on its card.
66
+ </Text>
67
+ <PiProxyNote theme={theme} />
68
+ {state.piLaunchers ? (
69
+ <ShellHint
70
+ theme={theme}
71
+ directory={state.piLaunchers}
72
+ accounts={accounts}
73
+ example="pi-<account>.sh"
74
+ note="Each runs pi on its account with the proxy its agents use in Paseo, whatever your shell exports."
75
+ />
76
+ ) : null}
77
+ {state.piHomes ? <HomesHint theme={theme} family="pi" homes={state.piHomes} store={store} /> : null}
78
+ </>
79
+ );
80
+ }
81
+
82
+ /**
83
+ * What a proxy set on a Pi card does and doesn't reach: it goes to the agents ZeroSub routes as
84
+ * environment variables, and to Pi elsewhere as its `httpProxy` setting and through the scripts.
85
+ */
86
+ function PiProxyNote({ theme }: { theme: Theme }) {
87
+ const text = useText(theme);
88
+ const points = [
89
+ "Pi agents Paseo starts or reopens on the account get it as https_proxy, HTTPS_PROXY, http_proxy and HTTP_PROXY, ahead of httpProxy in Pi's settings. Every request they make goes through it, Anthropic's and other providers' alike; only localhost, 127.0.0.1 and ::1 stay direct.",
90
+ "Agents already running keep the network they started with until they reopen.",
91
+ "It's also written as httpProxy in Pi's settings: an added account's in the settings.json of its folder, and Pi's own login's in ~/.pi/agent/settings.json once you set one on its card (added accounts without a proxy of their own share it). So pi started anywhere else goes through it too, but only when its environment names no proxy of its own, and a NO_PROXY there can still send Anthropic's requests around it. An account's pi-<account>.sh script sets the same variables as its agents get, so it doesn't depend on that.",
92
+ "An agent whose routing doesn't answer in time (ZeroSub stopped, say) opens without it, on the CLI login.",
93
+ "The IP on a card is the address Anthropic sees through that account's proxy. If this machine already sends everything through a system-wide or TUN proxy, going direct can show the same address, so give each key a proxy with its own exit to tell them apart.",
94
+ ];
95
+ return (
96
+ <View style={{ flexDirection: "row", alignItems: "flex-start", gap: 10, paddingHorizontal: 2 }}>
97
+ <Icon name="Globe" size={16} color={theme.colors.foregroundMuted} />
98
+ <View style={{ flex: 1, gap: 4 }}>
99
+ <Text style={text.strong}>About proxies on Pi accounts</Text>
100
+ {points.map((point) => (
101
+ <Text key={point} style={text.small}>
102
+ {`• ${point}`}
103
+ </Text>
104
+ ))}
105
+ </View>
106
+ </View>
107
+ );
108
+ }
109
+
110
+ /** The line to put the scripts' directory on `PATH`, and the scripts there. */
111
+ export function ShellHint({
112
+ theme,
113
+ directory,
114
+ accounts,
115
+ example,
116
+ note,
117
+ }: {
118
+ theme: Theme;
119
+ directory: string;
120
+ accounts: AccountView[];
121
+ /** What a script is called, shown while there's none. */
122
+ example: string;
123
+ /** What else to know about the scripts. */
124
+ note: string;
125
+ }) {
126
+ const text = useText(theme);
127
+ const toast = useToast();
128
+ // Readable when the path needs no quoting, which is nearly always.
129
+ const line = /^[\w./~+@%-]+$/.test(directory) ? `export PATH="${directory}:$PATH"` : `export PATH='${directory.replace(/'/g, "'\\''")}':"$PATH"`;
130
+ const commands = accounts.flatMap((account) => (account.launcher ? [account.launcher] : []));
131
+ const copy = useCallback(async () => {
132
+ try {
133
+ await copyText(line);
134
+ toast.show("Copied", { variant: "success" });
135
+ } catch {
136
+ toast.error("Couldn't copy. Select the text and copy it yourself.");
137
+ }
138
+ }, [line, toast]);
139
+ return (
140
+ <View style={{ flexDirection: "row", alignItems: "flex-start", gap: 10, paddingHorizontal: 2 }}>
141
+ <Icon name="SquareTerminal" size={16} color={theme.colors.foregroundMuted} />
142
+ <View style={{ flex: 1, gap: 4 }}>
143
+ <Text style={text.small}>
144
+ From a terminal on this host: add this line to your shell profile once, then run {commands.length > 0 ? commands.join(", ") : example}.
145
+ Accounts added later work without changing it. {note}
146
+ </Text>
147
+ <Text selectable style={[text.small, { color: theme.colors.foreground }]}>
148
+ {line}
149
+ </Text>
150
+ </View>
151
+ <IconButton theme={theme} icon="Copy" label="Copy" tooltip="Copy the line for your shell profile" onPress={() => void copy()} />
152
+ </View>
153
+ );
154
+ }
155
+
156
+ /** What the folder setting says for each family whose added accounts' folders ZeroSub keeps outside its own. */
157
+ const HOMES_COPY = {
158
+ claude: {
159
+ name: "Claude",
160
+ holds: "sign-in, settings and proxy",
161
+ variable: "CLAUDE_CONFIG_DIR",
162
+ setUp: "signed in",
163
+ runner: "a Claude agent or a terminal",
164
+ leftBehind: "its folder, sign-in and script stay",
165
+ rpc: setClaudeHomesDir,
166
+ },
167
+ pi: {
168
+ name: "Pi",
169
+ holds: "key, proxy and settings",
170
+ variable: "PI_CODING_AGENT_DIR",
171
+ setUp: "set up",
172
+ runner: "a Pi agent or a terminal",
173
+ leftBehind: "its folder, key and script stay",
174
+ rpc: setPiHomesDir,
175
+ },
176
+ } as const;
177
+
178
+ type HomesFamily = keyof typeof HOMES_COPY;
179
+ type HomesState = NonNullable<StateView["piHomes"]>;
180
+
181
+ /** Where a family's added accounts' folders are kept, and the way to keep them somewhere else. */
182
+ export function HomesHint({ theme, family, homes, store }: { theme: Theme; family: HomesFamily; homes: HomesState; store: ZeroSubStore }) {
183
+ const text = useText(theme);
184
+ const [editing, setEditing] = useState(false);
185
+ return (
186
+ <View style={{ flexDirection: "row", alignItems: "flex-start", gap: 10, paddingHorizontal: 2 }}>
187
+ <Icon name="FolderOpen" size={16} color={theme.colors.foregroundMuted} />
188
+ <View style={{ flex: 1, gap: 4 }}>
189
+ <Text style={text.small}>Each added account keeps its {HOMES_COPY[family].holds} in a folder of its own in</Text>
190
+ <Text selectable style={[text.small, { color: theme.colors.foreground }]}>
191
+ {homes.dir}
192
+ </Text>
193
+ </View>
194
+ <IconButton
195
+ theme={theme}
196
+ icon="FolderPen"
197
+ label="Change where accounts are kept"
198
+ tooltip="Keep the accounts' folders somewhere else; they move there"
199
+ tooltipAlign="end"
200
+ onPress={() => setEditing(true)}
201
+ />
202
+ {editing ? <HomesModal theme={theme} family={family} homes={homes} store={store} onClose={() => setEditing(false)} /> : null}
203
+ </View>
204
+ );
205
+ }
206
+
207
+ function HomesModal({ theme, family, homes, store, onClose }: { theme: Theme; family: HomesFamily; homes: HomesState; store: ZeroSubStore; onClose(): void }) {
208
+ const copy = HOMES_COPY[family];
209
+ const text = useText(theme);
210
+ const toast = useToast();
211
+ const inputStyle = useInputStyle(theme);
212
+ const [dir, setDir] = useState(homes.isDefault ? "" : homes.dir);
213
+ const typed = dir.trim();
214
+ const changed = typed === "" ? !homes.isDefault : typed !== homes.dir;
215
+ const [saving, setSaving] = useState(false);
216
+ const [error, setError] = useState<string | null>(null);
217
+ const save = useCallback(async () => {
218
+ setSaving(true);
219
+ setError(null);
220
+ try {
221
+ const result = await store.rpc(copy.rpc, { dir: typed });
222
+ const moving = result.moving > 0 ? ` · ${result.moving} account${result.moving === 1 ? "" : "s"} move there once nothing runs on ${result.moving === 1 ? "it" : "them"}` : "";
223
+ toast.show(`${copy.name} accounts are kept in ${result.dir} now${moving}`, { variant: "success", durationMs: 5_000 });
224
+ await store.refresh();
225
+ onClose();
226
+ } catch (failure) {
227
+ setError(describe(failure));
228
+ } finally {
229
+ setSaving(false);
230
+ }
231
+ }, [copy, typed, store, toast, onClose]);
232
+ return (
233
+ <Modal title={`Where ${copy.name} accounts are kept`} open onOpenChange={(open) => (open ? undefined : onClose())}>
234
+ <Modal.Content>
235
+ <Text style={text.muted}>
236
+ {`Now: ${homes.dir}${homes.isDefault ? ", beside the terminal scripts" : ""}. Each added account has a folder of its own there (its ${copy.variable}), named after it like its script, with its ${copy.holds}; new ones are ${copy.setUp} inside ZeroSub's own folder, then moved there.`}
237
+ </Text>
238
+ <Text style={text.muted}>
239
+ {`Saving another folder moves every account kept here, and any still in ZeroSub's own folder, to it. Each moves once nothing runs on it: ${copy.runner} using it holds it back until it stops. Removing an account later only takes it out of ZeroSub; ${copy.leftBehind}.`}
240
+ </Text>
241
+ <TextInput
242
+ value={dir}
243
+ onChangeText={setDir}
244
+ autoFocus
245
+ maxLength={1024}
246
+ placeholder={homes.isDefault ? homes.dir : "Default, beside the terminal scripts"}
247
+ placeholderTextColor={theme.colors.foregroundMuted}
248
+ autoCapitalize="none"
249
+ autoCorrect={false}
250
+ onSubmitEditing={() => (changed ? void save() : undefined)}
251
+ style={inputStyle}
252
+ accessibilityLabel={`Folder for ${copy.name} accounts`}
253
+ />
254
+ {error ? <Text style={text.danger}>{error}</Text> : null}
255
+ <View style={{ flexDirection: "row", gap: 8, justifyContent: "flex-end" }}>
256
+ <Button theme={theme} label="Cancel" tooltip="Keep the current folder" tooltipAlign="end" onPress={onClose} />
257
+ <Button theme={theme} tone="primary" label="Save" tooltip="Keep the accounts here" tooltipAlign="end" busy={saving} disabled={!changed} onPress={() => void save()} />
258
+ </View>
259
+ </Modal.Content>
260
+ </Modal>
261
+ );
262
+ }
263
+
264
+ /**
265
+ * A Pi account's key and base URL. Adding asks for a name and optional proxy too; editing keeps the
266
+ * key unless a new one is typed, and the proxy has its own button on the card.
267
+ */
268
+ function KeyForm({
269
+ theme,
270
+ store,
271
+ account,
272
+ onDone,
273
+ onCancel,
274
+ }: {
275
+ theme: Theme;
276
+ store: ZeroSubStore;
277
+ /** The account being edited; absent when adding one. */
278
+ account?: AccountView;
279
+ onDone(): void;
280
+ onCancel(): void;
281
+ }) {
282
+ const text = useText(theme);
283
+ const inputStyle = useInputStyle(theme);
284
+ const editing = Boolean(account);
285
+ const main = account?.kind === "main";
286
+ const current = account?.api ?? null;
287
+ const [label, setLabel] = useState("");
288
+ const [key, setKey] = useState("");
289
+ const [baseUrl, setBaseUrl] = useState(current?.baseUrl ?? "");
290
+ const [proxy, setProxy] = useState("");
291
+ const [saving, setSaving] = useState(false);
292
+ const [error, setError] = useState<string | null>(null);
293
+ const ready = editing ? true : Boolean(label.trim() && key.trim());
294
+ const submit = useCallback(async () => {
295
+ if (!ready) return;
296
+ setSaving(true);
297
+ setError(null);
298
+ try {
299
+ if (account) await store.rpc(updateApiAccount, { accountId: account.id, key: key.trim() || undefined, baseUrl: baseUrl.trim() });
300
+ else await store.rpc(addApiAccount, { label: label.trim(), key: key.trim(), baseUrl: baseUrl.trim() || undefined, proxy: proxy.trim() || undefined });
301
+ await store.refresh();
302
+ onDone();
303
+ } catch (failure) {
304
+ setError(describe(failure));
305
+ } finally {
306
+ setSaving(false);
307
+ }
308
+ }, [ready, account, store, key, baseUrl, label, proxy, onDone]);
309
+ const input = (props: { value: string; onChangeText(value: string): void; placeholder: string; label: string; maxLength: number; secure?: boolean; autoFocus?: boolean }) => (
310
+ <TextInput
311
+ value={props.value}
312
+ onChangeText={props.onChangeText}
313
+ maxLength={props.maxLength}
314
+ placeholder={props.placeholder}
315
+ placeholderTextColor={theme.colors.foregroundMuted}
316
+ autoCapitalize="none"
317
+ autoCorrect={false}
318
+ autoFocus={props.autoFocus}
319
+ secureTextEntry={props.secure}
320
+ style={inputStyle}
321
+ accessibilityLabel={props.label}
322
+ />
323
+ );
324
+ return (
325
+ <View style={{ gap: 12 }}>
326
+ {editing ? null : (
327
+ <Field theme={theme} title="Name">
328
+ {input({ value: label, onChangeText: setLabel, placeholder: "e.g. Work key", label: "Account name", maxLength: 40, autoFocus: true })}
329
+ </Field>
330
+ )}
331
+ <Field theme={theme} title="Anthropic API key">
332
+ {input({
333
+ value: key,
334
+ onChangeText: setKey,
335
+ placeholder: current ? `Leave empty to keep the current one${current.keyHint ? ` (…${current.keyHint})` : ""}; needed again for a new base URL` : "sk-ant-…",
336
+ label: "API key",
337
+ maxLength: 4096,
338
+ secure: true,
339
+ })}
340
+ </Field>
341
+ <Field theme={theme} title="Base URL (optional)">
342
+ {input({ value: baseUrl, onChangeText: setBaseUrl, placeholder: "Empty: Anthropic's API · e.g. https://gateway.example.com", label: "Base URL", maxLength: 2048 })}
343
+ {/^http:\/\//i.test(baseUrl.trim()) && !/^http:\/\/(localhost|127\.[\d.]+|\[::1\])(?=[:/]|$)/i.test(baseUrl.trim()) ? (
344
+ <Text style={text.small}>Over http:// the key travels unencrypted. Use https:// unless the gateway is on a network you trust.</Text>
345
+ ) : null}
346
+ </Field>
347
+ {editing ? null : (
348
+ <Field theme={theme} title="Proxy (optional)">
349
+ {input({ value: proxy, onChangeText: setProxy, placeholder: "http://127.0.0.1:7890", label: "Proxy URL", maxLength: 2048 })}
350
+ <Text style={text.small}>Every request its Pi agents make goes through it, Anthropic's and other providers' alike.</Text>
351
+ </Field>
352
+ )}
353
+ <Text style={text.small}>
354
+ {main
355
+ ? "This changes Pi's own ~/.pi/agent/auth.json and models.json, which pi in a terminal uses too (a copy of each as it was is kept in ZeroSub's backups). An Anthropic sign-in made with /login there is replaced by the key. Pi agents started afterwards use it; running ones keep theirs until they reopen."
356
+ : "Billed per use, so ZeroSub never moves agents onto it by itself: it's used only as the default or when you pick it for an agent. The key stays on this host."}
357
+ </Text>
358
+ {error ? <Text style={text.danger}>{error}</Text> : null}
359
+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8, justifyContent: "flex-end" }}>
360
+ <Button theme={theme} label="Cancel" tooltip={editing ? "Keep the current settings" : "Close without adding an account"} tooltipAlign="end" onPress={onCancel} />
361
+ <Button
362
+ theme={theme}
363
+ tone="primary"
364
+ label={editing ? "Save" : "Add account"}
365
+ tooltip={editing ? "Save these settings" : "Add this Pi account"}
366
+ tooltipAlign="end"
367
+ busy={saving}
368
+ disabled={!ready}
369
+ onPress={() => void submit()}
370
+ />
371
+ </View>
372
+ </View>
373
+ );
374
+ }
375
+
376
+ /** Adds back a Pi account from the folder ZeroSub kept when it was removed (its key, base URL and proxy are in it). */
377
+ function FolderForm({ theme, store, onDone, onCancel }: { theme: Theme; store: ZeroSubStore; onDone(): void; onCancel(): void }) {
378
+ const text = useText(theme);
379
+ const inputStyle = useInputStyle(theme);
380
+ const [path, setPath] = useState("");
381
+ const [saving, setSaving] = useState(false);
382
+ const [error, setError] = useState<string | null>(null);
383
+ const submit = useCallback(async () => {
384
+ if (!path.trim()) return;
385
+ setSaving(true);
386
+ setError(null);
387
+ try {
388
+ await store.rpc(importPiAccount, { path: path.trim() });
389
+ await store.refresh();
390
+ onDone();
391
+ } catch (failure) {
392
+ setError(describe(failure));
393
+ } finally {
394
+ setSaving(false);
395
+ }
396
+ }, [path, store, onDone]);
397
+ return (
398
+ <View style={{ gap: 12 }}>
399
+ <Text style={text.small}>
400
+ A Pi account removed here keeps its folder, with its key, base URL and proxy in its zerosub.json. Type the folder's full path to add it back as it was;
401
+ it's named after the folder, and you can rename it.
402
+ </Text>
403
+ <TextInput
404
+ value={path}
405
+ onChangeText={setPath}
406
+ autoFocus
407
+ maxLength={1024}
408
+ placeholder="~/.pi-config/pi-work"
409
+ placeholderTextColor={theme.colors.foregroundMuted}
410
+ autoCapitalize="none"
411
+ autoCorrect={false}
412
+ onSubmitEditing={() => void submit()}
413
+ style={inputStyle}
414
+ accessibilityLabel="Folder"
415
+ />
416
+ {error ? <Text style={text.danger}>{error}</Text> : null}
417
+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8, justifyContent: "flex-end" }}>
418
+ <Button theme={theme} label="Cancel" tooltip="Close without adding an account" tooltipAlign="end" onPress={onCancel} />
419
+ <Button theme={theme} tone="primary" label="Add account" tooltip="Add the account in this folder back" tooltipAlign="end" busy={saving} disabled={!path.trim()} onPress={() => void submit()} />
420
+ </View>
421
+ </View>
422
+ );
423
+ }
424
+
425
+ /** Adds a Pi account: an Anthropic API key, or the folder of one removed before. */
426
+ export function AddPiAccountModal({ theme, store, onClose }: { theme: Theme; store: ZeroSubStore; onClose(): void }) {
427
+ const toast = useToast();
428
+ const [mode, setMode] = useState<"key" | "folder">("key");
429
+ const done = () => {
430
+ toast.show("Pi account added. Pick it from a Pi agent's account button, or make it the default.", { variant: "success" });
431
+ onClose();
432
+ };
433
+ return (
434
+ <Modal title={mode === "key" ? "Add Pi API account" : "Add a Pi account's folder back"} open onOpenChange={(open) => (open ? undefined : onClose())}>
435
+ <Modal.Content>
436
+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8 }}>
437
+ <Button theme={theme} size="small" tone={mode === "key" ? "primary" : "secondary"} label="API key" tooltip="Add an Anthropic API key as a new account" tooltipAlign="start" onPress={() => setMode("key")} />
438
+ <Button
439
+ theme={theme}
440
+ size="small"
441
+ tone={mode === "folder" ? "primary" : "secondary"}
442
+ label="A folder set up already"
443
+ tooltip="Add back an account removed earlier, from the folder ZeroSub kept"
444
+ tooltipAlign="start"
445
+ onPress={() => setMode("folder")}
446
+ />
447
+ </View>
448
+ {mode === "key" ? <KeyForm theme={theme} store={store} onCancel={onClose} onDone={done} /> : <FolderForm theme={theme} store={store} onCancel={onClose} onDone={done} />}
449
+ </Modal.Content>
450
+ </Modal>
451
+ );
452
+ }
453
+
454
+ /** Changes a Pi account's key or base URL from its card (Pi's own login's too). */
455
+ export function ApiKeyModal({ theme, store, account, onClose }: { theme: Theme; store: ZeroSubStore; account: AccountView; onClose(): void }) {
456
+ const toast = useToast();
457
+ return (
458
+ <Modal title={`API settings for ${account.label}`} open onOpenChange={(open) => (open ? undefined : onClose())}>
459
+ <Modal.Content>
460
+ <KeyForm
461
+ theme={theme}
462
+ store={store}
463
+ account={account}
464
+ onCancel={onClose}
465
+ onDone={() => {
466
+ toast.show(`${account.label} updated. Agents started from now on use it.`, { variant: "success" });
467
+ onClose();
468
+ }}
469
+ />
470
+ </Modal.Content>
471
+ </Modal>
472
+ );
473
+ }
474
+
475
+ /** Sets or clears a Pi account's proxy (Pi's own login's too). */
476
+ export function ProxyModal({ theme, account, store, onClose }: { theme: Theme; account: AccountView; store: ZeroSubStore; onClose(): void }) {
477
+ const text = useText(theme);
478
+ const toast = useToast();
479
+ const inputStyle = useInputStyle(theme);
480
+ // The box starts with the current proxy, its password hidden: a change is only saved with the password typed in full.
481
+ const current = account.proxy ?? "";
482
+ const [proxy, setProxy] = useState(current);
483
+ const typed = proxy.trim();
484
+ const hidden = typed.includes(HIDDEN);
485
+ // Main's settings can outrank a proxy set here for Claude's CLI login: it's set there instead.
486
+ const blocked = account.proxyBlocked;
487
+ const changed = typed !== "" && typed !== current && !hidden && !blocked;
488
+ const inherited = account.inheritedProxy;
489
+ const followers = account.proxyFollowers.length > 0 ? `, and so do ${account.proxyFollowers.join(", ")}, which have no proxy of their own` : "";
490
+ const afterRemoval = inherited ? `they then go through ${inherited.proxy}, set in ${inherited.from}` : "they then use the network the daemon has";
491
+ const [saving, setSaving] = useState<"save" | "clear" | null>(null);
492
+ const [error, setError] = useState<string | null>(null);
493
+ const save = useCallback(
494
+ async (value: string) => {
495
+ setSaving(value ? "save" : "clear");
496
+ setError(null);
497
+ try {
498
+ const result = await store.rpc(setAccountProxy, { accountId: account.id, proxy: value });
499
+ toast.show(result.proxy ? `${account.label} now uses ${result.proxy}` : `${account.label} no longer uses a proxy`, { variant: "success" });
500
+ await store.refresh();
501
+ onClose();
502
+ } catch (failure) {
503
+ setError(describe(failure));
504
+ } finally {
505
+ setSaving(null);
506
+ }
507
+ },
508
+ [account, store, toast, onClose],
509
+ );
510
+ return (
511
+ <Modal title={`Proxy for ${account.label}`} open onOpenChange={(open) => (open ? undefined : onClose())}>
512
+ <Modal.Content>
513
+ <Text style={text.muted}>
514
+ {account.proxy
515
+ ? `Now: ${account.proxy}${account.proxyFile ? `, set in ${account.proxyFile}` : ""}.`
516
+ : inherited
517
+ ? `Now: no proxy of its own; it goes through ${inherited.proxy}, set in ${inherited.from}.`
518
+ : "Now: no proxy of its own; it uses the network the daemon has."}
519
+ {blocked
520
+ ? null
521
+ : account.family === "claude"
522
+ ? account.proxyFile
523
+ ? ` Saving changes it there, so plain claude in a terminal uses it too${followers}. Removing it takes it out of there, and ${afterRemoval}. Agents started afterwards use the new setting; running ones keep theirs until they reopen.`
524
+ : account.kind === "main"
525
+ ? " Agents started after saving use the new setting; running ones keep theirs until they reopen. Plain claude in a terminal doesn't: it goes the way ~/.claude/settings.json and your shell say."
526
+ : " Its agents started after saving use the new setting; running ones keep theirs until they reopen. It's kept in the env of its folder's settings.json, so Claude Code started on that folder uses it too."
527
+ : account.kind === "main"
528
+ ? ` Saving writes it as httpProxy in ~/.pi/agent/settings.json, so plain pi uses it too unless its environment names a proxy${followers || ", and so do added accounts without a proxy of their own"}. Pi agents started afterwards use the new setting; running ones keep theirs until they reopen.`
529
+ : " Its Pi agents started after saving use the new setting, for every request they make; running ones keep theirs until they reopen. It's also httpProxy in the settings of its folder, and its script uses it."}
530
+ </Text>
531
+ {blocked ? <Text style={text.danger}>{blocked}</Text> : null}
532
+ {blocked ? null : (
533
+ <>
534
+ <TextInput
535
+ value={proxy}
536
+ onChangeText={setProxy}
537
+ autoFocus
538
+ maxLength={2048}
539
+ // Empty keeps the proxy it goes through without one of its own, so that's what it shows.
540
+ placeholder={inherited?.proxy ?? "http://host:port"}
541
+ placeholderTextColor={theme.colors.foregroundMuted}
542
+ autoCapitalize="none"
543
+ autoCorrect={false}
544
+ onSubmitEditing={() => (changed ? void save(typed) : undefined)}
545
+ style={inputStyle}
546
+ accessibilityLabel="Proxy URL"
547
+ />
548
+ <Text style={text.small}>{hidden ? `${HIDDEN} hides the proxy's password: type it in full to save a change.` : "http:// or https://, with user:password@ if the proxy needs it."}</Text>
549
+ </>
550
+ )}
551
+ {error ? <Text style={text.danger}>{error}</Text> : null}
552
+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8, justifyContent: "flex-end" }}>
553
+ <Button theme={theme} label={blocked ? "Close" : "Cancel"} tooltip={blocked ? "Close" : "Keep the current proxy"} tooltipAlign="end" onPress={onClose} />
554
+ {account.proxy && !blocked ? (
555
+ <Button
556
+ theme={theme}
557
+ label="Remove proxy"
558
+ tooltip={account.proxyFile ? `Take the proxy out of ${account.proxyFile}` : "Stop using a proxy of its own"}
559
+ tooltipAlign="end"
560
+ busy={saving === "clear"}
561
+ onPress={() => void save("")}
562
+ />
563
+ ) : null}
564
+ {blocked ? null : (
565
+ <Button theme={theme} tone="primary" label="Save" tooltip="Use this proxy for the account" tooltipAlign="end" busy={saving === "save"} disabled={!changed} onPress={() => void save(typed)} />
566
+ )}
567
+ </View>
568
+ </Modal.Content>
569
+ </Modal>
570
+ );
571
+ }