@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
package/server/process.ts CHANGED
@@ -9,6 +9,8 @@ export interface RunResult {
9
9
  }
10
10
 
11
11
  const MAX_OUTPUT_BYTES = 1024 * 1024;
12
+ /** How long output may still arrive after the child exits, before pipes held open by its own children are let go. */
13
+ const EXIT_DRAIN_MS = 1_000;
12
14
 
13
15
  /** Runs a command to completion with a timeout. Never throws for a non-zero exit. */
14
16
  export function run(
@@ -24,6 +26,8 @@ export function run(
24
26
  let outputExceeded = false;
25
27
  const decoders = { stdout: new StringDecoder("utf8"), stderr: new StringDecoder("utf8") };
26
28
  let killTimer: ReturnType<typeof setTimeout> | undefined;
29
+ let drainTimer: ReturnType<typeof setTimeout> | undefined;
30
+ let finished = false;
27
31
  let child: ChildProcess;
28
32
  try {
29
33
  child = spawn(command, [...args], {
@@ -65,14 +69,27 @@ export function run(
65
69
  child.on("error", (error) => {
66
70
  stderr += error.message;
67
71
  });
68
- child.on("close", (code) => {
72
+ const finish = (code: number | null) => {
73
+ if (finished) return;
74
+ finished = true;
69
75
  clearTimeout(timer);
70
76
  clearTimeout(killTimer);
77
+ clearTimeout(drainTimer);
71
78
  stdout += decoders.stdout.end();
72
79
  stderr += decoders.stderr.end();
73
80
  if (outputExceeded) stderr = `Command output exceeded the 1 MiB limit.${stderr ? `\n${stderr}` : ""}`;
74
81
  resolve({ code: outputExceeded ? null : code, stdout, stderr, timedOut });
82
+ };
83
+ // "close" waits for every process holding the pipes, so a helper the command left running would
84
+ // keep the caller waiting until it ends too.
85
+ child.on("exit", (code) => {
86
+ drainTimer = setTimeout(() => {
87
+ child.stdout?.destroy();
88
+ child.stderr?.destroy();
89
+ finish(code);
90
+ }, EXIT_DRAIN_MS);
75
91
  });
92
+ child.on("close", finish);
76
93
  if (options.input !== undefined) child.stdin?.end(options.input);
77
94
  else child.stdin?.end();
78
95
  });
@@ -0,0 +1,66 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { createInterface } from "node:readline";
5
+
6
+ /**
7
+ * The homes in `homes` a process was started with, by the line for it in `ps -E` (its command, then
8
+ * its environment, space-separated): one of `variables` (`PI_CODING_AGENT_DIR`, say) set to exactly
9
+ * that path. A command that only mentions one may match too, which only makes a move wait.
10
+ */
11
+ export function homesInEnvironment(line: string, homes: readonly string[], variables: readonly string[]): string[] {
12
+ const has = (needle: string) => {
13
+ for (let at = line.indexOf(needle); at >= 0; at = line.indexOf(needle, at + 1)) {
14
+ const end = at + needle.length;
15
+ if ((at === 0 || /\s/.test(line[at - 1]!)) && (end === line.length || /\s/.test(line[end]!))) return true;
16
+ }
17
+ return false;
18
+ };
19
+ return homes.filter((home) => variables.some((variable) => has(`${variable}=${home}`)));
20
+ }
21
+
22
+ /**
23
+ * Calls `visit` with each of the user's processes as one line: its command, then its environment.
24
+ * macOS lists them with `ps -E` (only one's own processes show their environment, which is all this
25
+ * needs); Linux reads `/proc`. Streamed, since every environment together runs to megabytes.
26
+ */
27
+ export async function eachProcessEnvironment(visit: (line: string) => void): Promise<void> {
28
+ if (process.platform === "linux") {
29
+ for (const pid of await readdir("/proc").catch(() => [] as string[])) {
30
+ if (!/^\d+$/.test(pid)) continue;
31
+ const environ = await readFile(join("/proc", pid, "environ"), "utf8").catch(() => null);
32
+ if (environ) visit(` ${environ.split("\0").join(" ")}`);
33
+ }
34
+ return;
35
+ }
36
+ if (process.platform !== "darwin") throw new Error(`ZeroSub can't tell which processes use a home on ${process.platform}`);
37
+ await new Promise<void>((resolve, reject) => {
38
+ const child = spawn("/bin/ps", ["-xEww", "-o", "command="], { stdio: ["ignore", "pipe", "pipe"] });
39
+ const timer = setTimeout(() => child.kill("SIGKILL"), 15_000);
40
+ let stderr = "";
41
+ child.stderr.on("data", (chunk: Buffer) => void (stderr += chunk.toString("utf8").slice(0, 2_000)));
42
+ createInterface({ input: child.stdout }).on("line", visit);
43
+ child.on("error", (error) => {
44
+ clearTimeout(timer);
45
+ reject(error);
46
+ });
47
+ child.on("close", (code, signal) => {
48
+ clearTimeout(timer);
49
+ if (code === 0) resolve();
50
+ else reject(new Error(`couldn't list running processes (${signal === "SIGKILL" ? "timed out" : stderr.trim() || `exit ${code}`})`));
51
+ });
52
+ });
53
+ }
54
+
55
+
56
+ /** `ip=` and `loc=` from a `/cdn-cgi/trace` answer (one `key=value` a line). */
57
+ export function parseTrace(text: string): { ip: string; country: string | null } | null {
58
+ const fields = new Map<string, string>();
59
+ for (const line of text.split("\n")) {
60
+ const at = line.indexOf("=");
61
+ if (at > 0) fields.set(line.slice(0, at), line.slice(at + 1).trim());
62
+ }
63
+ const ip = fields.get("ip");
64
+ return ip ? { ip, country: fields.get("loc") || null } : null;
65
+ }
66
+
@@ -0,0 +1,28 @@
1
+ import { FAMILIES, type Family } from "../shared/model";
2
+
3
+ /**
4
+ * The `env` Paseo's config gives each family's built-in provider (`agents.providers.claude.env`,
5
+ * say), which Paseo layers over the daemon's environment for every session on it. ZeroSub's own
6
+ * calls with an account's token and the CLI processes it starts for an account use it too, so they
7
+ * go out the way that account's agents do (through a proxy set there, for one). Empty until the
8
+ * config is first read, and for a provider ZeroSub doesn't route because it brings its own
9
+ * credentials; a config that can't be read keeps what was read last.
10
+ */
11
+ const envs = new Map<Family, Record<string, string>>();
12
+
13
+ export function providerEnv(family: Family): Record<string, string> {
14
+ return envs.get(family) ?? {};
15
+ }
16
+
17
+ /** Remembers the built-in providers' `env` from the config's `providers`, given the families ZeroSub routes. */
18
+ export function rememberProviderEnvs(routed: Readonly<Record<string, Family>>, providers: Record<string, unknown> | undefined): void {
19
+ for (const family of FAMILIES) {
20
+ const entry = providers?.[family];
21
+ const env = entry && typeof entry === "object" && !Array.isArray(entry) ? (entry as { env?: unknown }).env : undefined;
22
+ const strings: Record<string, string> = {};
23
+ if (routed[family] === family && env && typeof env === "object" && !Array.isArray(env)) {
24
+ for (const [key, value] of Object.entries(env)) if (typeof value === "string") strings[key] = value;
25
+ }
26
+ envs.set(family, strings);
27
+ }
28
+ }
@@ -0,0 +1,282 @@
1
+ import { request as httpsRequest } from "node:https";
2
+ import { connect as netConnect, type Socket } from "node:net";
3
+ import { connect as tlsConnect } from "node:tls";
4
+ import { HIDDEN } from "../shared/model";
5
+
6
+ /** The order Node clients read them in (undici's `EnvHttpProxyAgent`, as Pi uses): the first one set wins. */
7
+ export const PROXY_KEYS = ["https_proxy", "HTTPS_PROXY", "http_proxy", "HTTP_PROXY"] as const;
8
+
9
+ /** The proxy an environment names, in the order Node clients read the variables in; null without one. */
10
+ export function proxyFromEnv(env: Record<string, string | undefined>): string | null {
11
+ for (const key of PROXY_KEYS) {
12
+ const value = env[key]?.trim();
13
+ if (value) return value;
14
+ }
15
+ return null;
16
+ }
17
+
18
+ export const NO_PROXY_KEYS = ["no_proxy", "NO_PROXY"] as const;
19
+
20
+ /** Hosts that stay direct when ZeroSub gives a process a proxy: this machine, where a local gateway may be. */
21
+ export const REQUIRED_NO_PROXY = ["localhost", "127.0.0.1", "::1"] as const;
22
+
23
+ /** For Claude Code, its updater's host as well. */
24
+ export const CLAUDE_REQUIRED_NO_PROXY = [...REQUIRED_NO_PROXY, "downloads.claude.ai"] as const;
25
+
26
+ /** The no-proxy list in an environment: `*` if either variable is, else both when they differ. */
27
+ export function noProxyFromEnv(env: Record<string, string | undefined>): string | null {
28
+ const { no_proxy: lower, NO_PROXY: upper } = env;
29
+ if (lower === "*" || upper === "*") return "*";
30
+ if (lower && upper && lower !== upper) return `${lower},${upper}`;
31
+ return lower || upper || null;
32
+ }
33
+
34
+ /**
35
+ * Whether a request to `target` goes direct under the no-proxy list `noProxy`: `*` for everything,
36
+ * `host:port`, `.suffix` (the domain itself or any below it), otherwise the exact host.
37
+ */
38
+ export function bypassesProxy(noProxy: string | null, target: string): boolean {
39
+ if (!noProxy) return false;
40
+ if (noProxy === "*") return true;
41
+ const url = new URL(target);
42
+ const host = url.hostname.toLowerCase();
43
+ const port = url.port || (url.protocol === "https:" || url.protocol === "wss:" ? "443" : "80");
44
+ return noProxy
45
+ .split(/[,\s]+/)
46
+ .filter(Boolean)
47
+ .some((raw) => {
48
+ const entry = raw.toLowerCase();
49
+ if (entry.includes(":")) return `${host}:${port}` === entry;
50
+ if (entry.startsWith(".")) return host === entry.slice(1) || host.endsWith(entry);
51
+ return host === entry;
52
+ });
53
+ }
54
+
55
+ /** Where Claude Code signs in, reads usage and sends an account's requests. */
56
+ const CLAUDE_DOMAINS = ["anthropic.com", "claude.ai", "claude.com"];
57
+
58
+ /** `noProxy` without anything that could send Anthropic or Claude traffic past the proxy (see `withoutDomains`). */
59
+ export function withoutClaudeDomains(noProxy: string | null): string {
60
+ return withoutDomains(noProxy, CLAUDE_DOMAINS);
61
+ }
62
+
63
+ /**
64
+ * `noProxy` without anything that could send a request to one of `domains` past the proxy, in any of
65
+ * the forms HTTP clients accept: `*`, `*.domain`, `.domain`, `domain`, with or without a port, for
66
+ * those domains, one below them (`api.anthropic.com`) or above them (`.com`). The rest (`localhost`,
67
+ * an intranet's domain, address ranges) stays as it was.
68
+ */
69
+ export function withoutDomains(noProxy: string | null, domains: readonly string[]): string {
70
+ const wanted = domains.map((domain) => domain.toLowerCase()).filter(Boolean);
71
+ return (noProxy ?? "")
72
+ .split(/[,\s]+/)
73
+ .filter((entry) => {
74
+ if (!entry) return false;
75
+ // Read the way the loosest client reads it. undici (Pi's) drops a port, a leading `*.` or `.`
76
+ // and a trailing dot, and from 8.12 (Pi 1.5.0 on) takes `*`, alone or with a port (`*:443`),
77
+ // for every host wherever it stands in the list.
78
+ const host = entry
79
+ .toLowerCase()
80
+ .replace(/:\d*$/, "")
81
+ .replace(/^\*?\.?/, "")
82
+ .replace(/\.$/, "");
83
+ if (!host || host === "*") return false;
84
+ return !wanted.some((domain) => host === domain || domain.endsWith(`.${host}`) || host.endsWith(`.${domain}`));
85
+ })
86
+ .join(",");
87
+ }
88
+
89
+ /** Adds this machine's addresses, without duplicating entries. */
90
+ export function withRequiredNoProxy(noProxy: string | null, required: readonly string[] = REQUIRED_NO_PROXY): string {
91
+ const entries = (noProxy ?? "").split(/[\s,]+/).filter(Boolean);
92
+ const seen = new Set<string>();
93
+ const result: string[] = [];
94
+ for (const entry of [...required, ...entries]) {
95
+ const key = entry.toLowerCase();
96
+ if (!seen.has(key)) {
97
+ seen.add(key);
98
+ result.push(entry);
99
+ }
100
+ }
101
+ return result.join(",");
102
+ }
103
+
104
+ /** Adds this machine's addresses and Claude's updater host, as Claude Code's processes need. */
105
+ export function withClaudeNoProxy(noProxy: string | null): string {
106
+ return withRequiredNoProxy(noProxy, CLAUDE_REQUIRED_NO_PROXY);
107
+ }
108
+
109
+ /**
110
+ * Checks a proxy typed by the user and returns it in canonical form. Only http:// and https://
111
+ * proxies are accepted: they're what Claude Code, Pi and ZeroSub's own requests can all use. One
112
+ * still holding the hidden password it was shown with (see `maskProxy`) isn't a proxy to save.
113
+ */
114
+ export function normalizeProxy(input: string): string {
115
+ const value = input.trim();
116
+ if (value.includes(HIDDEN)) throw new Error(`${HIDDEN} hides the proxy's password: type it in full`);
117
+ let url: URL;
118
+ try {
119
+ url = new URL(value);
120
+ } catch {
121
+ throw new Error("Enter the proxy as a URL, like http://127.0.0.1:7890");
122
+ }
123
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
124
+ throw new Error(`${url.protocol.replace(/:$/, "")} proxies aren't supported; use an http:// or https:// proxy`);
125
+ }
126
+ if (!url.hostname) throw new Error("The proxy needs a host, like http://127.0.0.1:7890");
127
+ if ((url.pathname && url.pathname !== "/") || url.search || url.hash) {
128
+ throw new Error("The proxy is just scheme, host and port, like http://127.0.0.1:7890");
129
+ }
130
+ const auth = url.username || url.password ? `${url.username}${url.password ? `:${url.password}` : ""}@` : "";
131
+ return `${url.protocol}//${auth}${url.host}`;
132
+ }
133
+
134
+ /**
135
+ * The proxy for display: the password, if any, is hidden, and so is a user name with no password
136
+ * (often a token). A proxy written without a scheme is read as http://,
137
+ * and one that can't be read at all shows only what follows its last `@`.
138
+ */
139
+ export function maskProxy(proxy: string): string {
140
+ const value = proxy.trim();
141
+ const scheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(value);
142
+ let url: URL;
143
+ try {
144
+ url = new URL(scheme ? value : `http://${value}`);
145
+ } catch {
146
+ const at = value.lastIndexOf("@");
147
+ return at === -1 ? HIDDEN : `${HIDDEN}${value.slice(at)}`;
148
+ }
149
+ if (!url.username && !url.password) return value;
150
+ const prefix = scheme ? `${url.protocol}//` : "";
151
+ const credentials = url.password ? `${url.username}:${HIDDEN}` : HIDDEN;
152
+ return `${prefix}${credentials}@${url.host}`;
153
+ }
154
+
155
+ /**
156
+ * Opens a raw tunnel to `host:port` through an HTTP(S) proxy with CONNECT. Anything other than an
157
+ * http:// or https:// proxy is refused rather than skipped, so a misconfigured proxy never turns
158
+ * into a direct connection.
159
+ */
160
+ export function openTunnel(proxy: string, host: string, port: number, signal?: AbortSignal): Promise<Socket> {
161
+ let url: URL;
162
+ try {
163
+ // One without a scheme (`127.0.0.1:7890`, as the environment or a settings file may have it) is http://.
164
+ url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(proxy.trim()) ? proxy.trim() : `http://${proxy.trim()}`);
165
+ } catch {
166
+ return Promise.reject(new Error("The account's proxy isn't a valid URL"));
167
+ }
168
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
169
+ return Promise.reject(new Error(`Proxy scheme ${url.protocol} isn't supported here; use an http:// or https:// proxy`));
170
+ }
171
+ const proxyPort = Number(url.port) || (url.protocol === "https:" ? 443 : 80);
172
+ const authority = `${host}:${port}`;
173
+ const lines = [`CONNECT ${authority} HTTP/1.1`, `Host: ${authority}`];
174
+ if (url.username || url.password) {
175
+ const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
176
+ lines.push(`Proxy-Authorization: Basic ${Buffer.from(credentials).toString("base64")}`);
177
+ }
178
+
179
+ return new Promise((resolve, reject) => {
180
+ const socket: Socket =
181
+ url.protocol === "https:"
182
+ ? tlsConnect({ host: url.hostname, port: proxyPort, servername: url.hostname })
183
+ : netConnect({ host: url.hostname, port: proxyPort });
184
+ let head = Buffer.alloc(0);
185
+ const fail = (error: Error) => {
186
+ cleanup();
187
+ socket.destroy();
188
+ reject(error);
189
+ };
190
+ const onAbort = () => fail(signal?.reason instanceof Error ? signal.reason : new Error("Request aborted"));
191
+ const onError = (error: Error) => fail(new Error(`Proxy connection failed: ${error.message}`));
192
+ const onClose = () => fail(new Error("The proxy closed the connection before the tunnel opened"));
193
+ const onData = (chunk: Buffer) => {
194
+ head = Buffer.concat([head, chunk]);
195
+ const end = head.indexOf("\r\n\r\n");
196
+ if (end === -1) {
197
+ if (head.length > 16 * 1024) fail(new Error("The proxy sent an oversized reply"));
198
+ return;
199
+ }
200
+ const status = /^HTTP\/1\.[01] (\d{3})/.exec(head.subarray(0, end).toString("latin1"));
201
+ if (status?.[1] !== "200") {
202
+ fail(new Error(`The proxy refused the tunnel (${status ? `HTTP ${status[1]}` : "unreadable reply"})`));
203
+ return;
204
+ }
205
+ cleanup();
206
+ const rest = head.subarray(end + 4);
207
+ if (rest.length > 0) socket.unshift(rest);
208
+ resolve(socket);
209
+ };
210
+ const cleanup = () => {
211
+ socket.off("data", onData);
212
+ socket.off("error", onError);
213
+ socket.off("close", onClose);
214
+ signal?.removeEventListener("abort", onAbort);
215
+ };
216
+ if (signal?.aborted) return onAbort();
217
+ signal?.addEventListener("abort", onAbort, { once: true });
218
+ socket.on("data", onData);
219
+ socket.on("error", onError);
220
+ socket.on("close", onClose);
221
+ socket.once(url.protocol === "https:" ? "secureConnect" : "connect", () => socket.write(`${lines.join("\r\n")}\r\n\r\n`));
222
+ });
223
+ }
224
+
225
+ interface ProxiedInit {
226
+ method?: string;
227
+ headers?: Record<string, string>;
228
+ body?: string;
229
+ signal?: AbortSignal;
230
+ }
231
+
232
+ /**
233
+ * `fetch`, but through `proxy` when one is set, the way the account's CLI would reach the same
234
+ * host for that account. Only https:// targets are supported; that's all ZeroSub calls.
235
+ */
236
+ export async function proxiedFetch(proxy: string | null, target: string, init: ProxiedInit = {}): Promise<Response> {
237
+ if (!proxy) return fetch(target, init);
238
+ const url = new URL(target);
239
+ if (url.protocol !== "https:") throw new Error("Only https:// requests go through the account's proxy");
240
+ const port = Number(url.port) || 443;
241
+ const tunnel = await openTunnel(proxy, url.hostname, port, init.signal);
242
+
243
+ return new Promise<Response>((resolve, reject) => {
244
+ const headers: Record<string, string> = { ...init.headers };
245
+ if (init.body !== undefined) headers["Content-Length"] = String(Buffer.byteLength(init.body));
246
+ const req = httpsRequest(
247
+ {
248
+ host: url.hostname,
249
+ port,
250
+ path: `${url.pathname}${url.search}`,
251
+ method: init.method ?? "GET",
252
+ headers,
253
+ // No agent: Node only uses `createConnection` without one. `agent: false` would make a fresh
254
+ // agent, which connects straight to the host and leaves the tunnel unused.
255
+ servername: url.hostname,
256
+ createConnection: () => tlsConnect({ socket: tunnel, servername: url.hostname }),
257
+ signal: init.signal,
258
+ },
259
+ (res) => {
260
+ const chunks: Buffer[] = [];
261
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
262
+ res.on("error", reject);
263
+ res.on("end", () => {
264
+ const responseHeaders = new Headers();
265
+ for (const [name, value] of Object.entries(res.headers)) {
266
+ if (Array.isArray(value)) for (const entry of value) responseHeaders.append(name, entry);
267
+ else if (value !== undefined) responseHeaders.set(name, value);
268
+ }
269
+ const status = res.statusCode ?? 502;
270
+ const empty = status === 204 || status === 304;
271
+ resolve(new Response(empty ? null : new Uint8Array(Buffer.concat(chunks)), { status, headers: responseHeaders }));
272
+ });
273
+ },
274
+ );
275
+ req.on("error", (error) => {
276
+ tunnel.destroy();
277
+ reject(error);
278
+ });
279
+ if (init.body !== undefined) req.write(init.body);
280
+ req.end();
281
+ });
282
+ }
package/server/reopen.ts CHANGED
@@ -4,13 +4,40 @@ import { homedir } from "node:os";
4
4
  import { delimiter, dirname, join } from "node:path";
5
5
  import { paseoHome } from "./paths";
6
6
 
7
+ /** The part of the plugin's Paseo connection a reopen needs. */
8
+ export interface ReopenHost {
9
+ agents: { ref(agentId: string): unknown };
10
+ }
11
+
12
+ /**
13
+ * The host's own reopen, when it has one: Paseo 0.16's `agents.ref(id).reload()` closes and reopens
14
+ * the provider session in the daemon with the current configuration, rerunning session-open hooks.
15
+ * `null` on older hosts.
16
+ */
17
+ export function hostReload(paseo: ReopenHost | null | undefined, agentId: string): (() => Promise<unknown>) | null {
18
+ let ref: { reload?: unknown } | undefined;
19
+ try {
20
+ ref = paseo?.agents.ref(agentId) as { reload?: unknown } | undefined;
21
+ } catch {
22
+ return null;
23
+ }
24
+ const reload = ref?.reload;
25
+ return typeof reload === "function" ? () => (reload as () => Promise<unknown>).call(ref) : null;
26
+ }
27
+
28
+ /** Whether the host can reopen sessions itself. A ref is a local handle: building one sends nothing. */
29
+ export function hostCanReload(paseo: ReopenHost | null | undefined): boolean {
30
+ return hostReload(paseo, "zerosub-capability-check") !== null;
31
+ }
32
+
7
33
  /**
8
34
  * Reopens an agent's provider session so it picks up a new account.
9
35
  *
10
- * The plugin SDK has no session reopen (`agents.ref(id).refresh()` only refetches data), so this
11
- * uses the bundled CLI's `paseo agent reload`, which the daemon implements as close + reopen with
12
- * the current configuration. The CLI connects on its own; on a password-protected daemon it cannot,
13
- * and the switch then applies the next time the session opens.
36
+ * Through the host's own reopen when it has one (Paseo 0.16+). Otherwise through the bundled CLI's
37
+ * `paseo agent reload`, which the daemon implements as close + reopen with the current
38
+ * configuration. The CLI has to find the agent in its agent list first, which leaves out background
39
+ * agents, so on older hosts a background agent only changes accounts when its session next opens.
40
+ * The CLI connects on its own; when it can't, the switch also applies the next time the session opens.
14
41
  */
15
42
  export class Reopener {
16
43
  private cli: { at: number; path: Promise<string | null> } | null = null;
@@ -22,8 +49,18 @@ export class Reopener {
22
49
  return this.cli.path;
23
50
  }
24
51
 
25
- /** `timedOut`: the command was stopped before the daemon answered, so the reload may still finish. */
26
- async reopen(agentId: string): Promise<{ ok: true } | { ok: false; error: string; timedOut: boolean }> {
52
+ /** `timedOut`: the reopen was stopped, or gave up, before the daemon answered, so it may still finish. */
53
+ async reopen(agentId: string, paseo?: ReopenHost | null): Promise<{ ok: true } | { ok: false; error: string; timedOut: boolean }> {
54
+ const reload = hostReload(paseo, agentId);
55
+ if (reload) {
56
+ try {
57
+ await reload();
58
+ return { ok: true };
59
+ } catch (error) {
60
+ const message = error instanceof Error ? error.message : String(error);
61
+ return { ok: false, error: message || "Reload failed.", timedOut: STOPPED_WAITING.test(message) };
62
+ }
63
+ }
27
64
  const cli = await this.locate();
28
65
  if (!cli) return { ok: false, error: "The paseo command-line tool was not found on the daemon machine.", timedOut: false };
29
66
  const args = ["agent", "reload", agentId, "--json", "--home", paseoHome()];
@@ -39,16 +76,21 @@ export class Reopener {
39
76
  (error, _stdout, stderr) => {
40
77
  if (!error) return resolve({ ok: true });
41
78
  const detail = `${stderr || error.message}`.trim().split("\n").slice(-3).join(" ");
42
- resolve({ ok: false, error: explainFailure(detail), timedOut: error.killed === true });
79
+ // The CLI gives up on the daemon's answer by itself after a minute, which says as little.
80
+ const timedOut = error.killed === true || STOPPED_WAITING.test(`${stderr}\n${error.message}`);
81
+ resolve({ ok: false, error: explainFailure(detail), timedOut });
43
82
  },
44
83
  );
45
84
  });
46
85
  }
47
86
  }
48
87
 
88
+ /** The Paseo CLI's own "no answer in time" (`DAEMON_REQUEST_TIMEOUT`), e.g. "Timeout waiting for message (60000ms)". */
89
+ const STOPPED_WAITING = /Timeout waiting for message|DAEMON_REQUEST_TIMEOUT/;
90
+
49
91
  function explainFailure(detail: string): string {
50
92
  if (/transport closed|cannot connect|cannot reach|password|unauthori[sz]ed|DAEMON_NOT_RUNNING/i.test(detail)) {
51
- return "Paseo's CLI could not connect to this daemon (it may require a password). The agent switches accounts the next time its session starts.";
93
+ return "Paseo's CLI could not connect to this daemon (it may require a password)";
52
94
  }
53
95
  return detail || "Reload failed.";
54
96
  }