tokenmaxxing 1.74.0 → 1.76.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenmaxxing",
3
- "version": "1.74.0",
3
+ "version": "1.76.0",
4
4
  "description": "Automatic Claude Code account switching: pool multiple accounts, start each session on its own account, and resume a session on a fresher account when quota fills.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/cli/serve.ts CHANGED
@@ -130,12 +130,8 @@ async function apiCall(req: Request): Promise<Response> {
130
130
  const method = (call.method ?? "").trim().toUpperCase();
131
131
  if (method === "") return json({ error: "missing method" }, 400);
132
132
  if (!call.url) return json({ error: "missing url" }, 400);
133
- let target: URL;
134
- try {
135
- target = new URL(call.url);
136
- } catch {
137
- return json({ error: "invalid url" }, 400);
138
- }
133
+ const target = URL.parse(call.url);
134
+ if (!target) return json({ error: "invalid url" }, 400);
139
135
  const pool = POOLS.find((p) => p.usageUrl === `${target.origin}${target.pathname}`);
140
136
  if (method !== "GET" || !pool) {
141
137
  return json({ error: `unsupported request: this hub serves ${POOLS.map((p) => `GET ${p.usageUrl}`).join(" and ")} only` }, 400);
@@ -166,16 +162,20 @@ function keyMatches(presented: string, key: string): boolean {
166
162
  return a.length === b.length && timingSafeEqual(a, b);
167
163
  }
168
164
 
169
- async function handle(req: Request, key: string): Promise<Response> {
170
- const url = new URL(req.url);
171
- if (!url.pathname.startsWith(MANAGEMENT_PREFIX)) return json({ error: "not found" }, 404);
165
+ function unauthorized(req: Request, key: string): Response | null {
172
166
  const presented = presentedKey(req);
173
167
  if (presented === "") return json({ error: "missing management key" }, 401);
174
168
  if (!keyMatches(presented, key)) return json({ error: "invalid management key" }, 401);
175
- const route = url.pathname.slice(MANAGEMENT_PREFIX.length);
176
- if (route === "auth-files" && req.method === "GET") return json(authFiles(loadConfig(), Date.now()));
177
- if (route === "api-call" && req.method === "POST") return apiCall(req);
178
- return json({ error: "not found" }, 404);
169
+ return null;
170
+ }
171
+
172
+ function guarded(key: string, handler: (req: Request) => Response | Promise<Response>): (req: Request) => Response | Promise<Response> {
173
+ return (req) => unauthorized(req, key) ?? handler(req);
174
+ }
175
+
176
+ function notFound(req: Request, key: string): Response {
177
+ const url = new URL(req.url);
178
+ return (url.pathname.startsWith(MANAGEMENT_PREFIX) ? unauthorized(req, key) : null) ?? json({ error: "not found" }, 404);
179
179
  }
180
180
 
181
181
  function managementKey(): string {
@@ -204,7 +204,11 @@ export async function cmdServe(args: string[]): Promise<number> {
204
204
  server = Bun.serve({
205
205
  hostname: "localhost",
206
206
  port: cfg.hub.port,
207
- fetch: (req) => handle(req, key),
207
+ routes: {
208
+ [`${MANAGEMENT_PREFIX}auth-files`]: { GET: guarded(key, () => json(authFiles(loadConfig(), Date.now()))) },
209
+ [`${MANAGEMENT_PREFIX}api-call`]: { POST: guarded(key, apiCall) },
210
+ },
211
+ fetch: (req) => notFound(req, key),
208
212
  error: (e) => {
209
213
  log("hub.error", { err: errorMessage(e) });
210
214
  return json({ error: "internal error" }, 500);
package/src/lib/claude.ts CHANGED
@@ -3,7 +3,6 @@ import { join } from "node:path";
3
3
  import { z } from "zod";
4
4
  import { readItem, writeItem, deleteItem, isolatedTarget, readStore, storeTarget, claudeAiOauthOnly } from "./credstore.ts";
5
5
  import { resolveRealClaude, resolveVerifiedClaude } from "./claudebin.ts";
6
- import { withClaudeRefreshLock } from "./claudelock.ts";
7
6
  import { ensurePathInRc, hubActivationHint, installSupervisor, managedShellRcSkipLines, shellRcPath, timerActivationHint } from "./install.ts";
8
7
  import { withLock } from "./lock.ts";
9
8
  import { errorMessage, log } from "./log.ts";
@@ -177,7 +176,7 @@ async function login(): Promise<Harvest | null> {
177
176
  await onExit;
178
177
  restoreTermios(savedTermios);
179
178
 
180
- const blobRaw = await withClaudeRefreshLock(onboardDir, () => readItem(iso));
179
+ const blobRaw = await readItem(iso);
181
180
  if (!blobRaw || !identityReady(cjPath)) {
182
181
  console.error(c.red("no login detected in the isolated session - nothing changed."));
183
182
  return null;
package/src/lib/decide.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { countBy } from "es-toolkit";
1
2
  import { withLock } from "./lock.ts";
2
3
  import { loadAccounts, loadConfig, liveWaitClaims, releaseWaitClaim, replaceWaitClaim, saveAccounts } from "./state.ts";
3
4
  import { isExhausted, limitWindows, liveUsed, nextWeeklyReset, pickBest, pickWaitTarget, sessionWindow, thresholdBars, weeklyWindow, type PickCtx } from "./picker.ts";
@@ -157,11 +158,8 @@ export async function evaluateAndMaybeSwap(p: Provider, now = Date.now(), canRes
157
158
  const fresh = loadAccounts(p.pool);
158
159
  const current = seatOf(fresh);
159
160
  const ctx: PickCtx = { now, thresholds: bars, currentId: current?.id ?? null, families: switchFamilies, seats };
160
- const waiters = new Map<string, number>();
161
- for (const claim of liveWaitClaims(now)) {
162
- if (claim.sessionId === waiterId) continue;
163
- waiters.set(claim.accountId, (waiters.get(claim.accountId) ?? 0) + 1);
164
- }
161
+ const others = liveWaitClaims(now).filter((c) => c.sessionId !== waiterId);
162
+ const waiters = new Map(Object.entries(countBy(others, (c) => c.accountId)));
165
163
  const target = pickWaitTarget(usable(fresh.accounts), ctx, waiters, MAX_WAITERS_PER_ACCOUNT, now + cfg.policy.maxWaitMs);
166
164
 
167
165
  if (!target) {
package/src/lib/paths.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { homedir } from "node:os";
1
+ import { homedir, userInfo } from "node:os";
2
2
  import { join } from "node:path";
3
3
  import { z } from "zod";
4
4
 
@@ -123,8 +123,20 @@ export function opencodeGoAuthJsonFor(accountId: string): string {
123
123
  return join(opencodeGoStoreDirFor(accountId), "auth.json");
124
124
  }
125
125
 
126
+ const CLAUDE_KEYCHAIN_ACCOUNT_PATTERN = /^[a-zA-Z0-9._-]+$/;
127
+
128
+ function claudeKeychainAccount(): string {
129
+ let name: string;
130
+ try {
131
+ name = process.env.USER || userInfo().username;
132
+ } catch {
133
+ return "claude-code-user";
134
+ }
135
+ return CLAUDE_KEYCHAIN_ACCOUNT_PATTERN.test(name) ? name : "claude-code-user";
136
+ }
137
+
126
138
  export const keychain = {
127
- account: env("TOKENMAXXING_KEYCHAIN_ACCOUNT", process.env.USER ?? "unknown"),
139
+ account: optionalEnv("TOKENMAXXING_KEYCHAIN_ACCOUNT") ?? claudeKeychainAccount(),
128
140
  } as const;
129
141
 
130
142
  export function shortId(accountId: string): string {
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { countBy } from "es-toolkit";
3
4
  import { z } from "zod";
4
5
  import { writeFileAtomic } from "./atomic.ts";
5
6
  import { pidExists, pidStartTime } from "./proc.ts";
@@ -70,7 +71,5 @@ export function livingPresences(dir: string): LivingPresence[] {
70
71
  }
71
72
 
72
73
  export function seatCounts(dir: string): Map<string, number> {
73
- const counts = new Map<string, number>();
74
- for (const presence of livingPresences(dir)) counts.set(presence.accountId, (counts.get(presence.accountId) ?? 0) + 1);
75
- return counts;
74
+ return new Map(Object.entries(countBy(livingPresences(dir), (p) => p.accountId)));
76
75
  }
@@ -1,105 +0,0 @@
1
- import { mkdirSync, realpathSync, rmdirSync, statSync, utimesSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { delay } from "es-toolkit";
4
- import { errorMessage, log } from "./log.ts";
5
- import { ErrnoSchema } from "./types.ts";
6
-
7
- const STALE_MS = 60_000;
8
- const HEARTBEAT_MS = 5_000;
9
- const ATTEMPTS = 5;
10
- const RETRY_MS = 1_000;
11
-
12
- function tryAcquire(lockDir: string): boolean {
13
- try {
14
- mkdirSync(lockDir);
15
- return true;
16
- } catch (e) {
17
- if (ErrnoSchema.safeParse(e).data?.code !== "EEXIST") throw e;
18
- }
19
- try {
20
- if (Date.now() - statSync(lockDir).mtimeMs > STALE_MS) {
21
- rmdirSync(lockDir);
22
- mkdirSync(lockDir);
23
- return true;
24
- }
25
- } catch { }
26
- return false;
27
- }
28
-
29
- export async function withClaudeRefreshLock<T>(
30
- dir: string,
31
- fn: (lock: { compromised: () => boolean }) => Promise<T> | T,
32
- opts: { attempts?: number; retryMs?: number; heartbeatMs?: number } = {},
33
- ): Promise<T> {
34
- const attempts = opts.attempts ?? ATTEMPTS;
35
- const retryMs = opts.retryMs ?? RETRY_MS;
36
- mkdirSync(dir, { recursive: true });
37
- const primary = join(dir, ".oauth_refresh.lock");
38
- let legacyRoot = dir;
39
- try { legacyRoot = realpathSync(dir); } catch { }
40
- const legacy = `${legacyRoot}.lock`;
41
-
42
- const held: string[] = [];
43
- for (let attempt = 1; held.length === 0; attempt++) {
44
- if (tryAcquire(primary)) {
45
- try {
46
- if (tryAcquire(legacy)) {
47
- held.push(legacy, primary);
48
- break;
49
- }
50
- } catch (e) {
51
- log("claudelock.legacy_error", { err: errorMessage(e) });
52
- held.push(primary);
53
- break;
54
- }
55
- rmdirSync(primary);
56
- }
57
- if (attempt >= attempts) {
58
- log("claudelock.contested", { attempts: attempt });
59
- throw new Error(
60
- "claude's credential-refresh lock is contested (a token refresh is likely mid-flight) - not touching the credential store; retry shortly",
61
- );
62
- }
63
- await delay(retryMs + Math.random() * retryMs);
64
- }
65
-
66
- const ours = new Map<string, number>();
67
- for (const d of held) ours.set(d, statSync(d).mtimeMs);
68
- let compromised = false;
69
- const markCompromised = () => {
70
- if (!compromised) {
71
- compromised = true;
72
- log("claudelock.compromised", {});
73
- }
74
- };
75
- const heartbeat = setInterval(() => {
76
- const now = new Date();
77
- for (const d of held) {
78
- try {
79
- if (statSync(d).mtimeMs !== ours.get(d)) {
80
- markCompromised();
81
- continue;
82
- }
83
- utimesSync(d, now, now);
84
- ours.set(d, statSync(d).mtimeMs);
85
- } catch {
86
- markCompromised();
87
- }
88
- }
89
- }, opts.heartbeatMs ?? HEARTBEAT_MS);
90
-
91
- try {
92
- const result = await fn({ compromised: () => compromised });
93
- if (compromised) {
94
- throw new Error("claude's credential-refresh lock was reclaimed while held (this process stalled past the 60s stale bar) - treat this critical section as failed");
95
- }
96
- return result;
97
- } finally {
98
- clearInterval(heartbeat);
99
- for (const d of held) {
100
- try {
101
- if (statSync(d).mtimeMs === ours.get(d)) rmdirSync(d);
102
- } catch { }
103
- }
104
- }
105
- }