@kapybara/zerosub 1.0.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/LICENSE +21 -0
- package/README.md +152 -0
- package/client/accounts-surface.tsx +592 -0
- package/client/add-account.tsx +351 -0
- package/client/commands.ts +112 -0
- package/client/fork-confirm.tsx +57 -0
- package/client/pills.ts +251 -0
- package/client/reset-confirm.tsx +138 -0
- package/client/settings-screen.tsx +120 -0
- package/client/store.ts +139 -0
- package/client/switch-row.tsx +103 -0
- package/client/ui.tsx +231 -0
- package/index.client.tsx +39 -0
- package/index.server.ts +91 -0
- package/package.json +58 -0
- package/paseo-plugin.json +7 -0
- package/server/adapter.ts +126 -0
- package/server/binaries.ts +63 -0
- package/server/claude-resets.ts +192 -0
- package/server/claude.ts +478 -0
- package/server/codex.ts +459 -0
- package/server/families.ts +78 -0
- package/server/handoff.ts +175 -0
- package/server/homes.ts +352 -0
- package/server/json-file.ts +39 -0
- package/server/limits.ts +213 -0
- package/server/machine.ts +17 -0
- package/server/modes.ts +34 -0
- package/server/paths.ts +37 -0
- package/server/process.ts +66 -0
- package/server/reopen.ts +95 -0
- package/server/routing.ts +131 -0
- package/server/service.ts +1692 -0
- package/server/state.ts +177 -0
- package/server/switch-guard.ts +28 -0
- package/server/usage.ts +68 -0
- package/shared/format.ts +99 -0
- package/shared/model.ts +150 -0
- package/shared/preferences.ts +32 -0
- package/shared/rpc.ts +120 -0
- package/shared/timeline.ts +42 -0
package/server/state.ts
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { copyFile } from "node:fs/promises";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { AccountKindSchema, FamilySchema, type Family } from "../shared/model";
|
|
4
|
+
import { Mutex, readJson, writeJsonAtomic } from "./json-file";
|
|
5
|
+
import { statePath } from "./paths";
|
|
6
|
+
|
|
7
|
+
export const StoredAccountSchema = z.object({
|
|
8
|
+
id: z.string(),
|
|
9
|
+
family: FamilySchema,
|
|
10
|
+
label: z.string(),
|
|
11
|
+
/** The label was generated from the email and may be replaced when the identity is learned. */
|
|
12
|
+
autoLabel: z.boolean().default(true),
|
|
13
|
+
kind: AccountKindSchema,
|
|
14
|
+
/** Credential home (`CLAUDE_CONFIG_DIR` / `CODEX_HOME`). `null` for the CLI's own login. */
|
|
15
|
+
home: z.string().nullable(),
|
|
16
|
+
email: z.string().nullable().default(null),
|
|
17
|
+
plan: z.string().nullable().default(null),
|
|
18
|
+
organization: z.string().nullable().default(null),
|
|
19
|
+
/** Stable identity used to spot the same account being added twice. */
|
|
20
|
+
identity: z.string().nullable().default(null),
|
|
21
|
+
signedIn: z.boolean().default(true),
|
|
22
|
+
limitedUntil: z.string().nullable().default(null),
|
|
23
|
+
/** What kind of limit `limitedUntil` records; only `window` limits clear from usage readings. */
|
|
24
|
+
limitKind: z.enum(["window", "budget"]).nullable().default(null),
|
|
25
|
+
/** When the current limit was recorded. */
|
|
26
|
+
limitedAt: z.string().nullable().default(null),
|
|
27
|
+
createdAt: z.string(),
|
|
28
|
+
});
|
|
29
|
+
export type StoredAccount = z.infer<typeof StoredAccountSchema>;
|
|
30
|
+
|
|
31
|
+
export const BindingSchema = z.object({
|
|
32
|
+
accountId: z.string(),
|
|
33
|
+
/**
|
|
34
|
+
* `user`: chosen in the UI. `auto`: moved after a limit. `balance`: spread at creation.
|
|
35
|
+
* `thread`: a conversation that can't change accounts, pinned where it started.
|
|
36
|
+
*/
|
|
37
|
+
source: z.enum(["user", "auto", "balance", "thread"]),
|
|
38
|
+
at: z.string(),
|
|
39
|
+
});
|
|
40
|
+
export type Binding = z.infer<typeof BindingSchema>;
|
|
41
|
+
|
|
42
|
+
export const LiveSessionSchema = z.object({
|
|
43
|
+
accountId: z.string(),
|
|
44
|
+
family: FamilySchema,
|
|
45
|
+
openedAt: z.string(),
|
|
46
|
+
});
|
|
47
|
+
export type LiveSession = z.infer<typeof LiveSessionSchema>;
|
|
48
|
+
|
|
49
|
+
export const StoredStateSchema = z.object({
|
|
50
|
+
version: z.literal(1).default(1),
|
|
51
|
+
accounts: z.array(StoredAccountSchema).default([]),
|
|
52
|
+
defaults: z
|
|
53
|
+
.object({ claude: z.string().nullable().default(null), codex: z.string().nullable().default(null) })
|
|
54
|
+
.default({ claude: null, codex: null }),
|
|
55
|
+
/** Per-agent overrides of the default account. */
|
|
56
|
+
bindings: z.record(z.string(), BindingSchema).default({}),
|
|
57
|
+
/** Which account each agent's live provider session was opened with. */
|
|
58
|
+
sessions: z.record(z.string(), LiveSessionSchema).default({}),
|
|
59
|
+
});
|
|
60
|
+
export type StoredState = z.infer<typeof StoredStateSchema>;
|
|
61
|
+
|
|
62
|
+
export const MAIN_ACCOUNT_ID: Record<Family, string> = { claude: "claude-main", codex: "codex-main" };
|
|
63
|
+
|
|
64
|
+
export function emptyState(): StoredState {
|
|
65
|
+
return StoredStateSchema.parse({});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Keeps every entry that still validates, so one bad record (say, after a downgrade) can't wipe
|
|
70
|
+
* the accounts and every Codex thread's pin. Reports whether anything had to be dropped.
|
|
71
|
+
*/
|
|
72
|
+
export function salvageState(raw: unknown): { state: StoredState; dropped: boolean } {
|
|
73
|
+
const whole = StoredStateSchema.safeParse(raw);
|
|
74
|
+
if (whole.success) return { state: whole.data, dropped: false };
|
|
75
|
+
const source = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
|
|
76
|
+
let dropped = false;
|
|
77
|
+
const keep = <T>(schema: z.ZodType<T>, value: unknown): T | undefined => {
|
|
78
|
+
const parsed = schema.safeParse(value);
|
|
79
|
+
if (!parsed.success) dropped = true;
|
|
80
|
+
return parsed.success ? parsed.data : undefined;
|
|
81
|
+
};
|
|
82
|
+
const accounts = (Array.isArray(source.accounts) ? source.accounts : [])
|
|
83
|
+
.map((entry) => keep(StoredAccountSchema, entry))
|
|
84
|
+
.filter((entry): entry is StoredAccount => entry !== undefined);
|
|
85
|
+
const records = <T>(schema: z.ZodType<T>, value: unknown): Record<string, T> => {
|
|
86
|
+
const result: Record<string, T> = {};
|
|
87
|
+
if (!value || typeof value !== "object") return result;
|
|
88
|
+
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
|
|
89
|
+
const parsed = keep(schema, entry);
|
|
90
|
+
if (parsed !== undefined) result[key] = parsed;
|
|
91
|
+
}
|
|
92
|
+
return result;
|
|
93
|
+
};
|
|
94
|
+
const defaults = keep(StoredStateSchema.shape.defaults, source.defaults) ?? { claude: null, codex: null };
|
|
95
|
+
return {
|
|
96
|
+
state: {
|
|
97
|
+
version: 1,
|
|
98
|
+
accounts,
|
|
99
|
+
defaults,
|
|
100
|
+
bindings: records(BindingSchema, source.bindings),
|
|
101
|
+
sessions: records(LiveSessionSchema, source.sessions),
|
|
102
|
+
},
|
|
103
|
+
dropped: true,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The registry: small, read on every session open, written atomically. */
|
|
108
|
+
export class StateStore {
|
|
109
|
+
private cached: StoredState | null = null;
|
|
110
|
+
private readonly mutex = new Mutex();
|
|
111
|
+
|
|
112
|
+
constructor(private readonly path: string = statePath()) {}
|
|
113
|
+
|
|
114
|
+
async read(): Promise<StoredState> {
|
|
115
|
+
if (this.cached) return this.cached;
|
|
116
|
+
return this.mutex.run(async () => {
|
|
117
|
+
if (!this.cached) this.cached = await this.load();
|
|
118
|
+
return this.cached;
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Applies `change` to a copy and persists it. Returns the new state. */
|
|
123
|
+
update(change: (draft: StoredState) => void): Promise<StoredState> {
|
|
124
|
+
return this.mutex.run(async () => {
|
|
125
|
+
const current = this.cached ?? (await this.load());
|
|
126
|
+
const draft = structuredClone(current);
|
|
127
|
+
change(draft);
|
|
128
|
+
const next = StoredStateSchema.parse(draft);
|
|
129
|
+
await writeJsonAtomic(this.path, next);
|
|
130
|
+
this.cached = next;
|
|
131
|
+
return next;
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Throws on a transient read error so nothing overwrites a file that couldn't be read. */
|
|
136
|
+
private async load(): Promise<StoredState> {
|
|
137
|
+
let raw: unknown;
|
|
138
|
+
try {
|
|
139
|
+
raw = await readJson(this.path);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
142
|
+
await this.backup("unparseable");
|
|
143
|
+
return emptyState();
|
|
144
|
+
}
|
|
145
|
+
if (raw === undefined) return emptyState();
|
|
146
|
+
const { state, dropped } = salvageState(raw);
|
|
147
|
+
if (dropped) await this.backup("partly invalid");
|
|
148
|
+
return state;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private async backup(why: string): Promise<void> {
|
|
152
|
+
const copy = `${this.path}.bad-${Date.now()}`;
|
|
153
|
+
await copyFile(this.path, copy).catch(() => undefined);
|
|
154
|
+
console.error(`[ZeroSub] state file was ${why}; kept a copy at ${copy} and continued with what was readable`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function findAccount(state: StoredState, accountId: string | null | undefined): StoredAccount | undefined {
|
|
159
|
+
return accountId ? state.accounts.find((account) => account.id === accountId) : undefined;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function accountsOf(state: StoredState, family: Family): StoredAccount[] {
|
|
163
|
+
return state.accounts.filter((account) => account.family === family);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The explicit default, else the CLI's own login, else the first account. */
|
|
167
|
+
export function defaultAccount(state: StoredState, family: Family): StoredAccount | undefined {
|
|
168
|
+
const chosen = findAccount(state, state.defaults[family]);
|
|
169
|
+
if (chosen && chosen.family === family) return chosen;
|
|
170
|
+
const accounts = accountsOf(state, family);
|
|
171
|
+
return accounts.find((account) => account.kind === "main") ?? accounts[0];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The CLI's own login for a family, if registered. */
|
|
175
|
+
export function mainAccount(state: StoredState, family: Family): StoredAccount | undefined {
|
|
176
|
+
return findAccount(state, MAIN_ACCOUNT_ID[family]);
|
|
177
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A backstop against runaway switching, should limit detection ever misfire turn after turn. Only
|
|
3
|
+
* moves that actually happened count, so real limits can move an agent whenever one hits.
|
|
4
|
+
*/
|
|
5
|
+
export class SwitchGuard {
|
|
6
|
+
private readonly moves = new Map<string, number[]>();
|
|
7
|
+
|
|
8
|
+
constructor(
|
|
9
|
+
readonly limit = 4,
|
|
10
|
+
readonly windowMs = 10 * 60_000,
|
|
11
|
+
) {}
|
|
12
|
+
|
|
13
|
+
allows(agentId: string, now: number): boolean {
|
|
14
|
+
return this.recent(agentId, now).length < this.limit;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
note(agentId: string, now: number): void {
|
|
18
|
+
this.moves.set(agentId, [...this.recent(agentId, now), now]);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
forget(agentId: string): void {
|
|
22
|
+
this.moves.delete(agentId);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
private recent(agentId: string, now: number): number[] {
|
|
26
|
+
return (this.moves.get(agentId) ?? []).filter((at) => now - at < this.windowMs);
|
|
27
|
+
}
|
|
28
|
+
}
|
package/server/usage.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { UsageSchema, type Usage } from "../shared/model";
|
|
3
|
+
import { readJson, writeJsonAtomic } from "./json-file";
|
|
4
|
+
import { dataDir } from "./paths";
|
|
5
|
+
|
|
6
|
+
/** How close a limit notice's reset time must be to a window's for that window to be the full one. */
|
|
7
|
+
const MATCH_MS = 20 * 60_000;
|
|
8
|
+
|
|
9
|
+
/** How long to wait after the provider asks us to slow down (HTTP 429), from its `Retry-After`. */
|
|
10
|
+
export function retryDelayMs(retryAfter: string | null, now: number = Date.now()): number {
|
|
11
|
+
const fallback = 2 * 60_000;
|
|
12
|
+
if (!retryAfter) return fallback;
|
|
13
|
+
const seconds = Number(retryAfter);
|
|
14
|
+
const ms = Number.isFinite(seconds) ? seconds * 1_000 : Date.parse(retryAfter) - now;
|
|
15
|
+
if (!Number.isFinite(ms)) return fallback;
|
|
16
|
+
return Math.min(30 * 60_000, Math.max(30_000, ms));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The reading with the window a limit notice is about shown as full, since the notice is the
|
|
21
|
+
* freshest word on usage there is. That window is the one resetting when the notice says it will;
|
|
22
|
+
* when several do, the fullest one.
|
|
23
|
+
*/
|
|
24
|
+
export function showLimit(usage: Usage, resetsAt: string | null): Usage {
|
|
25
|
+
const at = resetsAt ? Date.parse(resetsAt) : Number.NaN;
|
|
26
|
+
if (!Number.isFinite(at)) return usage;
|
|
27
|
+
let match = -1;
|
|
28
|
+
for (const [index, window] of usage.windows.entries()) {
|
|
29
|
+
if (!window.resetsAt || Math.abs(Date.parse(window.resetsAt) - at) > MATCH_MS) continue;
|
|
30
|
+
if (match < 0 || window.usedPercent > (usage.windows[match]?.usedPercent ?? 0)) match = index;
|
|
31
|
+
}
|
|
32
|
+
if (match < 0) return usage;
|
|
33
|
+
return {
|
|
34
|
+
...usage,
|
|
35
|
+
windows: usage.windows.map((window, index) => (index === match ? { ...window, usedPercent: Math.max(100, window.usedPercent) } : window)),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The reading to show after a refresh. A failed or rate-limited refresh keeps the last windows, and
|
|
41
|
+
* the CLI's own cached copy only replaces a reading it is newer than.
|
|
42
|
+
*/
|
|
43
|
+
export function mergeUsage(previous: Usage | undefined, next: Usage): Usage {
|
|
44
|
+
if (!previous || previous.windows.length === 0) return next;
|
|
45
|
+
if (next.windows.length === 0) return { ...previous, error: next.error };
|
|
46
|
+
if (next.cached && Date.parse(next.fetchedAt) <= Date.parse(previous.fetchedAt)) return previous;
|
|
47
|
+
return next;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function usagePath(): string {
|
|
51
|
+
return join(dataDir(), "usage.json");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Each account's last reading, as `saveReadings` left it, so a reload never blanks the cards. */
|
|
55
|
+
export async function loadReadings(): Promise<Map<string, Usage>> {
|
|
56
|
+
const readings = new Map<string, Usage>();
|
|
57
|
+
const saved = await readJson(usagePath()).catch(() => undefined);
|
|
58
|
+
if (!saved || typeof saved !== "object") return readings;
|
|
59
|
+
for (const [accountId, value] of Object.entries(saved)) {
|
|
60
|
+
const parsed = UsageSchema.safeParse(value);
|
|
61
|
+
if (parsed.success) readings.set(accountId, parsed.data);
|
|
62
|
+
}
|
|
63
|
+
return readings;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function saveReadings(readings: ReadonlyMap<string, Usage>): Promise<void> {
|
|
67
|
+
return writeJsonAtomic(usagePath(), Object.fromEntries(readings));
|
|
68
|
+
}
|
package/shared/format.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { AccountView, UsageWindow } from "./model";
|
|
2
|
+
|
|
3
|
+
/** "in 2h 14m", "in 3d 4h", "now". */
|
|
4
|
+
export function formatResetIn(resetsAt: string | null, now: number = Date.now()): string | null {
|
|
5
|
+
if (!resetsAt) return null;
|
|
6
|
+
const at = Date.parse(resetsAt);
|
|
7
|
+
if (!Number.isFinite(at)) return null;
|
|
8
|
+
const minutes = Math.round((at - now) / 60_000);
|
|
9
|
+
if (minutes <= 0) return "now";
|
|
10
|
+
if (minutes < 60) return `in ${minutes}m`;
|
|
11
|
+
const hours = Math.floor(minutes / 60);
|
|
12
|
+
if (hours < 24) {
|
|
13
|
+
const rest = minutes % 60;
|
|
14
|
+
return rest === 0 ? `in ${hours}h` : `in ${hours}h ${rest}m`;
|
|
15
|
+
}
|
|
16
|
+
const days = Math.floor(hours / 24);
|
|
17
|
+
const restHours = hours % 24;
|
|
18
|
+
return restHours === 0 ? `in ${days}d` : `in ${days}d ${restHours}h`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function formatPercent(value: number): string {
|
|
22
|
+
return `${Math.round(Math.min(100, Math.max(0, value)))}%`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The busiest window decides how close an account is to being cut off. */
|
|
26
|
+
export function peakUsage(windows: readonly UsageWindow[]): UsageWindow | null {
|
|
27
|
+
let peak: UsageWindow | null = null;
|
|
28
|
+
for (const limit of windows) {
|
|
29
|
+
if (!peak || limit.usedPercent > peak.usedPercent) peak = limit;
|
|
30
|
+
}
|
|
31
|
+
return peak;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const PLAN_LABELS: Record<string, string> = {
|
|
35
|
+
max: "Max",
|
|
36
|
+
pro: "Pro",
|
|
37
|
+
prolite: "Pro Lite",
|
|
38
|
+
team: "Team",
|
|
39
|
+
enterprise: "Enterprise",
|
|
40
|
+
plus: "Plus",
|
|
41
|
+
go: "Go",
|
|
42
|
+
business: "Business",
|
|
43
|
+
self_serve_business_prolite: "Business",
|
|
44
|
+
self_serve_business_usage_based: "Business",
|
|
45
|
+
enterprise_cbp_automation: "Enterprise",
|
|
46
|
+
enterprise_cbp_usage_based: "Enterprise",
|
|
47
|
+
ent26: "Enterprise",
|
|
48
|
+
edu: "Edu",
|
|
49
|
+
edu_plus: "Edu Plus",
|
|
50
|
+
edu_pro: "Edu Pro",
|
|
51
|
+
free: "Free",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export function formatPlan(plan: string | null): string | null {
|
|
55
|
+
if (!plan) return null;
|
|
56
|
+
const key = plan.toLowerCase();
|
|
57
|
+
return PLAN_LABELS[key] ?? plan.charAt(0).toUpperCase() + plan.slice(1);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Short name for a composer pill: the nickname, trimmed to fit. */
|
|
61
|
+
export function shortLabel(account: Pick<AccountView, "label">, max = 18): string {
|
|
62
|
+
const label = account.label.trim();
|
|
63
|
+
return label.length <= max ? label : `${label.slice(0, max - 1)}…`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** One line summarising an account's headroom, e.g. "42% of 5-hour used · resets in 2h". */
|
|
67
|
+
/**
|
|
68
|
+
* The line under an account's name: its email, plus its organization when that adds something.
|
|
69
|
+
* Claude names a personal organization after its owner ("…'s Organization"), which only repeats it.
|
|
70
|
+
*/
|
|
71
|
+
export function accountSubtitle(account: Pick<AccountView, "email" | "organization">): string | null {
|
|
72
|
+
const organization = account.organization?.trim() || null;
|
|
73
|
+
const telling =
|
|
74
|
+
organization && organization.toLowerCase() !== account.email?.toLowerCase() && !/'s organi[sz]ation$/i.test(organization)
|
|
75
|
+
? organization
|
|
76
|
+
: null;
|
|
77
|
+
return [account.email, telling].filter(Boolean).join(" · ") || null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** "just now", "6m ago", "3h ago", "2d ago". */
|
|
81
|
+
export function formatAge(at: string, now: number = Date.now()): string {
|
|
82
|
+
const minutes = Math.floor((now - Date.parse(at)) / 60_000);
|
|
83
|
+
if (!Number.isFinite(minutes) || minutes < 1) return "just now";
|
|
84
|
+
if (minutes < 60) return `${minutes}m ago`;
|
|
85
|
+
const hours = Math.round(minutes / 60);
|
|
86
|
+
return hours < 48 ? `${hours}h ago` : `${Math.round(hours / 24)}d ago`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function usageSummary(account: AccountView, now: number = Date.now()): string | null {
|
|
90
|
+
if (account.status === "limited") {
|
|
91
|
+
const reset = formatResetIn(account.limitedUntil, now);
|
|
92
|
+
return reset ? `Limit reached · resets ${reset}` : "Limit reached";
|
|
93
|
+
}
|
|
94
|
+
const peak = account.usage ? peakUsage(account.usage.windows) : null;
|
|
95
|
+
if (!peak) return null;
|
|
96
|
+
const reset = formatResetIn(peak.resetsAt, now);
|
|
97
|
+
const base = `${formatPercent(peak.usedPercent)} of ${peak.label.toLowerCase()} used`;
|
|
98
|
+
return reset ? `${base} · resets ${reset}` : base;
|
|
99
|
+
}
|
package/shared/model.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
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"]);
|
|
5
|
+
export type Family = z.infer<typeof FamilySchema>;
|
|
6
|
+
|
|
7
|
+
export const FAMILY_LABEL: Record<Family, string> = {
|
|
8
|
+
claude: "Claude",
|
|
9
|
+
codex: "ChatGPT",
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export const UsageWindowSchema = z.object({
|
|
13
|
+
/** Stable key, e.g. `five_hour`, `seven_day`, `seven_day_opus`, `primary`, `secondary`. */
|
|
14
|
+
id: z.string(),
|
|
15
|
+
label: z.string(),
|
|
16
|
+
/** 0–100. */
|
|
17
|
+
usedPercent: z.number(),
|
|
18
|
+
resetsAt: z.string().nullable(),
|
|
19
|
+
});
|
|
20
|
+
export type UsageWindow = z.infer<typeof UsageWindowSchema>;
|
|
21
|
+
|
|
22
|
+
/** Banked limit resets the provider has granted this account (Claude "limit reset", Codex reset credits). */
|
|
23
|
+
export const ResetOfferSchema = z.object({
|
|
24
|
+
/** Resets left to use. */
|
|
25
|
+
available: z.number(),
|
|
26
|
+
/** The provider will accept a redeem right now. */
|
|
27
|
+
usableNow: z.boolean(),
|
|
28
|
+
/** Why it can't be used yet, in plain words, when it can't. */
|
|
29
|
+
blockedReason: z.string().nullable(),
|
|
30
|
+
/** Use-by date of the next reset, if it expires. */
|
|
31
|
+
expiresAt: z.string().nullable(),
|
|
32
|
+
/** Which limits a reset refills, e.g. "5-hour", "weekly". Empty when the provider doesn't say. */
|
|
33
|
+
refills: z.array(z.string()),
|
|
34
|
+
/** The provider's own name for the reset, if it gives one. */
|
|
35
|
+
label: z.string().nullable(),
|
|
36
|
+
});
|
|
37
|
+
export type ResetOffer = z.infer<typeof ResetOfferSchema>;
|
|
38
|
+
|
|
39
|
+
export const UsageSchema = z.object({
|
|
40
|
+
fetchedAt: z.string(),
|
|
41
|
+
windows: z.array(UsageWindowSchema),
|
|
42
|
+
/** Why usage could not be read, if it could not. Old windows may still be shown. */
|
|
43
|
+
error: z.string().nullable(),
|
|
44
|
+
/** Read from the CLI's own cache rather than the provider, so possibly out of date. */
|
|
45
|
+
cached: z.boolean().default(false),
|
|
46
|
+
/** Banked resets, when the provider reports any. */
|
|
47
|
+
resets: ResetOfferSchema.nullable().default(null),
|
|
48
|
+
});
|
|
49
|
+
export type Usage = z.infer<typeof UsageSchema>;
|
|
50
|
+
|
|
51
|
+
export const AccountKindSchema = z.enum([
|
|
52
|
+
/** The login the CLI uses on its own (`~/.claude`, `~/.codex`). */
|
|
53
|
+
"main",
|
|
54
|
+
/** Created by this plugin: an isolated credential home that shares everything else with main. */
|
|
55
|
+
"managed",
|
|
56
|
+
]);
|
|
57
|
+
export type AccountKind = z.infer<typeof AccountKindSchema>;
|
|
58
|
+
|
|
59
|
+
export const AccountStatusSchema = z.enum(["ready", "signed_out", "limited", "checking"]);
|
|
60
|
+
export type AccountStatus = z.infer<typeof AccountStatusSchema>;
|
|
61
|
+
|
|
62
|
+
export const AccountViewSchema = z.object({
|
|
63
|
+
id: z.string(),
|
|
64
|
+
family: FamilySchema,
|
|
65
|
+
label: z.string(),
|
|
66
|
+
kind: AccountKindSchema,
|
|
67
|
+
email: z.string().nullable(),
|
|
68
|
+
plan: z.string().nullable(),
|
|
69
|
+
organization: z.string().nullable(),
|
|
70
|
+
status: AccountStatusSchema,
|
|
71
|
+
isDefault: z.boolean(),
|
|
72
|
+
limitedUntil: z.string().nullable(),
|
|
73
|
+
usage: UsageSchema.nullable(),
|
|
74
|
+
agentCount: z.number(),
|
|
75
|
+
home: z.string().nullable(),
|
|
76
|
+
});
|
|
77
|
+
export type AccountView = z.infer<typeof AccountViewSchema>;
|
|
78
|
+
|
|
79
|
+
export const AgentRouteSchema = z.object({
|
|
80
|
+
agentId: z.string(),
|
|
81
|
+
family: FamilySchema,
|
|
82
|
+
/** Account the agent uses now, or will use when its session next opens. */
|
|
83
|
+
accountId: z.string(),
|
|
84
|
+
/** Chosen for this agent explicitly (by the user or an automatic switch) rather than following the default. */
|
|
85
|
+
pinned: z.boolean(),
|
|
86
|
+
/** The live session still runs on a different account and is waiting to be reopened. */
|
|
87
|
+
pendingAccountId: z.string().nullable(),
|
|
88
|
+
/**
|
|
89
|
+
* The conversation can move to another account in place. False for Codex agents that already
|
|
90
|
+
* have history: ChatGPT accounts can't read each other's encrypted reasoning, so switching
|
|
91
|
+
* continues the work in a new agent instead.
|
|
92
|
+
*/
|
|
93
|
+
movable: z.boolean(),
|
|
94
|
+
});
|
|
95
|
+
export type AgentRoute = z.infer<typeof AgentRouteSchema>;
|
|
96
|
+
|
|
97
|
+
export const LoginStepSchema = z.enum([
|
|
98
|
+
"starting",
|
|
99
|
+
/** Waiting for the user to finish on the sign-in page (and paste a code, if using `codeUrl`). */
|
|
100
|
+
"waiting",
|
|
101
|
+
"verifying",
|
|
102
|
+
"done",
|
|
103
|
+
"failed",
|
|
104
|
+
"canceled",
|
|
105
|
+
]);
|
|
106
|
+
export type LoginStep = z.infer<typeof LoginStepSchema>;
|
|
107
|
+
|
|
108
|
+
export const LoginMethodSchema = z.enum([
|
|
109
|
+
/** Finishes by itself when the link is opened on the daemon machine. */
|
|
110
|
+
"browser",
|
|
111
|
+
/** Works from any device: paste a code back (Claude) or type a code on the page (ChatGPT). */
|
|
112
|
+
"code",
|
|
113
|
+
]);
|
|
114
|
+
export type LoginMethod = z.infer<typeof LoginMethodSchema>;
|
|
115
|
+
|
|
116
|
+
export const LoginViewSchema = z.object({
|
|
117
|
+
id: z.string(),
|
|
118
|
+
family: FamilySchema,
|
|
119
|
+
method: LoginMethodSchema,
|
|
120
|
+
/** Set once the account exists (immediately when signing an existing account back in). */
|
|
121
|
+
accountId: z.string().nullable(),
|
|
122
|
+
step: LoginStepSchema,
|
|
123
|
+
/** Link that completes by itself (browser callback) or the device-code page. */
|
|
124
|
+
url: z.string().nullable(),
|
|
125
|
+
/** Link whose page shows a code to paste back; works from any device. */
|
|
126
|
+
codeUrl: z.string().nullable(),
|
|
127
|
+
/** Device code the user types on the sign-in page (ChatGPT device flow). */
|
|
128
|
+
userCode: z.string().nullable(),
|
|
129
|
+
message: z.string().nullable(),
|
|
130
|
+
startedAt: z.string(),
|
|
131
|
+
});
|
|
132
|
+
export type LoginView = z.infer<typeof LoginViewSchema>;
|
|
133
|
+
|
|
134
|
+
export const StateViewSchema = z.object({
|
|
135
|
+
accounts: z.array(AccountViewSchema),
|
|
136
|
+
agents: z.array(AgentRouteSchema),
|
|
137
|
+
logins: z.array(LoginViewSchema),
|
|
138
|
+
/** Paseo provider IDs (including custom profiles) that route through each family. */
|
|
139
|
+
providers: z.record(z.string(), FamilySchema),
|
|
140
|
+
/** Live sessions can be reopened on another account without waiting for the next session start. */
|
|
141
|
+
canReopen: z.boolean(),
|
|
142
|
+
/**
|
|
143
|
+
* A browser on the daemon's machine can finish a sign-in by itself. False on servers, containers
|
|
144
|
+
* and daemons started over SSH, where only the code sign-in works.
|
|
145
|
+
*/
|
|
146
|
+
browserSignIn: z.boolean().default(true),
|
|
147
|
+
showComposerPill: z.boolean(),
|
|
148
|
+
warnings: z.array(z.string()),
|
|
149
|
+
});
|
|
150
|
+
export type StateView = z.infer<typeof StateViewSchema>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { defineSettings } from "@getpaseo/plugin";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
/** Sent after a switch or a reset, so it must read right for both. */
|
|
5
|
+
export const DEFAULT_CONTINUE_PROMPT =
|
|
6
|
+
"You were interrupted by a usage limit; that has been sorted out. Continue exactly where you left off.";
|
|
7
|
+
|
|
8
|
+
export const preferences = defineSettings({
|
|
9
|
+
id: "preferences",
|
|
10
|
+
scope: "host",
|
|
11
|
+
version: 1,
|
|
12
|
+
schema: z.object({
|
|
13
|
+
/** Move an agent to another account of the same provider when its account hits a usage limit. */
|
|
14
|
+
autoSwitch: z.boolean().default(true),
|
|
15
|
+
/** After an automatic switch, send a follow-up so the interrupted turn keeps going. */
|
|
16
|
+
autoContinue: z.boolean().default(true),
|
|
17
|
+
continuePrompt: z.string().trim().min(1).max(500).default(DEFAULT_CONTINUE_PROMPT),
|
|
18
|
+
/** New agents start on the account with the most headroom instead of the default. */
|
|
19
|
+
balanceNewAgents: z.boolean().default(false),
|
|
20
|
+
/** When every account of a provider is at its limit, spend a banked reset instead of stopping. */
|
|
21
|
+
autoRedeem: z.boolean().default(false),
|
|
22
|
+
/**
|
|
23
|
+
* When every account of a provider is at its limit, carry the chat on in a new agent on the
|
|
24
|
+
* other provider (Claude ↔ ChatGPT), in a mode no more permissive than the original's.
|
|
25
|
+
*/
|
|
26
|
+
forkOtherProvider: z.boolean().default(false),
|
|
27
|
+
/** Show the account pill in the composer of Claude and Codex agents. */
|
|
28
|
+
showComposerPill: z.boolean().default(true),
|
|
29
|
+
}),
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
export type Preferences = z.output<typeof preferences.schema>;
|
package/shared/rpc.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { defineRpc } from "@getpaseo/plugin";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { FamilySchema, LoginMethodSchema, LoginViewSchema, StateViewSchema } from "./model";
|
|
4
|
+
|
|
5
|
+
export const getState = defineRpc({
|
|
6
|
+
name: "zerosub.state",
|
|
7
|
+
input: z.object({ refreshUsage: z.boolean().optional() }),
|
|
8
|
+
output: StateViewSchema,
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
export const startLogin = defineRpc({
|
|
12
|
+
name: "zerosub.login.start",
|
|
13
|
+
input: z.object({
|
|
14
|
+
family: FamilySchema,
|
|
15
|
+
/** Sign an existing account back in instead of adding a new one. */
|
|
16
|
+
accountId: z.string().optional(),
|
|
17
|
+
method: LoginMethodSchema.default("browser"),
|
|
18
|
+
}),
|
|
19
|
+
output: LoginViewSchema,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
export const submitLoginCode = defineRpc({
|
|
23
|
+
name: "zerosub.login.code",
|
|
24
|
+
input: z.object({ loginId: z.string(), code: z.string().trim().min(1) }),
|
|
25
|
+
output: LoginViewSchema,
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
export const cancelLogin = defineRpc({
|
|
29
|
+
name: "zerosub.login.cancel",
|
|
30
|
+
input: z.object({ loginId: z.string() }),
|
|
31
|
+
output: LoginViewSchema.nullable(),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
export const renameAccount = defineRpc({
|
|
35
|
+
name: "zerosub.accounts.rename",
|
|
36
|
+
input: z.object({ accountId: z.string(), label: z.string().trim().min(1).max(40) }),
|
|
37
|
+
output: z.object({ ok: z.literal(true) }),
|
|
38
|
+
});
|
|
39
|
+
|
|
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() }),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
export const ReopenSummarySchema = z.object({
|
|
47
|
+
reopened: z.array(z.string()),
|
|
48
|
+
/** Busy agents move when their current turn ends. */
|
|
49
|
+
deferred: z.array(z.string()),
|
|
50
|
+
failed: z.array(z.object({ agentId: z.string(), error: z.string() })),
|
|
51
|
+
/** A conversation that could not move in place and continues in this new agent instead. */
|
|
52
|
+
continuedIn: z.object({ agentId: z.string(), title: z.string() }).nullable().default(null),
|
|
53
|
+
});
|
|
54
|
+
export type ReopenSummary = z.infer<typeof ReopenSummarySchema>;
|
|
55
|
+
|
|
56
|
+
export const clearAccountLimit = defineRpc({
|
|
57
|
+
name: "zerosub.accounts.available",
|
|
58
|
+
input: z.object({ accountId: z.string() }),
|
|
59
|
+
output: z.object({ ok: z.literal(true) }),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
export const RedeemOutcomeSchema = z.enum([
|
|
63
|
+
/** Limits were refilled. */
|
|
64
|
+
"reset",
|
|
65
|
+
/** The provider kept the reset because the account isn't at a limit. */
|
|
66
|
+
"not_limited",
|
|
67
|
+
/** No banked reset to use. */
|
|
68
|
+
"none",
|
|
69
|
+
"already_used",
|
|
70
|
+
/** Resets are cooling down; try later. */
|
|
71
|
+
"cooldown",
|
|
72
|
+
/** The provider won't let this account use a reset right now. */
|
|
73
|
+
"unavailable",
|
|
74
|
+
/** The request failed or its result is unknown. */
|
|
75
|
+
"error",
|
|
76
|
+
]);
|
|
77
|
+
export type RedeemOutcome = z.infer<typeof RedeemOutcomeSchema>;
|
|
78
|
+
|
|
79
|
+
export const RedeemResultSchema = z.object({
|
|
80
|
+
outcome: RedeemOutcomeSchema,
|
|
81
|
+
message: z.string(),
|
|
82
|
+
/** Resets left afterwards, when the provider says. */
|
|
83
|
+
left: z.number().nullable(),
|
|
84
|
+
/** The agent the reset was used for, if any, was told to carry on. */
|
|
85
|
+
continued: z.boolean(),
|
|
86
|
+
});
|
|
87
|
+
export type RedeemResult = z.infer<typeof RedeemResultSchema>;
|
|
88
|
+
|
|
89
|
+
export const redeemReset = defineRpc({
|
|
90
|
+
name: "zerosub.accounts.redeem",
|
|
91
|
+
input: z.object({
|
|
92
|
+
accountId: z.string(),
|
|
93
|
+
/** An agent stopped by this account's limit; it carries on after a successful reset. */
|
|
94
|
+
agentId: z.string().optional(),
|
|
95
|
+
}),
|
|
96
|
+
output: RedeemResultSchema,
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
export const setDefaultAccount = defineRpc({
|
|
100
|
+
name: "zerosub.accounts.default",
|
|
101
|
+
input: z.object({ accountId: z.string() }),
|
|
102
|
+
output: ReopenSummarySchema,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
/** Carries an agent's work on in a new agent on the other provider (Claude ↔ ChatGPT). */
|
|
106
|
+
export const forkAgent = defineRpc({
|
|
107
|
+
name: "zerosub.agents.fork",
|
|
108
|
+
input: z.object({ agentId: z.string() }),
|
|
109
|
+
output: z.object({ agentId: z.string(), title: z.string() }),
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
export const setAgentAccount = defineRpc({
|
|
113
|
+
name: "zerosub.agents.account",
|
|
114
|
+
input: z.object({
|
|
115
|
+
agentId: z.string(),
|
|
116
|
+
/** `null` makes the agent follow the default account again. */
|
|
117
|
+
accountId: z.string().nullable(),
|
|
118
|
+
}),
|
|
119
|
+
output: ReopenSummarySchema,
|
|
120
|
+
});
|