opencode-account-quota 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/rules.js ADDED
@@ -0,0 +1,259 @@
1
+ // Decision rules (B03, B06; S01 §§2–5, 8, 11–12). Pure: state and clock come from the caller. Nothing here
2
+ // reads the network, writes storage, switches accounts or sends prompts; a result is only advice to display.
3
+ import { isRef } from "./inventory.js"
4
+
5
+ // Freshness: how long a sample stays Fresh (drawn as current and decisive). A known reset ends it sooner; past either it
6
+ // is Stale, never 0%. ChatGPT (Codex) and Claude Code usage follow the plugin option `usageFreshnessSeconds` of the
7
+ // location's server instance: a positive safe integer up to MAX_USAGE_FRESHNESS (one hour); missing or anything else is
8
+ // USAGE_FRESHNESS. DeepSeek balances keep 2 min and the Anthropic API 5 min. This is not the age limit of a Claude step
9
+ // event (claude.js), a retry wait or a window's real expiry. Callers pass the table on; nothing here holds an option.
10
+ export const USAGE_FRESHNESS = 150
11
+ export const MAX_USAGE_FRESHNESS = 3600
12
+ export const usageFreshness = (value) =>
13
+ (Number.isSafeInteger(value) && value > 0 && value <= MAX_USAGE_FRESHNESS ? value : USAGE_FRESHNESS)
14
+ // Milliseconds per integration for a usage freshness in seconds (invalid → the default).
15
+ export function freshness(seconds) {
16
+ const usage = usageFreshness(seconds) * 1000
17
+ return Object.freeze({ openai: usage, "claude-agent": usage, deepseek: 120_000, anthropic: 300_000 })
18
+ }
19
+ export const TTL = freshness(USAGE_FRESHNESS)
20
+ const BALANCE = new Set(["deepseek"])
21
+ export const TURN_END = new Set(["session.execution.succeeded", "session.execution.failed"])
22
+
23
+ export const isNumber = (value) => typeof value === "number" && Number.isFinite(value)
24
+ export const isTime = (ms) => isNumber(ms) && !Number.isNaN(new Date(ms).getTime())
25
+ const DECIMAL = /^-?(0|[1-9]\d{0,17})(\.\d{1,18})?$/
26
+
27
+ export const validThreshold = (value) => Number.isInteger(value) && value >= 90 && value <= 100
28
+ export const isDecimal = (value) => typeof value === "string" && DECIMAL.test(value)
29
+ export const isCurrency = (value) => typeof value === "string" && /^[A-Z]{3}$/.test(value)
30
+ export const selectionKey = (selection) =>
31
+ `${selection.providerID}/${selection.modelID}${selection.variant ? "#" + selection.variant : ""}`
32
+
33
+ // Exact decimal comparison of source strings: no binary floating point, "1.10" equals "1.1000".
34
+ export function compareDecimal(a, b) {
35
+ const [ai, af = ""] = a.split(".")
36
+ const [bi, bf = ""] = b.split(".")
37
+ const width = Math.max(af.length, bf.length)
38
+ const scaled = (int, frac) => {
39
+ const value = BigInt(int.replace("-", "") + frac.padEnd(width, "0"))
40
+ return int.startsWith("-") ? -value : value
41
+ }
42
+ const x = scaled(ai, af)
43
+ const y = scaled(bi, bf)
44
+ return x < y ? -1 : x > y ? 1 : 0
45
+ }
46
+
47
+ // A sample is attributed to one account, source, window and scope ("general" or an exact selectionKey).
48
+ export function validSample(s) {
49
+ if (!s || typeof s !== "object" || ![s.integrationID, s.connectionID, s.source, s.window, s.scope].every(isRef)) return false
50
+ if (!isTime(s.observedAt) || (s.resetsAt !== undefined && !isTime(s.resetsAt))) return false
51
+ if (s.balances !== undefined) {
52
+ return typeof s.available === "boolean" && Array.isArray(s.balances) && s.balances.length > 0 &&
53
+ s.balances.length <= 8 && s.balances.every((b) => isCurrency(b?.currency) && isDecimal(b.total)) &&
54
+ new Set(s.balances.map((b) => b.currency)).size === s.balances.length
55
+ }
56
+ return typeof s.used === "number" && Number.isFinite(s.used) && s.used >= 0 && s.used <= 100
57
+ }
58
+
59
+ const pick = (s) => ({
60
+ integrationID: s.integrationID, connectionID: s.connectionID, source: s.source, window: s.window, scope: s.scope,
61
+ observedAt: s.observedAt,
62
+ ...(s.resetsAt !== undefined ? { resetsAt: s.resetsAt } : {}),
63
+ ...(s.balances !== undefined ? { available: s.available, balances: s.balances.map(({ currency, total }) => ({ currency, total })) }
64
+ : { used: s.used }),
65
+ })
66
+ const sampleKey = (s) => JSON.stringify([s.integrationID, s.connectionID, s.source, s.window, s.scope])
67
+ const sourceKey = (s) => JSON.stringify([s.integrationID, s.connectionID, s.source])
68
+
69
+ // In-memory measurements, indexed by account, source, window and scope. Late samples are dropped, a newer
70
+ // failure keeps the older value visible but no longer decisive, and a newer sample clears its source's failure.
71
+ export function createCache() {
72
+ const samples = new Map()
73
+ const failures = new Map()
74
+ return {
75
+ record(sample) {
76
+ if (!validSample(sample)) return false
77
+ const prior = samples.get(sampleKey(sample))
78
+ const failure = failures.get(sourceKey(sample))
79
+ if ((prior && prior.observedAt >= sample.observedAt) || (failure && failure.at >= sample.observedAt)) return false
80
+ samples.set(sampleKey(sample), pick(sample))
81
+ failures.delete(sourceKey(sample))
82
+ return true
83
+ },
84
+ fail({ integrationID, connectionID, source }, at, reason, retryAt) {
85
+ const key = sourceKey({ integrationID, connectionID, source })
86
+ if (!isTime(at) || (failures.get(key)?.at ?? -Infinity) >= at) return false
87
+ failures.set(key, { integrationID, connectionID, source, at, reason, ...(isTime(retryAt) ? { retryAt } : {}) })
88
+ return true
89
+ },
90
+ list: () => ({ samples: [...samples.values()], failures: [...failures.values()] }),
91
+ // Everything held for one integration (or one of its connections), e.g. when its data can no longer be attributed.
92
+ forget(integrationID, connectionID) {
93
+ for (const map of [samples, failures]) {
94
+ for (const [key, item] of map) {
95
+ if (item.integrationID === integrationID && (connectionID === undefined || item.connectionID === connectionID)) map.delete(key)
96
+ }
97
+ }
98
+ },
99
+ clear() {
100
+ samples.clear()
101
+ failures.clear()
102
+ },
103
+ }
104
+ }
105
+
106
+ // `ttl`: a freshness table (freshness()); the default one when left out.
107
+ export const expiresAt = (s, ttl = TTL) =>
108
+ Math.min(s.observedAt + (Object.hasOwn(ttl, s.integrationID) ? ttl[s.integrationID] : 120_000), s.resetsAt ?? Infinity)
109
+
110
+ // Fresh | Stale | No data | Refresh failed. Reaching resetsAt makes a value stale; it never
111
+ // becomes 0% by itself.
112
+ export function sampleState(sample, failure, now, ttl = TTL) {
113
+ if (failure && (!sample || failure.at >= sample.observedAt)) return "Refresh failed"
114
+ if (!sample) return "No data"
115
+ if (now >= expiresAt(sample, ttl)) return "Stale"
116
+ return "Fresh"
117
+ }
118
+
119
+ // Truncated to two decimals, never rounded up to a threshold; rounded first to 6 decimals so binary noise does not
120
+ // show 8.2 as 8.19%.
121
+ export const percent = (value) => `${Math.floor(Math.round(value * 1e6) / 1e4) / 100}%`
122
+ export const windowLabel = (window, scope) =>
123
+ (window === "5h" ? "5 h" : window === "weekly" ? "Weekly" : window) + (scope === "general" ? "" : ` (${scope.split("/").pop()})`)
124
+
125
+ function accountData(integrationID, connectionID, scope, samples, failures) {
126
+ const own = samples.filter((s) => s.integrationID === integrationID && s.connectionID === connectionID &&
127
+ (s.scope === "general" || s.scope === scope))
128
+ const failureOf = (source) => failures.find((f) =>
129
+ f.integrationID === integrationID && f.connectionID === connectionID && f.source === source)
130
+ return { own, failureOf }
131
+ }
132
+
133
+ // What a trigger is about and what a fresh sample measured: one window and scope, or one balance currency.
134
+ const dimension = (window, scope) => JSON.stringify([window, scope])
135
+
136
+ function quotaTrigger(data, threshold, now, ttl) {
137
+ let hit
138
+ for (const s of data.own) {
139
+ if (s.used === undefined || sampleState(s, data.failureOf(s.source), now, ttl) !== "Fresh") continue
140
+ if (s.used >= threshold && (!hit || s.used > hit.used)) hit = s
141
+ }
142
+ return hit && { window: hit.window, scope: hit.scope, used: hit.used, keys: [dimension(hit.window, hit.scope)],
143
+ text: `${windowLabel(hit.window, hit.scope)}: ${percent(hit.used)} used` }
144
+ }
145
+
146
+ // Kept apart from routing.js's: the data shapes differ ({ own, failureOf } here, { samples, failure } there).
147
+ const freshBalance = (data, now, ttl) =>
148
+ data.own.find((s) => s.balances && sampleState(s, data.failureOf(s.source), now, ttl) === "Fresh")
149
+
150
+ function balanceTrigger(data, minimums, now, ttl) {
151
+ const sample = freshBalance(data, now, ttl)
152
+ const low = (sample?.balances ?? []).filter((b) => isDecimal(minimums[b.currency]) && compareDecimal(b.total, minimums[b.currency]) <= 0)
153
+ return low.length > 0 && {
154
+ window: "balance", currencies: low.map((b) => b.currency), keys: low.map((b) => dimension("balance", b.currency)),
155
+ text: "Low balance: " + low.map((b) => `${b.currency} ${b.total}`).join(", "),
156
+ }
157
+ }
158
+
159
+ // Dimensions of the active account backed by a fresh sample: what an "idle" result really measured, so the
160
+ // caller can tell a confirmed recovery from data that is only stale, failed or missing.
161
+ const measured = (data, balance, now, ttl) => balance
162
+ ? (freshBalance(data, now, ttl)?.balances ?? []).map((b) => dimension("balance", b.currency))
163
+ : data.own.filter((s) => s.used !== undefined && sampleState(s, data.failureOf(s.source), now, ttl) === "Fresh").map((s) => dimension(s.window, s.scope))
164
+
165
+ // Identity gate. The snapshot never proves an independent quota holder, the same billing scope or access to the exact
166
+ // model, so no other account is ever a confirmed destination (decision 1 in the evidence file): this names why.
167
+ function excluded(candidate) {
168
+ if (candidate.reconnectRequired) return "Reconnect required"
169
+ if (candidate.method === "external") return "Profile not verified"
170
+ return "Independent quota not proven"
171
+ }
172
+
173
+ // One integration, connections already in priority order. Returns
174
+ // { kind: "idle", measured? } nothing reached the threshold (or nothing to evaluate);
175
+ // `measured` lists the dimensions a fresh sample backs
176
+ // { kind: "none", reason, trigger } No confirmed alternative, with the reason of the next account in the order
177
+ // `ttl`: the freshness table of the snapshot's location (freshness()); the default one when left out.
178
+ export function recommend({ integration, selection, threshold, minimums = {}, samples = [], failures = [], now, ttl = TTL }) {
179
+ if (!validThreshold(threshold) || !integration || !selection || selection.providerID !== integration.id) return { kind: "idle" }
180
+ const scope = selectionKey(selection)
181
+ const order = integration.connections
182
+ const activeID = integration.activeID ?? order.find((c) => c.active)?.id
183
+ if (!isRef(activeID)) return { kind: "idle" }
184
+ const source = accountData(integration.id, activeID, scope, samples, failures)
185
+ const balance = BALANCE.has(integration.id)
186
+ const trigger = balance ? balanceTrigger(source, minimums, now, ttl) : quotaTrigger(source, threshold, now, ttl)
187
+ if (!trigger) return { kind: "idle", measured: measured(source, balance, now, ttl) }
188
+ const start = order.findIndex((c) => c.id === activeID)
189
+ if (start < 0) return { kind: "none", reason: "Active account is not in the priority order", trigger }
190
+ const next = order[(start + 1) % order.length]
191
+ return { kind: "none", reason: order.length > 1 ? excluded(next) : "No other account in this integration", trigger }
192
+ }
193
+
194
+ const contextKey = (selection, account) => JSON.stringify([selectionKey(selection), account ?? null])
195
+ // A plain copy: the host's selection may be a reactive object that changes in place.
196
+ const pin = ({ providerID, modelID, variant }) => ({ providerID, modelID, ...(variant ? { variant } : {}) })
197
+ const motiveOf = (result) => (result && result.kind !== "idle" && result.trigger
198
+ ? JSON.stringify([result.kind, result.to ?? result.reason, result.trigger.keys]) : undefined)
199
+ // Recovery needs a fresh sample of what triggered: stale, failed or missing data is not a recovery.
200
+ const recovered = (result, keys) => result?.kind === "idle" && keys.length > 0 && keys.every((key) => result.measured?.includes(key))
201
+
202
+ // Turn-end advisor (B03.5). A notice is born only from a final turn result of the session on screen, once per
203
+ // event; steps, tools, compaction and host retries do not count. Afterwards it is only revalidated against the
204
+ // held snapshot and the clock: it stays while they give the same advice for the same selection and active
205
+ // account, and is withdrawn otherwise (recovery, newer failure, stale or reset sample, missing account,
206
+ // selection or session). Revalidating never raises a notice. An episode lasts from the first notice until a
207
+ // fresh sample of its trigger shows recovery; within it a dismissed motive is not raised again. A changed
208
+ // selection or account starts another episode; the invalidation counter of the snapshot plays no part.
209
+ // view: { account(selection), evaluate(selection) } over the snapshot held at one instant
210
+ // context: view + { sessionID, selection } of the session on screen
211
+ export function createAdvisor() {
212
+ let notice
213
+ let episode
214
+ const seen = []
215
+ const revalidate = (view) => {
216
+ if (notice && (view.account(notice.selection) !== notice.account || motiveOf(view.evaluate(notice.selection)) !== notice.motive)) notice = undefined
217
+ if (episode && view.account(episode.selection) === episode.account && recovered(view.evaluate(episode.selection), episode.keys)) episode = undefined
218
+ }
219
+ return {
220
+ // Returns true only when a notice that was not on screen is raised.
221
+ turnEnded(event, context) {
222
+ if (!TURN_END.has(event?.type) || event.data?.sessionID !== context.sessionID || !isRef(event.id) || !context.selection) return false
223
+ if (seen.includes(event.id)) return false
224
+ seen.push(event.id)
225
+ if (seen.length > 64) seen.shift()
226
+ const account = context.account(context.selection)
227
+ const key = contextKey(context.selection, account)
228
+ const result = context.evaluate(context.selection)
229
+ const motive = motiveOf(result)
230
+ if (notice && (notice.key !== key || notice.sessionID !== context.sessionID || notice.motive !== motive)) notice = undefined
231
+ if (episode && (episode.key !== key || recovered(result, episode.keys))) episode = undefined
232
+ if (!motive) return false
233
+ const selection = pin(context.selection)
234
+ episode ??= { key, selection, account, keys: [], dismissed: new Set() }
235
+ episode.keys = result.trigger.keys
236
+ if (episode.dismissed.has(motive)) return false
237
+ const shown = notice !== undefined
238
+ notice = { key, sessionID: context.sessionID, selection, account, motive, result, afterFailure: event.type === "session.execution.failed" }
239
+ return !shown
240
+ },
241
+ // A new snapshot, or the clock reached a sample's expiry: withdraw what is no longer true.
242
+ observe: revalidate,
243
+ // What the session on screen may show now, with the current values. Leaving its session, selection or
244
+ // account ends the notice; while the context is unknown (no session, no snapshot) the caller shows nothing.
245
+ current(context) {
246
+ if (notice && (context.sessionID !== notice.sessionID || !context.selection ||
247
+ contextKey(context.selection, context.account(context.selection)) !== notice.key)) notice = undefined
248
+ revalidate(context)
249
+ return notice && { ...notice, result: context.evaluate(notice.selection) }
250
+ },
251
+ dismiss() {
252
+ if (notice) episode?.dismissed.add(notice.motive)
253
+ notice = undefined
254
+ },
255
+ pending: () => notice !== undefined,
256
+ // Something a reload can change: a notice on screen, or a dismissed episode waiting for a fresh sample of recovery.
257
+ watching: () => notice !== undefined || episode !== undefined,
258
+ }
259
+ }