@yolk-sdk/pool 0.0.0-stage → 0.1.0-canary.116

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 @@
1
+ {"version":3,"file":"rank.mjs","names":[],"sources":["../src/rank.ts"],"sourcesContent":["import { Data, Predicate } from 'effect'\nimport type { ProviderSubscriptionUsageSnapshot } from '@yolk-sdk/agent/providers/subscription-usage'\nimport type { PoolCooldown } from './model.ts'\n\n/** One usage window of a reading, as the ranking reads it. */\nexport type PoolWindow = {\n /** Window length; absent when the provider's window has no fixed length (a billing month). */\n readonly durationMinutes?: number\n readonly usedPercent: number\n /** When the window resets; absent when it has not started. */\n readonly resetsAtMs?: number\n /** Lowercase model substrings the window limits; empty for every model. */\n readonly models: ReadonlyArray<string>\n}\n\ntype MutablePoolWindow = { -readonly [Key in keyof PoolWindow]: PoolWindow[Key] }\n\n/** The latest quota reading of one account. */\nexport type PoolReading = {\n readonly fetchedAtMs: number\n readonly windows: ReadonlyArray<PoolWindow>\n}\n\n/** A configured account as the ranking sees it. */\nexport type PoolCandidate = {\n readonly id: string\n readonly priority: number\n}\n\n/**\n * The route a request pins: its model id, trimmed and lowercased. Reasoning effort is a separate\n * request field and never part of the route.\n */\nexport const poolRoute = (model: string) => model.trim().toLowerCase()\n\n/**\n * A usage snapshot as the ranking reads it; an unreadable `fetchedAt` yields no reading. Windows\n * without a length still block a used-up account but never rank it. A window that reports only\n * `resetsAfterSeconds` resets that long after the reading.\n */\nexport const poolReadingFromSnapshot = (\n snapshot: ProviderSubscriptionUsageSnapshot\n): PoolReading | undefined => {\n const fetchedAtMs = Date.parse(snapshot.fetchedAt)\n\n if (!Number.isFinite(fetchedAtMs)) {\n return undefined\n }\n\n const windows = Array.from(snapshot.windows).map((window): PoolWindow => {\n const resetsAtMs =\n window.resetsAt !== undefined\n ? Date.parse(window.resetsAt)\n : window.resetsAfterSeconds !== undefined\n ? fetchedAtMs + window.resetsAfterSeconds * 1000\n : Number.NaN\n\n const models = (window.models ?? []).flatMap(model => {\n const normalized = model.trim().toLowerCase()\n\n return normalized === '' ? [] : [normalized]\n })\n\n const fields: MutablePoolWindow = { usedPercent: window.usedPercent, models }\n\n if (window.windowDurationMinutes !== undefined) {\n fields.durationMinutes = window.windowDurationMinutes\n }\n\n if (Number.isFinite(resetsAtMs)) {\n fields.resetsAtMs = resetsAtMs\n }\n\n return fields\n })\n\n return { fetchedAtMs, windows }\n}\n\n/** Why the ranking chose an account. */\nexport type PoolDecision = Data.TaggedEnum<{\n /** Fresh readings ranked it first; `resetsAtMs` is its longest window's reset, if started. */\n Quota: { readonly accountId: string; readonly resetsAtMs: number | undefined }\n /** No candidate is usable by a fresh reading; the route's pin is still available. */\n Sticky: { readonly accountId: string }\n /** No candidate is usable by a fresh reading and no pin is: highest priority, then lowest id. */\n FillFirst: { readonly accountId: string }\n}>\n\nexport const PoolDecision = Data.taggedEnum<PoolDecision>()\n\nexport type PoolRankInput = {\n /** Configured accounts. */\n readonly accounts: ReadonlyArray<PoolCandidate>\n /** Accounts that cannot serve now: an active cooldown, or already tried by this request. */\n readonly unavailable: ReadonlySet<string>\n readonly readings: ReadonlyMap<string, PoolReading>\n /** The account the route is pinned to, if any. */\n readonly pin: string | undefined\n readonly route: string\n readonly nowMs: number\n readonly maxAgeMs: number\n readonly reservePercent: number\n}\n\nconst appliesTo = (window: PoolWindow, route: string) =>\n window.models.length === 0 || window.models.some(model => route.includes(model))\n\nconst hasStarted = (window: PoolWindow, nowMs: number) =>\n window.resetsAtMs !== undefined && window.resetsAtMs > nowMs\n\ntype AccountRank =\n /** No window of the reading applies to the route: the reading says nothing. */\n | { readonly kind: 'unknown' }\n /** An applicable started window is used up to the reserve. */\n | { readonly kind: 'exhausted' }\n | { readonly kind: 'usable'; readonly resetsAtMs: number | undefined }\n\n/**\n * The reset of the account's longest window with a length that applies to the route (undefined\n * when it has not started, or no applicable window has a length). Unusable when no window applies\n * or an applicable started window is used up to the reserve; a window whose reset has passed counts\n * as fresh, whatever the reading said.\n */\nconst accountRank = (\n reading: PoolReading,\n route: string,\n nowMs: number,\n reservePercent: number\n): AccountRank => {\n let usable = false\n let longest = 0\n let resetsAtMs: number | undefined\n\n for (const window of reading.windows) {\n if (!appliesTo(window, route)) {\n continue\n }\n\n const started = hasStarted(window, nowMs)\n\n if (started && window.usedPercent >= 100 - reservePercent) {\n return { kind: 'exhausted' }\n }\n\n usable = true\n\n if (window.durationMinutes === undefined) {\n continue\n }\n\n if (window.durationMinutes > longest) {\n longest = window.durationMinutes\n resetsAtMs = started ? window.resetsAtMs : undefined\n } else if (\n window.durationMinutes === longest &&\n started &&\n window.resetsAtMs !== undefined &&\n (resetsAtMs === undefined || window.resetsAtMs < resetsAtMs)\n ) {\n resetsAtMs = window.resetsAtMs\n }\n }\n\n return usable ? { kind: 'usable', resetsAtMs } : { kind: 'unknown' }\n}\n\ntype Ranked = { readonly candidate: PoolCandidate; readonly resetsAtMs: number | undefined }\n\n/** Code-unit id order, so ties never depend on locale. */\nconst idBefore = (a: string, b: string) => a < b\n\n/**\n * Started windows by soonest reset, then windows that have not started; ties by higher priority,\n * then lower id.\n */\nconst ranksBefore = (a: Ranked, b: Ranked) => {\n if (a.resetsAtMs !== undefined && b.resetsAtMs !== undefined) {\n if (a.resetsAtMs !== b.resetsAtMs) {\n return a.resetsAtMs < b.resetsAtMs\n }\n } else if (a.resetsAtMs !== undefined || b.resetsAtMs !== undefined) {\n return a.resetsAtMs !== undefined\n }\n\n if (a.candidate.priority !== b.candidate.priority) {\n return a.candidate.priority > b.candidate.priority\n }\n\n return idBefore(a.candidate.id, b.candidate.id)\n}\n\n/** Highest priority, then lowest id. */\nconst fillFirst = (candidates: ReadonlyArray<PoolCandidate>): PoolCandidate | undefined => {\n let best: PoolCandidate | undefined\n\n for (const candidate of candidates) {\n if (\n best === undefined ||\n candidate.priority > best.priority ||\n (candidate.priority === best.priority && idBefore(candidate.id, best.id))\n ) {\n best = candidate\n }\n }\n\n return best\n}\n\n/**\n * Expiring-first: the available account whose longest applicable window resets soonest and still\n * has quota. When no available account is usable by a fresh reading (within `maxAgeMs`), it routes\n * stickily: the pin while it is available, else fill-first, preferring accounts that no fresh\n * reading shows used up; those serve only when nothing else is left, so the provider's own answer\n * decides. Undefined when no account is available.\n */\nexport const rankPool = (input: PoolRankInput): PoolDecision | undefined => {\n const candidates = input.accounts.filter(account => !input.unavailable.has(account.id))\n const exhausted = new Set<string>()\n\n let best: Ranked | undefined\n\n for (const candidate of candidates) {\n const reading = input.readings.get(candidate.id)\n\n if (reading === undefined || input.nowMs - reading.fetchedAtMs > input.maxAgeMs) {\n continue\n }\n\n const rank = accountRank(reading, input.route, input.nowMs, input.reservePercent)\n\n if (rank.kind === 'exhausted') {\n exhausted.add(candidate.id)\n }\n\n if (rank.kind !== 'usable') {\n continue\n }\n\n const next: Ranked = { candidate, resetsAtMs: rank.resetsAtMs }\n\n if (best === undefined || ranksBefore(next, best)) {\n best = next\n }\n }\n\n if (best !== undefined) {\n return PoolDecision.Quota({ accountId: best.candidate.id, resetsAtMs: best.resetsAtMs })\n }\n\n const unexhausted = candidates.filter(candidate => !exhausted.has(candidate.id))\n const fallback = unexhausted.length > 0 ? unexhausted : candidates\n\n if (input.pin !== undefined && fallback.some(candidate => candidate.id === input.pin)) {\n return PoolDecision.Sticky({ accountId: input.pin })\n }\n\n const first = fillFirst(fallback)\n\n return first === undefined ? undefined : PoolDecision.FillFirst({ accountId: first.id })\n}\n\n/** Whether a cooldown still keeps its account out at `nowMs`. */\nexport const isCooldownActive = (cooldown: PoolCooldown, nowMs: number) => cooldown.untilMs > nowMs\n\n/**\n * Every account-wide window of the reading has quota left or has reset; model-scoped windows block\n * only their models through ranking, never the whole account. A reading without account-wide\n * windows proves nothing.\n */\nconst hasQuotaLeft = (reading: PoolReading, nowMs: number) => {\n const accountWide = reading.windows.filter(window => window.models.length === 0)\n\n return (\n accountWide.length > 0 &&\n accountWide.every(window => !hasStarted(window, nowMs) || window.usedPercent < 100)\n )\n}\n\n/**\n * Active quota cooldowns that a fresh reading taken after they began shows to be over (a limit\n * reset was spent, or the provider reset early). A reading from before the lockout never clears\n * one, and auth cooldowns are never cleared by readings.\n */\nexport const staleQuotaCooldowns = (input: {\n readonly cooldowns: ReadonlyArray<PoolCooldown>\n readonly readings: ReadonlyMap<string, PoolReading>\n readonly nowMs: number\n readonly maxAgeMs: number\n}): ReadonlyArray<PoolCooldown> =>\n input.cooldowns.filter(cooldown => {\n if (\n !Predicate.isTagged(cooldown, 'PoolQuotaCooldown') ||\n !isCooldownActive(cooldown, input.nowMs)\n ) {\n return false\n }\n\n const reading = input.readings.get(cooldown.accountId)\n\n return (\n reading !== undefined &&\n input.nowMs - reading.fetchedAtMs <= input.maxAgeMs &&\n reading.fetchedAtMs > cooldown.startedAtMs &&\n hasQuotaLeft(reading, input.nowMs)\n )\n })\n"],"mappings":";;;;;;AAiCA,MAAa,aAAa,UAAkB,MAAM,KAAK,EAAE,YAAY;;;;;;AAOrE,MAAa,2BACX,aAC4B;CAC5B,MAAM,cAAc,KAAK,MAAM,SAAS,SAAS;CAEjD,IAAI,CAAC,OAAO,SAAS,WAAW,GAC9B;CA8BF,OAAO;EAAE;EAAa,SA3BN,MAAM,KAAK,SAAS,OAAO,EAAE,KAAK,WAAuB;GACvE,MAAM,aACJ,OAAO,aAAa,KAAA,IAChB,KAAK,MAAM,OAAO,QAAQ,IAC1B,OAAO,uBAAuB,KAAA,IAC5B,cAAc,OAAO,qBAAqB,MAC1C;GAER,MAAM,UAAU,OAAO,UAAU,CAAC,GAAG,SAAQ,UAAS;IACpD,MAAM,aAAa,MAAM,KAAK,EAAE,YAAY;IAE5C,OAAO,eAAe,KAAK,CAAC,IAAI,CAAC,UAAU;GAC7C,CAAC;GAED,MAAM,SAA4B;IAAE,aAAa,OAAO;IAAa;GAAO;GAE5E,IAAI,OAAO,0BAA0B,KAAA,GACnC,OAAO,kBAAkB,OAAO;GAGlC,IAAI,OAAO,SAAS,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AAQ;CAEhC,OAAO,UAAU,KAAA,IAAY,KAAA,IAAY,aAAa,UAAU,EAAE,WAAW,MAAM,GAAG,CAAC;AACzF;;AAGA,MAAa,oBAAoB,UAAwB,UAAkB,SAAS,UAAU;;;;;;AAO9F,MAAM,gBAAgB,SAAsB,UAAkB;CAC5D,MAAM,cAAc,QAAQ,QAAQ,QAAO,WAAU,OAAO,OAAO,WAAW,CAAC;CAE/E,OACE,YAAY,SAAS,KACrB,YAAY,OAAM,WAAU,CAAC,WAAW,QAAQ,KAAK,KAAK,OAAO,cAAc,GAAG;AAEtF;;;;;;AAOA,MAAa,uBAAuB,UAMlC,MAAM,UAAU,QAAO,aAAY;CACjC,IACE,CAAC,UAAU,SAAS,UAAU,mBAAmB,KACjD,CAAC,iBAAiB,UAAU,MAAM,KAAK,GAEvC,OAAO;CAGT,MAAM,UAAU,MAAM,SAAS,IAAI,SAAS,SAAS;CAErD,OACE,YAAY,KAAA,KACZ,MAAM,QAAQ,QAAQ,eAAe,MAAM,YAC3C,QAAQ,cAAc,SAAS,eAC/B,aAAa,SAAS,MAAM,KAAK;AAErC,CAAC"}
@@ -0,0 +1,89 @@
1
+ import { PoolCooldown, PoolPin, PoolStoreError } from "./model.mjs";
2
+ import { Effect } from "effect";
3
+ import * as Schema from "effect/Schema";
4
+ import { ProviderSubscriptionUsageSnapshot } from "@yolk-sdk/agent/providers/subscription-usage";
5
+
6
+ //#region src/store.d.ts
7
+ declare const PoolStoredReading_base: Schema.Class<PoolStoredReading, Schema.Struct<{
8
+ readonly accountId: Schema.Trimmed;
9
+ readonly snapshot: typeof ProviderSubscriptionUsageSnapshot;
10
+ }>, {}>;
11
+ /** The latest usage snapshot of one account. */
12
+ declare class PoolStoredReading extends PoolStoredReading_base {}
13
+ /** What one pick reads: the route's pin plus the cooldowns and readings of the pool's accounts. */
14
+ type PoolStoreSnapshot = {
15
+ readonly pin: PoolPin | undefined;
16
+ readonly cooldowns: ReadonlyArray<PoolCooldown>;
17
+ readonly readings: ReadonlyArray<PoolStoredReading>;
18
+ };
19
+ /** Everything a store holds for one pool, for host UIs. */
20
+ type PoolStoreState = {
21
+ readonly pins: ReadonlyArray<PoolPin>;
22
+ readonly cooldowns: ReadonlyArray<PoolCooldown>;
23
+ readonly readings: ReadonlyArray<PoolStoredReading>;
24
+ };
25
+ /**
26
+ * Pool state shared by every instance of a host (ADR 0011). Hosts implement it on their database;
27
+ * `makeMemoryPoolStore` serves tests and single-process hosts, and `poolStoreContract` pins the
28
+ * semantics every implementation must meet.
29
+ *
30
+ * - Pins are keyed by `(poolId, route)`; cooldowns and readings by account id, so a cooldown or
31
+ * reading applies to every pool the account is in.
32
+ * - Operations must be atomic per key: concurrent `movePin` calls with the same `expected` let
33
+ * exactly one through.
34
+ */
35
+ type PoolStoreApi = {
36
+ /** The route's pin and the requested accounts' cooldowns (expired ones included) and readings. */readonly load: (input: {
37
+ readonly poolId: string;
38
+ readonly route: string;
39
+ readonly accountIds: ReadonlyArray<string>;
40
+ }) => Effect.Effect<PoolStoreSnapshot, PoolStoreError>;
41
+ /**
42
+ * Compare-and-set: writes `pin` when the route's current account is `expected` (`undefined`:
43
+ * the route has no pin yet). Returns whether it wrote.
44
+ */
45
+ readonly movePin: (input: {
46
+ readonly expected: string | undefined;
47
+ readonly pin: PoolPin;
48
+ }) => Effect.Effect<boolean, PoolStoreError>;
49
+ /**
50
+ * Records a cooldown; when the account already has one, the one that ends later stays, and of two
51
+ * that end together the one that started later (a newer failure must not be cleared by a reading
52
+ * taken before it).
53
+ */
54
+ readonly putCooldown: (cooldown: PoolCooldown) => Effect.Effect<void, PoolStoreError>;
55
+ /**
56
+ * Removes the account's cooldown only when it is the one observed (same `startedAtMs`). Returns
57
+ * whether it removed one.
58
+ */
59
+ readonly clearCooldown: (input: {
60
+ readonly accountId: string;
61
+ readonly startedAtMs: number;
62
+ }) => Effect.Effect<boolean, PoolStoreError>; /** Records a reading unless the stored one was fetched later. */
63
+ readonly putReading: (reading: PoolStoredReading) => Effect.Effect<void, PoolStoreError>; /** The pool's pins and the requested accounts' cooldowns and readings. */
64
+ readonly state: (input: {
65
+ readonly poolId: string;
66
+ readonly accountIds: ReadonlyArray<string>;
67
+ }) => Effect.Effect<PoolStoreState, PoolStoreError>;
68
+ };
69
+ /**
70
+ * An in-memory `PoolStoreApi`: state lives in this process only, so it suits tests and hosts that
71
+ * run one long-lived process. Serverless hosts implement the port on their database.
72
+ */
73
+ declare const makeMemoryPoolStore: () => PoolStoreApi;
74
+ declare const PoolStoreContractViolation_base: Schema.Class<PoolStoreContractViolation, Schema.TaggedStruct<"PoolStoreContractViolation", {
75
+ readonly case: Schema.String;
76
+ readonly message: Schema.String;
77
+ }>, import("effect/Cause").YieldableError>;
78
+ /** A `PoolStoreApi` implementation broke the store contract. */
79
+ declare class PoolStoreContractViolation extends PoolStoreContractViolation_base {}
80
+ /** One semantic every `PoolStoreApi` must meet. Run each case against a fresh, empty store. */
81
+ type PoolStoreContractCase = {
82
+ readonly name: string;
83
+ readonly run: (store: PoolStoreApi) => Effect.Effect<void, PoolStoreContractViolation | PoolStoreError>;
84
+ };
85
+ /** The `PoolStoreApi` contract. Hosts run every case against a fresh store of their implementation. */
86
+ declare const poolStoreContract: ReadonlyArray<PoolStoreContractCase>;
87
+ //#endregion
88
+ export { PoolStoreApi, PoolStoreContractCase, PoolStoreContractViolation, PoolStoreError, PoolStoreSnapshot, PoolStoreState, PoolStoredReading, makeMemoryPoolStore, poolStoreContract };
89
+ //# sourceMappingURL=store.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.mts","names":[],"sources":["../src/store.ts"],"mappings":";;;;;;cAY2C,sBAAA;;;;;cAG9B,iBAAA,SAA0B,sBAGrC;;KAGU,iBAAA;EAAA,SACD,GAAA,EAAK,OAAA;EAAA,SACL,SAAA,EAAW,aAAA,CAAc,YAAA;EAAA,SACzB,QAAA,EAAU,aAAA,CAAc,iBAAA;AAAA;;KAIvB,cAAA;EAAA,SACD,IAAA,EAAM,a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, PoolStoreError } from "./model.mjs";
2
+ import { Chunk, Effect, Predicate } from "effect";
3
+ import * as Schema from "effect/Schema";
4
+ import { ProviderSubscriptionUsageSnapshot } from "@yolk-sdk/agent/providers/subscription-usage";
5
+ //#region src/store.ts
6
+ /** The latest usage snapshot of one account. */
7
+ var PoolStoredReading = class extends Schema.Class("PoolStoredReading")({
8
+ accountId: PoolAccountId,
9
+ snapshot: ProviderSubscriptionUsageSnapshot
10
+ }) {};
11
+ const pinKey = (poolId, route) => JSON.stringify([poolId, route]);
12
+ const fetchedAtMs = (reading) => Date.parse(reading.snapshot.fetchedAt);
13
+ /**
14
+ * An in-memory `PoolStoreApi`: state lives in this process only, so it suits tests and hosts that
15
+ * run one long-lived process. Serverless hosts implement the port on their database.
16
+ */
17
+ const makeMemoryPoolStore = () => {
18
+ const pins = /* @__PURE__ */ new Map();
19
+ const cooldowns = /* @__PURE__ */ new Map();
20
+ const readings = /* @__PURE__ */ new Map();
21
+ const pick = (source, accountIds) => accountIds.flatMap((accountId) => {
22
+ const value = source.get(accountId);
23
+ return value === void 0 ? [] : [value];
24
+ });
25
+ return {
26
+ load: (input) => Effect.sync(() => ({
27
+ pin: pins.get(pinKey(input.poolId, input.route)),
28
+ cooldowns: pick(cooldowns, input.accountIds),
29
+ readings: pick(readings, input.accountIds)
30
+ })),
31
+ movePin: (input) => Effect.sync(() => {
32
+ const key = pinKey(input.pin.poolId, input.pin.route);
33
+ if (pins.get(key)?.accountId !== input.expected) return false;
34
+ pins.set(key, input.pin);
35
+ return true;
36
+ }),
37
+ putCooldown: (cooldown) => Effect.sync(() => {
38
+ const current = cooldowns.get(cooldown.accountId);
39
+ if (current === void 0 || cooldown.untilMs > current.untilMs || cooldown.untilMs === current.untilMs && cooldown.startedAtMs > current.startedAtMs) cooldowns.set(cooldown.accountId, cooldown);
40
+ }),
41
+ clearCooldown: (input) => Effect.sync(() => {
42
+ const current = cooldowns.get(input.accountId);
43
+ if (current === void 0 || current.startedAtMs !== input.startedAtMs) return false;
44
+ cooldowns.delete(input.accountId);
45
+ return true;
46
+ }),
47
+ putReading: (reading) => Effect.sync(() => {
48
+ const current = readings.get(reading.accountId);
49
+ if (current === void 0 || fetchedAtMs(reading) >= fetchedAtMs(current)) readings.set(reading.accountId, reading);
50
+ }),
51
+ state: (input) => Effect.sync(() => ({
52
+ pins: Array.from(pins.values()).filter((pin) => pin.poolId === input.poolId).sort((a, b) => a.route < b.route ? -1 : a.route > b.route ? 1 : 0),
53
+ cooldowns: pick(cooldowns, input.accountIds),
54
+ readings: pick(readings, input.accountIds)
55
+ }))
56
+ };
57
+ };
58
+ /** A `PoolStoreApi` implementation broke the store contract. */
59
+ var PoolStoreContractViolation = class extends Schema.TaggedError()("PoolStoreContractViolation", {
60
+ case: Schema.String,
61
+ message: Schema.String
62
+ }) {};
63
+ const contractCase = (name, run) => ({
64
+ name,
65
+ run: (store) => run(store, (condition, message) => condition ? Effect.void : Effect.fail(new PoolStoreContractViolation({
66
+ case: name,
67
+ message
68
+ })))
69
+ });
70
+ const contractPin = (route, accountId, pinnedAtMs, poolId = "pool") => PoolPin.make({
71
+ poolId,
72
+ route,
73
+ accountId,
74
+ pinnedAtMs
75
+ });
76
+ const contractReading = (accountId, fetchedAt) => PoolStoredReading.make({
77
+ accountId,
78
+ snapshot: ProviderSubscriptionUsageSnapshot.make({
79
+ provider: "contract",
80
+ fetchedAt,
81
+ windows: Chunk.empty()
82
+ })
83
+ });
84
+ /** The `PoolStoreApi` contract. Hosts run every case against a fresh store of their implementation. */
85
+ const poolStoreContract = [
86
+ contractCase("pins are created once and moved by compare-and-set", (store, expect) => Effect.gen(function* () {
87
+ const load = store.load({
88
+ poolId: "pool",
89
+ route: "model",
90
+ accountIds: []
91
+ });
92
+ yield* expect((yield* load).pin === void 0, "a new route has no pin");
93
+ yield* expect(yield* store.movePin({
94
+ expected: void 0,
95
+ pin: contractPin("model", "a", 1)
96
+ }), "the first pin is written");
97
+ yield* expect(!(yield* store.movePin({
98
+ expected: void 0,
99
+ pin: contractPin("model", "b", 2)
100
+ })), "creating a pin that already exists is refused");
101
+ yield* expect(!(yield* store.movePin({
102
+ expected: "b",
103
+ pin: contractPin("model", "c", 3)
104
+ })), "a move expecting another account is refused");
105
+ yield* expect(yield* store.movePin({
106
+ expected: "a",
107
+ pin: contractPin("model", "b", 4)
108
+ }), "a move expecting the current account is written");
109
+ const pin = (yield* load).pin;
110
+ yield* expect(pin?.accountId === "b" && pin.pinnedAtMs === 4, "load returns the latest pin with its time");
111
+ })),
112
+ contractCase("pins are keyed by pool and route", (store, expect) => Effect.gen(function* () {
113
+ yield* store.movePin({
114
+ expected: void 0,
115
+ pin: contractPin("one", "a", 1)
116
+ });
117
+ yield* store.movePin({
118
+ expected: void 0,
119
+ pin: contractPin("two", "b", 1)
120
+ });
121
+ yield* store.movePin({
122
+ expected: void 0,
123
+ pin: contractPin("one", "c", 1, "other")
124
+ });
125
+ const one = yield* store.load({
126
+ poolId: "pool",
127
+ route: "one",
128
+ accountIds: []
129
+ });
130
+ const two = yield* store.load({
131
+ poolId: "pool",
132
+ route: "two",
133
+ accountIds: []
134
+ });
135
+ const other = yield* store.load({
136
+ poolId: "other",
137
+ route: "one",
138
+ accountIds: []
139
+ });
140
+ yield* expect(one.pin?.accountId === "a" && two.pin?.accountId === "b" && other.pin?.accountId === "c", "each (pool, route) keeps its own pin");
141
+ yield* expect((yield* store.state({
142
+ poolId: "pool",
143
+ accountIds: []
144
+ })).pins.map((pin) => pin.route).join() === "one,two", "state lists the pool’s pins only, ordered by route");
145
+ })),
146
+ contractCase("concurrent moves from the same pin let exactly one through", (store, expect) => Effect.gen(function* () {
147
+ yield* store.movePin({
148
+ expected: void 0,
149
+ pin: contractPin("model", "a", 1)
150
+ });
151
+ yield* expect((yield* Effect.all([
152
+ "b",
153
+ "c",
154
+ "d",
155
+ "e"
156
+ ].map((accountId) => store.movePin({
157
+ expected: "a",
158
+ pin: contractPin("model", accountId, 2)
159
+ })), { concurrency: "unbounded" })).filter(Boolean).length === 1, "exactly one move is written");
160
+ })),
161
+ contractCase("cooldowns keep the later end and clear only when observed", (store, expect) => Effect.gen(function* () {
162
+ const load = store.load({
163
+ poolId: "pool",
164
+ route: "model",
165
+ accountIds: ["a", "b"]
166
+ });
167
+ yield* store.putCooldown(PoolQuotaCooldown.make({
168
+ accountId: "a",
169
+ startedAtMs: 1,
170
+ untilMs: 100
171
+ }));
172
+ yield* store.putCooldown(PoolAuthCooldown.make({
173
+ accountId: "a",
174
+ startedAtMs: 2,
175
+ untilMs: 50
176
+ }));
177
+ const kept = (yield* load).cooldowns;
178
+ yield* expect(kept.length === 1 && Predicate.isTagged(kept[0], "PoolQuotaCooldown") && kept[0].untilMs === 100, "an earlier-ending cooldown does not replace a later one");
179
+ yield* store.putCooldown(PoolAuthCooldown.make({
180
+ accountId: "a",
181
+ startedAtMs: 3,
182
+ untilMs: 200
183
+ }));
184
+ const replaced = (yield* load).cooldowns;
185
+ yield* expect(replaced.length === 1 && Predicate.isTagged(replaced[0], "PoolAuthCooldown") && replaced[0].startedAtMs === 3, "a later-ending cooldown replaces the current one");
186
+ yield* store.putCooldown(PoolQuotaCooldown.make({
187
+ accountId: "a",
188
+ startedAtMs: 4,
189
+ untilMs: 200
190
+ }));
191
+ yield* store.putCooldown(PoolQuotaCooldown.make({
192
+ accountId: "a",
193
+ startedAtMs: 2,
194
+ untilMs: 200
195
+ }));
196
+ const renewed = (yield* load).cooldowns;
197
+ yield* expect(renewed.length === 1 && renewed[0]?.startedAtMs === 4, "of two cooldowns that end together, the later-started one stays, whatever the write order");
198
+ yield* expect(!(yield* store.clearCooldown({
199
+ accountId: "a",
200
+ startedAtMs: 3
201
+ })), "clearing a cooldown that is no longer current is refused");
202
+ yield* expect(yield* store.clearCooldown({
203
+ accountId: "a",
204
+ startedAtMs: 4
205
+ }), "clearing the observed cooldown succeeds");
206
+ yield* expect((yield* load).cooldowns.length === 0, "a cleared cooldown is gone");
207
+ yield* expect(!(yield* store.clearCooldown({
208
+ accountId: "b",
209
+ startedAtMs: 3
210
+ })), "clearing an account without a cooldown is refused");
211
+ })),
212
+ contractCase("cooldowns and readings are returned for the requested accounts only", (store, expect) => Effect.gen(function* () {
213
+ yield* store.putCooldown(PoolQuotaCooldown.make({
214
+ accountId: "a",
215
+ startedAtMs: 1,
216
+ untilMs: 9
217
+ }));
218
+ yield* store.putCooldown(PoolQuotaCooldown.make({
219
+ accountId: "b",
220
+ startedAtMs: 1,
221
+ untilMs: 9
222
+ }));
223
+ yield* store.putReading(contractReading("a", "2026-10-15T12:00:00.000Z"));
224
+ yield* store.putReading(contractReading("b", "2026-10-15T12:00:00.000Z"));
225
+ const snapshot = yield* store.load({
226
+ poolId: "pool",
227
+ route: "model",
228
+ accountIds: ["b"]
229
+ });
230
+ const state = yield* store.state({
231
+ poolId: "pool",
232
+ accountIds: ["a"]
233
+ });
234
+ yield* expect(snapshot.cooldowns.every((cooldown) => cooldown.accountId === "b") && snapshot.cooldowns.length === 1 && snapshot.readings.every((reading) => reading.accountId === "b") && snapshot.readings.length === 1, "load filters by account");
235
+ yield* expect(state.cooldowns.length === 1 && state.cooldowns[0]?.accountId === "a" && state.readings.length === 1 && state.readings[0]?.accountId === "a", "state filters by account");
236
+ })),
237
+ contractCase("readings keep the latest fetch", (store, expect) => Effect.gen(function* () {
238
+ const load = store.load({
239
+ poolId: "pool",
240
+ route: "model",
241
+ accountIds: ["a"]
242
+ });
243
+ yield* store.putReading(contractReading("a", "2026-10-15T12:00:00.000Z"));
244
+ yield* store.putReading(contractReading("a", "2026-10-15T11:00:00.000Z"));
245
+ yield* expect((yield* load).readings[0]?.snapshot.fetchedAt === "2026-10-15T12:00:00.000Z", "an older reading does not replace a newer one");
246
+ yield* store.putReading(contractReading("a", "2026-10-15T13:00:00.000Z"));
247
+ yield* expect((yield* load).readings[0]?.snapshot.fetchedAt === "2026-10-15T13:00:00.000Z", "a newer reading replaces the stored one");
248
+ }))
249
+ ];
250
+ //#endregion
251
+ export { PoolStoreContractViolation, PoolStoreError, PoolStoredReading, makeMemoryPoolStore, poolStoreContract };
252
+
253
+ //# sourceMappingURL=store.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.mjs","names":[],"sources":["../src/store.ts"],"sourcesContent":["import { Chunk, Effect, Predicate } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport { ProviderSubscriptionUsageSnapshot } from '@yolk-sdk/agent/providers/subscription-usage'\nimport {\n PoolAccountId,\n PoolAuthCooldown,\n PoolPin,\n PoolQuotaCooldown,\n type PoolCooldown,\n type PoolStoreError\n} from './model.ts'\n\nexport { PoolStoreError } from './model.ts'\n\n/** The latest usage snapshot of one account. */\nexport class PoolStoredReading extends Schema.Class<PoolStoredReading>('PoolStoredReading')({\n accountId: PoolAccountId,\n snapshot: ProviderSubscriptionUsageSnapshot\n}) {}\n\n/** What one pick reads: the route's pin plus the cooldowns and readings of the pool's accounts. */\nexport type PoolStoreSnapshot = {\n readonly pin: PoolPin | undefined\n readonly cooldowns: ReadonlyArray<PoolCooldown>\n readonly readings: ReadonlyArray<PoolStoredReading>\n}\n\n/** Everything a store holds for one pool, for host UIs. */\nexport type PoolStoreState = {\n readonly pins: ReadonlyArray<PoolPin>\n readonly cooldowns: ReadonlyArray<PoolCooldown>\n readonly readings: ReadonlyArray<PoolStoredReading>\n}\n\n/**\n * Pool state shared by every instance of a host (ADR 0011). Hosts implement it on their database;\n * `makeMemoryPoolStore` serves tests and single-process hosts, and `poolStoreContract` pins the\n * semantics every implementation must meet.\n *\n * - Pins are keyed by `(poolId, route)`; cooldowns and readings by account id, so a cooldown or\n * reading applies to every pool the account is in.\n * - Operations must be atomic per key: concurrent `movePin` calls with the same `expected` let\n * exactly one through.\n */\nexport type PoolStoreApi = {\n /** The route's pin and the requested accounts' cooldowns (expired ones included) and readings. */\n readonly load: (input: {\n readonly poolId: string\n readonly route: string\n readonly accountIds: ReadonlyArray<string>\n }) => Effect.Effect<PoolStoreSnapshot, PoolStoreError>\n /**\n * Compare-and-set: writes `pin` when the route's current account is `expected` (`undefined`:\n * the route has no pin yet). Returns whether it wrote.\n */\n readonly movePin: (input: {\n readonly expected: string | undefined\n readonly pin: PoolPin\n }) => Effect.Effect<boolean, PoolStoreError>\n /**\n * Records a cooldown; when the account already has one, the one that ends later stays, and of two\n * that end together the one that started later (a newer failure must not be cleared by a reading\n * taken before it).\n */\n readonly putCooldown: (cooldown: PoolCooldown) => Effect.Effect<void, PoolStoreError>\n /**\n * Removes the account's cooldown only when it is the one observed (same `startedAtMs`). Returns\n * whether it removed one.\n */\n readonly clearCooldown: (input: {\n readonly accountId: string\n readonly startedAtMs: number\n }) => Effect.Effect<boolean, PoolStoreError>\n /** Records a reading unless the stored one was fetched later. */\n readonly putReading: (reading: PoolStoredReading) => Effect.Effect<void, PoolStoreError>\n /** The pool's pins and the requested accounts' cooldowns and readings. */\n readonly state: (input: {\n readonly poolId: string\n readonly accountIds: ReadonlyArray<string>\n }) => Effect.Effect<PoolStoreState, PoolStoreError>\n}\n\nconst pinKey = (poolId: string, route: string) => JSON.stringify([poolId, route])\n\nconst fetchedAtMs = (reading: PoolStoredReading) => Date.parse(reading.snapshot.fetchedAt)\n\n/**\n * An in-memory `PoolStoreApi`: state lives in this process only, so it suits tests and hosts that\n * run one long-lived process. Serverless hosts implement the port on their database.\n */\nexport const makeMemoryPoolStore = (): PoolStoreApi => {\n const pins = new Map<string, PoolPin>()\n const cooldowns = new Map<string, PoolCooldown>()\n const readings = new Map<string, PoolStoredReading>()\n\n const pick = <A>(source: Map<string, A>, accountIds: ReadonlyArray<string>) =>\n accountIds.flatMap(accountId => {\n const value = source.get(accountId)\n\n return value === undefined ? [] : [value]\n })\n\n return {\n load: input =>\n Effect.sync(() => ({\n pin: pins.get(pinKey(input.poolId, input.route)),\n cooldowns: pick(cooldowns, input.accountIds),\n readings: pick(readings, input.accountIds)\n })),\n movePin: input =>\n Effect.sync(() => {\n const key = pinKey(input.pin.poolId, input.pin.route)\n\n if (pins.get(key)?.accountId !== input.expected) {\n return false\n }\n\n pins.set(key, input.pin)\n\n return true\n }),\n putCooldown: cooldown =>\n Effect.sync(() => {\n const current = cooldowns.get(cooldown.accountId)\n\n if (\n current === undefined ||\n cooldown.untilMs > current.untilMs ||\n (cooldown.untilMs === current.untilMs && cooldown.startedAtMs > current.startedAtMs)\n ) {\n cooldowns.set(cooldown.accountId, cooldown)\n }\n }),\n clearCooldown: input =>\n Effect.sync(() => {\n const current = cooldowns.get(input.accountId)\n\n if (current === undefined || current.startedAtMs !== input.startedAtMs) {\n return false\n }\n\n cooldowns.delete(input.accountId)\n\n return true\n }),\n putReading: reading =>\n Effect.sync(() => {\n const current = readings.get(reading.accountId)\n\n if (current === undefined || fetchedAtMs(reading) >= fetchedAtMs(current)) {\n readings.set(reading.accountId, reading)\n }\n }),\n state: input =>\n Effect.sync(() => ({\n pins: Array.from(pins.values())\n .filter(pin => pin.poolId === input.poolId)\n .sort((a, b) => (a.route < b.route ? -1 : a.route > b.route ? 1 : 0)),\n cooldowns: pick(cooldowns, input.accountIds),\n readings: pick(readings, input.accountIds)\n }))\n }\n}\n\n/** A `PoolStoreApi` implementation broke the store contract. */\nexport class PoolStoreContractViolation extends Schema.TaggedError<PoolStoreContractViolation>()(\n 'PoolStoreContractViolation',\n {\n case: Schema.String,\n message: Schema.String\n }\n) {}\n\n/** One semantic every `PoolStoreApi` must meet. Run each case against a fresh, empty store. */\nexport type PoolStoreContractCase = {\n readonly name: string\n readonly run: (\n store: PoolStoreApi\n ) => Effect.Effect<void, PoolStoreContractViolation | PoolStoreError>\n}\n\nconst contractCase = (\n name: string,\n run: (\n store: PoolStoreApi,\n expect: (condition: boolean, message: string) => Effect.Effect<void, PoolStoreContractViolation>\n ) => Effect.Effect<void, PoolStoreContractViolation | PoolStoreError>\n): PoolStoreContractCase => ({\n name,\n run: store =>\n run(store, (condition, message) =>\n condition ? Effect.void : Effect.fail(new PoolStoreContractViolation({ case: name, message }))\n )\n})\n\nconst contractPin = (route: string, accountId: string, pinnedAtMs: number, poolId = 'pool') =>\n PoolPin.make({ poolId, route, accountId, pinnedAtMs })\n\nconst contractReading = (accountId: string, fetchedAt: string) =>\n PoolStoredReading.make({\n accountId,\n snapshot: ProviderSubscriptionUsageSnapshot.make({\n provider: 'contract',\n fetchedAt,\n windows: Chunk.empty()\n })\n })\n\n/** The `PoolStoreApi` contract. Hosts run every case against a fresh store of their implementation. */\nexport const poolStoreContract: ReadonlyArray<PoolStoreContractCase> = [\n contractCase('pins are created once and moved by compare-and-set', (store, expect) =>\n Effect.gen(function* () {\n const load = store.load({ poolId: 'pool', route: 'model', accountIds: [] })\n\n yield* expect((yield* load).pin === undefined, 'a new route has no pin')\n yield* expect(\n yield* store.movePin({ expected: undefined, pin: contractPin('model', 'a', 1) }),\n 'the first pin is written'\n )\n yield* expect(\n !(yield* store.movePin({ expected: undefined, pin: contractPin('model', 'b', 2) })),\n 'creating a pin that already exists is refused'\n )\n yield* expect(\n !(yield* store.movePin({ expected: 'b', pin: contractPin('model', 'c', 3) })),\n 'a move expecting another account is refused'\n )\n yield* expect(\n yield* store.movePin({ expected: 'a', pin: contractPin('model', 'b', 4) }),\n 'a move expecting the current account is written'\n )\n\n const pin = (yield* load).pin\n\n yield* expect(\n pin?.accountId === 'b' && pin.pinnedAtMs === 4,\n 'load returns the latest pin with its time'\n )\n })\n ),\n contractCase('pins are keyed by pool and route', (store, expect) =>\n Effect.gen(function* () {\n yield* store.movePin({ expected: undefined, pin: contractPin('one', 'a', 1) })\n yield* store.movePin({ expected: undefined, pin: contractPin('two', 'b', 1) })\n yield* store.movePin({ expected: undefined, pin: contractPin('one', 'c', 1, 'other') })\n\n const one = yield* store.load({ poolId: 'pool', route: 'one', accountIds: [] })\n const two = yield* store.load({ poolId: 'pool', route: 'two', accountIds: [] })\n const other = yield* store.load({ poolId: 'other', route: 'one', accountIds: [] })\n\n yield* expect(\n one.pin?.accountId === 'a' && two.pin?.accountId === 'b' && other.pin?.accountId === 'c',\n 'each (pool, route) keeps its own pin'\n )\n\n const state = yield* store.state({ poolId: 'pool', accountIds: [] })\n\n yield* expect(\n state.pins.map(pin => pin.route).join() === 'one,two',\n 'state lists the pool’s pins only, ordered by route'\n )\n })\n ),\n contractCase('concurrent moves from the same pin let exactly one through', (store, expect) =>\n Effect.gen(function* () {\n yield* store.movePin({ expected: undefined, pin: contractPin('model', 'a', 1) })\n\n const results = yield* Effect.all(\n ['b', 'c', 'd', 'e'].map(accountId =>\n store.movePin({ expected: 'a', pin: contractPin('model', accountId, 2) })\n ),\n { concurrency: 'unbounded' }\n )\n\n yield* expect(results.filter(Boolean).length === 1, 'exactly one move is written')\n })\n ),\n contractCase('cooldowns keep the later end and clear only when observed', (store, expect) =>\n Effect.gen(function* () {\n const load = store.load({ poolId: 'pool', route: 'model', accountIds: ['a', 'b'] })\n\n yield* store.putCooldown(\n PoolQuotaCooldown.make({ accountId: 'a', startedAtMs: 1, untilMs: 100 })\n )\n yield* store.putCooldown(\n PoolAuthCooldown.make({ accountId: 'a', startedAtMs: 2, untilMs: 50 })\n )\n\n const kept = (yield* load).cooldowns\n\n yield* expect(\n kept.length === 1 &&\n Predicate.isTagged(kept[0], 'PoolQuotaCooldown') &&\n kept[0].untilMs === 100,\n 'an earlier-ending cooldown does not replace a later one'\n )\n\n yield* store.putCooldown(\n PoolAuthCooldown.make({ accountId: 'a', startedAtMs: 3, untilMs: 200 })\n )\n\n const replaced = (yield* load).cooldowns\n\n yield* expect(\n replaced.length === 1 &&\n Predicate.isTagged(replaced[0], 'PoolAuthCooldown') &&\n replaced[0].startedAtMs === 3,\n 'a later-ending cooldown replaces the current one'\n )\n\n yield* store.putCooldown(\n PoolQuotaCooldown.make({ accountId: 'a', startedAtMs: 4, untilMs: 200 })\n )\n\n yield* store.putCooldown(\n PoolQuotaCooldown.make({ accountId: 'a', startedAtMs: 2, untilMs: 200 })\n )\n\n const renewed = (yield* load).cooldowns\n\n yield* expect(\n renewed.length === 1 && renewed[0]?.startedAtMs === 4,\n 'of two cooldowns that end together, the later-started one stays, whatever the write order'\n )\n yield* expect(\n !(yield* store.clearCooldown({ accountId: 'a', startedAtMs: 3 })),\n 'clearing a cooldown that is no longer current is refused'\n )\n yield* expect(\n yield* store.clearCooldown({ accountId: 'a', startedAtMs: 4 }),\n 'clearing the observed cooldown succeeds'\n )\n yield* expect((yield* load).cooldowns.length === 0, 'a cleared cooldown is gone')\n yield* expect(\n !(yield* store.clearCooldown({ accountId: 'b', startedAtMs: 3 })),\n 'clearing an account without a cooldown is refused'\n )\n })\n ),\n contractCase(\n 'cooldowns and readings are returned for the requested accounts only',\n (store, expect) =>\n Effect.gen(function* () {\n yield* store.putCooldown(\n PoolQuotaCooldown.make({ accountId: 'a', startedAtMs: 1, untilMs: 9 })\n )\n yield* store.putCooldown(\n PoolQuotaCooldown.make({ accountId: 'b', startedAtMs: 1, untilMs: 9 })\n )\n yield* store.putReading(contractReading('a', '2026-10-15T12:00:00.000Z'))\n yield* store.putReading(contractReading('b', '2026-10-15T12:00:00.000Z'))\n\n const snapshot = yield* store.load({ poolId: 'pool', route: 'model', accountIds: ['b'] })\n const state = yield* store.state({ poolId: 'pool', accountIds: ['a'] })\n\n yield* expect(\n snapshot.cooldowns.every(cooldown => cooldown.accountId === 'b') &&\n snapshot.cooldowns.length === 1 &&\n snapshot.readings.every(reading => reading.accountId === 'b') &&\n snapshot.readings.length === 1,\n 'load filters by account'\n )\n yield* expect(\n state.cooldowns.length === 1 &&\n state.cooldowns[0]?.accountId === 'a' &&\n state.readings.length === 1 &&\n state.readings[0]?.accountId === 'a',\n 'state filters by account'\n )\n })\n ),\n contractCase('readings keep the latest fetch', (store, expect) =>\n Effect.gen(function* () {\n const load = store.load({ poolId: 'pool', route: 'model', accountIds: ['a'] })\n\n yield* store.putReading(contractReading('a', '2026-10-15T12:00:00.000Z'))\n yield* store.putReading(contractReading('a', '2026-10-15T11:00:00.000Z'))\n\n yield* expect(\n (yield* load).readings[0]?.snapshot.fetchedAt === '2026-10-15T12:00:00.000Z',\n 'an older reading does not replace a newer one'\n )\n\n yield* store.putReading(contractReading('a', '2026-10-15T13:00:00.000Z'))\n\n yield* expect(\n (yield* load).readings[0]?.snapshot.fetchedAt === '2026-10-15T13:00:00.000Z',\n 'a newer reading replaces the stored one'\n )\n })\n )\n]\n"],"mappings":";;;;;;AAeA,IAAa,oBAAb,cAAuC,OAAO,MAAyB,mBAAmB,EAAE;CAC1F,WAAW;CACX,UAAU;AACZ,CAAC,EAAE,CAAC;AAgEJ,MAAM,UAAU,QAAgB,UAAkB,KAAK,UAAU,CAAC,QAAQ,KAAK,CAAC;AAEhF,MAAM,eAAe,YAA+B,KAAK,MAAM,QAAQ,SAAS,SAAS;;;;;AAMzF,MAAa,4BAA0C;CACrD,MAAM,uBAAO,IAAI,IAAqB;CACtC,MAAM,4BAAY,IAAI,IAA0B;CAChD,MAAM,2BAAW,IAAI,IAA+B;CAEpD,MAAM,QAAW,QAAwB,eACvC,WAAW,SAAQ,cAAa;EAC9B,MAAM,QAAQ,OAAO,IAAI,SAAS;EAElC,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,KAAK;CAC1C,CAAC;CAEH,OAAO;EACL,OAAM,UACJ,OAAO,YAAY;GACjB,KAAK,KAAK,IAAI,OAAO,MAAM,QAAQ,MAAM,KAAK,CAAC;GAC/C,WAAW,KAAK,WAAW,MAAM,UAAU;GAC3C,UAAU,KAAK,UAAU,MAAM,UAAU;EAC3C,EAAE;EACJ,UAAS,UACP,OAAO,WAAW;GAChB,MAAM,MAAM,OAAO,MAAM,IAAI,QAAQ,MAAM,IAAI,KAAK;GAEpD,IAAI,KAAK,IAAI,GAAG,GAAG,cAAc,MAAM,UACrC,OAAO;GAGT,KAAK,IAAI,KAAK,MAAM,GAAG;GAEvB,OAAO;EACT,CAAC;EACH,cAAa,aACX,OAAO,WAAW;GAChB,MAAM,UAAU,UAAU,IAAI,SAAS,SAAS;GAEhD,IACE,YAAY,KAAA,KACZ,SAAS,UAAU,QAAQ,WAC1B,SAA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,KAAK,0BAA0B,CAAC;EACxE,OAAO,MAAM,WAAW,gBAAgB,KAAK,0BAA0B,CAAC;EAExE,MAAM,WAAW,OAAO,MAAM,KAAK;GAAE,QAAQ;GAAQ,OAAO;GAAS,YAAY,CAAC,GAAG;EAAE,CAAC;EACxF,MAAM,QAAQ,OAAO,MAAM,MAAM;GAAE,QAAQ;GAAQ,YAAY,CAAC,GAAG;EAAE,CAAC;EAEtE,OAAO,OACL,SAAS,UAAU,OAAM,aAAY,SAAS,cAAc,GAAG,KAC7D,SAAS,UAAU,WAAW,KAC9B,SAAS,SAAS,OAAM,YAAW,QAAQ,cAAc,GAAG,KAC5D,SAAS,SAAS,WAAW,GAC/B,yBACF;EACA,OAAO,OACL,MAAM,UAAU,WAAW,KACzB,MAAM,UAAU,IAAI,cAAc,OAClC,MAAM,SAAS,WAAW,KAC1B,MAAM,SAAS,IAAI,cAAc,KACnC,0BACF;CACF,CAAC,CACL;CACA,aAAa,mCAAmC,OAAO,WACrD,OAAO,IAAI,aAAa;EACtB,MAAM,OAAO,MAAM,KAAK;GAAE,QAAQ;GAAQ,OAAO;GAAS,YAAY,CAAC,GAAG;EAAE,CAAC;EAE7E,OAAO,MAAM,WAAW,gBAAgB,KAAK,0BAA0B,CAAC;EACxE,OAAO,MAAM,WAAW,gBAAgB,KAAK,0BAA0B,CAAC;EAExE,OAAO,QACJ,OAAO,MAAM,SAAS,IAAI,SAAS,cAAc,4BAClD,+CACF;EAEA,OAAO,MAAM,WAAW,gBAAgB,KAAK,0BAA0B,CAAC;EAExE,OAAO,QACJ,OAAO,MAAM,SAAS,IAAI,SAAS,cAAc,4BAClD,yCACF;CACF,CAAC,CACH;AACF"}
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@yolk-sdk/pool",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-canary.116",
4
+ "description": "Subscription account pools for Yolk agents: expiring-first routing and failover across several accounts of one provider behind one LLMProvider.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/magoz/yolk-sdk.git",
11
+ "directory": "packages/pool"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/magoz/yolk-sdk/issues"
15
+ },
16
+ "homepage": "https://github.com/magoz/yolk-sdk#readme",
17
+ "keywords": [
18
+ "agents",
19
+ "llm",
20
+ "subscriptions",
21
+ "routing",
22
+ "failover",
23
+ "effect"
24
+ ],
25
+ "engines": {
26
+ "node": ">=22"
27
+ },
28
+ "exports": {
29
+ "./package.json": "./package.json",
30
+ ".": {
31
+ "types": "./dist/index.d.mts",
32
+ "import": "./dist/index.mjs",
33
+ "default": "./dist/index.mjs"
34
+ },
35
+ "./store": {
36
+ "types": "./dist/store.d.mts",
37
+ "import": "./dist/store.mjs",
38
+ "default": "./dist/store.mjs"
39
+ }
40
+ },
41
+ "files": [
42
+ "src/**/*.ts",
43
+ "!src/**/*.test.ts",
44
+ "!src/**/*.test.tsx",
45
+ "dist/**/*",
46
+ "README.md"
47
+ ],
48
+ "publishConfig": {
49
+ "access": "public",
50
+ "provenance": true
51
+ },
52
+ "dependencies": {
53
+ "effect": "4.0.5",
54
+ "@yolk-sdk/agent": "^0.1.0-canary.116"
55
+ },
56
+ "scripts": {
57
+ "build": "tsdown",
58
+ "check": "tsc -p tsconfig.json --noEmit",
59
+ "test": "vitest run --passWithNoTests",
60
+ "test:run": "vitest run --passWithNoTests"
61
+ }
6
62
  }
package/src/index.ts ADDED
@@ -0,0 +1,32 @@
1
+ export {
2
+ defaultPoolMaxAgeMs,
3
+ makePool,
4
+ poolAuthCooldownMs,
5
+ poolFailureCooldown,
6
+ poolMaxCooldownMs,
7
+ poolQuotaRetryAfterFloorMs
8
+ } from './pool.ts'
9
+
10
+ export type { Pool, PoolAccount, PoolAccountState, PoolOptions, PoolState } from './pool.ts'
11
+
12
+ export {
13
+ PoolAccountId,
14
+ PoolAuthCooldown,
15
+ PoolConfigError,
16
+ PoolCooldown,
17
+ PoolPin,
18
+ PoolQuotaCooldown,
19
+ PoolStoreError,
20
+ PoolUnknownAccountError
21
+ } from './model.ts'
22
+
23
+ export {
24
+ isCooldownActive,
25
+ PoolDecision,
26
+ poolReadingFromSnapshot,
27
+ poolRoute,
28
+ rankPool,
29
+ staleQuotaCooldowns
30
+ } from './rank.ts'
31
+
32
+ export type { PoolCandidate, PoolRankInput, PoolReading, PoolWindow } from './rank.ts'
package/src/model.ts ADDED
@@ -0,0 +1,81 @@
1
+ import * as Schema from 'effect/Schema'
2
+
3
+ const NonEmptyTrimmedString = Schema.Trimmed.pipe(Schema.check(Schema.isNonEmpty()))
4
+
5
+ const EpochMs = Schema.Finite
6
+
7
+ /** A host-chosen account id, unique within the accounts a store serves. */
8
+ export const PoolAccountId = NonEmptyTrimmedString
9
+
10
+ /**
11
+ * The account currently serving one route of a pool. A route is a lowercased model id, so every
12
+ * reasoning effort of a model shares one pin.
13
+ */
14
+ export class PoolPin extends Schema.Class<PoolPin>('PoolPin')({
15
+ poolId: NonEmptyTrimmedString,
16
+ route: NonEmptyTrimmedString,
17
+ accountId: PoolAccountId,
18
+ pinnedAtMs: EpochMs
19
+ }) {}
20
+
21
+ /** The account's subscription quota is exhausted until `untilMs` (a provider quota reset). */
22
+ export class PoolQuotaCooldown extends Schema.TaggedClass<PoolQuotaCooldown>()(
23
+ 'PoolQuotaCooldown',
24
+ {
25
+ accountId: PoolAccountId,
26
+ startedAtMs: EpochMs,
27
+ untilMs: EpochMs
28
+ }
29
+ ) {}
30
+
31
+ /** The provider rejected the account's credentials; it sits out until `untilMs`. */
32
+ export class PoolAuthCooldown extends Schema.TaggedClass<PoolAuthCooldown>()('PoolAuthCooldown', {
33
+ accountId: PoolAccountId,
34
+ startedAtMs: EpochMs,
35
+ untilMs: EpochMs
36
+ }) {}
37
+
38
+ /**
39
+ * Why an account sits out. One cooldown per account: writing keeps the one that ends later (on a
40
+ * tie, the one that started later; see `PoolStoreApi.putCooldown`), and a reading can clear only a
41
+ * quota cooldown it postdates.
42
+ */
43
+ export const PoolCooldown = Schema.Union([PoolQuotaCooldown, PoolAuthCooldown])
44
+
45
+ export type PoolCooldown = typeof PoolCooldown.Type
46
+
47
+ /** A pool store operation failed. The pool degrades to stateless fill-first routing on reads. */
48
+ export class PoolStoreError extends Schema.TaggedError<PoolStoreError>()('PoolStoreError', {
49
+ operation: Schema.Literals([
50
+ 'load',
51
+ 'movePin',
52
+ 'putCooldown',
53
+ 'clearCooldown',
54
+ 'putReading',
55
+ 'state'
56
+ ]),
57
+ message: Schema.String
58
+ }) {}
59
+
60
+ /** `makePool` rejected its configuration. */
61
+ export class PoolConfigError extends Schema.TaggedError<PoolConfigError>()('PoolConfigError', {
62
+ reason: Schema.Literals([
63
+ 'invalid_pool_id',
64
+ 'no_accounts',
65
+ 'invalid_account_id',
66
+ 'duplicate_account_id',
67
+ 'invalid_priority',
68
+ 'invalid_max_age',
69
+ 'invalid_reserve_percent'
70
+ ]),
71
+ message: Schema.String
72
+ }) {}
73
+
74
+ /** A reading or lookup named an account the pool was not configured with. */
75
+ export class PoolUnknownAccountError extends Schema.TaggedError<PoolUnknownAccountError>()(
76
+ 'PoolUnknownAccountError',
77
+ {
78
+ poolId: Schema.String,
79
+ accountId: Schema.String
80
+ }
81
+ ) {}