@kapybara/zerosub 1.2.1 → 1.3.0

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 CHANGED
@@ -37,7 +37,9 @@ Then open **Accounts (ZeroSub)** in the sidebar.
37
37
  - In a browser on the host's own computer, the page finishes by itself.
38
38
  - Anywhere else, choose **Use a code instead**. For Claude, paste the code shown after sign-in. For ChatGPT, type the code shown in Paseo on the page. Phones, and hosts without a desktop (servers, containers, daemons started over SSH), start with the code.
39
39
  3. Choose which account agents use:
40
- - **Make default**: new agents, and agents that follow the default, use it.
40
+ - **Make default**: new agents, and agents that follow the default, use it. Open Claude agents switch right away, busy ones after their turn.
41
+ - To leave open agents where they are, turn off **Move open agents when the default changes** (in Accounts, or **Settings → Plugins → zerosub → ZeroSub preferences**). Each open agent that follows the default then stays pinned to the account it's using, even after it reopens, unless that account is signed out, disabled or at its limit. New agents, and agents that aren't open at the time, use the new default.
42
+ - A kept agent still switches when its account hits a limit. To move it to the new default, choose **Follow default** from its account button, or type `/account default`.
41
43
  - **The account button in an agent's message box**: moves that one agent.
42
44
  - **`/account work`** in the message box, or `/account default` to follow the default again.
43
45
  - **⌘K → "Make … the default"**.
@@ -639,6 +639,13 @@ function AutomationSettings({ theme }: { theme: Theme }) {
639
639
  disabled={settings.saving}
640
640
  onValueChange={(balanceNewAgents) => save({ balanceNewAgents })}
641
641
  />
642
+ <SettingsSwitch
643
+ label="Move open agents when the default changes"
644
+ hint="Off: open agents stay on the account they're using, even after they reopen. New agents, and agents that aren't open at the time, use the new default."
645
+ value={settings.values.moveAgentsOnDefaultChange}
646
+ disabled={settings.saving}
647
+ onValueChange={(moveAgentsOnDefaultChange) => save({ moveAgentsOnDefaultChange })}
648
+ />
642
649
  <SettingsSwitch
643
650
  label="Use banked resets when every account is out"
644
651
  hint="Spends one of the account's banked resets instead of stopping. Resets are scarce, so this is off unless you turn it on."
@@ -42,6 +42,13 @@ export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurface
42
42
  actionLabel="Open accounts"
43
43
  onPress={onOpenAccounts}
44
44
  />
45
+ <SettingsSwitch
46
+ label="Move open agents when the default changes"
47
+ hint="Off: open agents stay on the account they're using, even after they reopen. New agents, and agents that aren't open at the time, use the new default."
48
+ value={settings.values.moveAgentsOnDefaultChange}
49
+ disabled={settings.saving}
50
+ onValueChange={(moveAgentsOnDefaultChange) => save({ moveAgentsOnDefaultChange })}
51
+ />
45
52
  </SettingsCard>
46
53
  </SettingsSection>
47
54
  <SettingsSection title="Automatic switching">
package/client/store.ts CHANGED
@@ -19,111 +19,138 @@ export interface StoreSnapshot {
19
19
  * One poller per installation feeds the surface, composer pills and commands.
20
20
  * Polling is cheap: the daemon answers from memory and refreshes usage on its own schedule.
21
21
  */
22
- export class ZeroSubStore {
23
- private snapshot: StoreSnapshot = { state: null, error: null };
24
- private readonly listeners = new Set<() => void>();
25
- private timer: ReturnType<typeof setTimeout> | null = null;
26
- private inFlight: Promise<void> | null = null;
27
- private issued = 0;
28
- private published = 0;
29
- private stopped = false;
30
- /** Poll intervals wanted by open views; the shortest wins. */
31
- private readonly watchers: number[] = [];
22
+ export interface ZeroSubStore {
23
+ readonly current: StoreSnapshot;
24
+ start(): void;
25
+ stop(): void;
26
+ rpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
27
+ contract: PluginRpcContract<InputSchema, OutputSchema>,
28
+ input: ZodInput<InputSchema>,
29
+ ): Promise<ZodOutput<OutputSchema>>;
30
+ subscribe(listener: () => void): () => void;
31
+ getSnapshot(): StoreSnapshot;
32
+ watch(intervalMs: number): () => void;
33
+ watchClosely(): () => void;
34
+ refresh(options?: { refreshUsage?: boolean; fresh?: boolean }): Promise<void>;
35
+ }
32
36
 
33
- constructor(private readonly client: PluginClientContext) {}
37
+ /**
38
+ * A closure, not a class: Hermes in React Native 0.81 has no class support in eval'd code. This bundle is
39
+ * large enough to be compiled lazily, so a class silently becomes undefined and `new` throws reading `.prototype`.
40
+ */
41
+ export function createZeroSubStore(client: PluginClientContext): ZeroSubStore {
42
+ let snapshot: StoreSnapshot = { state: null, error: null };
43
+ const listeners = new Set<() => void>();
44
+ let timer: ReturnType<typeof setTimeout> | null = null;
45
+ let inFlight: Promise<void> | null = null;
46
+ let issued = 0;
47
+ let published = 0;
48
+ let stopped = false;
49
+ /** Poll intervals wanted by open views; the shortest wins. */
50
+ const watchers: number[] = [];
34
51
 
35
- start(): void {
36
- void this.refresh();
52
+ function start(): void {
53
+ void refresh();
37
54
  }
38
55
 
39
- stop(): void {
40
- this.stopped = true;
41
- if (this.timer) clearTimeout(this.timer);
42
- this.listeners.clear();
56
+ function stop(): void {
57
+ stopped = true;
58
+ if (timer) clearTimeout(timer);
59
+ listeners.clear();
43
60
  }
44
61
 
45
62
  /** Calls a daemon handler, then refreshes state so every view sees the result. */
46
- async rpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
63
+ async function rpc<InputSchema extends ZodType, OutputSchema extends ZodType>(
47
64
  contract: PluginRpcContract<InputSchema, OutputSchema>,
48
65
  input: ZodInput<InputSchema>,
49
66
  ): Promise<ZodOutput<OutputSchema>> {
50
67
  try {
51
- return await this.client.rpc(contract, input);
68
+ return await client.rpc(contract, input);
52
69
  } finally {
53
70
  // A poll already in flight started before this action, so ask again once it lands.
54
- void this.refresh({ fresh: true });
71
+ void refresh({ fresh: true });
55
72
  }
56
73
  }
57
74
 
58
- get current(): StoreSnapshot {
59
- return this.snapshot;
60
- }
61
-
62
- subscribe = (listener: () => void): (() => void) => {
63
- this.listeners.add(listener);
64
- return () => this.listeners.delete(listener);
75
+ const subscribe = (listener: () => void): (() => void) => {
76
+ listeners.add(listener);
77
+ return () => listeners.delete(listener);
65
78
  };
66
79
 
67
- getSnapshot = (): StoreSnapshot => this.snapshot;
80
+ const getSnapshot = (): StoreSnapshot => snapshot;
68
81
 
69
82
  /** Poll at least this often until the returned function is called. */
70
- watch(intervalMs: number): () => void {
71
- this.watchers.push(intervalMs);
72
- this.schedule();
83
+ function watch(intervalMs: number): () => void {
84
+ watchers.push(intervalMs);
85
+ schedule();
73
86
  let watching = true;
74
87
  return () => {
75
88
  if (!watching) return;
76
89
  watching = false;
77
- const index = this.watchers.indexOf(intervalMs);
78
- if (index >= 0) this.watchers.splice(index, 1);
79
- this.schedule();
90
+ const index = watchers.indexOf(intervalMs);
91
+ if (index >= 0) watchers.splice(index, 1);
92
+ schedule();
80
93
  };
81
94
  }
82
95
 
83
96
  /** Poll quickly while something (a sign-in flow) is waiting on the daemon. */
84
- watchClosely(): () => void {
85
- return this.watch(ACTIVE_POLL_MS);
97
+ function watchClosely(): () => void {
98
+ return watch(ACTIVE_POLL_MS);
86
99
  }
87
100
 
88
- refresh(options: { refreshUsage?: boolean; fresh?: boolean } = {}): Promise<void> {
89
- if (this.inFlight && !options.refreshUsage) {
90
- if (!options.fresh) return this.inFlight;
91
- return this.inFlight.then(() => this.refresh({ refreshUsage: options.refreshUsage }));
101
+ function refresh(options: { refreshUsage?: boolean; fresh?: boolean } = {}): Promise<void> {
102
+ if (inFlight && !options.refreshUsage) {
103
+ if (!options.fresh) return inFlight;
104
+ return inFlight.then(() => refresh({ refreshUsage: options.refreshUsage }));
92
105
  }
93
- const sequence = ++this.issued;
94
- const run = this.client
106
+ const sequence = ++issued;
107
+ const run = client
95
108
  .rpc(getState, { refreshUsage: options.refreshUsage })
96
109
  .then((state) => {
97
110
  // An older, slower answer must not overwrite a newer one.
98
- if (sequence >= this.published) {
99
- this.published = sequence;
100
- this.publish({ state, error: null });
111
+ if (sequence >= published) {
112
+ published = sequence;
113
+ publish({ state, error: null });
101
114
  }
102
115
  })
103
116
  .catch((error: unknown) => {
104
- if (sequence >= this.published) this.publish({ state: this.snapshot.state, error: describe(error) });
117
+ if (sequence >= published) publish({ state: snapshot.state, error: describe(error) });
105
118
  })
106
119
  .finally(() => {
107
- if (this.inFlight === run) this.inFlight = null;
108
- this.schedule();
120
+ if (inFlight === run) inFlight = null;
121
+ schedule();
109
122
  });
110
- this.inFlight = run;
123
+ inFlight = run;
111
124
  return run;
112
125
  }
113
126
 
114
- private publish(next: StoreSnapshot): void {
115
- if (this.stopped) return;
116
- this.snapshot = next;
117
- for (const listener of [...this.listeners]) listener();
127
+ function publish(next: StoreSnapshot): void {
128
+ if (stopped) return;
129
+ snapshot = next;
130
+ for (const listener of [...listeners]) listener();
118
131
  }
119
132
 
120
- private schedule(): void {
121
- if (this.stopped) return;
122
- if (this.timer) clearTimeout(this.timer);
123
- const loginActive = this.snapshot.state?.logins.some((login) => isOpen(login.step)) ?? false;
124
- const delay = Math.min(IDLE_POLL_MS, loginActive ? ACTIVE_POLL_MS : IDLE_POLL_MS, ...this.watchers);
125
- this.timer = setTimeout(() => void this.refresh(), delay);
133
+ function schedule(): void {
134
+ if (stopped) return;
135
+ if (timer) clearTimeout(timer);
136
+ const loginActive = snapshot.state?.logins.some((login) => isOpen(login.step)) ?? false;
137
+ const delay = Math.min(IDLE_POLL_MS, loginActive ? ACTIVE_POLL_MS : IDLE_POLL_MS, ...watchers);
138
+ timer = setTimeout(() => void refresh(), delay);
126
139
  }
140
+
141
+ return {
142
+ get current() {
143
+ return snapshot;
144
+ },
145
+ start,
146
+ stop,
147
+ rpc,
148
+ subscribe,
149
+ getSnapshot,
150
+ watch,
151
+ watchClosely,
152
+ refresh,
153
+ };
127
154
  }
128
155
 
129
156
  function isOpen(step: string): boolean {
package/index.client.tsx CHANGED
@@ -3,12 +3,12 @@ import { AccountsSurface } from "./client/accounts-surface";
3
3
  import { contributeCommands } from "./client/commands";
4
4
  import { contributePills } from "./client/pills";
5
5
  import { PreferencesScreen } from "./client/settings-screen";
6
- import { ZeroSubStore } from "./client/store";
6
+ import { createZeroSubStore } from "./client/store";
7
7
  import { SwitchRowView } from "./client/switch-row";
8
8
  import { SWITCH_ROW_KIND, SWITCH_ROW_VERSION, SwitchRowSchema } from "./shared/timeline";
9
9
 
10
10
  export default function contribute(client: PluginClientContext) {
11
- const store = new ZeroSubStore(client);
11
+ const store = createZeroSubStore(client);
12
12
  store.start();
13
13
 
14
14
  client.addSurface("accounts", (props) => <AccountsSurface {...props} store={store} />);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kapybara/zerosub",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "description": "ZeroSub: use several Claude and ChatGPT (Codex) subscriptions side by side in Paseo. Add accounts in-app, pick one per agent, and switch automatically when an account hits its limit.",
5
5
  "keywords": [
6
6
  "paseo",
@@ -46,6 +46,7 @@
46
46
  "@tanstack/react-query": "^5.90.11",
47
47
  "@types/node": "^22.20.4",
48
48
  "@types/react": "~19.2.0",
49
+ "esbuild": "^0.28.2",
49
50
  "react": "19.1.0",
50
51
  "react-native": "0.81.5",
51
52
  "typescript": "^5.9.3",
package/server/claude.ts CHANGED
@@ -271,6 +271,7 @@ class ClaudeLogin extends ProgressEmitter implements LoginHandle {
271
271
  private poll: ReturnType<typeof setInterval> | null = null;
272
272
  private canceled = false;
273
273
  private exited = false;
274
+ private killTimer: ReturnType<typeof setTimeout> | undefined;
274
275
 
275
276
  constructor(command: string, args: string[], env: NodeJS.ProcessEnv, private readonly capture: string | null) {
276
277
  super();
@@ -295,14 +296,17 @@ class ClaudeLogin extends ProgressEmitter implements LoginHandle {
295
296
  resolve({ ok: false, message: friendlyFailure(failure ?? this.stderr.trim()) });
296
297
  });
297
298
  });
298
- this.child.stdout.on("data", (chunk: Buffer) => {
299
- this.stdout += stripAnsi(chunk.toString("utf8"));
299
+ // Decoding the stream, not each chunk, keeps a character split across two chunks whole.
300
+ this.child.stdout.setEncoding("utf8");
301
+ this.child.stderr.setEncoding("utf8");
302
+ this.child.stdout.on("data", (chunk: string) => {
303
+ this.stdout = (this.stdout + stripAnsi(chunk)).slice(-16_384);
300
304
  const manual = firstUrl(this.stdout, /\/oauth\/authorize/);
301
305
  if (manual && manual !== this.progress.codeUrl) this.update({ codeUrl: manual, step: "waiting" });
302
306
  });
303
- this.child.stderr.on("data", (chunk: Buffer) => {
304
- const text = stripAnsi(chunk.toString("utf8"));
305
- this.stderr += text;
307
+ this.child.stderr.on("data", (chunk: string) => {
308
+ const text = stripAnsi(chunk);
309
+ this.stderr = (this.stderr + text).slice(-16_384);
306
310
  if (/invalid code/i.test(text)) {
307
311
  this.update({ message: "That code didn't work. Copy the whole code from the page and paste it again." });
308
312
  }
@@ -332,11 +336,17 @@ class ClaudeLogin extends ProgressEmitter implements LoginHandle {
332
336
  }
333
337
 
334
338
  cancel(): void {
339
+ if (this.exited || this.canceled) return;
335
340
  this.canceled = true;
336
341
  this.child.kill("SIGTERM");
342
+ this.killTimer = setTimeout(() => {
343
+ if (!this.exited) this.child.kill("SIGKILL");
344
+ }, 3_000);
345
+ this.killTimer.unref();
337
346
  }
338
347
 
339
348
  private stop(): void {
349
+ clearTimeout(this.killTimer);
340
350
  if (this.poll) clearInterval(this.poll);
341
351
  if (this.capture) void rm(this.capture, { force: true });
342
352
  }
package/server/codex.ts CHANGED
@@ -20,10 +20,17 @@ const CLIENT_NAME = "codex_cli_rs";
20
20
 
21
21
  type Json = Record<string, unknown>;
22
22
 
23
+ const MAX_FRAME_BYTES = 1024 * 1024;
24
+ /** Its steps time out one by one, so without this a stuck read could keep its callers waiting ~150 s. */
25
+ const READ_DEADLINE_MS = 60_000;
26
+
23
27
  /** Newline-delimited JSON-RPC with `codex app-server` (no `jsonrpc` field on the wire). */
24
28
  class AppServer {
25
29
  private nextId = 1;
26
30
  private buffer = "";
31
+ /** Dropping the rest of a message over the limit, up to its newline. */
32
+ private skipping = false;
33
+ private warnedOversized = false;
27
34
  private stderr = "";
28
35
  private closed = false;
29
36
  private ending = false;
@@ -33,9 +40,12 @@ class AppServer {
33
40
 
34
41
  private constructor(private readonly child: ChildProcessWithoutNullStreams) {
35
42
  child.stdin.on("error", () => undefined);
36
- child.stdout.on("data", (chunk: Buffer) => this.receive(chunk.toString("utf8")));
37
- child.stderr.on("data", (chunk: Buffer) => {
38
- this.stderr = (this.stderr + chunk.toString("utf8")).slice(-4_000);
43
+ // Decoding the stream, not each chunk, keeps a character split across two chunks whole.
44
+ child.stdout.setEncoding("utf8");
45
+ child.stderr.setEncoding("utf8");
46
+ child.stdout.on("data", (text: string) => this.receive(text));
47
+ child.stderr.on("data", (text: string) => {
48
+ this.stderr = (this.stderr + text).slice(-4_000);
39
49
  });
40
50
  this.exited = new Promise((resolve) => {
41
51
  const finish = (error?: Error) => {
@@ -50,14 +60,17 @@ class AppServer {
50
60
  });
51
61
  }
52
62
 
53
- static async open(env: NodeJS.ProcessEnv): Promise<AppServer> {
63
+ static async open(env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<AppServer> {
54
64
  const { command, prefix } = await providerCommand("codex");
65
+ signal?.throwIfAborted();
55
66
  const child = spawn(command, [...prefix, "app-server"], { env, stdio: ["pipe", "pipe", "pipe"] });
56
67
  const server = new AppServer(child);
68
+ // Stops the session wherever it is, even while it is still starting.
69
+ signal?.addEventListener("abort", () => server.close(), { once: true });
57
70
  try {
58
71
  await server.request(
59
72
  "initialize",
60
- { clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.2.1" }, capabilities: { experimentalApi: false } },
73
+ { clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.3.0" }, capabilities: { experimentalApi: false } },
61
74
  60_000,
62
75
  );
63
76
  server.send({ method: "initialized" });
@@ -113,13 +126,25 @@ class AppServer {
113
126
  }
114
127
 
115
128
  private receive(text: string): void {
116
- this.buffer += text;
129
+ if (this.closed || this.ending) return;
130
+ let rest = text;
131
+ if (this.skipping) {
132
+ const end = rest.indexOf("\n");
133
+ if (end < 0) return;
134
+ this.skipping = false;
135
+ rest = rest.slice(end + 1);
136
+ }
137
+ this.buffer += rest;
117
138
  let newline = this.buffer.indexOf("\n");
118
139
  while (newline >= 0) {
119
- const line = this.buffer.slice(0, newline).trim();
140
+ const line = this.buffer.slice(0, newline);
120
141
  this.buffer = this.buffer.slice(newline + 1);
121
142
  newline = this.buffer.indexOf("\n");
122
- if (!line) continue;
143
+ if (Buffer.byteLength(line, "utf8") > MAX_FRAME_BYTES) {
144
+ this.skipOversized();
145
+ continue;
146
+ }
147
+ if (!line.trim()) continue;
123
148
  let message: Json;
124
149
  try {
125
150
  message = JSON.parse(line) as Json;
@@ -128,6 +153,19 @@ class AppServer {
128
153
  }
129
154
  this.dispatch(message);
130
155
  }
156
+ // A message still arriving can't be kept past the limit either: drop it and skip to its newline.
157
+ if (Buffer.byteLength(this.buffer, "utf8") > MAX_FRAME_BYTES) {
158
+ this.buffer = "";
159
+ this.skipping = true;
160
+ this.skipOversized();
161
+ }
162
+ }
163
+
164
+ /** Only that message is lost; the session and every other request carry on. */
165
+ private skipOversized(): void {
166
+ if (this.warnedOversized) return;
167
+ this.warnedOversized = true;
168
+ console.warn("[ZeroSub] skipped a Codex message over the 1 MiB limit");
131
169
  }
132
170
 
133
171
  private dispatch(message: Json): void {
@@ -162,7 +200,7 @@ export class CodexAdapter implements FamilyAdapter {
162
200
  /** ChatGPT accounts can't decrypt each other's reasoning, so threads stay on their account. */
163
201
  readonly portable = false;
164
202
  readonly usageSpacingMs = 20_000;
165
- private readonly snapshots = new Map<string, { at: number; value: Promise<Snapshot> }>();
203
+ private readonly snapshots = new Map<string, { at: number; pending: boolean; value: Promise<Snapshot> }>();
166
204
 
167
205
  async env(home: string | null): Promise<EnvPatch> {
168
206
  if (!home) return { CODEX_HOME: null, CODEX_SQLITE_HOME: null };
@@ -197,15 +235,39 @@ export class CodexAdapter implements FamilyAdapter {
197
235
  private snapshot(home: string | null, fresh = false): Promise<Snapshot> {
198
236
  const key = home ?? "";
199
237
  const cached = this.snapshots.get(key);
200
- if (cached && Date.now() - cached.at < (fresh ? 5_000 : 15_000)) return cached.value;
201
- const value = this.readSnapshot(home);
202
- this.snapshots.set(key, { at: Date.now(), value });
203
- value.catch(() => this.snapshots.delete(key));
238
+ if (cached && (cached.pending || Date.now() - cached.at < (fresh ? 5_000 : 15_000))) return cached.value;
239
+ const value = this.readWithDeadline(home).finally(() => {
240
+ const current = this.snapshots.get(key);
241
+ if (current?.value === value) {
242
+ current.pending = false;
243
+ current.at = Date.now();
244
+ }
245
+ });
246
+ this.snapshots.set(key, { at: Date.now(), pending: true, value });
247
+ value.catch(() => {
248
+ if (this.snapshots.get(key)?.value === value) this.snapshots.delete(key);
249
+ });
204
250
  return value;
205
251
  }
206
252
 
207
- private async readSnapshot(home: string | null): Promise<Snapshot> {
208
- const server = await AppServer.open(spawnEnv(await this.env(home)));
253
+ /** Everyone waiting shares this read, so when it runs out of time they all get the error and the app server stops. */
254
+ private readWithDeadline(home: string | null): Promise<Snapshot> {
255
+ const deadline = new AbortController();
256
+ return new Promise((resolve, reject) => {
257
+ const timer = setTimeout(() => {
258
+ const error = new Error(`Codex did not answer within ${READ_DEADLINE_MS / 1000} s`);
259
+ deadline.abort(error);
260
+ reject(error);
261
+ }, READ_DEADLINE_MS);
262
+ timer.unref();
263
+ this.readSnapshot(home, deadline.signal)
264
+ .then(resolve, reject)
265
+ .finally(() => clearTimeout(timer));
266
+ });
267
+ }
268
+
269
+ private async readSnapshot(home: string | null, signal: AbortSignal): Promise<Snapshot> {
270
+ const server = await AppServer.open(spawnEnv(await this.env(home)), signal);
209
271
  try {
210
272
  const account = ((await server.request("account/read", {})) ?? {}) as Json;
211
273
  const details = account.account as { type?: unknown; email?: unknown; planType?: unknown } | null;
package/server/process.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { spawn, type ChildProcess } from "node:child_process";
2
+ import { StringDecoder } from "node:string_decoder";
2
3
 
3
4
  export interface RunResult {
4
5
  code: number | null;
@@ -7,6 +8,8 @@ export interface RunResult {
7
8
  timedOut: boolean;
8
9
  }
9
10
 
11
+ const MAX_OUTPUT_BYTES = 1024 * 1024;
12
+
10
13
  /** Runs a command to completion with a timeout. Never throws for a non-zero exit. */
11
14
  export function run(
12
15
  command: string,
@@ -17,6 +20,10 @@ export function run(
17
20
  let stdout = "";
18
21
  let stderr = "";
19
22
  let timedOut = false;
23
+ let outputBytes = 0;
24
+ let outputExceeded = false;
25
+ const decoders = { stdout: new StringDecoder("utf8"), stderr: new StringDecoder("utf8") };
26
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
20
27
  let child: ChildProcess;
21
28
  try {
22
29
  child = spawn(command, [...args], {
@@ -28,21 +35,43 @@ export function run(
28
35
  resolve({ code: null, stdout, stderr: error instanceof Error ? error.message : String(error), timedOut });
29
36
  return;
30
37
  }
38
+ const terminate = () => {
39
+ if (killTimer) return;
40
+ clearTimeout(timer);
41
+ child.kill("SIGTERM");
42
+ killTimer = setTimeout(() => child.kill("SIGKILL"), 2_000);
43
+ killTimer.unref();
44
+ };
31
45
  const timer = setTimeout(() => {
32
46
  timedOut = true;
33
- child.kill("SIGTERM");
34
- setTimeout(() => child.kill("SIGKILL"), 2_000).unref();
47
+ terminate();
35
48
  }, options.timeoutMs ?? 30_000);
49
+ const collect = (chunk: Buffer, stream: "stdout" | "stderr") => {
50
+ if (outputExceeded) return;
51
+ const remaining = MAX_OUTPUT_BYTES - outputBytes;
52
+ const text = decoders[stream].write(chunk.subarray(0, remaining));
53
+ if (stream === "stdout") stdout += text;
54
+ else stderr += text;
55
+ outputBytes += chunk.length;
56
+ if (outputBytes > MAX_OUTPUT_BYTES) {
57
+ outputExceeded = true;
58
+ terminate();
59
+ }
60
+ };
36
61
  // A child that exits early turns our stdin write into EPIPE; without a listener that kills the plugin.
37
62
  child.stdin?.on("error", () => undefined);
38
- child.stdout?.on("data", (chunk: Buffer) => (stdout += chunk.toString("utf8")));
39
- child.stderr?.on("data", (chunk: Buffer) => (stderr += chunk.toString("utf8")));
63
+ child.stdout?.on("data", (chunk: Buffer) => collect(chunk, "stdout"));
64
+ child.stderr?.on("data", (chunk: Buffer) => collect(chunk, "stderr"));
40
65
  child.on("error", (error) => {
41
66
  stderr += error.message;
42
67
  });
43
68
  child.on("close", (code) => {
44
69
  clearTimeout(timer);
45
- resolve({ code, stdout, stderr, timedOut });
70
+ clearTimeout(killTimer);
71
+ stdout += decoders.stdout.end();
72
+ stderr += decoders.stderr.end();
73
+ if (outputExceeded) stderr = `Command output exceeded the 1 MiB limit.${stderr ? `\n${stderr}` : ""}`;
74
+ resolve({ code: outputExceeded ? null : code, stdout, stderr, timedOut });
46
75
  });
47
76
  if (options.input !== undefined) child.stdin?.end(options.input);
48
77
  else child.stdin?.end();
package/server/reopen.ts CHANGED
@@ -26,11 +26,16 @@ export class Reopener {
26
26
  async reopen(agentId: string): Promise<{ ok: true } | { ok: false; error: string; timedOut: boolean }> {
27
27
  const cli = await this.locate();
28
28
  if (!cli) return { ok: false, error: "The paseo command-line tool was not found on the daemon machine.", timedOut: false };
29
+ const args = ["agent", "reload", agentId, "--json", "--home", paseoHome()];
30
+ // Node refuses to execFile a .cmd/.bat without a shell (spawn EINVAL), so run it through cmd.exe.
31
+ const viaCmd = process.platform === "win32" && /\.(cmd|bat)$/i.test(cli);
32
+ const file = viaCmd ? (process.env.ComSpec ?? "cmd.exe") : cli;
33
+ const argv = viaCmd ? ["/d", "/s", "/c", `"${[cli, ...args].map((part) => `"${part}"`).join(" ")}"`] : args;
29
34
  return new Promise((resolve) => {
30
35
  execFile(
31
- cli,
32
- ["agent", "reload", agentId, "--json", "--home", paseoHome()],
33
- { timeout: 90_000, maxBuffer: 1024 * 1024, env: process.env },
36
+ file,
37
+ argv,
38
+ { timeout: 90_000, maxBuffer: 1024 * 1024, env: process.env, windowsVerbatimArguments: viaCmd },
34
39
  (error, _stdout, stderr) => {
35
40
  if (!error) return resolve({ ok: true });
36
41
  const detail = `${stderr || error.message}`.trim().split("\n").slice(-3).join(" ");
@@ -57,16 +62,17 @@ async function isExecutable(path: string): Promise<boolean> {
57
62
  }
58
63
  }
59
64
 
60
- async function findCli(): Promise<string | null> {
65
+ export async function findCli(exec: string = process.execPath): Promise<string | null> {
61
66
  const candidates: string[] = [];
62
67
  const executable = process.platform === "win32" ? "paseo.cmd" : "paseo";
63
68
 
64
69
  // The daemon (and this subprocess) usually run inside the desktop app bundle, which ships the CLI.
65
- const exec = process.execPath;
66
70
  const appContents = exec.match(/^(.*?\.app\/Contents)\//)?.[1];
67
71
  if (appContents) candidates.push(join(appContents, "Resources", "bin", "paseo"));
68
72
  const resources = findAncestor(exec, "resources");
69
73
  if (resources) candidates.push(join(resources, "bin", executable));
74
+ // The Windows desktop app keeps `resources/` beside Paseo.exe, not above it.
75
+ candidates.push(join(dirname(exec), "resources", "bin", executable));
70
76
 
71
77
  for (const directory of (process.env.PATH ?? "").split(delimiter)) {
72
78
  if (directory) candidates.push(join(directory, executable));
package/server/service.ts CHANGED
@@ -40,7 +40,7 @@ import { homesDir } from "./paths";
40
40
  import { Reopener } from "./reopen";
41
41
  import { SwitchGuard } from "./switch-guard";
42
42
  import { loadReadings, mergeUsage, saveReadings, showLimit } from "./usage";
43
- import { chooseAccount, isLimited, mostAvailable } from "./routing";
43
+ import { chooseAccount, isLimited, isUsable, mostAvailable } from "./routing";
44
44
  import {
45
45
  MAIN_ACCOUNT_ID,
46
46
  StateStore,
@@ -79,11 +79,14 @@ const PRUNE_MS = 10 * 60_000;
79
79
  /** After a reset, limit notices from turns that were already running are stale. */
80
80
  const RESET_GRACE_MS = 5 * 60_000;
81
81
  const AGENT_LIST_MS = 3_000;
82
+ /** How long a default change waits for sessions already being routed to record their account. */
83
+ const ROUTING_WAIT_MS = 5_000;
82
84
 
83
85
  const DEFAULT_PREFERENCES: Preferences = {
84
86
  autoSwitch: true,
85
87
  autoContinue: true,
86
88
  continuePrompt: DEFAULT_CONTINUE_PROMPT,
89
+ moveAgentsOnDefaultChange: true,
87
90
  balanceNewAgents: false,
88
91
  showComposerPill: true,
89
92
  autoRedeem: false,
@@ -140,6 +143,8 @@ export class Service {
140
143
  private readonly deferred = new Map<string, SwitchRow | null>();
141
144
  /** Agents in the middle of a failover, so nothing else moves them at the same time. */
142
145
  private readonly switching = new Set<string>();
146
+ /** Interactive sessions being routed right now, and their agents. Where each opens isn't recorded yet. */
147
+ private readonly routing = new Map<Promise<unknown>, string>();
143
148
  /** One failover at a time per exhausted account. */
144
149
  private readonly failoverLocks = new Map<string, Mutex>();
145
150
  private readonly switchGuard = new SwitchGuard();
@@ -339,6 +344,20 @@ export class Service {
339
344
  async onSessionOpen(
340
345
  request: PluginSessionOpenRequest,
341
346
  context: PluginHookContext,
347
+ ): Promise<PluginSessionOpenRequest | undefined> {
348
+ const routed = this.route(request, context);
349
+ if (request.purpose !== "interactive") return routed;
350
+ this.routing.set(routed, request.agentId);
351
+ try {
352
+ return await routed;
353
+ } finally {
354
+ this.routing.delete(routed);
355
+ }
356
+ }
357
+
358
+ private async route(
359
+ request: PluginSessionOpenRequest,
360
+ context: PluginHookContext,
342
361
  ): Promise<PluginSessionOpenRequest | undefined> {
343
362
  this.attach(context.paseo);
344
363
  const family = (await this.families.resolve(context.paseo))[request.provider];
@@ -1303,10 +1322,18 @@ export class Service {
1303
1322
  if (!account) throw new Error("That account no longer exists.");
1304
1323
  if (!account.signedIn) throw new Error(`${account.label} is signed out. Sign it in first.`);
1305
1324
  if (account.disabled) throw new Error(`${account.label} is disabled. Enable it before making it the default.`);
1306
- if (!this.adapters[account.family].portable) await this.pinThreads(paseo, account.family);
1325
+ const portable = this.adapters[account.family].portable;
1326
+ if (!portable) await this.pinThreads(paseo, account.family);
1307
1327
  await this.store.update((draft) => {
1308
1328
  draft.defaults[account.family] = account.id;
1309
1329
  });
1330
+ if (portable && !this.prefs.moveAgentsOnDefaultChange) {
1331
+ // The new default is for what comes next: open agents stay on the account they run on.
1332
+ const { kept, moving } = await this.keepOpenAgents(paseo, account.family, account.id);
1333
+ console.log(`[ZeroSub] ${account.label} is the default now; ${kept} open agent(s) stay on their account`);
1334
+ // Agents that can't stay where they are move as they would with the switch on; nothing else does.
1335
+ return moving.length > 0 ? this.reconcile(paseo, "default", moving) : emptySummary();
1336
+ }
1310
1337
  // Conversations that can't move (Codex threads) are pinned, so this only moves portable ones.
1311
1338
  return this.reconcile(paseo, "default");
1312
1339
  }
@@ -1366,6 +1393,50 @@ export class Service {
1366
1393
  });
1367
1394
  }
1368
1395
 
1396
+ /**
1397
+ * Pins each open agent that follows the default to the account it runs on, so the new default
1398
+ * doesn't move it, now or when it next opens. Runs once the new default is in place, so an agent
1399
+ * that opened under the old one just before is kept too, even if its session was still being
1400
+ * routed. Agents already on the new default keep following it. An account that's gone, signed
1401
+ * out, disabled or at its limit is no place to keep work, so those agents come back in `moving`.
1402
+ */
1403
+ private async keepOpenAgents(
1404
+ paseo: PaseoApi,
1405
+ family: Family,
1406
+ newDefault: string,
1407
+ ): Promise<{ kept: number; moving: string[] }> {
1408
+ // A session being routed may have gone by the old default: let it record where it opens first.
1409
+ if (this.routing.size > 0) await withTimeout(Promise.allSettled(this.routing.keys()), ROUTING_WAIT_MS);
1410
+ const families = await this.families.resolve(paseo);
1411
+ const open = (await listAgents(paseo, false)).agents.filter(
1412
+ (agent) => families[agent.provider] === family && !agent.archived && isLive(agent.status),
1413
+ );
1414
+ let kept = 0;
1415
+ const moving: string[] = [];
1416
+ if (open.length === 0) return { kept, moving };
1417
+ const now = Date.now();
1418
+ const at = new Date(now).toISOString();
1419
+ await this.store.update((draft) => {
1420
+ // Where these open isn't recorded yet, and a session routed now goes by the new default.
1421
+ const routing = new Set(this.routing.values());
1422
+ for (const agent of open) {
1423
+ if (routing.has(agent.id)) continue;
1424
+ // An agent with an account of its own never followed the default.
1425
+ if (findAccount(draft, draft.bindings[agent.id]?.accountId)?.family === family) continue;
1426
+ // Still starting, and not routed yet: it will be, by the new default.
1427
+ if (agent.status === "initializing" && !draft.sessions[agent.id]) continue;
1428
+ const current = findAccount(draft, this.runningOn(draft, agent.id, family));
1429
+ if (!current || current.family !== family || !isUsable(current, now)) moving.push(agent.id);
1430
+ else if (current.id !== newDefault) {
1431
+ // "auto", like a limit switch, so the account button still offers "Follow default".
1432
+ draft.bindings[agent.id] = { accountId: current.id, source: "auto", at };
1433
+ kept += 1;
1434
+ }
1435
+ }
1436
+ });
1437
+ return { kept, moving };
1438
+ }
1439
+
1369
1440
  async clearLimit(accountId: string): Promise<void> {
1370
1441
  const state = await this.store.update((draft) => {
1371
1442
  const account = findAccount(draft, accountId);
package/server/state.ts CHANGED
@@ -33,7 +33,8 @@ export type StoredAccount = z.infer<typeof StoredAccountSchema>;
33
33
  export const BindingSchema = z.object({
34
34
  accountId: z.string(),
35
35
  /**
36
- * `user`: chosen in the UI. `auto`: moved after a limit. `balance`: spread at creation.
36
+ * `user`: chosen in the UI. `auto`: moved after a limit, or kept on its account when the default
37
+ * changed. `balance`: spread at creation.
37
38
  * `thread`: a conversation that can't change accounts, pinned where it started.
38
39
  */
39
40
  source: z.enum(["user", "auto", "balance", "thread"]),
@@ -15,6 +15,13 @@ export const preferences = defineSettings({
15
15
  /** After an automatic switch, send a follow-up so the interrupted turn keeps going. */
16
16
  autoContinue: z.boolean().default(true),
17
17
  continuePrompt: z.string().trim().min(1).max(500).default(DEFAULT_CONTINUE_PROMPT),
18
+ /**
19
+ * When the default account changes, open agents that follow it move to the new one. Off, each
20
+ * stays pinned to the account it runs on (so it stays there when it next opens too), unless that
21
+ * account can't be used right now, and the new default is for new agents and ones that aren't
22
+ * open at the time. Codex threads never move either way.
23
+ */
24
+ moveAgentsOnDefaultChange: z.boolean().default(true),
18
25
  /** New agents start on the account with the most headroom instead of the default. */
19
26
  balanceNewAgents: z.boolean().default(false),
20
27
  /** When every account of a provider is at its limit, spend a banked reset instead of stopping. */