@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/shared/model.ts CHANGED
@@ -1,14 +1,53 @@
1
1
  import { z } from "zod";
2
2
 
3
- /** The two subscription families this plugin manages. Custom provider profiles map onto one of them. */
4
- export const FamilySchema = z.enum(["claude", "codex"]);
3
+ /**
4
+ * The provider families this plugin manages: the subscription CLIs (Claude Code, Codex, Grok Build,
5
+ * Cursor), and Pi, whose added accounts are Anthropic API keys. Custom provider profiles map onto one of them.
6
+ */
7
+ export const FamilySchema = z.enum(["claude", "codex", "pi", "grok", "cursor"]);
5
8
  export type Family = z.infer<typeof FamilySchema>;
9
+ export const FAMILIES: readonly Family[] = FamilySchema.options;
6
10
 
7
11
  export const FAMILY_LABEL: Record<Family, string> = {
8
12
  claude: "Claude",
9
13
  codex: "ChatGPT",
14
+ pi: "Pi",
15
+ grok: "Grok",
16
+ cursor: "Cursor",
10
17
  };
11
18
 
19
+ /** Paseo's OpenCode harness provider. It runs on the host itself, so a fork to it uses no account. */
20
+ export const OPENCODE_PROVIDER = "opencode";
21
+ export const OPENCODE_LABEL = "OpenCode";
22
+ /**
23
+ * The provider a stopped chat can carry on with when every account of its own is out (Claude ↔
24
+ * ChatGPT); null for Pi, whose added accounts are billed per use and never take work over by themselves,
25
+ * and for Grok and Cursor, whose chats don't fork to another provider.
26
+ */
27
+ export const OTHER_FAMILY: Record<Family, Family | null> = { claude: "codex", codex: "claude", pi: null, grok: null, cursor: null };
28
+
29
+ /**
30
+ * Families not every Paseo user runs: one shows once its CLI login is registered (its CLI is there,
31
+ * and for Grok and Cursor a Paseo provider runs it) or an account of it was added, and its CLI is only
32
+ * missed once an account of it was added.
33
+ */
34
+ export const OPTIONAL: Record<Family, boolean> = { claude: false, codex: false, pi: true, grok: true, cursor: true };
35
+
36
+ /** The families the Accounts screen shows, given the accounts there are (the CLI logins registered included). */
37
+ export function shownFamilies(accounts: readonly { family: Family }[]): Family[] {
38
+ return FAMILIES.filter((family) => !OPTIONAL[family] || accounts.some((account) => account.family === family));
39
+ }
40
+
41
+ /**
42
+ * For a provider whose conversations can't change accounts in place: one with history carries on in a
43
+ * new agent on the account picked for it (Codex's). False for Grok's and Cursor's, which stay on their
44
+ * account until moving them is known to work; only new agents follow a pick or the default.
45
+ */
46
+ export const HAND_OFF: Record<Family, boolean> = { claude: true, codex: true, pi: true, grok: false, cursor: false };
47
+
48
+ /** Stands for a proxy's password (or a user name with none) wherever the proxy is shown. */
49
+ export const HIDDEN = "•••";
50
+
12
51
  export const UsageWindowSchema = z.object({
13
52
  /** Stable key, e.g. `five_hour`, `seven_day`, `seven_day_opus`, `primary`, `secondary`. */
14
53
  id: z.string(),
@@ -46,6 +85,20 @@ export const CreditsSchema = z.object({
46
85
  });
47
86
  export type Credits = z.infer<typeof CreditsSchema>;
48
87
 
88
+ /**
89
+ * Pay-as-you-go usage past the plan's limits (Claude "extra usage"), as the usage response reports it.
90
+ * `spend` and `limit` are Claude's `used_credits` and `monthly_limit`, in minor units of `currency`
91
+ * (cents for USD); `null` when the response leaves those amounts out. A read without spend omits
92
+ * `extraUsage`, keeping the last known value; a successful spend read can clear it with `null`.
93
+ */
94
+ export const ExtraUsageSchema = z.object({
95
+ enabled: z.boolean(),
96
+ spend: z.number().nullable().default(null),
97
+ limit: z.number().nullable().default(null),
98
+ currency: z.string().nullable().default(null),
99
+ });
100
+ export type ExtraUsage = z.infer<typeof ExtraUsageSchema>;
101
+
49
102
  export const UsageSchema = z.object({
50
103
  fetchedAt: z.string(),
51
104
  windows: z.array(UsageWindowSchema),
@@ -57,6 +110,8 @@ export const UsageSchema = z.object({
57
110
  resets: ResetOfferSchema.nullable().default(null),
58
111
  /** Credits the account can spend past full windows, when the provider reports any. */
59
112
  credits: CreditsSchema.nullable().default(null),
113
+ /** Claude extra usage, when the usage response reports it. Shown on the account card. */
114
+ extraUsage: ExtraUsageSchema.nullable().optional(),
60
115
  });
61
116
  export type Usage = z.infer<typeof UsageSchema>;
62
117
 
@@ -68,10 +123,203 @@ export const AccountKindSchema = z.enum([
68
123
  ]);
69
124
  export type AccountKind = z.infer<typeof AccountKindSchema>;
70
125
 
126
+ export const AuthKindSchema = z.enum([
127
+ /** Signed in with a Claude or ChatGPT subscription (or, for Pi's own login, whatever Pi is signed in to). */
128
+ "subscription",
129
+ /**
130
+ * An API key or token (a Claude account's, optionally against another base URL; an added Pi
131
+ * account's Anthropic key; an Azure OpenAI account's), billed per use, so never picked
132
+ * automatically. An Azure OpenAI account can be, as a last resort, once `paidApiFallback` is on.
133
+ */
134
+ "api",
135
+ ]);
136
+ export type AuthKind = z.infer<typeof AuthKindSchema>;
137
+
138
+ /**
139
+ * The paid API behind an `api` account that stands in for a subscription, set when it's added. Never
140
+ * inferred from `auth`: a Claude or Pi API-key account has none, and is only used when chosen.
141
+ */
142
+ export const ApiProviderSchema = z.enum([
143
+ /** An Azure OpenAI resource, under ChatGPT (Codex). */
144
+ "azure",
145
+ ]);
146
+ export type ApiProvider = z.infer<typeof ApiProviderSchema>;
147
+
148
+ /** An Azure OpenAI account: a ChatGPT (Codex) account added as one, marked `provider: "azure"`. */
149
+ export function isAzureAccount(account: { family: Family; provider?: ApiProvider }): boolean {
150
+ return account.family === "codex" && account.provider === "azure";
151
+ }
152
+
153
+ export const ApiKeyKindSchema = z.enum([
154
+ /** `ANTHROPIC_API_KEY`, sent as `x-api-key`. */
155
+ "api_key",
156
+ /** `ANTHROPIC_AUTH_TOKEN`, sent as `Authorization: Bearer`. */
157
+ "auth_token",
158
+ ]);
159
+ export type ApiKeyKind = z.infer<typeof ApiKeyKindSchema>;
160
+
161
+ /** Claude Code's own switches for a Claude API account; each is off unless the user turns it on. */
162
+ export const TrafficSwitchesSchema = z.object({
163
+ /** `DISABLE_TELEMETRY`. */
164
+ disableTelemetry: z.boolean().default(false),
165
+ /** `DISABLE_ERROR_REPORTING`. */
166
+ disableErrorReporting: z.boolean().default(false),
167
+ /** `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`: everything not needed to talk to the model. */
168
+ disableNonessentialTraffic: z.boolean().default(false),
169
+ });
170
+ export type TrafficSwitches = z.infer<typeof TrafficSwitchesSchema>;
171
+
172
+ /** An API key's settings as shown in the app; the key itself never leaves the host. */
173
+ export const ApiSummarySchema = TrafficSwitchesSchema.extend({
174
+ /** Left out by providers whose accounts only take an API key (Pi's). */
175
+ keyKind: ApiKeyKindSchema.default("api_key"),
176
+ /** The key's last four characters, or empty for a key too short to show any of it. */
177
+ keyHint: z.string(),
178
+ /** Where Anthropic's requests go, or null for Anthropic's own API. */
179
+ baseUrl: z.string().nullable(),
180
+ });
181
+ /** As an adapter gives it: the kind and switches may be left out, and are filled in for the client. */
182
+ export type ApiSummary = z.input<typeof ApiSummarySchema>;
183
+
184
+ /** USD per million tokens for one model on a paid API account; null where the user left it empty. */
185
+ export const ApiPriceSchema = z.object({
186
+ input: z.number().nonnegative().nullable().default(null),
187
+ /** Cached input (OpenAI), or cache reads (Anthropic). */
188
+ cachedInput: z.number().nonnegative().nullable().default(null),
189
+ /** Cache writes (Anthropic); Azure OpenAI has none. */
190
+ cacheWrite: z.number().nonnegative().nullable().default(null),
191
+ output: z.number().nonnegative().nullable().default(null),
192
+ });
193
+ export type ApiPrice = z.infer<typeof ApiPriceSchema>;
194
+
195
+ /**
196
+ * Tokens one model used. `input` is every input token, cached ones included (as OpenAI and Codex
197
+ * count them): `cachedInput` of them were read from the cache, and `cacheWrite` written to it.
198
+ */
199
+ export const TokenCountSchema = z.object({
200
+ input: z.number().nonnegative().default(0),
201
+ cachedInput: z.number().nonnegative().default(0),
202
+ cacheWrite: z.number().nonnegative().default(0),
203
+ output: z.number().nonnegative().default(0),
204
+ });
205
+ export type TokenCount = z.infer<typeof TokenCountSchema>;
206
+
207
+ /** A paid API account's tokens this calendar month (UTC), as its CLI counted them, by model. */
208
+ export const ApiMonthSchema = z.object({
209
+ /** `YYYY-MM`, UTC. */
210
+ month: z.string(),
211
+ models: z.record(z.string(), TokenCountSchema).default({}),
212
+ /** Turns that ended on the account whose tokens couldn't be read (no session file found). */
213
+ uncounted: z.number().nonnegative().default(0),
214
+ updatedAt: z.string().nullable().default(null),
215
+ });
216
+ export type ApiMonth = z.infer<typeof ApiMonthSchema>;
217
+
218
+ /** Month key (`YYYY-MM`, UTC) API token totals are kept under. */
219
+ export function usageMonth(at: number | Date = Date.now()): string {
220
+ return new Date(at).toISOString().slice(0, 7);
221
+ }
222
+
223
+ /**
224
+ * The estimated cost of `month` at `prices` (USD per million tokens, by model). `complete` is false
225
+ * when a model that used tokens has no price, or a price it needs is empty; `usd` then counts only
226
+ * what has a price, and is null when nothing does.
227
+ */
228
+ export function estimateApiCost(month: ApiMonth | null, prices: Readonly<Record<string, ApiPrice>>): { usd: number | null; complete: boolean } {
229
+ if (!month) return { usd: null, complete: true };
230
+ let usd = 0;
231
+ let priced = false;
232
+ let complete = true;
233
+ for (const [model, count] of Object.entries(month.models)) {
234
+ const price = prices[model];
235
+ const uncached = Math.max(0, count.input - count.cachedInput - count.cacheWrite);
236
+ const parts: Array<[number, number | null | undefined]> = [
237
+ [uncached, price?.input],
238
+ // Cache reads or writes without a price of their own are counted at the input price.
239
+ [count.cachedInput, price?.cachedInput ?? price?.input],
240
+ [count.cacheWrite, price?.cacheWrite ?? price?.input],
241
+ [count.output, price?.output],
242
+ ];
243
+ for (const [tokens, perMillion] of parts) {
244
+ if (tokens === 0) continue;
245
+ if (perMillion == null) {
246
+ complete = false;
247
+ continue;
248
+ }
249
+ usd += (tokens / 1_000_000) * perMillion;
250
+ priced = true;
251
+ }
252
+ }
253
+ return { usd: priced ? usd : null, complete };
254
+ }
255
+
256
+ /** A month's tokens over every model. */
257
+ export function totalTokens(month: ApiMonth | null): TokenCount {
258
+ const total = { input: 0, cachedInput: 0, cacheWrite: 0, output: 0 };
259
+ for (const count of Object.values(month?.models ?? {})) {
260
+ total.input += count.input;
261
+ total.cachedInput += count.cachedInput;
262
+ total.cacheWrite += count.cacheWrite;
263
+ total.output += count.output;
264
+ }
265
+ return total;
266
+ }
267
+
268
+ /** An Azure OpenAI account (a ChatGPT/Codex account on an API key) as the app sees it. The key never leaves the host. */
269
+ export const AzureSummarySchema = z.object({
270
+ /** The endpoint's base URL, e.g. `https://<resource>.openai.azure.com/openai/v1`. */
271
+ endpoint: z.string(),
272
+ host: z.string(),
273
+ /** The key's last four characters, or empty for a key too short to show any of it. */
274
+ keyHint: z.string(),
275
+ /** USD per million tokens, by model (deployment name). */
276
+ prices: z.record(z.string(), ApiPriceSchema).default({}),
277
+ /** This month's tokens; null before the first counted turn. */
278
+ usage: ApiMonthSchema.nullable().default(null),
279
+ });
280
+ export type AzureSummary = z.infer<typeof AzureSummarySchema>;
281
+
282
+ /** The address an account's requests come from, as the provider's edge sees it. */
283
+ export const EgressSchema = z.object({
284
+ /** From the last check that worked. */
285
+ ip: z.string().nullable(),
286
+ /** The country the edge places it in, like "US". */
287
+ country: z.string().nullable(),
288
+ /** When that check was. */
289
+ checkedAt: z.string().nullable(),
290
+ /** Why the latest check failed, when it did. */
291
+ error: z.string().nullable(),
292
+ });
293
+ export type Egress = z.infer<typeof EgressSchema>;
294
+
71
295
  /** `disabled`: the user set it aside for a while; it stays signed in but nothing is routed to it. */
72
296
  export const AccountStatusSchema = z.enum(["ready", "signed_out", "limited", "checking", "disabled"]);
73
297
  export type AccountStatus = z.infer<typeof AccountStatusSchema>;
74
298
 
299
+ /** An account projected to this share of its 5-hour window, or already there, is held back when spreading. */
300
+ export const PACE_GATE_PERCENT = 80;
301
+
302
+ /** How pacing reads an account (see `paceScore` in server/routing.ts). Sent only while spreading is on. */
303
+ export const PaceViewSchema = z.object({
304
+ /** 5-hour use in the latest reading; 0 once that window has reset; null with no 5-hour reading. */
305
+ fiveHourUsed: z.number().nullable(),
306
+ /** `paceScore(...).fiveHour`: projected an hour ahead, pending agents included. */
307
+ fiveHourProjected: z.number(),
308
+ /** The part of `fiveHourProjected` charged for pending agents. */
309
+ pendingFiveHour: z.number(),
310
+ /** Weekly use in the latest reading; 0 once it has reset; null with no weekly reading. */
311
+ weeklyUsed: z.number().nullable(),
312
+ /** Weekly percent charged for pending agents. */
313
+ pendingWeekly: z.number(),
314
+ /** Percent of the week gone at the reading, 0 to 100; null when the reset time is unknown or passed. */
315
+ weekElapsed: z.number().nullable(),
316
+ /** Agents placed here in the last `PENDING_MS` that the reading may not show. */
317
+ pending: z.number(),
318
+ /** `paceScore(...).gated`: new agents go to accounts under the gate first. */
319
+ gated: z.boolean(),
320
+ });
321
+ export type PaceView = z.infer<typeof PaceViewSchema>;
322
+
75
323
  export const AccountViewSchema = z.object({
76
324
  id: z.string(),
77
325
  family: FamilySchema,
@@ -82,10 +330,47 @@ export const AccountViewSchema = z.object({
82
330
  organization: z.string().nullable(),
83
331
  status: AccountStatusSchema,
84
332
  isDefault: z.boolean(),
333
+ /** Set while the next new agent of this family will start on this account (one-time pick). */
334
+ nextAgentUntil: z.string().nullable().optional(),
85
335
  limitedUntil: z.string().nullable(),
86
336
  usage: UsageSchema.nullable(),
87
337
  agentCount: z.number(),
88
338
  home: z.string().nullable(),
339
+ auth: AuthKindSchema.default("subscription"),
340
+ /** An added Pi account's key (reduced to a hint) and base URL, and Pi's own login's while it keeps an Anthropic key. */
341
+ api: ApiSummarySchema.nullable().default(null),
342
+ /** Its key and base URL can be changed from its card (API accounts, and Pi's own login). */
343
+ apiEditable: z.boolean().default(false),
344
+ /** The account's own proxy, password hidden (as `HIDDEN`). Null when it uses whatever it inherits. */
345
+ proxy: z.string().nullable().default(null),
346
+ /** A proxy can be set for this account here (Claude and Pi accounts, their CLI logins included). */
347
+ proxyEditable: z.boolean().default(false),
348
+ /** Why a proxy can't be set for it just now (the CLI login's, while main's settings would outrank it); null when one can. */
349
+ proxyBlocked: z.string().nullable().default(null),
350
+ /** The proxy it goes through without one of its own, password hidden, and where that's set. */
351
+ inheritedProxy: z.object({ proxy: z.string(), from: z.string() }).nullable().default(null),
352
+ /**
353
+ * The user's file its own proxy is kept in (Pi's own login: `httpProxy` in `~/.pi/agent/settings.json`;
354
+ * Claude's CLI login: `env` in `~/.claude/settings.json`, when that sets one).
355
+ */
356
+ proxyFile: z.string().nullable().default(null),
357
+ /** Added accounts that go through the same proxy, having none of their own, while it's kept in `proxyFile`. */
358
+ proxyFollowers: z.array(z.string()).default([]),
359
+ /** Command (a script in `StateView.launchers` or `StateView.piLaunchers`) that starts the CLI on this account. */
360
+ launcher: z.string().nullable().default(null),
361
+ /** Where the account's requests come from, as Anthropic sees them; null when unknown or not Anthropic. */
362
+ egress: EgressSchema.nullable().default(null),
363
+ /**
364
+ * The home is outside ZeroSub's own `homes/` folder (where added Pi accounts are kept): removing the
365
+ * account only takes it out of ZeroSub, and its folder, key and script stay.
366
+ */
367
+ externalHome: z.boolean().default(false),
368
+ /** Set for an Azure OpenAI account (a ChatGPT/Codex account on an API key); null for any other. */
369
+ azure: AzureSummarySchema.nullable().default(null),
370
+ /** The account's home is due to move to `to`, and hasn't yet: what it waits for, or what went wrong. */
371
+ moving: z.object({ to: z.string(), waiting: z.string().nullable(), error: z.string().nullable() }).nullable().default(null),
372
+ /** How pacing reads this account; null unless spreading is on and it's one of two or more accounts that can stand in. */
373
+ pace: PaceViewSchema.nullable().default(null),
89
374
  });
90
375
  export type AccountView = z.infer<typeof AccountViewSchema>;
91
376
 
@@ -98,6 +383,13 @@ export const AgentRouteSchema = z.object({
98
383
  pinned: z.boolean(),
99
384
  /** The live session still runs on a different account and is waiting to be reopened. */
100
385
  pendingAccountId: z.string().nullable(),
386
+ /**
387
+ * While `pendingAccountId` is set, when the session moves: `idle` once the agent is idle (within
388
+ * half a minute), `turn` when its current turn ends, `background` once background work it left
389
+ * running stops, `restart` when its session next starts (it isn't moved unattended, reloading it
390
+ * didn't work, or Paseo's CLI isn't there to do it).
391
+ */
392
+ waiting: z.enum(["idle", "turn", "background", "restart"]).nullable().default(null),
101
393
  /**
102
394
  * The conversation can move to another account in place. False for Codex agents that already
103
395
  * have history: ChatGPT accounts can't read each other's encrypted reasoning, so switching
@@ -106,6 +398,12 @@ export const AgentRouteSchema = z.object({
106
398
  movable: z.boolean(),
107
399
  /** The agent started on this account because its weekly reset was near, and is still on it. */
108
400
  selectionReason: z.literal("weekly_reset").optional(),
401
+ /**
402
+ * Whether the Account control can show in this agent's composer: its metadata holds its ID (see
403
+ * `AGENT_METADATA_KEY`), or is being given it. False for an agent from before the control that
404
+ * hasn't opened a session since, and for one that couldn't be given it: the account button stands in.
405
+ */
406
+ inComposer: z.boolean().optional(),
109
407
  });
110
408
  export type AgentRoute = z.infer<typeof AgentRouteSchema>;
111
409
 
@@ -146,6 +444,20 @@ export const LoginViewSchema = z.object({
146
444
  });
147
445
  export type LoginView = z.infer<typeof LoginViewSchema>;
148
446
 
447
+ /**
448
+ * Agent metadata (Paseo 0.16 and later) naming the account a new agent starts on. The account
449
+ * control in a composer that has no agent yet sets it, and anything else that creates an agent can
450
+ * (`paseo.agents.create({ metadata })`). Routing reads it once, when the agent is created.
451
+ */
452
+ export const ACCOUNT_METADATA_KEY = "zerosub.account";
453
+
454
+ /**
455
+ * Agent metadata holding the agent's own ID. Paseo doesn't tell a composer item which agent's
456
+ * composer it sits in, only that agent's metadata, so the daemon writes the ID there and the
457
+ * Account control reads it back to find the agent's account.
458
+ */
459
+ export const AGENT_METADATA_KEY = "zerosub.agent";
460
+
149
461
  export const StateViewSchema = z.object({
150
462
  accounts: z.array(AccountViewSchema),
151
463
  agents: z.array(AgentRouteSchema),
@@ -159,7 +471,32 @@ export const StateViewSchema = z.object({
159
471
  * and daemons started over SSH, where only the code sign-in works.
160
472
  */
161
473
  browserSignIn: z.boolean().default(true),
474
+ /** Directory with a `claude-<account>.sh` script per added Claude account, to put on `PATH`. */
475
+ launchers: z.string().nullable().default(null),
476
+ /** Directory with a `pi-<account>.sh` script per added Pi account, to put on `PATH`. */
477
+ piLaunchers: z.string().nullable().default(null),
478
+ /** The folder added Pi accounts' homes are kept in (`~/.pi-config`, say), and whether it's the default. */
479
+ piHomes: z.object({ dir: z.string(), isDefault: z.boolean() }).nullable().default(null),
480
+ /** The folder added Claude accounts' homes are kept in (`~/.claude-config`, say), and whether it's the default. */
481
+ claudeHomes: z.object({ dir: z.string(), isDefault: z.boolean() }).nullable().default(null),
162
482
  showComposerPill: z.boolean(),
483
+ /** This host's Paseo lists OpenCode as available, so "Continue on OpenCode" can work. */
484
+ openCodeAvailable: z.boolean().default(false),
485
+ /** Accounts at their limit are skipped, so agents can't be moved onto one by hand either. */
486
+ autoSwitch: z.boolean().default(true),
487
+ /** New agents without an account of their own start on the one with the most room, not on the default. */
488
+ balanceNewAgents: z.boolean().optional(),
489
+ /** While spreading is on: per family, the account a new agent naming none would start on. */
490
+ pacedNext: z.record(z.string(), z.string()).optional(),
491
+ /**
492
+ * This host's Paseo keeps agent metadata (0.16 and later), which carries the Account control's
493
+ * choice for a new agent and tells it which running agent it belongs to. Without it the control
494
+ * isn't shown, and the account button stays: an app from 0.16 would take the choice and then fail
495
+ * to create the agent on an older host.
496
+ */
497
+ agentMetadata: z.boolean().optional(),
498
+ /** Paid API accounts (Azure OpenAI) may take work over by themselves once every subscription is out. */
499
+ paidApiFallback: z.boolean().optional(),
163
500
  warnings: z.array(z.string()),
164
501
  });
165
502
  export type StateView = z.infer<typeof StateViewSchema>;
@@ -33,9 +33,30 @@ export const preferences = defineSettings({
33
33
  useCredits: z.boolean().default(false),
34
34
  /**
35
35
  * When every account of a provider is at its limit, carry the chat on in a new agent on the
36
- * other provider (Claude ↔ ChatGPT), in a mode no more permissive than the original's.
36
+ * other provider (Claude ↔ ChatGPT) or, for Claude, on OpenCode. ChatGPT gets a mode no looser than the original's; OpenCode runs the host's policy.
37
37
  */
38
38
  forkOtherProvider: z.boolean().default(false),
39
+ /** Where a stopped Claude chat continues when the fork option is on. */
40
+ claudeForkDestination: z.enum(["codex", "opencode"]).default("codex"),
41
+ /** OpenCode model for that fork, from this host's catalog. Empty uses the host's default. */
42
+ forkOpenCodeModel: z.string().default(""),
43
+ /** Thinking option that model offers, from this host's catalog. Empty uses the model's default. */
44
+ forkOpenCodeThinking: z.string().default(""),
45
+ /**
46
+ * Off unless turned on. Two ChatGPT accounts in one workspace may keep a Codex conversation:
47
+ * a limit reloads that agent on the other account. Every other case, including a workspace
48
+ * that is out of credits, still opens a new tab. A failed resume puts the agent back and
49
+ * opens that tab.
50
+ */
51
+ codexSameConversation: z.boolean().default(false),
52
+ /**
53
+ * Off unless turned on. When every subscription account of a provider is out (at its limit,
54
+ * signed out or disabled), routing may move agents onto a paid API account that stands in for
55
+ * one (an Azure OpenAI account under ChatGPT), billed per token; a banked reset goes first when
56
+ * `autoRedeem` is on. Off, such an account is only used when picked for an agent or made the
57
+ * default, like any API-key account.
58
+ */
59
+ paidApiFallback: z.boolean().default(false),
39
60
  /** Show the account pill in the composer of Claude and Codex agents. */
40
61
  showComposerPill: z.boolean().default(true),
41
62
  }),
package/shared/rpc.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { defineRpc } from "@getpaseo/plugin";
2
2
  import { z } from "zod";
3
- import { FamilySchema, LoginMethodSchema, LoginViewSchema, StateViewSchema } from "./model";
3
+ import { ApiKeyKindSchema, ApiPriceSchema, FamilySchema, LoginMethodSchema, LoginViewSchema, StateViewSchema, TrafficSwitchesSchema } from "./model";
4
4
 
5
5
  export const getState = defineRpc({
6
6
  name: "zerosub.state",
@@ -15,6 +15,8 @@ export const startLogin = defineRpc({
15
15
  /** Sign an existing account back in instead of adding a new one. */
16
16
  accountId: z.string().optional(),
17
17
  method: LoginMethodSchema.default("browser"),
18
+ /** A new account's proxy, set before the CLI signs in so the sign-in goes through it too. */
19
+ proxy: z.string().trim().max(2048).optional(),
18
20
  }),
19
21
  output: LoginViewSchema,
20
22
  });
@@ -37,10 +39,104 @@ export const renameAccount = defineRpc({
37
39
  output: z.object({ ok: z.literal(true) }),
38
40
  });
39
41
 
40
- export const removeAccount = defineRpc({
41
- name: "zerosub.accounts.remove",
42
- input: z.object({ accountId: z.string() }),
43
- output: z.object({ ok: z.literal(true), movedAgents: z.number() }),
42
+ const ApiFieldsSchema = TrafficSwitchesSchema.extend({
43
+ /** Left out for a Pi account, which only takes an API key. */
44
+ keyKind: ApiKeyKindSchema.optional(),
45
+ /** Empty or omitted when editing: keep the current key. */
46
+ key: z.string().trim().max(4096).optional(),
47
+ /** Empty for Anthropic's own API. */
48
+ baseUrl: z.string().trim().max(2048).optional(),
49
+ });
50
+
51
+ /**
52
+ * Adds an account that uses an API key or token instead of a subscription: a Claude one, or a Pi one
53
+ * (an Anthropic API key Pi agents on it use), with an optional base URL and proxy.
54
+ */
55
+ export const addApiAccount = defineRpc({
56
+ name: "zerosub.accounts.api.add",
57
+ input: ApiFieldsSchema.extend({
58
+ /** Left out, it's a Claude one when `keyKind` is given and a Pi one otherwise. */
59
+ family: z.enum(["claude", "pi"]).optional(),
60
+ label: z.string().trim().min(1).max(40),
61
+ key: z.string().trim().min(1).max(4096),
62
+ proxy: z.string().trim().max(2048).optional(),
63
+ }),
64
+ output: z.object({ accountId: z.string() }),
65
+ });
66
+
67
+ /** Changes an API account's key (empty or omitted keeps it), base URL or traffic switches; Pi's own login's too. */
68
+ export const updateApiAccount = defineRpc({
69
+ name: "zerosub.accounts.api.update",
70
+ input: ApiFieldsSchema.extend({ accountId: z.string() }),
71
+ output: z.object({ ok: z.literal(true) }),
72
+ });
73
+
74
+ /**
75
+ * Adds an Azure OpenAI account under ChatGPT (Codex): an endpoint and an API key. The key is checked
76
+ * against the endpoint first; a refused one isn't saved, and `warning` says when it couldn't be checked.
77
+ */
78
+ export const addAzureAccount = defineRpc({
79
+ name: "zerosub.accounts.azure.add",
80
+ input: z.object({
81
+ label: z.string().trim().min(1).max(40),
82
+ /** `https://<resource>.openai.azure.com/openai/v1`; a bare resource URL gets `/openai/v1`. */
83
+ endpoint: z.string().trim().min(1).max(2048),
84
+ key: z.string().trim().min(1).max(4096),
85
+ }),
86
+ output: z.object({ accountId: z.string(), warning: z.string().nullable() }),
87
+ });
88
+
89
+ /** Changes an Azure OpenAI account's endpoint, key (empty or omitted keeps it) or price table (USD per million tokens, by model). */
90
+ export const updateAzureAccount = defineRpc({
91
+ name: "zerosub.accounts.azure.update",
92
+ input: z.object({
93
+ accountId: z.string(),
94
+ endpoint: z.string().trim().max(2048).optional(),
95
+ key: z.string().trim().max(4096).optional(),
96
+ prices: z.record(z.string().trim().max(200), ApiPriceSchema).optional(),
97
+ }),
98
+ output: z.object({ ok: z.literal(true), warning: z.string().nullable() }),
99
+ });
100
+
101
+ /** Sets a Claude or Pi account's proxy (their CLI logins' included); an empty value clears it. */
102
+ export const setAccountProxy = defineRpc({
103
+ name: "zerosub.accounts.proxy",
104
+ input: z.object({ accountId: z.string(), proxy: z.string().trim().max(2048) }),
105
+ output: z.object({ ok: z.literal(true), proxy: z.string().nullable() }),
106
+ });
107
+
108
+ /**
109
+ * Changes the folder added Claude accounts' homes are kept in (empty: the default, `~/.claude-config`);
110
+ * the accounts kept before move there. `moving`: how many are due to move.
111
+ */
112
+ export const setClaudeHomesDir = defineRpc({
113
+ name: "zerosub.accounts.homes",
114
+ input: z.object({ dir: z.string().trim().max(1024) }),
115
+ output: z.object({ ok: z.literal(true), dir: z.string(), moving: z.number() }),
116
+ });
117
+
118
+ /** Adds a folder Claude Code is signed in with already as a Claude account, where it is. */
119
+ export const importAccount = defineRpc({
120
+ name: "zerosub.accounts.import",
121
+ input: z.object({ path: z.string().trim().min(1).max(1024) }),
122
+ output: z.object({ accountId: z.string() }),
123
+ });
124
+
125
+ /**
126
+ * Changes the folder added Pi accounts' homes are kept in (empty: the default, `~/.pi-config`); the
127
+ * accounts kept before move there. `moving`: how many are due to move.
128
+ */
129
+ export const setPiHomesDir = defineRpc({
130
+ name: "zerosub.accounts.pi.homes",
131
+ input: z.object({ dir: z.string().trim().max(1024) }),
132
+ output: z.object({ ok: z.literal(true), dir: z.string(), moving: z.number() }),
133
+ });
134
+
135
+ /** Adds back a Pi account from the folder ZeroSub kept when it was removed. */
136
+ export const importPiAccount = defineRpc({
137
+ name: "zerosub.accounts.pi.import",
138
+ input: z.object({ path: z.string().trim().min(1).max(1024) }),
139
+ output: z.object({ accountId: z.string() }),
44
140
  });
45
141
 
46
142
  export const ReopenSummarySchema = z.object({
@@ -48,11 +144,20 @@ export const ReopenSummarySchema = z.object({
48
144
  /** Busy agents move when their current turn ends. */
49
145
  deferred: z.array(z.string()),
50
146
  failed: z.array(z.object({ agentId: z.string(), error: z.string() })),
147
+ /** Still being moved when the answer was sent; the move goes on, and each agent's timeline says how it went. */
148
+ pending: z.array(z.string()).default([]),
51
149
  /** A conversation that could not move in place and continues in this account's agent instead. */
52
150
  continuedIn: z.object({ agentId: z.string(), title: z.string() }).nullable().default(null),
53
151
  });
54
152
  export type ReopenSummary = z.infer<typeof ReopenSummarySchema>;
55
153
 
154
+ /** `movedAgents`: how many agents ran on the account. `moves`: how moving them went (older servers don't say). */
155
+ export const removeAccount = defineRpc({
156
+ name: "zerosub.accounts.remove",
157
+ input: z.object({ accountId: z.string() }),
158
+ output: z.object({ ok: z.literal(true), movedAgents: z.number(), moves: ReopenSummarySchema.optional() }),
159
+ });
160
+
56
161
  export const clearAccountLimit = defineRpc({
57
162
  name: "zerosub.accounts.available",
58
163
  input: z.object({ accountId: z.string() }),
@@ -73,6 +178,8 @@ export const RedeemOutcomeSchema = z.enum([
73
178
  "unavailable",
74
179
  /** The request failed or its result is unknown. */
75
180
  "error",
181
+ /** Still going when the answer was sent (or one already was); the account's usage shows the result. */
182
+ "pending",
76
183
  ]);
77
184
  export type RedeemOutcome = z.infer<typeof RedeemOutcomeSchema>;
78
185
 
@@ -96,6 +203,12 @@ export const redeemReset = defineRpc({
96
203
  output: RedeemResultSchema,
97
204
  });
98
205
 
206
+ export const setNextAgentAccount = defineRpc({
207
+ name: "zerosub.accounts.next_agent",
208
+ input: z.object({ accountId: z.string(), enabled: z.boolean() }),
209
+ output: z.object({ until: z.string().nullable() }),
210
+ });
211
+
99
212
  export const setDefaultAccount = defineRpc({
100
213
  name: "zerosub.accounts.default",
101
214
  input: z.object({ accountId: z.string() }),
@@ -112,11 +225,20 @@ export const setAccountEnabled = defineRpc({
112
225
  }),
113
226
  });
114
227
 
115
- /** Carries an agent's work on in a new agent on the other provider (Claude ↔ ChatGPT). */
228
+ /** Carries an agent's work on in a new agent on the other provider (Claude ↔ ChatGPT), or on this host's OpenCode. */
116
229
  export const forkAgent = defineRpc({
117
230
  name: "zerosub.agents.fork",
118
- input: z.object({ agentId: z.string() }),
119
- output: z.object({ agentId: z.string(), title: z.string() }),
231
+ input: z.object({ agentId: z.string(), destination: z.enum(["other", "opencode"]).default("other") }),
232
+ output: z.object({
233
+ agentId: z.string(),
234
+ title: z.string(),
235
+ /**
236
+ * Whether the conversation was delivered: `sent` and confirmed, `up-to-date` (nothing new to
237
+ * send), `found` (an existing continuation without a provable checkpoint; nothing was sent),
238
+ * or `uncertain` (a previous handoff has no trustworthy receipt; nothing more was sent).
239
+ */
240
+ delivery: z.enum(["sent", "up-to-date", "found", "uncertain"]).default("sent"),
241
+ }),
120
242
  });
121
243
 
122
244
  export const setAgentAccount = defineRpc({
@@ -25,6 +25,8 @@ export const SwitchRowSchema = z.object({
25
25
  "enabled",
26
26
  /** Every account of this provider is at its limit; nothing to switch to. */
27
27
  "exhausted",
28
+ /** `from` still works but is projected past the 5-hour pacing gate; a cold idle agent moved off it. */
29
+ "pacing",
28
30
  ]),
29
31
  /** When the exhausted account frees up again, if known. */
30
32
  resetsAt: z.string().nullable(),
@@ -34,12 +36,21 @@ export const SwitchRowSchema = z.object({
34
36
  continuedIn: z.object({ agentId: z.string(), title: z.string() }).nullable().default(null),
35
37
  /** Set when `continuedIn` runs on the other provider (a fork from Claude to ChatGPT, or back). */
36
38
  toFamily: FamilySchema.nullable().default(null),
39
+ /** Set when the fork went to a provider outside the account families, e.g. OpenCode. It has no account. */
40
+ toProvider: z.string().nullable().default(null),
37
41
  /**
38
42
  * `switched`: the agent now runs on `to`. `pending`: it moves when its session next starts.
39
43
  * `continued`: the work goes on in `continuedIn`. `stayed`: it remains on `from` (see `detail`).
40
44
  * `reset`: a banked reset refilled `from`, and the agent stayed on it.
41
45
  */
42
46
  outcome: z.enum(["switched", "pending", "continued", "stayed", "reset"]).default("switched"),
47
+ /** Delivery state for a fork row. Undefined retains the pre-delivery-status rendering. */
48
+ delivery: z.enum(["sent", "up-to-date", "found", "uncertain"]).optional(),
49
+ /**
50
+ * The agent reloaded on `to` and kept this conversation. Absent on older rows, and on a new-tab
51
+ * handoff, so a client that does not know the field still parses the row.
52
+ */
53
+ sameConversation: z.boolean().optional(),
43
54
  detail: z.string().nullable().default(null),
44
55
  at: z.string(),
45
56
  });