@robotostudio/ai-pool 0.0.0-stage → 0.1.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 +111 -2
- package/dist/failure.d.ts +39 -0
- package/dist/failure.js +102 -0
- package/dist/headroom.d.ts +34 -0
- package/dist/headroom.js +98 -0
- package/dist/pool.d.ts +107 -0
- package/dist/pool.js +91 -0
- package/package.json +48 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Roboto Studio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @robotostudio/ai-pool
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The pure half of a pool of AI logins (Claude, Codex and Grok subscriptions and API keys): which login a run may
|
|
4
|
+
lease, which one it takes, and what a provider failure does to it. It also reads the vendor's plan windows from the
|
|
5
|
+
`anthropic-ratelimit-unified-*` headers and from the Claude Agent SDK's rate-limit events.
|
|
6
|
+
|
|
7
|
+
It has no I/O. Your app keeps the store and its lock, the sealing of each login, the database roles and the events,
|
|
8
|
+
and calls these functions inside its own transaction. It needs no Effect. Its one dependency is `zod`, to parse the
|
|
9
|
+
vendor's events.
|
|
10
|
+
|
|
11
|
+
## Use it
|
|
12
|
+
|
|
13
|
+
1. Install it: `bun add @robotostudio/ai-pool`.
|
|
14
|
+
2. Implement `PoolStore` over your database: `modify(scope, f)` runs `f` in one transaction, under your lock.
|
|
15
|
+
3. Lease inside `modify`: apply the due resets, hand a run back the login it still holds, else `leasable`, then
|
|
16
|
+
`pick`. Write the run's lease fresh each time: that renews its clock.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import {
|
|
20
|
+
dueResets,
|
|
21
|
+
heldBy,
|
|
22
|
+
leasable,
|
|
23
|
+
pick,
|
|
24
|
+
type PoolStore,
|
|
25
|
+
} from "@robotostudio/ai-pool/pool";
|
|
26
|
+
|
|
27
|
+
declare const store: PoolStore;
|
|
28
|
+
|
|
29
|
+
const leased = await store.modify("my-team", (credentials, leases) => {
|
|
30
|
+
const now = Date.now();
|
|
31
|
+
const back = dueResets(credentials, now);
|
|
32
|
+
const current = credentials.map((c) => back.find((b) => b.id === c.id) || c);
|
|
33
|
+
const lapse = { ms: 5 * 60_000, unclocked: "lapsed" } as const;
|
|
34
|
+
// The run's old lease goes; a fresh one renews its clock, on the login it held or on a new pick.
|
|
35
|
+
const others = leases.filter((l) => l.holder !== "run-1");
|
|
36
|
+
const chosen =
|
|
37
|
+
heldBy(current, leases, now, { holder: "run-1", lapse }) ||
|
|
38
|
+
pick(leasable(current, others, now, { lapse, full: "skip" }), {
|
|
39
|
+
policy: "random-sub-first",
|
|
40
|
+
});
|
|
41
|
+
const added = chosen
|
|
42
|
+
? [{ credentialId: chosen.id, holder: "run-1", aliveAt: now }]
|
|
43
|
+
: [];
|
|
44
|
+
|
|
45
|
+
return [chosen, current, [...others, ...added]];
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
4. When the vendor refuses a turn, ask what it does to the login, and write that state. Do it inside `modify`, with
|
|
50
|
+
the login's row as it is now: a login already Disabled stays Disabled.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { onFailure } from "@robotostudio/ai-pool/failure";
|
|
54
|
+
import { planReading } from "@robotostudio/ai-pool/headroom";
|
|
55
|
+
import type { Credential } from "@robotostudio/ai-pool/pool";
|
|
56
|
+
|
|
57
|
+
declare const login: Credential;
|
|
58
|
+
|
|
59
|
+
const state = onFailure(
|
|
60
|
+
{ text: error.message, reading: planReading(rateLimitEvents) },
|
|
61
|
+
login,
|
|
62
|
+
Date.now(),
|
|
63
|
+
{ fallbackMs: 60 * 60_000, authDisables: "any" },
|
|
64
|
+
);
|
|
65
|
+
// { type: "exhausted", resetsAt } for a usage limit, { type: "disabled" } for a refused login, or undefined.
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## What it exports
|
|
69
|
+
|
|
70
|
+
| Entry | Exports |
|
|
71
|
+
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
72
|
+
| `/pool` | types `Harness`, `Method`, `State`, `Credential`, `Lease`, `LeasableOptions`, `PickPolicy`, `PoolStore`; `SUB_LEASE_CAP`, `leaseCap`, `isDue`, `dueResets`, `heldBy`, `leasable`, `quotaLeft`, `pick` |
|
|
73
|
+
| `/headroom` | types `Headroom`, `PlanReading`; `planReading`, `headroomFromHeaders` |
|
|
74
|
+
| `/failure` | types `ProviderClass`, `Signal`, `FailureOptions`; `providerClass`, `resetTime`, `exhaustedUntil`, `onFailure` |
|
|
75
|
+
|
|
76
|
+
- A Credential is Available, Exhausted until `resetsAt`, or Disabled. An Exhausted one whose reset has passed counts
|
|
77
|
+
as Available: `dueResets` gives the rows to write back.
|
|
78
|
+
- A lease is not a state. It is a `Lease` row beside the Credential: its holder, and the holder's last sign of life.
|
|
79
|
+
- `heldBy` hands a run the login it still holds, so it takes no second slot. A lapsed lease, a Disabled login and a
|
|
80
|
+
still Exhausted one are not handed back.
|
|
81
|
+
- `leaseCap`: a Codex or Grok subscription serves one run, because each run rotates its refresh token. Else the
|
|
82
|
+
Credential's own `leaseCap` above 0, else 16 for a Claude subscription and no cap for a key.
|
|
83
|
+
- `quotaLeft` and the `full` check read the five-hour and seven-day windows only. A per-model weekly or a monthly
|
|
84
|
+
window is not in `Headroom`.
|
|
85
|
+
|
|
86
|
+
## Pick your policy
|
|
87
|
+
|
|
88
|
+
The two apps that this package came from differ on purpose in these places. Each one is an option. You name it.
|
|
89
|
+
|
|
90
|
+
| Option | Values | What it does |
|
|
91
|
+
| --------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
92
|
+
| `pick(…, { policy })` | `random-sub-first`, `most-left` | One subscription at random, a key only when no subscription is left; or the most quota left, away from the run's `previous` login, then the least recently leased. |
|
|
93
|
+
| `leasable(…, { lapse: { ms } })` | ms, or no `lapse` | A lease whose holder showed no sign of life for this long stops counting against the cap. No `lapse`: a lease counts until you remove it. |
|
|
94
|
+
| `leasable(…, { lapse: { unclocked } })` | `lapsed`, `live` | A lease with no `aliveAt`: its holder is gone, or it is an old row from before the clock. |
|
|
95
|
+
| `leasable(…, { full })` | `skip`, `rank` | A window read full with its reset ahead: leave the login out until the reset, or keep it and let `most-left` rank it last. |
|
|
96
|
+
| `onFailure(…, { fallbackMs })` | ms | How long a usage limit keeps the login Exhausted when no reset parses from the reading or the text. |
|
|
97
|
+
| `onFailure(…, { authDisables })` | `any`, `sub` | Which logins a refused login Disables: any, or only a subscription. A key's 401 may be the app's own fault. |
|
|
98
|
+
|
|
99
|
+
These were merged, not made options. In each, one copy had no rule for the input, or read it wrongly:
|
|
100
|
+
|
|
101
|
+
- The failure text patterns are the union of both copies. A key's spend cap (`enforced_spend_limit_reached`, "reached
|
|
102
|
+
your specified API usage limits") is a usage limit until 00:00 UTC on the 1st. One copy read the first as a throttle.
|
|
103
|
+
- `resetTime` reads `resets 3:45pm` with no zone as UTC, and refuses another zone such as `(PST)`.
|
|
104
|
+
- `planReading` takes the SDK's flat event and Claude Code's `unifiedWindows` event. A reading that names one window
|
|
105
|
+
keeps that window.
|
|
106
|
+
|
|
107
|
+
## Not here
|
|
108
|
+
|
|
109
|
+
- The store, its lock and the leases' table.
|
|
110
|
+
- Sealing a login at rest. Use the platform's crypto or `jose`.
|
|
111
|
+
- Spend budgets, the audit trail, gauges for a screen, and a breaker across the fleet.
|
|
112
|
+
- Usage readers for Anthropic's OAuth usage endpoint, Codex's `wham/usage` and Grok's billing.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { PlanReading } from "./headroom.ts";
|
|
2
|
+
import type { Credential, State } from "./pool.ts";
|
|
3
|
+
/** What a failure says of the login: the plan's limit, a throttle, the vendor's overload, or a refused login. */
|
|
4
|
+
export type ProviderClass = "usage_limit" | "rate_limit" | "overloaded" | "auth";
|
|
5
|
+
/** A provider failure: the vendor's text, the HTTP status when there was a response, and the run's plan reading. */
|
|
6
|
+
export interface Signal {
|
|
7
|
+
readonly text?: string;
|
|
8
|
+
readonly status?: number;
|
|
9
|
+
readonly reading?: PlanReading | undefined;
|
|
10
|
+
}
|
|
11
|
+
/** The class of a provider failure; undefined when it says nothing about the provider. */
|
|
12
|
+
export declare const providerClass: ({ text, status, reading, }: Signal) => ProviderClass | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* The reset a vendor's text names, epoch ms: "resets at <ISO>"; the session limit's "resets 7:10pm (UTC)" as the next
|
|
15
|
+
* such time after `now`; or the weekly limit's "resets Nov 2, 6am (UTC)" as the next such date, at most 8 days out.
|
|
16
|
+
* The clock is read as UTC, the zone the CLI prints in a sandbox. Another zone in the parentheses is no reset.
|
|
17
|
+
*/
|
|
18
|
+
export declare const resetTime: (text: string, now: number) => number | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* When an Exhausted login comes back: the refused headline's reset, else the reset the text names, else 00:00 UTC on
|
|
21
|
+
* the 1st for a key's spend limit, else `fallbackMs` from `now`.
|
|
22
|
+
*/
|
|
23
|
+
export declare const exhaustedUntil: (signal: Signal, now: number, fallbackMs: number) => number;
|
|
24
|
+
export interface FailureOptions {
|
|
25
|
+
/** How long a usage limit with no reset that parses keeps the login Exhausted, in ms. */
|
|
26
|
+
readonly fallbackMs: number;
|
|
27
|
+
/**
|
|
28
|
+
* Which logins a refused login (`auth`) Disables: `any`, or only a `sub`. A key's 401 may be the app's own fault
|
|
29
|
+
* (a wrong header, a person's revoke), so `sub` leaves a key or gateway as it is.
|
|
30
|
+
*/
|
|
31
|
+
readonly authDisables: "any" | "sub";
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* What a provider failure does to the login that met it: a usage limit makes it Exhausted until `exhaustedUntil`, a
|
|
35
|
+
* refused login makes it Disabled (as `authDisables` says), and a throttle, an overload or anything else leaves it as
|
|
36
|
+
* it is (undefined). A login already Disabled stays so: only a person brings it back, never a reset. Pass the row as
|
|
37
|
+
* it is now, read in the same transaction as the write.
|
|
38
|
+
*/
|
|
39
|
+
export declare const onFailure: (signal: Signal, credential: Pick<Credential, "method" | "state">, now: number, { fallbackMs, authDisables }: FailureOptions) => State | undefined;
|
package/dist/failure.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// A status only (`API Error: 401`, `status: 401`, `401 Unauthorized`, Codex's `unauthorized (401)`), never the
|
|
2
|
+
// digits inside a request id. An org that turned off subscription logins, and a login whose refresh was refused, too.
|
|
3
|
+
const AUTH = /authenticat|not logged in|invalid api key|invalid x-api-key|(?:API Error|status):? 401\b|\b401 Unauthorized|\bunauthorized \(401\)|access token could not be refreshed|disabled Claude subscription access/iu;
|
|
4
|
+
// The plan's own limit, which names its reset. A key's spend cap is one too: it holds until the 1st.
|
|
5
|
+
const USAGE_LIMIT = /hit your (?:session |weekly )?limit|usage limit/iu;
|
|
6
|
+
const SPEND_LIMIT = /enforced_spend_limit_reached|reached your specified API usage limits/iu;
|
|
7
|
+
const OVERLOADED = /API Error:? 5\d\d\b|overloaded|Internal server error|\bapi_error\b|model is at capacity/iu;
|
|
8
|
+
const THROTTLED = /(?:API Error|status):? 429\b|\b429 Too Many Requests|rate.limit/iu;
|
|
9
|
+
/** The class of a provider failure; undefined when it says nothing about the provider. */
|
|
10
|
+
export const providerClass = ({ text = "", status = 0, reading, }) => {
|
|
11
|
+
if (reading?.refused) {
|
|
12
|
+
return "usage_limit";
|
|
13
|
+
}
|
|
14
|
+
if (status === 401 || AUTH.test(text)) {
|
|
15
|
+
return "auth";
|
|
16
|
+
}
|
|
17
|
+
if (USAGE_LIMIT.test(text) || SPEND_LIMIT.test(text)) {
|
|
18
|
+
return "usage_limit";
|
|
19
|
+
}
|
|
20
|
+
if (status >= 500 || OVERLOADED.test(text)) {
|
|
21
|
+
return "overloaded";
|
|
22
|
+
}
|
|
23
|
+
return status === 429 || THROTTLED.test(text) ? "rate_limit" : undefined;
|
|
24
|
+
};
|
|
25
|
+
// `resets 7:10pm (UTC)`, `resets Nov 2, 6am (UTC)`, or with no zone. Another zone does not match.
|
|
26
|
+
const CLOCK = /resets (?:([a-z]{3}) (\d{1,2}), )?(\d{1,2})(?::(\d{2}))?(am|pm)(?! \((?!UTC\)))/iu;
|
|
27
|
+
const DAY = 24 * 60 * 60 * 1000;
|
|
28
|
+
const MONTHS = [
|
|
29
|
+
"jan",
|
|
30
|
+
"feb",
|
|
31
|
+
"mar",
|
|
32
|
+
"apr",
|
|
33
|
+
"may",
|
|
34
|
+
"jun",
|
|
35
|
+
"jul",
|
|
36
|
+
"aug",
|
|
37
|
+
"sep",
|
|
38
|
+
"oct",
|
|
39
|
+
"nov",
|
|
40
|
+
"dec",
|
|
41
|
+
];
|
|
42
|
+
/**
|
|
43
|
+
* The reset a vendor's text names, epoch ms: "resets at <ISO>"; the session limit's "resets 7:10pm (UTC)" as the next
|
|
44
|
+
* such time after `now`; or the weekly limit's "resets Nov 2, 6am (UTC)" as the next such date, at most 8 days out.
|
|
45
|
+
* The clock is read as UTC, the zone the CLI prints in a sandbox. Another zone in the parentheses is no reset.
|
|
46
|
+
*/
|
|
47
|
+
export const resetTime = (text, now) => {
|
|
48
|
+
const iso = Date.parse(/resets at (\S+)/iu.exec(text)?.[1] || "");
|
|
49
|
+
if (Number.isFinite(iso)) {
|
|
50
|
+
return iso;
|
|
51
|
+
}
|
|
52
|
+
const [, monthName, day, hour, minute, half] = CLOCK.exec(text) || [];
|
|
53
|
+
if (!hour) {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
const hours = (Number(hour) % 12) + (half?.toLowerCase() === "pm" ? 12 : 0);
|
|
57
|
+
const at = (y, m, d) => Date.UTC(y, m, d, hours, Number(minute || 0));
|
|
58
|
+
const today = new Date(now);
|
|
59
|
+
if (!monthName) {
|
|
60
|
+
const next = at(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
|
|
61
|
+
return next > now ? next : next + DAY;
|
|
62
|
+
}
|
|
63
|
+
const month = MONTHS.indexOf(monthName.toLowerCase());
|
|
64
|
+
const year = today.getUTCFullYear();
|
|
65
|
+
const thisYear = at(year, month, Number(day));
|
|
66
|
+
const next = thisYear > now ? thisYear : at(year + 1, month, Number(day));
|
|
67
|
+
// A weekly reset is at most a week out: a date read just after it passed is no reset, not one a year away.
|
|
68
|
+
return month !== -1 && next - now <= 8 * DAY ? next : undefined;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* When an Exhausted login comes back: the refused headline's reset, else the reset the text names, else 00:00 UTC on
|
|
72
|
+
* the 1st for a key's spend limit, else `fallbackMs` from `now`.
|
|
73
|
+
*/
|
|
74
|
+
export const exhaustedUntil = (signal, now, fallbackMs) => {
|
|
75
|
+
const text = signal.text || "";
|
|
76
|
+
const at = new Date(now);
|
|
77
|
+
return (signal.reading?.refused?.resetsAt ??
|
|
78
|
+
resetTime(text, now) ??
|
|
79
|
+
(SPEND_LIMIT.test(text)
|
|
80
|
+
? Date.UTC(at.getUTCFullYear(), at.getUTCMonth() + 1, 1)
|
|
81
|
+
: now + fallbackMs));
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* What a provider failure does to the login that met it: a usage limit makes it Exhausted until `exhaustedUntil`, a
|
|
85
|
+
* refused login makes it Disabled (as `authDisables` says), and a throttle, an overload or anything else leaves it as
|
|
86
|
+
* it is (undefined). A login already Disabled stays so: only a person brings it back, never a reset. Pass the row as
|
|
87
|
+
* it is now, read in the same transaction as the write.
|
|
88
|
+
*/
|
|
89
|
+
export const onFailure = (signal, credential, now, { fallbackMs, authDisables }) => {
|
|
90
|
+
const cls = providerClass(signal);
|
|
91
|
+
if (credential.state.type === "disabled") {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
if (cls === "usage_limit") {
|
|
95
|
+
return {
|
|
96
|
+
type: "exhausted",
|
|
97
|
+
resetsAt: exhaustedUntil(signal, now, fallbackMs),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
const disables = authDisables === "any" || credential.method === "sub";
|
|
101
|
+
return cls === "auth" && disables ? { type: "disabled" } : undefined;
|
|
102
|
+
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One login's plan windows: each one's share used (0 to 1) and its reset (epoch ms). A window named with no figure
|
|
3
|
+
* holds its reset alone. `checkedAt` (epoch ms) is when the app read it: `quotaLeft` takes a window with no reset as
|
|
4
|
+
* reset once its length has passed since then.
|
|
5
|
+
*/
|
|
6
|
+
export interface Headroom {
|
|
7
|
+
readonly fiveHour?: number;
|
|
8
|
+
readonly sevenDay?: number;
|
|
9
|
+
readonly fiveHourResetsAt?: number;
|
|
10
|
+
readonly sevenDayResetsAt?: number;
|
|
11
|
+
readonly checkedAt?: number;
|
|
12
|
+
}
|
|
13
|
+
/** What the vendor last said of the plan: its windows, and whether it refused the turn until a reset. */
|
|
14
|
+
export interface PlanReading {
|
|
15
|
+
readonly headroom: Headroom | undefined;
|
|
16
|
+
/** The headline window is `rejected` and no overage serves it: the plan's limit, until its reset. */
|
|
17
|
+
readonly refused: {
|
|
18
|
+
readonly resetsAt: number | undefined;
|
|
19
|
+
} | undefined;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* What a run's rate-limit events say of the plan, oldest first, in either form the vendor sends. Each of the
|
|
23
|
+
* five-hour and seven-day windows takes its latest mention. Only the last event decides whether the plan refused the
|
|
24
|
+
* turn. Other windows and anything that is no rate-limit event are skipped; none at all is undefined.
|
|
25
|
+
*/
|
|
26
|
+
export declare const planReading: (events: readonly unknown[]) => PlanReading | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* A subscription's windows from the `anthropic-ratelimit-unified-{5h,7d}-{utilization,status,reset}` headers of any
|
|
29
|
+
* Messages answer: utilization 0 to 1, the reset in epoch seconds. A `rejected` window is full. A window with no
|
|
30
|
+
* figure is skipped; undefined when none parses, as for an API key, whose headers are per-minute buckets.
|
|
31
|
+
*/
|
|
32
|
+
export declare const headroomFromHeaders: (headers: {
|
|
33
|
+
readonly get: (name: string) => string | null;
|
|
34
|
+
}) => Headroom | undefined;
|
package/dist/headroom.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// What a vendor says of a login's plan windows: the `anthropic-ratelimit-unified-*` headers of a Messages answer, and
|
|
2
|
+
// the rate-limit events the Claude Agent SDK and Claude Code stream.
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
/** A window as the vendor names it: `utilization` 0 to 1, `resetsAt` in epoch seconds. */
|
|
5
|
+
const Window = z.object({
|
|
6
|
+
utilization: z.number().optional(),
|
|
7
|
+
resetsAt: z.number().optional(),
|
|
8
|
+
});
|
|
9
|
+
/** `SDKRateLimitInfo`: one window per event under `rateLimitType`, or every window under `unifiedWindows`. */
|
|
10
|
+
const Info = Window.extend({
|
|
11
|
+
status: z.string(),
|
|
12
|
+
rateLimitType: z.string().optional(),
|
|
13
|
+
isUsingOverage: z.boolean().optional(),
|
|
14
|
+
overageStatus: z.string().optional(),
|
|
15
|
+
unifiedWindows: z
|
|
16
|
+
.object({ five_hour: Window.optional(), seven_day: Window.optional() })
|
|
17
|
+
.optional(),
|
|
18
|
+
});
|
|
19
|
+
/** The info bare, as the SDK's `rate_limit` event data, or inside Claude Code's stream event. */
|
|
20
|
+
const Event = z.union([
|
|
21
|
+
z
|
|
22
|
+
.object({ type: z.literal("rate_limit_event"), rate_limit_info: Info })
|
|
23
|
+
.transform((e) => e.rate_limit_info),
|
|
24
|
+
// Bare, its `status` must be the SDK's own: a `system` or task message also carries a string `status`.
|
|
25
|
+
Info.extend({ status: z.enum(["allowed", "allowed_warning", "rejected"]) }),
|
|
26
|
+
]);
|
|
27
|
+
/** A figure the vendor gave: a finite number, 0 included. */
|
|
28
|
+
const given = (n) => Number.isFinite(n);
|
|
29
|
+
// A vendor reports a window past full: Claude's utilization is "usually 0-1".
|
|
30
|
+
const clamp = (used) => Math.min(1, Math.max(0, used));
|
|
31
|
+
const millis = (seconds = 0) => seconds > 0 ? Math.round(seconds * 1000) : undefined;
|
|
32
|
+
/** The two windows as `Headroom`, a window's missing figure or reset left out; undefined when nothing is left. */
|
|
33
|
+
const headroomOf = (five, seven) => {
|
|
34
|
+
const fiveAt = millis(five?.resetsAt);
|
|
35
|
+
const sevenAt = millis(seven?.resetsAt);
|
|
36
|
+
const h = {
|
|
37
|
+
...(given(five?.utilization) && { fiveHour: clamp(five.utilization) }),
|
|
38
|
+
...(given(seven?.utilization) && { sevenDay: clamp(seven.utilization) }),
|
|
39
|
+
...(given(fiveAt) && { fiveHourResetsAt: fiveAt }),
|
|
40
|
+
...(given(sevenAt) && { sevenDayResetsAt: sevenAt }),
|
|
41
|
+
};
|
|
42
|
+
return Object.keys(h).length > 0 ? h : undefined;
|
|
43
|
+
};
|
|
44
|
+
/** The window `type` names in one event: under `unifiedWindows`, or the event itself when it is that window's. */
|
|
45
|
+
const windowIn = (info, type) => {
|
|
46
|
+
if (info.unifiedWindows) {
|
|
47
|
+
return info.unifiedWindows[type];
|
|
48
|
+
}
|
|
49
|
+
return info.rateLimitType === type ? info : undefined;
|
|
50
|
+
};
|
|
51
|
+
/** The `overageStatus` values under which Claude continues a turn on overage past a `rejected` headline. */
|
|
52
|
+
const OVERAGE_SERVES = new Set(["allowed", "allowed_warning"]);
|
|
53
|
+
/**
|
|
54
|
+
* What a run's rate-limit events say of the plan, oldest first, in either form the vendor sends. Each of the
|
|
55
|
+
* five-hour and seven-day windows takes its latest mention. Only the last event decides whether the plan refused the
|
|
56
|
+
* turn. Other windows and anything that is no rate-limit event are skipped; none at all is undefined.
|
|
57
|
+
*/
|
|
58
|
+
export const planReading = (events) => {
|
|
59
|
+
const infos = events.flatMap((e) => Event.safeParse(e).data || []);
|
|
60
|
+
const last = infos.at(-1);
|
|
61
|
+
if (!last) {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
const latest = (type) => infos.flatMap((i) => windowIn(i, type) || []).at(-1);
|
|
65
|
+
const served = last.isUsingOverage === true ||
|
|
66
|
+
OVERAGE_SERVES.has(last.overageStatus || "");
|
|
67
|
+
return {
|
|
68
|
+
headroom: headroomOf(latest("five_hour"), latest("seven_day")),
|
|
69
|
+
refused: last.status === "rejected" && !served
|
|
70
|
+
? { resetsAt: millis(last.resetsAt) }
|
|
71
|
+
: undefined,
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
/** A number a header holds; undefined for an absent, empty or non-numeric one, which `Number` would read as 0. */
|
|
75
|
+
const figure = (value) => {
|
|
76
|
+
const n = Number(value || Number.NaN);
|
|
77
|
+
return Number.isFinite(n) ? n : undefined;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* A subscription's windows from the `anthropic-ratelimit-unified-{5h,7d}-{utilization,status,reset}` headers of any
|
|
81
|
+
* Messages answer: utilization 0 to 1, the reset in epoch seconds. A `rejected` window is full. A window with no
|
|
82
|
+
* figure is skipped; undefined when none parses, as for an API key, whose headers are per-minute buckets.
|
|
83
|
+
*/
|
|
84
|
+
export const headroomFromHeaders = (headers) => {
|
|
85
|
+
const window = (h) => {
|
|
86
|
+
const header = (field) => headers.get(`anthropic-ratelimit-unified-${h}-${field}`);
|
|
87
|
+
const used = figure(header("utilization"));
|
|
88
|
+
const reset = figure(header("reset"));
|
|
89
|
+
if (!given(used)) {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
utilization: header("status") === "rejected" ? 1 : used,
|
|
94
|
+
...(given(reset) && { resetsAt: reset }),
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
return headroomOf(window("5h"), window("7d"));
|
|
98
|
+
};
|
package/dist/pool.d.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { Headroom } from "./headroom.ts";
|
|
2
|
+
export type Harness = "claude" | "codex" | "grok";
|
|
3
|
+
/** `sub` is the harness's own subscription login; `key` and `gateway` bill per token. */
|
|
4
|
+
export type Method = "sub" | "key" | "gateway";
|
|
5
|
+
/**
|
|
6
|
+
* A Credential's state. Exhausted holds until `resetsAt` (epoch ms), then counts as Available with no one touching it.
|
|
7
|
+
* Disabled holds until a person brings it back. A lease is not a state: it is a `Lease` row beside the Credential.
|
|
8
|
+
*/
|
|
9
|
+
export type State = {
|
|
10
|
+
readonly type: "available";
|
|
11
|
+
} | {
|
|
12
|
+
readonly type: "exhausted";
|
|
13
|
+
readonly resetsAt: number;
|
|
14
|
+
} | {
|
|
15
|
+
readonly type: "disabled";
|
|
16
|
+
};
|
|
17
|
+
/** One login of one harness. An app's own row type may carry more fields: every function here passes them through. */
|
|
18
|
+
export interface Credential {
|
|
19
|
+
readonly id: string;
|
|
20
|
+
readonly harness: Harness;
|
|
21
|
+
readonly method: Method;
|
|
22
|
+
readonly state: State;
|
|
23
|
+
/** How many runs may hold it at once. None is the default `leaseCap` gives it. */
|
|
24
|
+
readonly leaseCap?: number;
|
|
25
|
+
/** The last reading of its plan windows. None is a login never read. */
|
|
26
|
+
readonly headroom?: Headroom;
|
|
27
|
+
/** When it was last leased, epoch ms. None is never leased. */
|
|
28
|
+
readonly lastLeasedAt?: number;
|
|
29
|
+
}
|
|
30
|
+
/** One run's hold on one Credential. `holder` names the run (or its claim); `aliveAt` is its last sign of life, epoch ms. */
|
|
31
|
+
export interface Lease {
|
|
32
|
+
readonly credentialId: string;
|
|
33
|
+
readonly holder: string;
|
|
34
|
+
readonly aliveAt?: number;
|
|
35
|
+
}
|
|
36
|
+
/** Runs on one Claude subscription at once (a load spike measured 16). A key has no cap: its limits are per org. */
|
|
37
|
+
export declare const SUB_LEASE_CAP = 16;
|
|
38
|
+
/**
|
|
39
|
+
* How many runs may hold `c` at once. A Codex or Grok subscription serves one run whatever its `leaseCap`: each run
|
|
40
|
+
* rotates the login's refresh token. Else its own `leaseCap` above 0, else 16 for a subscription and no cap for a key.
|
|
41
|
+
*/
|
|
42
|
+
export declare const leaseCap: (c: Credential) => number;
|
|
43
|
+
/** Exhausted, with its reset passed by `now`: Available again. */
|
|
44
|
+
export declare const isDue: (state: State, now: number) => boolean;
|
|
45
|
+
/** The Credentials whose reset is due at `now`, set Available: what the app writes back. */
|
|
46
|
+
export declare const dueResets: <C extends Credential>(credentials: readonly C[], now: number) => C[];
|
|
47
|
+
export interface LeasableOptions {
|
|
48
|
+
/**
|
|
49
|
+
* A lease whose holder showed no sign of life for `ms` stops counting against the cap. `unclocked` says what a lease
|
|
50
|
+
* with no `aliveAt` is: `lapsed` (its holder is gone) or `live` (an old row from before the clock). None: every lease
|
|
51
|
+
* counts until the app removes it.
|
|
52
|
+
*/
|
|
53
|
+
readonly lapse?: {
|
|
54
|
+
readonly ms: number;
|
|
55
|
+
readonly unclocked: "lapsed" | "live";
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* A window read full (used 1) with its reset still ahead: `skip` leaves the Credential out until that reset (a full
|
|
59
|
+
* window with no reset is no skip: no reset is known to be ahead). `rank` keeps it, and `most-left` ranks it last.
|
|
60
|
+
*/
|
|
61
|
+
readonly full: "skip" | "rank";
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The Credentials a run may lease at `now`: Available, or Exhausted with its reset due; under its lease cap, counting
|
|
65
|
+
* only live leases; and, with `full: "skip"`, no window full until a reset still ahead.
|
|
66
|
+
*/
|
|
67
|
+
export declare const leasable: <C extends Credential>(credentials: readonly C[], leases: readonly Lease[], now: number, { lapse, full }: LeasableOptions) => C[];
|
|
68
|
+
/**
|
|
69
|
+
* The Credential `holder` already leases, so a run that asks again keeps its login and takes no second slot. Only a
|
|
70
|
+
* live lease (the same `lapse` as `leasable`: a lapsed one may be another run's slot by now), on an Available login or
|
|
71
|
+
* one whose reset is due: a Disabled or still Exhausted login is no longer the run's to use, and the run leases anew.
|
|
72
|
+
* Pass one pool's Credentials: one harness and one method.
|
|
73
|
+
*/
|
|
74
|
+
export declare const heldBy: <C extends Credential>(credentials: readonly C[], leases: readonly Lease[], now: number, { holder, lapse, }: Pick<LeasableOptions, "lapse"> & {
|
|
75
|
+
readonly holder: string;
|
|
76
|
+
}) => C | undefined;
|
|
77
|
+
/**
|
|
78
|
+
* A login's quota left (0 to 1): 1 less its most used window. A window that has reset by `now` is unused: its
|
|
79
|
+
* `resetsAt` has passed, or with none, its length since `checkedAt`. No reading is 1 left. Only the five-hour and
|
|
80
|
+
* seven-day windows count: a per-model weekly or a monthly window is not in `Headroom`.
|
|
81
|
+
*/
|
|
82
|
+
export declare const quotaLeft: (headroom: Headroom | undefined, now: number) => number;
|
|
83
|
+
/**
|
|
84
|
+
* How `pick` chooses among leasable Credentials.
|
|
85
|
+
* - `random-sub-first`: one subscription at random, since a subscription is flat cost; a key only when no
|
|
86
|
+
* subscription is left, since a key bills per token; then one key at random.
|
|
87
|
+
* - `most-left`: not the run's `previous` login unless it is the only one; then the most quota left (`quotaLeft`);
|
|
88
|
+
* then the least recently leased, never leased first; then the order given.
|
|
89
|
+
*/
|
|
90
|
+
export type PickPolicy = {
|
|
91
|
+
readonly policy: "random-sub-first";
|
|
92
|
+
readonly random?: () => number;
|
|
93
|
+
} | {
|
|
94
|
+
readonly policy: "most-left";
|
|
95
|
+
readonly now: number;
|
|
96
|
+
readonly previous?: string;
|
|
97
|
+
};
|
|
98
|
+
/** The Credential a run leases, from `leasable`'s answer. None when there is none. */
|
|
99
|
+
export declare const pick: <C extends Credential>(candidates: readonly C[], how: PickPolicy) => C | undefined;
|
|
100
|
+
/**
|
|
101
|
+
* The app's store of one scope's Credentials and Leases (a team, a workspace, a whole fleet). `modify` runs `f` in
|
|
102
|
+
* one transaction under the store's own lock, so two runs never lease past a cap. `f` returns its answer and the
|
|
103
|
+
* scope's Credentials and Leases as they are after it; the store writes the difference.
|
|
104
|
+
*/
|
|
105
|
+
export interface PoolStore<C extends Credential = Credential, L extends Lease = Lease> {
|
|
106
|
+
readonly modify: <A>(scope: string, f: (credentials: readonly C[], leases: readonly L[]) => readonly [A, readonly C[], readonly L[]]) => Promise<A>;
|
|
107
|
+
}
|
package/dist/pool.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/** Runs on one Claude subscription at once (a load spike measured 16). A key has no cap: its limits are per org. */
|
|
2
|
+
export const SUB_LEASE_CAP = 16;
|
|
3
|
+
/**
|
|
4
|
+
* How many runs may hold `c` at once. A Codex or Grok subscription serves one run whatever its `leaseCap`: each run
|
|
5
|
+
* rotates the login's refresh token. Else its own `leaseCap` above 0, else 16 for a subscription and no cap for a key.
|
|
6
|
+
*/
|
|
7
|
+
export const leaseCap = (c) => {
|
|
8
|
+
const own = c.leaseCap ?? 0;
|
|
9
|
+
if (c.method === "sub" && c.harness !== "claude") {
|
|
10
|
+
return 1;
|
|
11
|
+
}
|
|
12
|
+
if (own > 0) {
|
|
13
|
+
return own;
|
|
14
|
+
}
|
|
15
|
+
return c.method === "sub" ? SUB_LEASE_CAP : Infinity;
|
|
16
|
+
};
|
|
17
|
+
/** Exhausted, with its reset passed by `now`: Available again. */
|
|
18
|
+
export const isDue = (state, now) => state.type === "exhausted" && state.resetsAt <= now;
|
|
19
|
+
/** The Credentials whose reset is due at `now`, set Available: what the app writes back. */
|
|
20
|
+
export const dueResets = (credentials, now) => credentials.flatMap((c) => isDue(c.state, now) ? [{ ...c, state: { type: "available" } }] : []);
|
|
21
|
+
const HOUR = 60 * 60 * 1000;
|
|
22
|
+
/** Each plan window: its share used (0 to 1), its reset, and its length for a reading with no reset. */
|
|
23
|
+
const windows = (h) => [
|
|
24
|
+
{ used: h.fiveHour, resetsAt: h.fiveHourResetsAt, length: 5 * HOUR },
|
|
25
|
+
{ used: h.sevenDay, resetsAt: h.sevenDayResetsAt, length: 7 * 24 * HOUR },
|
|
26
|
+
];
|
|
27
|
+
/** A lease still counts at `now`: no lapse is set, or its holder showed life within `lapse.ms`. */
|
|
28
|
+
const isLive = (l, now, lapse) => !lapse ||
|
|
29
|
+
now - (l.aliveAt ?? (lapse.unclocked === "live" ? now : -Infinity)) <
|
|
30
|
+
lapse.ms;
|
|
31
|
+
const isFull = (h, now) => !!h && windows(h).some((w) => (w.used ?? 0) >= 1 && (w.resetsAt ?? 0) > now);
|
|
32
|
+
/**
|
|
33
|
+
* The Credentials a run may lease at `now`: Available, or Exhausted with its reset due; under its lease cap, counting
|
|
34
|
+
* only live leases; and, with `full: "skip"`, no window full until a reset still ahead.
|
|
35
|
+
*/
|
|
36
|
+
export const leasable = (credentials, leases, now, { lapse, full }) => {
|
|
37
|
+
const held = new Map();
|
|
38
|
+
for (const l of leases) {
|
|
39
|
+
if (isLive(l, now, lapse)) {
|
|
40
|
+
held.set(l.credentialId, (held.get(l.credentialId) ?? 0) + 1);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return credentials.filter((c) => (c.state.type === "available" || isDue(c.state, now)) &&
|
|
44
|
+
(held.get(c.id) ?? 0) < leaseCap(c) &&
|
|
45
|
+
!(full === "skip" && isFull(c.headroom, now)));
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* The Credential `holder` already leases, so a run that asks again keeps its login and takes no second slot. Only a
|
|
49
|
+
* live lease (the same `lapse` as `leasable`: a lapsed one may be another run's slot by now), on an Available login or
|
|
50
|
+
* one whose reset is due: a Disabled or still Exhausted login is no longer the run's to use, and the run leases anew.
|
|
51
|
+
* Pass one pool's Credentials: one harness and one method.
|
|
52
|
+
*/
|
|
53
|
+
export const heldBy = (credentials, leases, now, { holder, lapse, }) => {
|
|
54
|
+
const mine = new Set(leases.flatMap((l) => l.holder === holder && isLive(l, now, lapse) ? [l.credentialId] : []));
|
|
55
|
+
return credentials.find((c) => mine.has(c.id) && (c.state.type === "available" || isDue(c.state, now)));
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* A login's quota left (0 to 1): 1 less its most used window. A window that has reset by `now` is unused: its
|
|
59
|
+
* `resetsAt` has passed, or with none, its length since `checkedAt`. No reading is 1 left. Only the five-hour and
|
|
60
|
+
* seven-day windows count: a per-model weekly or a monthly window is not in `Headroom`.
|
|
61
|
+
*/
|
|
62
|
+
export const quotaLeft = (headroom, now) => {
|
|
63
|
+
if (!headroom) {
|
|
64
|
+
return 1;
|
|
65
|
+
}
|
|
66
|
+
const used = windows(headroom).map((w) => {
|
|
67
|
+
// No reset and no `checkedAt`: no reset is known, so the window counts.
|
|
68
|
+
const resetAt = w.resetsAt ?? (headroom.checkedAt ?? Infinity) + w.length;
|
|
69
|
+
return resetAt <= now ? 0 : (w.used ?? 0);
|
|
70
|
+
});
|
|
71
|
+
return 1 - Math.max(0, ...used);
|
|
72
|
+
};
|
|
73
|
+
const mostLeft = (candidates, now, previous) => {
|
|
74
|
+
const others = candidates.filter((c) => c.id !== previous);
|
|
75
|
+
const from = others.length > 0 ? others : candidates;
|
|
76
|
+
const left = (c) => quotaLeft(c.headroom, now);
|
|
77
|
+
const most = Math.max(...from.map(left));
|
|
78
|
+
// `toSorted` is stable: of equal `lastLeasedAt`, the order given wins.
|
|
79
|
+
return from
|
|
80
|
+
.filter((c) => left(c) === most)
|
|
81
|
+
.toSorted((a, b) => (a.lastLeasedAt ?? -1) - (b.lastLeasedAt ?? -1))[0];
|
|
82
|
+
};
|
|
83
|
+
/** The Credential a run leases, from `leasable`'s answer. None when there is none. */
|
|
84
|
+
export const pick = (candidates, how) => {
|
|
85
|
+
if (how.policy === "most-left") {
|
|
86
|
+
return mostLeft(candidates, how.now, how.previous);
|
|
87
|
+
}
|
|
88
|
+
const subs = candidates.filter((c) => c.method === "sub");
|
|
89
|
+
const from = subs.length > 0 ? subs : candidates;
|
|
90
|
+
return from[Math.floor((how.random || Math.random)() * from.length)];
|
|
91
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@robotostudio/ai-pool",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The pure half of a pool of AI logins: which login a run may lease, which one it takes, and what a provider failure does to it.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/robotostudio/platform.git",
|
|
9
|
+
"directory": "packages/ai-pool"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"!dist/**/*.test.*",
|
|
14
|
+
"LICENSE",
|
|
15
|
+
"README.md"
|
|
16
|
+
],
|
|
17
|
+
"type": "module",
|
|
18
|
+
"exports": {
|
|
19
|
+
"./pool": {
|
|
20
|
+
"types": "./dist/pool.d.ts",
|
|
21
|
+
"default": "./dist/pool.js"
|
|
22
|
+
},
|
|
23
|
+
"./headroom": {
|
|
24
|
+
"types": "./dist/headroom.d.ts",
|
|
25
|
+
"default": "./dist/headroom.js"
|
|
26
|
+
},
|
|
27
|
+
"./failure": {
|
|
28
|
+
"types": "./dist/failure.d.ts",
|
|
29
|
+
"default": "./dist/failure.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
37
|
+
"lint": "oxlint",
|
|
38
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
39
|
+
"test": "node --test 'src/**/*.test.ts'"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"zod": "^4.6.7"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@robotostudio/tsconfig": "workspace:*"
|
|
46
|
+
},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=22.18"
|
|
49
|
+
}
|
|
50
|
+
}
|