@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/index.client.tsx CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { PluginClientContext } from "@getpaseo/plugin/client";
2
2
  import { AccountsSurface } from "./client/accounts-surface";
3
3
  import { contributeCommands } from "./client/commands";
4
+ import { contributeComposerItem } from "./client/composer-item";
4
5
  import { contributePills } from "./client/pills";
5
6
  import { PreferencesScreen } from "./client/settings-screen";
6
7
  import { createZeroSubStore } from "./client/store";
@@ -29,10 +30,12 @@ export default function contribute(client: PluginClientContext) {
29
30
  });
30
31
 
31
32
  const stopCommands = contributeCommands(client, store);
32
- const stopPills = contributePills(client, store);
33
+ const control = contributeComposerItem(client, store);
34
+ const stopPills = contributePills(client, store, control.added);
33
35
 
34
36
  return () => {
35
37
  stopPills();
38
+ control.stop();
36
39
  stopCommands();
37
40
  store.stop();
38
41
  };
package/index.server.ts CHANGED
@@ -1,9 +1,14 @@
1
1
  import type { PluginServerContext, PluginSettingsState } from "@getpaseo/plugin/server";
2
2
  import { ClaudeAdapter } from "./server/claude";
3
3
  import { CodexAdapter } from "./server/codex";
4
+ import { CursorAdapter } from "./server/cursor";
5
+ import { GrokAdapter } from "./server/grok";
6
+ import { PiAdapter } from "./server/pi";
4
7
  import { Service, describe } from "./server/service";
5
8
  import { preferences } from "./shared/preferences";
6
9
  import {
10
+ addApiAccount,
11
+ addAzureAccount,
7
12
  cancelLogin,
8
13
  clearAccountLimit,
9
14
  getState,
@@ -12,14 +17,22 @@ import {
12
17
  renameAccount,
13
18
  setAgentAccount,
14
19
  setDefaultAccount,
20
+ setNextAgentAccount,
15
21
  setAccountEnabled,
16
22
  forkAgent,
23
+ importAccount,
24
+ importPiAccount,
25
+ setAccountProxy,
26
+ setClaudeHomesDir,
27
+ setPiHomesDir,
17
28
  startLogin,
18
29
  submitLoginCode,
30
+ updateApiAccount,
31
+ updateAzureAccount,
19
32
  } from "./shared/rpc";
20
33
 
21
34
  export default function contribute(server: PluginServerContext) {
22
- const service = new Service({ claude: new ClaudeAdapter(), codex: new CodexAdapter() });
35
+ const service = new Service({ claude: new ClaudeAdapter(), codex: new CodexAdapter(), pi: new PiAdapter(), grok: new GrokAdapter(), cursor: new CursorAdapter() });
23
36
 
24
37
  const settings = server.registerSettings(preferences);
25
38
  const applySettings = (state: PluginSettingsState<typeof preferences.schema>) => {
@@ -28,20 +41,23 @@ export default function contribute(server: PluginServerContext) {
28
41
  void settings.read().then(applySettings, (error: unknown) => console.error("[ZeroSub] could not read preferences", describe(error)));
29
42
  const stopSettings = settings.subscribe(applySettings);
30
43
 
31
- void service.start().catch((error: unknown) => console.error("[ZeroSub] startup failed", describe(error)));
44
+ void service.start().catch((error: unknown) => console.error("[ZeroSub] startup failed; trying again in 30 s", describe(error)));
32
45
 
33
46
  // Never let routing break or stall an agent: on any error, or if it takes too long (Paseo fails
34
- // a hook after 30s), the session simply opens on its usual login.
47
+ // a hook after 30s), the session simply opens on its usual login. Routing is told it was given
48
+ // up on, so it doesn't record an account the session never opened on.
35
49
  server.before("agent.session_open", async ({ request }, context) => {
50
+ const late = new AbortController();
36
51
  let timer: ReturnType<typeof setTimeout> | undefined;
37
52
  const deadline = new Promise<undefined>((resolve) => {
38
53
  timer = setTimeout(() => {
39
54
  console.error(`[ZeroSub] routing ${request.agentId} took too long; using the default login`);
55
+ late.abort();
40
56
  resolve(undefined);
41
57
  }, 15_000);
42
58
  });
43
59
  try {
44
- return await Promise.race([service.onSessionOpen(request, context), deadline]);
60
+ return await Promise.race([service.onSessionOpen(request, context, late.signal), deadline]);
45
61
  } catch (error) {
46
62
  console.error(`[ZeroSub] could not route ${request.agentId}; using the default login`, describe(error));
47
63
  return undefined;
@@ -60,22 +76,37 @@ export default function contribute(server: PluginServerContext) {
60
76
  console.error(`[ZeroSub] failover for ${event.agent.id} failed`, describe(error));
61
77
  });
62
78
  });
79
+ // A new agent is in the next state the app reads, so its composer has its account at once.
80
+ server.on("agent.created", () => {
81
+ service.onAgentCreated();
82
+ });
63
83
  server.on("agent.archived", (event) => {
64
84
  void service.onAgentArchived(event.agent.id).catch(() => undefined);
65
85
  });
86
+ // Paseo 0.11 and later say when an agent closes, though the plugin SDK's types don't list it yet.
87
+ // An older Paseo refuses the event; agents then keep their record until their session next opens.
88
+ try {
89
+ const lifecycle = server as unknown as { on(name: "agent.closed", handler: (event: { agent: { id: string } }) => void): unknown };
90
+ lifecycle.on("agent.closed", (event) => {
91
+ void service.onAgentClosed(event.agent.id).catch(() => undefined);
92
+ });
93
+ } catch (error) {
94
+ console.error("[ZeroSub] this Paseo doesn't report closed agents", describe(error));
95
+ }
66
96
 
67
97
  server.handle(getState, ({ refreshUsage }, { paseo }) => service.view(paseo, refreshUsage));
68
- server.handle(startLogin, ({ family, method, accountId }) => service.startLogin(family, method, accountId));
98
+ server.handle(startLogin, ({ family, method, accountId, proxy }) => service.startLogin(family, method, accountId, proxy));
69
99
  server.handle(submitLoginCode, ({ loginId, code }) => service.submitCode(loginId, code));
70
100
  server.handle(cancelLogin, ({ loginId }) => service.cancelLogin(loginId));
71
101
  server.handle(renameAccount, async ({ accountId, label }) => {
72
102
  await service.rename(accountId, label);
73
103
  return { ok: true as const };
74
104
  });
75
- server.handle(removeAccount, async ({ accountId }, { paseo }) => ({
76
- ok: true as const,
77
- movedAgents: await service.remove(paseo, accountId),
78
- }));
105
+ server.handle(removeAccount, async ({ accountId }, { paseo }) => {
106
+ const { affected, moves } = await service.remove(paseo, accountId);
107
+ return { ok: true as const, movedAgents: affected, moves };
108
+ });
109
+ server.handle(setNextAgentAccount, ({ accountId, enabled }) => service.setNextAgent(accountId, enabled));
79
110
  server.handle(setDefaultAccount, ({ accountId }, { paseo }) => service.setDefault(paseo, accountId));
80
111
  server.handle(clearAccountLimit, async ({ accountId }) => {
81
112
  await service.clearLimit(accountId);
@@ -83,8 +114,20 @@ export default function contribute(server: PluginServerContext) {
83
114
  });
84
115
  server.handle(redeemReset, ({ accountId, agentId }, { paseo }) => service.redeem(paseo, accountId, agentId));
85
116
  server.handle(setAgentAccount, ({ agentId, accountId }, { paseo }) => service.setAgentAccount(paseo, agentId, accountId));
86
- server.handle(forkAgent, ({ agentId }, { paseo }) => service.forkAgent(paseo, agentId));
117
+ server.handle(forkAgent, ({ agentId, destination }, { paseo }) => service.forkAgent(paseo, agentId, destination));
87
118
  server.handle(setAccountEnabled, ({ accountId, enabled }, { paseo }) => service.setAccountEnabled(paseo, accountId, enabled));
119
+ server.handle(addApiAccount, async (input) => ({ accountId: await service.addApiAccount(input) }));
120
+ server.handle(updateApiAccount, async ({ accountId, ...input }) => {
121
+ await service.updateApiAccount(accountId, input);
122
+ return { ok: true as const };
123
+ });
124
+ server.handle(addAzureAccount, (input) => service.addAzureAccount(input));
125
+ server.handle(updateAzureAccount, async ({ accountId, ...input }) => ({ ok: true as const, ...(await service.updateAzureAccount(accountId, input)) }));
126
+ server.handle(setAccountProxy, async ({ accountId, proxy }) => ({ ok: true as const, proxy: await service.setProxy(accountId, proxy) }));
127
+ server.handle(setClaudeHomesDir, async ({ dir }) => ({ ok: true as const, ...(await service.setClaudeHomesDir(dir)) }));
128
+ server.handle(importAccount, async ({ path }) => ({ accountId: await service.importAccount(path) }));
129
+ server.handle(setPiHomesDir, async ({ dir }) => ({ ok: true as const, ...(await service.setPiHomesDir(dir)) }));
130
+ server.handle(importPiAccount, async ({ path }) => ({ accountId: await service.importPiAccount(path) }));
88
131
 
89
132
  return async () => {
90
133
  stopSettings();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kapybara/zerosub",
3
- "version": "1.5.1",
3
+ "version": "1.18.2",
4
4
  "description": "ZeroSub: use several Claude and ChatGPT (Codex) subscriptions side by side in Paseo. Add accounts in-app, pick one per agent, and switch automatically when an account hits its limit.",
5
5
  "keywords": [
6
6
  "paseo",
@@ -31,12 +31,15 @@
31
31
  "server/",
32
32
  "shared/",
33
33
  "!**/*.test.ts",
34
+ "!**/*.test-support.ts",
34
35
  "README.md",
35
36
  "LICENSE"
36
37
  ],
37
38
  "scripts": {
38
39
  "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.server.json",
39
- "test": "vitest run",
40
+ "guard:context": "node scripts/guard-context.mjs",
41
+ "guard:history": "node scripts/guard-context.mjs --history origin/main",
42
+ "test": "npm run guard:context && vitest run",
40
43
  "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
44
  },
42
45
  "devDependencies": {
@@ -3,6 +3,11 @@ import type { Identity } from "./adapter";
3
3
 
4
4
  type AccountIdentity = Pick<Identity, "identity" | "email">;
5
5
 
6
+ /** A Codex key read without its workspace, because `account/rateLimits/read` failed (see codex.ts). */
7
+ export function withoutWorkspace(identity: string | null | undefined): boolean {
8
+ return identity?.startsWith("chatgpt-email|") === true;
9
+ }
10
+
6
11
  /** Compare old workspace-only Codex keys using their saved email, without rewriting the registry. */
7
12
  export function sameAccountIdentity(
8
13
  family: Family, left: AccountIdentity, right: AccountIdentity, unknownMemberIsDuplicate = false,
@@ -12,6 +17,12 @@ export function sameAccountIdentity(
12
17
  const workspace = /^chatgpt\|([^|]+)(?:\|(.+))?$/;
13
18
  const a = workspace.exec(left.identity);
14
19
  const b = workspace.exec(right.identity);
20
+ if (withoutWorkspace(left.identity) || withoutWorkspace(right.identity)) {
21
+ // Such a key can't say which workspace it is, only whose: the same email is the same person.
22
+ const memberA = (a?.[2] ?? left.email)?.trim().toLowerCase();
23
+ const memberB = (b?.[2] ?? right.email)?.trim().toLowerCase();
24
+ return !!memberA && memberA === memberB;
25
+ }
15
26
  if (!a || !b) return left.identity === right.identity;
16
27
  if (a[1] !== b[1]) return false;
17
28
  const memberA = (a[2] ?? left.email)?.trim().toLowerCase();
package/server/adapter.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { PluginLifecycleEvents, PluginTurnOutcome } from "@getpaseo/plugin/server";
2
- import type { Family, LoginMethod, LoginStep, Usage } from "../shared/model";
2
+ import type { ApiSummary, Family, LoginMethod, LoginStep, Usage } from "../shared/model";
3
3
  import type { RedeemOutcome } from "../shared/rpc";
4
+ import type { ApiConfig } from "./homes";
5
+ import { providerEnv } from "./provider-env";
4
6
 
5
7
  /**
6
8
  * One timeline entry. Taken from the SDK rather than `@getpaseo/protocol`: Paseo only supplies
@@ -41,6 +43,11 @@ export interface LimitHit {
41
43
  /** When the limit lifts, if the provider said. */
42
44
  resetsAt: string | null;
43
45
  message: string;
46
+ /**
47
+ * The lowercase model name a limit is scoped to ("fable", "opus"): the limit of that model's own
48
+ * window, which leaves the account usable for other models. Null for a limit of the whole account.
49
+ */
50
+ scope?: string | null;
44
51
  }
45
52
 
46
53
  /** A finished turn, as Paseo reports it. */
@@ -70,6 +77,18 @@ export interface LoginHandle {
70
77
  readonly finished: Promise<{ ok: boolean; message: string | null }>;
71
78
  }
72
79
 
80
+ /** Where an account's CLI gets its proxy (see `FamilyAdapter.proxyState`). */
81
+ export interface ProxyState {
82
+ /** Its own proxy, or null when it uses whatever it inherits. */
83
+ own: string | null;
84
+ /** The user's file its own proxy is kept in, where setting one changes it; null when that's ZeroSub's own. */
85
+ file: string | null;
86
+ /** The proxy it goes through without one of its own, and where that's set; null when that's direct. */
87
+ inherited: { proxy: string; from: string } | null;
88
+ /** Why one can't be set here just now; null when it can. */
89
+ blocked?: string | null;
90
+ }
91
+
73
92
  /**
74
93
  * Launch-environment changes for a session. `null` means "inherit the daemon's value": the key is
75
94
  * dropped from the per-session override map, and left untouched for processes ZeroSub spawns.
@@ -84,10 +103,16 @@ export interface FamilyAdapter {
84
103
  /** Shortest gap between usage checks for one account, even when a refresh is forced. */
85
104
  readonly usageSpacingMs: number;
86
105
  available(): Promise<{ ok: boolean; detail: string | null }>;
87
- /** Creates or refreshes a managed home: isolated credentials, everything else shared with main. */
88
- prepareHome(home: string): Promise<void>;
89
- /** `home === null` is the CLI's own login. */
90
- env(home: string | null): Promise<EnvPatch>;
106
+ /**
107
+ * Creates or refreshes a managed home: isolated credentials, everything else shared with main.
108
+ * `wanted`, if given, is asked once nothing else works on the home; false leaves it untouched.
109
+ */
110
+ prepareHome(home: string, wanted?: () => Promise<boolean>): Promise<void>;
111
+ /**
112
+ * `home === null` is the CLI's own login. `session`, when the patch is for a session Paseo opens:
113
+ * the folder it runs in.
114
+ */
115
+ env(home: string | null, session?: { cwd: string }): Promise<EnvPatch>;
91
116
  identity(home: string | null): Promise<Identity>;
92
117
  /**
93
118
  * Usage windows and banked resets. `renewLogin` lets the adapter have the CLI refresh an expired
@@ -103,15 +128,97 @@ export interface FamilyAdapter {
103
128
  redeemReset(home: string | null, options?: { onlyAtLimit?: boolean }): Promise<RedeemReply>;
104
129
  login(home: string | null, method: LoginMethod): Promise<LoginHandle>;
105
130
  logout(home: string): Promise<void>;
131
+ /**
132
+ * An API account's key (reduced to a hint), base URL and, for Claude, its key kind and traffic
133
+ * switches; null for a subscription login. `home === null` (the CLI login) only where `mainApi` says so.
134
+ */
135
+ api?(home: string | null): Promise<ApiSummary | null>;
136
+ /** The CLI login's Anthropic key and base URL can be set here too. */
137
+ readonly mainApi?: boolean;
138
+ /**
139
+ * Stores an API account's key (`null` keeps the current one), base URL and, for Claude, key kind
140
+ * and traffic switches. `wanted`, if given, is asked once nothing else works on the home; false
141
+ * throws and writes nothing.
142
+ */
143
+ setApi?(home: string | null, config: ApiConfig, wanted?: () => Promise<boolean>): Promise<void>;
144
+ /**
145
+ * The proxy an added account's requests to `baseUrl` would cross as plain http:// (`through`: as
146
+ * if it were that one), which could read its key; null when none would. For providers whose API
147
+ * accounts keep their key in the home's settings (Claude's; Pi checks its own when it writes).
148
+ */
149
+ clearTextProxy?(home: string, baseUrl: string | null, through?: string): Promise<string | null>;
150
+ /**
151
+ * Where an account's CLI (`home === null`: the CLI's own login) gets its proxy, for providers that
152
+ * let ZeroSub set one per account (Claude's and Pi's).
153
+ */
154
+ proxyState?(home: string | null): Promise<ProxyState>;
155
+ /** Sets (or clears, with `null`) an account's proxy, for processes started afterwards. `wanted` as for `setApi`. */
156
+ setProxy?(home: string | null, proxy: string | null, wanted?: () => Promise<boolean>): Promise<void>;
157
+ /** The address Anthropic sees the account's requests come from; null when they go somewhere else first. */
158
+ egress?(home: string | null): Promise<{ ip: string; country: string | null } | null>;
159
+ /**
160
+ * Which of `homes` a process of the provider's CLI runs on right now, so a home isn't moved under
161
+ * it (see `Service.placeHomes`). Providers that have it keep added accounts' homes outside `homes/`.
162
+ */
163
+ homesInUse?(homes: readonly string[]): Promise<Set<string>>;
164
+ /**
165
+ * Whether `home` holds an account's sign-in or key: what a folder made again by a sync, or by the
166
+ * CLI started on it, lacks. Tells which of two folders an interrupted move left is the account.
167
+ */
168
+ holdsAccount?(home: string): Promise<boolean>;
169
+ /**
170
+ * Before a home's folder moves from `from` to `to`: copies what the CLI keeps for it outside the
171
+ * folder (Claude's Keychain entry on macOS) to where it looks for `to`'s, and checks the copy.
172
+ * Nothing to do where the sign-in lives in the folder. Repeating it after it worked does nothing.
173
+ */
174
+ copyCredentials?(from: string, to: string): Promise<void>;
175
+ /**
176
+ * Undoes `copyCredentials` for a move that didn't happen: removes `to`'s copy, but only while it's
177
+ * the same as `from`'s, so an entry that was there before is never touched.
178
+ */
179
+ dropCopiedCredentials?(from: string, to: string): Promise<void>;
180
+ /**
181
+ * Once the account's home is saved as `to`: removes `from`'s copy, but only while `to` holds a
182
+ * sign-in of its own, so the account's login is never left nowhere. False when it left `from`'s.
183
+ */
184
+ dropOldCredentials?(from: string, to: string): Promise<boolean>;
106
185
  /** Looks for a subscription usage-limit failure in a finished turn. */
107
186
  detectLimit(event: TurnEvent): LimitHit | null;
108
187
  /** Looks for a turn that failed because the account's login is no longer valid. */
109
188
  detectSignOut(event: TurnEvent): string | null;
110
189
  }
111
190
 
112
- /** The environment for a process ZeroSub spawns against `patch`. */
113
- export function spawnEnv(patch: EnvPatch): NodeJS.ProcessEnv {
114
- const env: NodeJS.ProcessEnv = { ...process.env };
191
+ /**
192
+ * Stands in for a family the service was given no adapter for: never available, so it never shows
193
+ * and nothing is routed to it.
194
+ */
195
+ export function missingAdapter(family: Family): FamilyAdapter {
196
+ const none = async (): Promise<never> => {
197
+ throw new Error(`${family} isn't set up here.`);
198
+ };
199
+ return {
200
+ family,
201
+ portable: true,
202
+ usageSpacingMs: 60_000,
203
+ available: async () => ({ ok: false, detail: null }),
204
+ prepareHome: none,
205
+ env: async () => ({}),
206
+ identity: none,
207
+ usage: none,
208
+ redeemReset: none,
209
+ login: none,
210
+ logout: none,
211
+ detectLimit: () => null,
212
+ detectSignOut: () => null,
213
+ };
214
+ }
215
+
216
+ /**
217
+ * The environment for a process ZeroSub spawns against `patch`: what Paseo gives a session of the
218
+ * family's provider, the daemon's environment with the provider's configured `env` over it.
219
+ */
220
+ export function spawnEnv(patch: EnvPatch, family: Family): NodeJS.ProcessEnv {
221
+ const env: NodeJS.ProcessEnv = { ...process.env, ...providerEnv(family) };
115
222
  for (const [key, value] of Object.entries(patch)) if (value !== null) env[key] = value;
116
223
  return env;
117
224
  }
@@ -0,0 +1,144 @@
1
+ import { mkdir } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { z } from "zod";
4
+ import { ApiMonthSchema, ApiPriceSchema, TokenCountSchema, usageMonth, type ApiMonth, type ApiPrice, type TokenCount } from "../shared/model";
5
+ import { Mutex, readJson, writeJsonAtomic } from "./json-file";
6
+ import { dataDir } from "./paths";
7
+
8
+ /**
9
+ * Monthly token totals of the paid API accounts (Azure OpenAI under ChatGPT), counted per turn from
10
+ * the CLI's own session files, in `$PASEO_HOME/zerosub/api-usage.json`. No keys, no text.
11
+ */
12
+
13
+ /** What one Codex thread had used by the last time its tokens were counted (see `countThread`). */
14
+ const ThreadMarkSchema = TokenCountSchema.extend({ at: z.string() });
15
+
16
+ export interface ApiUsageFile {
17
+ accounts: Record<string, ApiMonth>;
18
+ threads: Record<string, TokenCount & { at: string }>;
19
+ }
20
+
21
+ /** A thread not counted for this long is forgotten (its next turn counts from what it had then). */
22
+ const MARK_KEEP_MS = 62 * 24 * 60 * 60_000;
23
+
24
+ export const EMPTY_COUNT: TokenCount = { input: 0, cachedInput: 0, cacheWrite: 0, output: 0 };
25
+
26
+ /** A price table as read back from a file: entries that don't parse, or have no model name, are left out. */
27
+ export function cleanPrices(value: unknown): Record<string, ApiPrice> {
28
+ const prices: Record<string, ApiPrice> = {};
29
+ if (!value || typeof value !== "object" || Array.isArray(value)) return prices;
30
+ for (const [model, entry] of Object.entries(value)) {
31
+ const parsed = ApiPriceSchema.safeParse(entry);
32
+ if (model.trim() && parsed.success) prices[model.trim()] = parsed.data;
33
+ }
34
+ return prices;
35
+ }
36
+
37
+ function emptyMonth(now: number): ApiMonth {
38
+ return { month: usageMonth(now), models: {}, uncounted: 0, updatedAt: null };
39
+ }
40
+
41
+ /** Adds `delta` tokens of `model` to the account's month, starting a new month (UTC) when it has turned. */
42
+ export function addApiTokens(month: ApiMonth | undefined, model: string, delta: TokenCount, now: number): ApiMonth {
43
+ const current = month && month.month === usageMonth(now) ? structuredClone(month) : emptyMonth(now);
44
+ const entry = current.models[model] ?? EMPTY_COUNT;
45
+ current.models[model] = {
46
+ input: entry.input + delta.input,
47
+ cachedInput: entry.cachedInput + delta.cachedInput,
48
+ cacheWrite: entry.cacheWrite + delta.cacheWrite,
49
+ output: entry.output + delta.output,
50
+ };
51
+ current.updatedAt = new Date(now).toISOString();
52
+ return current;
53
+ }
54
+
55
+ /** Notes a turn whose tokens couldn't be read, in the account's month. */
56
+ export function addUncounted(month: ApiMonth | undefined, now: number): ApiMonth {
57
+ const current = month && month.month === usageMonth(now) ? structuredClone(month) : emptyMonth(now);
58
+ current.uncounted += 1;
59
+ current.updatedAt = new Date(now).toISOString();
60
+ return current;
61
+ }
62
+
63
+ /** The month as it shows now: an earlier month's totals don't count any more. */
64
+ export function currentMonth(month: ApiMonth | undefined, now: number): ApiMonth | null {
65
+ return month && month.month === usageMonth(now) ? month : null;
66
+ }
67
+
68
+ /** How much more a thread used since `previous`; all of `total` when it's new or its count went back. */
69
+ export function tokenDelta(previous: TokenCount | undefined, total: TokenCount): TokenCount {
70
+ if (!previous || total.input < previous.input || total.output < previous.output) return { ...total };
71
+ return {
72
+ input: total.input - previous.input,
73
+ cachedInput: Math.max(0, total.cachedInput - previous.cachedInput),
74
+ cacheWrite: Math.max(0, total.cacheWrite - previous.cacheWrite),
75
+ output: total.output - previous.output,
76
+ };
77
+ }
78
+
79
+ function usagePath(): string {
80
+ return join(dataDir(), "api-usage.json");
81
+ }
82
+
83
+ export class ApiUsageStore {
84
+ private cached: ApiUsageFile | null = null;
85
+ private readonly mutex = new Mutex();
86
+
87
+ constructor(private readonly path: string = usagePath()) {}
88
+
89
+ async read(): Promise<ApiUsageFile> {
90
+ if (this.cached) return this.cached;
91
+ const raw = (await readJson(this.path).catch(() => undefined)) as Partial<ApiUsageFile> | undefined;
92
+ const file: ApiUsageFile = { accounts: {}, threads: {} };
93
+ for (const [id, value] of Object.entries(raw?.accounts ?? {})) {
94
+ const parsed = ApiMonthSchema.safeParse(value);
95
+ if (parsed.success) file.accounts[id] = parsed.data;
96
+ }
97
+ for (const [id, value] of Object.entries(raw?.threads ?? {})) {
98
+ const parsed = ThreadMarkSchema.safeParse(value);
99
+ if (parsed.success) file.threads[id] = parsed.data;
100
+ }
101
+ this.cached ??= file;
102
+ return this.cached;
103
+ }
104
+
105
+ update(change: (draft: ApiUsageFile) => void): Promise<ApiUsageFile> {
106
+ return this.mutex.run(async () => {
107
+ const draft = structuredClone(await this.read());
108
+ change(draft);
109
+ const now = Date.now();
110
+ for (const [id, mark] of Object.entries(draft.threads)) if (now - Date.parse(mark.at) > MARK_KEEP_MS) delete draft.threads[id];
111
+ await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
112
+ await writeJsonAtomic(this.path, draft, { durable: false });
113
+ this.cached = draft;
114
+ return draft;
115
+ });
116
+ }
117
+
118
+ /**
119
+ * Counts what a Codex thread used since it was last counted, against `accountId`'s month. Each thread
120
+ * runs on one account (Codex threads can't change accounts), so its whole growth is that account's.
121
+ */
122
+ async countThread(accountId: string, threadId: string, reading: { model: string | null; total: TokenCount }, fallbackModel: string, now = Date.now()): Promise<TokenCount> {
123
+ let delta: TokenCount = EMPTY_COUNT;
124
+ await this.update((draft) => {
125
+ delta = tokenDelta(draft.threads[threadId], reading.total);
126
+ draft.threads[threadId] = { ...reading.total, at: new Date(now).toISOString() };
127
+ if (delta.input + delta.output > 0) draft.accounts[accountId] = addApiTokens(draft.accounts[accountId], reading.model ?? fallbackModel, delta, now);
128
+ });
129
+ return delta;
130
+ }
131
+
132
+ async noteUncounted(accountId: string, now = Date.now()): Promise<void> {
133
+ await this.update((draft) => {
134
+ draft.accounts[accountId] = addUncounted(draft.accounts[accountId], now);
135
+ });
136
+ }
137
+
138
+ async forget(accountId: string): Promise<void> {
139
+ if (!(await this.read()).accounts[accountId]) return;
140
+ await this.update((draft) => {
141
+ delete draft.accounts[accountId];
142
+ });
143
+ }
144
+ }