@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.
@@ -0,0 +1,103 @@
1
+ import type { PluginTimelineItemProps } from "@getpaseo/plugin/client";
2
+ import { Icon } from "@getpaseo/plugin/client/react-native";
3
+ import { Text, View } from "react-native";
4
+ import { formatResetIn } from "../shared/format";
5
+ import { FAMILY_LABEL } from "../shared/model";
6
+ import type { SwitchRow } from "../shared/timeline";
7
+
8
+ function cause(row: SwitchRow): string | null {
9
+ const reset = formatResetIn(row.resetsAt);
10
+ const from = row.from ?? "The previous account";
11
+ switch (row.reason) {
12
+ case "limit":
13
+ return `${from} hit its usage limit${reset ? ` (resets ${reset})` : ""}.`;
14
+ case "signed_out":
15
+ return `${from} is signed out — sign it in again from Accounts.`;
16
+ case "removed":
17
+ return `${from} was removed.`;
18
+ case "default":
19
+ return "The default account changed.";
20
+ default:
21
+ return null;
22
+ }
23
+ }
24
+
25
+ /** The work went on in a new agent on the other provider (Claude ↔ ChatGPT). */
26
+ function isFork(row: SwitchRow): boolean {
27
+ return row.toFamily !== null && row.toFamily !== row.family;
28
+ }
29
+
30
+ export function describeRow(row: SwitchRow): string {
31
+ if (isFork(row) && row.toFamily && row.continuedIn) {
32
+ const reset = formatResetIn(row.resetsAt);
33
+ const lead =
34
+ row.reason === "exhausted"
35
+ ? `Every ${FAMILY_LABEL[row.family]} account is at its limit${reset ? ` (${row.from ?? "this one"} resets ${reset})` : ""}, so the work`
36
+ : "The work";
37
+ return `${lead} continues on ${FAMILY_LABEL[row.toFamily]} in a new agent: “${row.continuedIn.title}” (${row.to}).`;
38
+ }
39
+ if (row.reason === "exhausted") {
40
+ const reset = formatResetIn(row.resetsAt);
41
+ return `Every ${FAMILY_LABEL[row.family]} account is at its limit${
42
+ reset ? `; ${row.from ?? "this one"} resets ${reset}` : ""
43
+ }. Add another account, use a banked reset from the account button, or wait.${row.detail ? ` ${row.detail}` : ""}`;
44
+ }
45
+ if (row.outcome === "reset") {
46
+ return `${row.from ?? "This account"} hit its usage limit, so a banked reset was used. ${row.detail ?? "Limits reset."}${
47
+ row.continued ? " Carrying on." : ""
48
+ }`;
49
+ }
50
+ const why = cause(row);
51
+ const lead = why ? `${why} ` : "";
52
+ switch (row.outcome) {
53
+ case "continued":
54
+ return row.continuedIn
55
+ ? `${lead}ChatGPT conversations can't change accounts, so this one continues in a new agent: “${row.continuedIn.title}” on ${row.to}.`
56
+ : `${lead}Continuing on ${row.to}.`;
57
+ case "stayed":
58
+ return `${lead}This conversation stays on ${row.from ?? "its account"}.${row.detail ? ` ${row.detail}` : ""}`;
59
+ case "pending":
60
+ return `${lead}Moves to ${row.to} when its session next starts.`;
61
+ default: {
62
+ const from = row.from && row.reason !== "limit" && row.reason !== "signed_out" ? `from ${row.from} ` : "";
63
+ return `${lead}Switched ${from}to ${row.to}${row.continued ? " and carried on" : ""}.`;
64
+ }
65
+ }
66
+ }
67
+
68
+ /** Inline note in an agent's timeline when ZeroSub moved it to another account. */
69
+ export function SwitchRowView({ item, theme }: PluginTimelineItemProps<SwitchRow>) {
70
+ const row = item.data;
71
+ const forked = isFork(row);
72
+ const warning =
73
+ !forked && (row.reason === "limit" || row.reason === "signed_out" || row.reason === "exhausted" || row.outcome === "stayed");
74
+ const icon = forked
75
+ ? "GitFork"
76
+ : row.reason === "exhausted" || row.outcome === "stayed"
77
+ ? "CircleAlert"
78
+ : row.outcome === "continued"
79
+ ? "CopyPlus"
80
+ : row.outcome === "reset"
81
+ ? "TimerReset"
82
+ : "ArrowRightLeft";
83
+ return (
84
+ <View
85
+ style={{
86
+ flexDirection: "row",
87
+ alignItems: "flex-start",
88
+ gap: 8,
89
+ paddingVertical: 6,
90
+ paddingHorizontal: 10,
91
+ borderRadius: 8,
92
+ borderWidth: 1,
93
+ borderColor: theme.colors.border,
94
+ backgroundColor: theme.colors.surface1,
95
+ alignSelf: "flex-start",
96
+ maxWidth: "100%",
97
+ }}
98
+ >
99
+ <Icon name={icon} size={14} color={warning ? theme.colors.statusWarning : theme.colors.foregroundMuted} />
100
+ <Text style={{ color: theme.colors.foregroundMuted, fontSize: 13, flexShrink: 1 }}>{describeRow(row)}</Text>
101
+ </View>
102
+ );
103
+ }
package/client/ui.tsx ADDED
@@ -0,0 +1,231 @@
1
+ import type { PluginHostProps } from "@getpaseo/plugin/client";
2
+ import { Icon } from "@getpaseo/plugin/client/react-native";
3
+ import { useMemo, type ReactNode } from "react";
4
+ import { ActivityIndicator, Pressable, Text, View } from "react-native";
5
+ import { formatPercent, formatResetIn } from "../shared/format";
6
+ import type { UsageWindow } from "../shared/model";
7
+
8
+ type Theme = PluginHostProps["theme"];
9
+
10
+ export type ButtonTone = "primary" | "secondary" | "danger" | "ghost";
11
+
12
+ export function Button({
13
+ theme,
14
+ label,
15
+ icon,
16
+ tone = "secondary",
17
+ size = "regular",
18
+ onPress,
19
+ disabled,
20
+ busy,
21
+ accessibilityLabel,
22
+ }: {
23
+ theme: Theme;
24
+ label: string;
25
+ icon?: string;
26
+ tone?: ButtonTone;
27
+ /** `small` fits a card's footer. */
28
+ size?: "regular" | "small";
29
+ onPress(): void;
30
+ disabled?: boolean;
31
+ busy?: boolean;
32
+ accessibilityLabel?: string;
33
+ }) {
34
+ const small = size === "small";
35
+ const colors = theme.colors;
36
+ const palette = {
37
+ primary: { background: colors.accent, foreground: colors.accentForeground, border: colors.accent },
38
+ secondary: { background: colors.surface2, foreground: colors.foreground, border: colors.border },
39
+ danger: { background: colors.surface2, foreground: colors.statusDanger, border: colors.border },
40
+ ghost: { background: "transparent", foreground: colors.foregroundMuted, border: "transparent" },
41
+ }[tone];
42
+ const inactive = disabled || busy;
43
+ return (
44
+ <Pressable
45
+ accessibilityRole="button"
46
+ accessibilityLabel={accessibilityLabel ?? label}
47
+ accessibilityState={{ disabled: Boolean(inactive), busy: Boolean(busy) }}
48
+ disabled={inactive}
49
+ onPress={onPress}
50
+ style={({ pressed }) => ({
51
+ flexDirection: "row",
52
+ alignItems: "center",
53
+ justifyContent: "center",
54
+ gap: small ? 5 : 6,
55
+ paddingHorizontal: small ? 10 : 12,
56
+ paddingVertical: small ? 5 : 8,
57
+ borderRadius: small ? 7 : 8,
58
+ borderWidth: 1,
59
+ borderColor: palette.border,
60
+ backgroundColor: palette.background,
61
+ opacity: inactive ? 0.55 : pressed ? 0.8 : 1,
62
+ })}
63
+ >
64
+ {busy ? (
65
+ <ActivityIndicator size="small" color={palette.foreground} />
66
+ ) : icon ? (
67
+ <Icon name={icon} size={small ? 13 : 15} color={palette.foreground} />
68
+ ) : null}
69
+ <Text style={{ color: palette.foreground, fontSize: small ? 12 : 13, fontWeight: "600" }}>{label}</Text>
70
+ </Pressable>
71
+ );
72
+ }
73
+
74
+ export function IconButton({
75
+ theme,
76
+ icon,
77
+ label,
78
+ tone = "default",
79
+ onPress,
80
+ disabled,
81
+ busy,
82
+ }: {
83
+ theme: Theme;
84
+ icon: string;
85
+ label: string;
86
+ tone?: "default" | "danger";
87
+ onPress(): void;
88
+ disabled?: boolean;
89
+ busy?: boolean;
90
+ }) {
91
+ const colors = theme.colors;
92
+ const inactive = disabled || busy;
93
+ return (
94
+ <Pressable
95
+ accessibilityRole="button"
96
+ accessibilityLabel={label}
97
+ accessibilityState={{ disabled: Boolean(inactive), busy: Boolean(busy) }}
98
+ disabled={inactive}
99
+ onPress={onPress}
100
+ hitSlop={4}
101
+ style={(state) => {
102
+ const active = state.pressed || (state as { hovered?: boolean }).hovered;
103
+ return {
104
+ width: 30,
105
+ height: 30,
106
+ borderRadius: 8,
107
+ alignItems: "center",
108
+ justifyContent: "center",
109
+ backgroundColor: active ? colors.surface2 : "transparent",
110
+ opacity: inactive ? 0.45 : 1,
111
+ };
112
+ }}
113
+ >
114
+ {({ pressed, hovered }: { pressed: boolean; hovered?: boolean }) =>
115
+ busy ? (
116
+ <ActivityIndicator size="small" color={colors.foregroundMuted} />
117
+ ) : (
118
+ <Icon
119
+ name={icon}
120
+ size={15}
121
+ color={
122
+ tone === "danger" && (pressed || hovered) ? colors.statusDanger : colors.foregroundMuted
123
+ }
124
+ />
125
+ )
126
+ }
127
+ </Pressable>
128
+ );
129
+ }
130
+
131
+ export function Badge({
132
+ theme,
133
+ label,
134
+ tone = "muted",
135
+ }: {
136
+ theme: Theme;
137
+ label: string;
138
+ tone?: "muted" | "accent" | "success" | "warning" | "danger";
139
+ }) {
140
+ const colors = theme.colors;
141
+ const color = {
142
+ muted: colors.foregroundMuted,
143
+ accent: colors.accent,
144
+ success: colors.statusSuccess,
145
+ warning: colors.statusWarning,
146
+ danger: colors.statusDanger,
147
+ }[tone];
148
+ return (
149
+ <View
150
+ style={{
151
+ paddingHorizontal: 7,
152
+ paddingVertical: 2,
153
+ borderRadius: 999,
154
+ borderWidth: 1,
155
+ borderColor: tone === "muted" ? colors.border : color,
156
+ }}
157
+ >
158
+ <Text style={{ color, fontSize: 11, fontWeight: "600" }}>{label}</Text>
159
+ </View>
160
+ );
161
+ }
162
+
163
+ export function UsageBar({ theme, limit }: { theme: Theme; limit: UsageWindow }) {
164
+ const colors = theme.colors;
165
+ const percent = Math.min(100, Math.max(0, limit.usedPercent));
166
+ const fill =
167
+ percent >= 90 ? colors.statusDanger : percent >= 70 ? colors.statusWarning : colors.statusSuccess;
168
+ const reset = formatResetIn(limit.resetsAt);
169
+ return (
170
+ <View style={{ gap: 4 }}>
171
+ <View style={{ flexDirection: "row", flexWrap: "wrap", justifyContent: "space-between", columnGap: 8 }}>
172
+ <Text style={{ color: colors.foregroundMuted, fontSize: 12 }}>{limit.label}</Text>
173
+ <Text style={{ color: colors.foregroundMuted, fontSize: 12 }}>
174
+ <Text style={{ color: colors.foreground, fontWeight: "600" }}>{formatPercent(percent)}</Text> used
175
+ {reset ? ` · resets ${reset}` : ""}
176
+ </Text>
177
+ </View>
178
+ <View
179
+ accessibilityRole="progressbar"
180
+ accessibilityLabel={`${limit.label} usage`}
181
+ accessibilityValue={{ min: 0, max: 100, now: Math.round(percent) }}
182
+ style={{ height: 6, borderRadius: 3, backgroundColor: colors.surface2, overflow: "hidden" }}
183
+ >
184
+ <View style={{ width: `${percent}%`, height: 6, borderRadius: 3, backgroundColor: fill }} />
185
+ </View>
186
+ </View>
187
+ );
188
+ }
189
+
190
+ export function Card({
191
+ theme,
192
+ children,
193
+ fill,
194
+ }: {
195
+ theme: Theme;
196
+ children: ReactNode;
197
+ fill?: boolean;
198
+ }) {
199
+ return (
200
+ <View
201
+ style={{
202
+ ...(fill ? { flex: 1, minWidth: 0 } : null),
203
+ padding: 16,
204
+ gap: 12,
205
+ borderRadius: 12,
206
+ borderWidth: 1,
207
+ borderColor: theme.colors.border,
208
+ backgroundColor: theme.colors.surface1,
209
+ }}
210
+ >
211
+ {children}
212
+ </View>
213
+ );
214
+ }
215
+
216
+ export function useText(theme: Theme) {
217
+ return useMemo(
218
+ () => ({
219
+ title: { color: theme.colors.foreground, fontSize: 22, fontWeight: "700" as const },
220
+ heading: { color: theme.colors.foreground, fontSize: 15, fontWeight: "700" as const },
221
+ body: { color: theme.colors.foreground, fontSize: 14 },
222
+ strong: { color: theme.colors.foreground, fontSize: 14, fontWeight: "600" as const },
223
+ muted: { color: theme.colors.foregroundMuted, fontSize: 13 },
224
+ small: { color: theme.colors.foregroundMuted, fontSize: 12 },
225
+ danger: { color: theme.colors.statusDanger, fontSize: 13 },
226
+ warning: { color: theme.colors.statusWarning, fontSize: 13 },
227
+ mono: { color: theme.colors.foreground, fontSize: 20, fontWeight: "700" as const, letterSpacing: 2 },
228
+ }),
229
+ [theme],
230
+ );
231
+ }
@@ -0,0 +1,39 @@
1
+ import type { PluginClientContext } from "@getpaseo/plugin/client";
2
+ import { AccountsSurface } from "./client/accounts-surface";
3
+ import { contributeCommands } from "./client/commands";
4
+ import { contributePills } from "./client/pills";
5
+ import { PreferencesScreen } from "./client/settings-screen";
6
+ import { ZeroSubStore } from "./client/store";
7
+ import { SwitchRowView } from "./client/switch-row";
8
+ import { SWITCH_ROW_KIND, SWITCH_ROW_VERSION, SwitchRowSchema } from "./shared/timeline";
9
+
10
+ export default function contribute(client: PluginClientContext) {
11
+ const store = new ZeroSubStore(client);
12
+ store.start();
13
+
14
+ client.addSurface("accounts", (props) => <AccountsSurface {...props} store={store} />);
15
+ client.addSidebarItem({ id: "accounts", title: "Accounts (ZeroSub)", icon: "Users", surface: "accounts" });
16
+ client.addSettingsScreen({
17
+ id: "preferences",
18
+ title: "ZeroSub preferences",
19
+ icon: "SlidersHorizontal",
20
+ Component: (props) => (
21
+ <PreferencesScreen {...props} onOpenAccounts={() => client.openSurface("accounts")} />
22
+ ),
23
+ });
24
+ client.addTimelineRenderer({
25
+ kind: SWITCH_ROW_KIND,
26
+ version: SWITCH_ROW_VERSION,
27
+ schema: SwitchRowSchema,
28
+ Component: SwitchRowView,
29
+ });
30
+
31
+ const stopCommands = contributeCommands(client, store);
32
+ const stopPills = contributePills(client, store);
33
+
34
+ return () => {
35
+ stopPills();
36
+ stopCommands();
37
+ store.stop();
38
+ };
39
+ }
@@ -0,0 +1,91 @@
1
+ import type { PluginServerContext, PluginSettingsState } from "@getpaseo/plugin/server";
2
+ import { ClaudeAdapter } from "./server/claude";
3
+ import { CodexAdapter } from "./server/codex";
4
+ import { Service, describe } from "./server/service";
5
+ import { preferences } from "./shared/preferences";
6
+ import {
7
+ cancelLogin,
8
+ clearAccountLimit,
9
+ getState,
10
+ redeemReset,
11
+ removeAccount,
12
+ renameAccount,
13
+ setAgentAccount,
14
+ setDefaultAccount,
15
+ forkAgent,
16
+ startLogin,
17
+ submitLoginCode,
18
+ } from "./shared/rpc";
19
+
20
+ export default function contribute(server: PluginServerContext) {
21
+ const service = new Service({ claude: new ClaudeAdapter(), codex: new CodexAdapter() });
22
+
23
+ const settings = server.registerSettings(preferences);
24
+ const applySettings = (state: PluginSettingsState<typeof preferences.schema>) => {
25
+ if (state.status === "ready") service.setPreferences(state.values);
26
+ };
27
+ void settings.read().then(applySettings, (error: unknown) => console.error("[ZeroSub] could not read preferences", describe(error)));
28
+ const stopSettings = settings.subscribe(applySettings);
29
+
30
+ void service.start().catch((error: unknown) => console.error("[ZeroSub] startup failed", describe(error)));
31
+
32
+ // Never let routing break or stall an agent: on any error, or if it takes too long (Paseo fails
33
+ // a hook after 30s), the session simply opens on its usual login.
34
+ server.before("agent.session_open", async ({ request }, context) => {
35
+ let timer: ReturnType<typeof setTimeout> | undefined;
36
+ const deadline = new Promise<undefined>((resolve) => {
37
+ timer = setTimeout(() => {
38
+ console.error(`[ZeroSub] routing ${request.agentId} took too long; using the default login`);
39
+ resolve(undefined);
40
+ }, 15_000);
41
+ });
42
+ try {
43
+ return await Promise.race([service.onSessionOpen(request, context), deadline]);
44
+ } catch (error) {
45
+ console.error(`[ZeroSub] could not route ${request.agentId}; using the default login`, describe(error));
46
+ return undefined;
47
+ } finally {
48
+ clearTimeout(timer);
49
+ }
50
+ });
51
+
52
+ server.on("agent.turn_started", (event, context) => {
53
+ void service.onTurnStarted(event.agent, context).catch(() => undefined);
54
+ });
55
+
56
+ // Failover can take longer than a hook invocation is allowed to, so it runs in the background.
57
+ server.on("agent.turn_ended", (event, context) => {
58
+ void service.onTurnEnded(event, context).catch((error: unknown) => {
59
+ console.error(`[ZeroSub] failover for ${event.agent.id} failed`, describe(error));
60
+ });
61
+ });
62
+ server.on("agent.archived", (event) => {
63
+ void service.onAgentArchived(event.agent.id).catch(() => undefined);
64
+ });
65
+
66
+ server.handle(getState, ({ refreshUsage }, { paseo }) => service.view(paseo, refreshUsage));
67
+ server.handle(startLogin, ({ family, method, accountId }) => service.startLogin(family, method, accountId));
68
+ server.handle(submitLoginCode, ({ loginId, code }) => service.submitCode(loginId, code));
69
+ server.handle(cancelLogin, ({ loginId }) => service.cancelLogin(loginId));
70
+ server.handle(renameAccount, async ({ accountId, label }) => {
71
+ await service.rename(accountId, label);
72
+ return { ok: true as const };
73
+ });
74
+ server.handle(removeAccount, async ({ accountId }, { paseo }) => ({
75
+ ok: true as const,
76
+ movedAgents: await service.remove(paseo, accountId),
77
+ }));
78
+ server.handle(setDefaultAccount, ({ accountId }, { paseo }) => service.setDefault(paseo, accountId));
79
+ server.handle(clearAccountLimit, async ({ accountId }) => {
80
+ await service.clearLimit(accountId);
81
+ return { ok: true as const };
82
+ });
83
+ server.handle(redeemReset, ({ accountId, agentId }, { paseo }) => service.redeem(paseo, accountId, agentId));
84
+ server.handle(setAgentAccount, ({ agentId, accountId }, { paseo }) => service.setAgentAccount(paseo, agentId, accountId));
85
+ server.handle(forkAgent, ({ agentId }, { paseo }) => service.forkAgent(paseo, agentId));
86
+
87
+ return async () => {
88
+ stopSettings();
89
+ await service.stop();
90
+ };
91
+ }
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@kapybara/zerosub",
3
+ "version": "1.0.0",
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
+ "keywords": [
6
+ "paseo",
7
+ "paseo-plugin",
8
+ "claude",
9
+ "claude-code",
10
+ "codex",
11
+ "chatgpt",
12
+ "subscriptions",
13
+ "accounts",
14
+ "usage-limits"
15
+ ],
16
+ "homepage": "https://github.com/kapybara-org/zerosub#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/kapybara-org/zerosub/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/kapybara-org/zerosub.git"
23
+ },
24
+ "license": "MIT",
25
+ "author": "Kapybara",
26
+ "files": [
27
+ "paseo-plugin.json",
28
+ "index.client.tsx",
29
+ "index.server.ts",
30
+ "client/",
31
+ "server/",
32
+ "shared/",
33
+ "!**/*.test.ts",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.server.json",
39
+ "test": "vitest run",
40
+ "audit:mobile": "! grep -rnE \"\\\\b(document|window|localStorage|navigator)\\\\.|<(div|span|p|a|button|input|img|ul|ol|li|section|header|footer|main|nav|form|label|h[1-6]|table|tr|td|svg|path|br|hr)[ >/]|className=|onClick=\" client/"
41
+ },
42
+ "devDependencies": {
43
+ "@getpaseo/client": "0.9.1",
44
+ "@getpaseo/plugin": "0.9.1",
45
+ "@getpaseo/protocol": "0.9.1",
46
+ "@tanstack/react-query": "^5.90.11",
47
+ "@types/node": "^22.20.4",
48
+ "@types/react": "~19.2.0",
49
+ "react": "19.1.0",
50
+ "react-native": "0.81.5",
51
+ "typescript": "^5.9.3",
52
+ "vitest": "^3.2.7",
53
+ "zod": "^4.4.3"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ }
58
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "id": "zerosub",
3
+ "description": "ZeroSub: use several Claude and ChatGPT (Codex) subscriptions side by side. Add accounts in-app, pick one per agent, and switch automatically when an account hits its limit.",
4
+ "requirements": {
5
+ "paseo": ">=0.9.1"
6
+ }
7
+ }
@@ -0,0 +1,126 @@
1
+ import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
2
+ import type { PluginTurnOutcome } from "@getpaseo/plugin/server";
3
+ import type { Family, LoginMethod, LoginStep, Usage } from "../shared/model";
4
+ import type { RedeemOutcome } from "../shared/rpc";
5
+
6
+ /** A provider's answer to a redeem request. */
7
+ export interface RedeemReply {
8
+ outcome: RedeemOutcome;
9
+ message: string;
10
+ left: number | null;
11
+ }
12
+
13
+ export interface Identity {
14
+ signedIn: boolean;
15
+ email: string | null;
16
+ plan: string | null;
17
+ organization: string | null;
18
+ /** Stable key for spotting the same account twice (org + email, or the ChatGPT account ID). */
19
+ identity: string | null;
20
+ }
21
+
22
+ /**
23
+ * `window`: a rolling usage window (5-hour, weekly, per-model) that usage readings track.
24
+ * `budget`: a spend cap, credit balance or org budget, invisible in usage windows.
25
+ */
26
+ export type LimitKind = "window" | "budget";
27
+
28
+ /** A usage reading, plus when to ask again if the provider said to slow down. */
29
+ export type UsageRead = Usage & { retryAt?: number };
30
+
31
+ export interface LimitHit {
32
+ kind: LimitKind;
33
+ /** When the limit lifts, if the provider said. */
34
+ resetsAt: string | null;
35
+ message: string;
36
+ }
37
+
38
+ export interface LoginProgress {
39
+ step: LoginStep;
40
+ /** Link that finishes by itself when opened on the daemon machine (localhost callback), or the device-code page. */
41
+ url: string | null;
42
+ /** Link whose page shows a code to paste back — works from any device. */
43
+ codeUrl: string | null;
44
+ userCode: string | null;
45
+ message: string | null;
46
+ }
47
+
48
+ export interface LoginHandle {
49
+ readonly progress: LoginProgress;
50
+ onProgress(listener: (progress: LoginProgress) => void): void;
51
+ submitCode(code: string): Promise<void>;
52
+ cancel(): void;
53
+ /** Settles when the flow ends. */
54
+ readonly finished: Promise<{ ok: boolean; message: string | null }>;
55
+ }
56
+
57
+ /**
58
+ * Launch-environment changes for a session. `null` means "inherit the daemon's value": the key is
59
+ * dropped from the per-session override map, and left untouched for processes ZeroSub spawns.
60
+ */
61
+ export type EnvPatch = Record<string, string | null>;
62
+
63
+ /** Everything provider-specific. The service only talks to accounts through this. */
64
+ export interface FamilyAdapter {
65
+ readonly family: Family;
66
+ /** A live conversation can reopen on another account of this provider. */
67
+ readonly portable: boolean;
68
+ /** Shortest gap between usage checks for one account, even when a refresh is forced. */
69
+ readonly usageSpacingMs: number;
70
+ available(): Promise<{ ok: boolean; detail: string | null }>;
71
+ /** Creates or refreshes a managed home: isolated credentials, everything else shared with main. */
72
+ prepareHome(home: string): Promise<void>;
73
+ /** `home === null` is the CLI's own login. */
74
+ env(home: string | null): Promise<EnvPatch>;
75
+ identity(home: string | null): Promise<Identity>;
76
+ /**
77
+ * Usage windows and banked resets. `renewLogin` lets the adapter have the CLI refresh an expired
78
+ * sign-in first (slow, so only for explicit requests, never background polls).
79
+ */
80
+ usage(home: string | null, options?: { renewLogin?: boolean }): Promise<UsageRead>;
81
+ /** Spends one banked reset. Only called for an explicit user request or the opt-in auto setting. */
82
+ /**
83
+ * Spends one banked reset. With `onlyAtLimit` (automatic use) it spends one only while the
84
+ * provider still sees the account at a limit, so two hosts sharing an account can't spend two
85
+ * resets on the same limit.
86
+ */
87
+ redeemReset(home: string | null, options?: { onlyAtLimit?: boolean }): Promise<RedeemReply>;
88
+ login(home: string | null, method: LoginMethod): Promise<LoginHandle>;
89
+ logout(home: string): Promise<void>;
90
+ /** Looks for a subscription usage-limit failure in a finished turn. */
91
+ detectLimit(event: { outcome: PluginTurnOutcome; timeline: readonly AgentTimelineItem[] }): LimitHit | null;
92
+ /** Looks for a turn that failed because the account's login is no longer valid. */
93
+ detectSignOut(event: { outcome: PluginTurnOutcome; timeline: readonly AgentTimelineItem[] }): string | null;
94
+ }
95
+
96
+ /** The environment for a process ZeroSub spawns against `patch`. */
97
+ export function spawnEnv(patch: EnvPatch): NodeJS.ProcessEnv {
98
+ const env: NodeJS.ProcessEnv = { ...process.env };
99
+ for (const [key, value] of Object.entries(patch)) if (value !== null) env[key] = value;
100
+ return env;
101
+ }
102
+
103
+ /** Applies `patch` to a session's launch override map. */
104
+ export function applyEnv(patch: EnvPatch, requestEnv: Record<string, string>): Record<string, string> {
105
+ const env = { ...requestEnv };
106
+ for (const [key, value] of Object.entries(patch)) {
107
+ if (value === null) delete env[key];
108
+ else env[key] = value;
109
+ }
110
+ return env;
111
+ }
112
+
113
+ /** Shared helper for login handles: progress state plus listeners. */
114
+ export class ProgressEmitter {
115
+ progress: LoginProgress = { step: "starting", url: null, codeUrl: null, userCode: null, message: null };
116
+ private readonly listeners = new Set<(progress: LoginProgress) => void>();
117
+
118
+ onProgress(listener: (progress: LoginProgress) => void): void {
119
+ this.listeners.add(listener);
120
+ }
121
+
122
+ update(patch: Partial<LoginProgress>): void {
123
+ this.progress = { ...this.progress, ...patch };
124
+ for (const listener of this.listeners) listener(this.progress);
125
+ }
126
+ }