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/LICENSE +21 -0
- package/README.md +82 -2
- package/claude.js +351 -0
- package/codex.js +87 -0
- package/deepseek.js +102 -0
- package/index.js +12 -0
- package/inventory.js +43 -0
- package/package.json +33 -4
- package/preferences.js +97 -0
- package/routing.js +219 -0
- package/rpc.js +233 -0
- package/rules.js +259 -0
- package/server.js +617 -0
- package/sync.js +60 -0
- package/tui.tsx +623 -0
- package/view.js +954 -0
package/inventory.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Only the server supplies the inventory and visible references. No credential values enter the DTO.
|
|
2
|
+
const METHODS = new Set(["key", "oauth", "external"])
|
|
3
|
+
|
|
4
|
+
export const isRef = (value) => typeof value === "string" && value !== "" && value.length <= 200
|
|
5
|
+
export const refKey = (integrationID, connectionID) => JSON.stringify([integrationID, connectionID])
|
|
6
|
+
// A plain JSON-like object: not null and not an array.
|
|
7
|
+
export const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
|
|
8
|
+
// Every saved credential the server lists natively is visible (personal-server authorization, S01 §1).
|
|
9
|
+
const listable = (row) => row?.type === "credential" && isRef(row.id) && typeof row.label === "string" && METHODS.has(row.method)
|
|
10
|
+
|
|
11
|
+
export const isAccountReference = (input) =>
|
|
12
|
+
!!input && typeof input === "object" && !Array.isArray(input) && Object.keys(input).length === 2 &&
|
|
13
|
+
Object.hasOwn(input, "integrationID") && Object.hasOwn(input, "connectionID") &&
|
|
14
|
+
isRef(input.integrationID) && isRef(input.connectionID)
|
|
15
|
+
|
|
16
|
+
export function inventorySnapshot(connections) {
|
|
17
|
+
if (!Array.isArray(connections)) {
|
|
18
|
+
return { schema: 1, revision: 0, inventory: "unavailable", integrations: [] }
|
|
19
|
+
}
|
|
20
|
+
const reads = connections.filter((read) => isRef(read?.integrationID))
|
|
21
|
+
const integrations = []
|
|
22
|
+
for (const { integrationID, connections: listed, active: ref } of reads) {
|
|
23
|
+
if (reads.filter((read) => read.integrationID === integrationID).length > 1) continue
|
|
24
|
+
const rows = Array.isArray(listed) ? listed : []
|
|
25
|
+
const visible = rows.filter(
|
|
26
|
+
(row) =>
|
|
27
|
+
listable(row) &&
|
|
28
|
+
rows.filter((other) => other?.id === row.id).length === 1,
|
|
29
|
+
)
|
|
30
|
+
// An integration with no visible account is listed only when its environment key is the active one.
|
|
31
|
+
if (visible.length === 0 && ref?.type !== "env") continue
|
|
32
|
+
const activeID = ref?.type === "credential" && visible.some((row) => row.id === ref.id) ? ref.id : undefined
|
|
33
|
+
integrations.push({
|
|
34
|
+
id: integrationID,
|
|
35
|
+
active: activeID !== undefined ? "connection" : ref == null ? "none" : ref.type === "env" ? "environment" : "unknown",
|
|
36
|
+
connections: visible.map((row) => ({
|
|
37
|
+
id: row.id, label: row.label, method: row.method, active: row.id === activeID,
|
|
38
|
+
...(row.status?.status === "needs_auth" ? { reconnectRequired: true } : {}),
|
|
39
|
+
})),
|
|
40
|
+
})
|
|
41
|
+
}
|
|
42
|
+
return { schema: 1, revision: 0, inventory: "available", integrations }
|
|
43
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-account-quota",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "OpenCode plugin to check the remaining quota of each connected account (ChatGPT, Claude Code, DeepSeek) and set a route order.",
|
|
5
|
+
"keywords": ["opencode", "opencode-plugin", "quota", "usage", "codex", "claude-code", "deepseek"],
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "JoelChinoP",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/JoelChinoP/opencode-account-quota.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/JoelChinoP/opencode-account-quota#readme",
|
|
13
|
+
"bugs": "https://github.com/JoelChinoP/opencode-account-quota/issues",
|
|
14
|
+
"type": "module",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./index.js",
|
|
17
|
+
"./tui": "./tui.tsx",
|
|
18
|
+
"./rpc": "./rpc.js"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"index.js",
|
|
22
|
+
"tui.tsx",
|
|
23
|
+
"rpc.js",
|
|
24
|
+
"inventory.js",
|
|
25
|
+
"server.js",
|
|
26
|
+
"sync.js",
|
|
27
|
+
"view.js",
|
|
28
|
+
"rules.js",
|
|
29
|
+
"preferences.js",
|
|
30
|
+
"routing.js",
|
|
31
|
+
"deepseek.js",
|
|
32
|
+
"codex.js",
|
|
33
|
+
"claude.js"
|
|
34
|
+
]
|
|
35
|
+
}
|
package/preferences.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Preferences (B04; S01 §§4–5, 9–10): the only data this plugin persists. Schema-versioned order of opaque
|
|
2
|
+
// references per integration, threshold, optional minimum balance per currency and the fixed Recommend mode.
|
|
3
|
+
// Never measurements, tokens, profile paths, messages, proposals or redemption IDs.
|
|
4
|
+
import { isRef } from "./inventory.js"
|
|
5
|
+
import { isDecimal, validThreshold } from "./rules.js"
|
|
6
|
+
|
|
7
|
+
export const KEY = "preferences"
|
|
8
|
+
// New preferences only (nothing stored yet): a USD 0.20 low-balance notice and no CNY minimum, by user
|
|
9
|
+
// decision. A stored record is used as it is, including `minimums: {}` (notice off); loading never writes.
|
|
10
|
+
const DEFAULTS = Object.freeze({ schema: 1, revision: 0, mode: "recommend", threshold: 95, order: Object.freeze({}), minimums: Object.freeze({ USD: "0.20" }) })
|
|
11
|
+
const MAX = 64
|
|
12
|
+
|
|
13
|
+
// Stricter than inventory.js's isRecord (a plain Object prototype): for what is stored and for proposals.
|
|
14
|
+
const isMap = (value) => !!value && typeof value === "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype
|
|
15
|
+
const exactKeys = (value, keys) => isMap(value) && Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key))
|
|
16
|
+
const validOrder = (order) => isMap(order) && Object.keys(order).length <= MAX && Object.entries(order).every(([id, list]) =>
|
|
17
|
+
isRef(id) && Array.isArray(list) && list.length <= MAX && list.every(isRef) && new Set(list).size === list.length)
|
|
18
|
+
// DeepSeek reports CNY and USD (S09); a minimum compares only within its own currency. An absent currency is
|
|
19
|
+
// "off", which is not the same as "0".
|
|
20
|
+
const validMinimums = (minimums) => isMap(minimums) &&
|
|
21
|
+
Object.entries(minimums).every(([currency, amount]) => (currency === "USD" || currency === "CNY") && isDecimal(amount) && !amount.startsWith("-"))
|
|
22
|
+
|
|
23
|
+
const valid = (value) => exactKeys(value, Object.keys(DEFAULTS)) && value.schema === 1 && Number.isSafeInteger(value.revision) &&
|
|
24
|
+
value.revision >= 0 && value.mode === "recommend" && validThreshold(value.threshold) && validOrder(value.order) && validMinimums(value.minimums)
|
|
25
|
+
|
|
26
|
+
// Nothing stored yet means defaults. An unknown schema or a damaged value is reported and never overwritten.
|
|
27
|
+
export function parseStored(value) {
|
|
28
|
+
if (value === undefined || value === null) return { state: "available", value: DEFAULTS }
|
|
29
|
+
return valid(value) ? { state: "available", value } : { state: "unsupported" }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Derived view, never written back: renamed or reconnect-required connections keep their place, entries absent
|
|
33
|
+
// from a successful native list are retired, and connections that are really new go last.
|
|
34
|
+
export function reconcile(saved = [], ids) {
|
|
35
|
+
return [...saved.filter((id) => ids.includes(id)), ...ids.filter((id) => !saved.includes(id))]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Validates a complete proposal against the current inventory of this server. Returns the value to store, or
|
|
39
|
+
// an error type: "invalid" for anything malformed or outside the inventory.
|
|
40
|
+
export function proposal(input, current, inventory) {
|
|
41
|
+
if (!exactKeys(input, ["revision", "threshold", "minimums", "order"])) return { error: "invalid" }
|
|
42
|
+
const { revision, threshold, minimums, order } = input
|
|
43
|
+
if (!Number.isSafeInteger(revision) || !validThreshold(threshold) || !validMinimums(minimums) || !validOrder(order)) return { error: "invalid" }
|
|
44
|
+
for (const [integrationID, ids] of Object.entries(order)) {
|
|
45
|
+
const listed = inventory.find((item) => item.id === integrationID)?.connections.map((c) => c.id)
|
|
46
|
+
if (!listed || !ids.every((id) => listed.includes(id))) return { error: "invalid" }
|
|
47
|
+
}
|
|
48
|
+
if (revision !== current.revision) return { error: "conflict" }
|
|
49
|
+
return { value: { schema: 1, revision: current.revision + 1, mode: "recommend", threshold, order, minimums } }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Route order (rotation plan R1): a separate key, so a TUI that only knows `preferences` keeps saving priorities
|
|
53
|
+
// without touching it. Only opaque references and their order: never measurements, decisions or session state. Empty
|
|
54
|
+
// by default; loading never writes. A row is one destination, not an alias: `binding: "current"` means "with the
|
|
55
|
+
// account active natively for that provider", `binding: "exact"` names one saved connection.
|
|
56
|
+
export const ROUTING_KEY = "routingPreferences"
|
|
57
|
+
const ROUTING_DEFAULTS = Object.freeze({ schema: 1, revision: 0, targets: Object.freeze([]) })
|
|
58
|
+
const TARGET = ["integrationID", "providerID", "binding"]
|
|
59
|
+
|
|
60
|
+
export function validTarget(t) {
|
|
61
|
+
if (!isMap(t)) return false
|
|
62
|
+
const extra = Object.keys(t).filter((key) => !TARGET.includes(key))
|
|
63
|
+
if (!TARGET.every((key) => Object.hasOwn(t, key)) || !extra.every((key) => ["modelID", "variant", "connectionID"].includes(key) && isRef(t[key]))) return false
|
|
64
|
+
if (!isRef(t.integrationID)) return false
|
|
65
|
+
// OpenCode names a provider and its integration with the same ID for every integration this plugin knows.
|
|
66
|
+
if (t.providerID !== t.integrationID) return false
|
|
67
|
+
if (t.binding === "current") return t.connectionID === undefined
|
|
68
|
+
return t.binding === "exact" && isRef(t.connectionID)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const targetKey = (t) => JSON.stringify([t.integrationID, t.providerID, t.modelID, t.variant ?? null, t.binding, t.connectionID ?? null])
|
|
72
|
+
const validTargets = (targets) => Array.isArray(targets) && targets.length <= MAX && targets.every(validTarget) &&
|
|
73
|
+
new Set(targets.map(targetKey)).size === targets.length
|
|
74
|
+
const validRouting = (value) => exactKeys(value, ["schema", "revision", "targets"]) && value.schema === 1 &&
|
|
75
|
+
Number.isSafeInteger(value.revision) && value.revision >= 0 && validTargets(value.targets)
|
|
76
|
+
|
|
77
|
+
// A future schema or a damaged value is read-only: reported, never overwritten.
|
|
78
|
+
export function parseRouting(value) {
|
|
79
|
+
if (value === undefined || value === null) return { state: "available", value: ROUTING_DEFAULTS }
|
|
80
|
+
return validRouting(value) ? { state: "available", value } : { state: "unsupported" }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// A complete proposal `{ revision, targets }` checked against this server's inventory: the integration must be listed
|
|
84
|
+
// and an exact connection must be one of its saved connections. Saving enables nothing and reads nothing.
|
|
85
|
+
export function routingProposal(input, current, inventory) {
|
|
86
|
+
if (!exactKeys(input, ["revision", "targets"]) || !Number.isSafeInteger(input.revision) || !validTargets(input.targets)) return { error: "invalid" }
|
|
87
|
+
for (const t of input.targets) {
|
|
88
|
+
const integration = inventory.find((item) => item.id === t.integrationID)
|
|
89
|
+
if (!integration) return { error: "invalid" }
|
|
90
|
+
if (t.binding === "exact" && !integration.connections.some((c) => c.id === t.connectionID)) return { error: "invalid" }
|
|
91
|
+
}
|
|
92
|
+
if (input.revision !== current.revision) return { error: "conflict" }
|
|
93
|
+
const targets = input.targets.map(({ integrationID, providerID, modelID, variant, binding, connectionID }) => ({
|
|
94
|
+
integrationID, providerID, ...(modelID ? { modelID } : {}), ...(variant ? { variant } : {}), binding, ...(connectionID ? { connectionID } : {}),
|
|
95
|
+
}))
|
|
96
|
+
return { value: { schema: 1, revision: current.revision + 1, targets } }
|
|
97
|
+
}
|
package/routing.js
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// Global route order engine (rotation plan R2). Pure: snapshot, clock and budgets come from the caller.
|
|
2
|
+
// Nothing here reads the network or storage, calls the host, switches models or accounts, or sends prompts.
|
|
3
|
+
//
|
|
4
|
+
// Rule: keep the user's selection while every applicable window of the account in use stays below the threshold.
|
|
5
|
+
// Once one reaches it, walk the list from the first row and stop at the first destination proven eligible. Neither
|
|
6
|
+
// the order nor the clock alone causes a change, and a reset never makes an account eligible: only a fresh reading does.
|
|
7
|
+
//
|
|
8
|
+
// Input: { selection, targets, integrations (snapshot DTO: connections carry samples and failure), threshold, minimums,
|
|
9
|
+
// now, readable: Set of integrations a policy read may refresh, visited: Set of refKeys already read for this
|
|
10
|
+
// decision, discarded: Set of refKeys whose reading no longer belongs to them, budget: { origin, candidates },
|
|
11
|
+
// paid: boolean, ttl: freshness table of the deciding location
|
|
12
|
+
// (rules.freshness; the default one when left out) }
|
|
13
|
+
// Output: { kind: "keep" | "needRead" | "suggest" | "noTarget", origin, trigger?, read?, target?, reason?,
|
|
14
|
+
// manual?, rows: [{ status, reason }] }
|
|
15
|
+
// keep below the threshold, or the origin could not be verified (`reason` says what to refresh)
|
|
16
|
+
// needRead one policy read of `read` would let the decision go on; the caller reads it and evaluates again
|
|
17
|
+
// suggest the first eligible destination, which this host cannot apply (`manual`, `reason`)
|
|
18
|
+
// noTarget no destination proven eligible; `reason` is the first useful one
|
|
19
|
+
import { refKey } from "./inventory.js"
|
|
20
|
+
import { compareDecimal, expiresAt, isDecimal, percent, sampleState, selectionKey, validThreshold, windowLabel } from "./rules.js"
|
|
21
|
+
|
|
22
|
+
// Windows a subscription destination must prove: a source that sent only one of them does not prove the other is absent.
|
|
23
|
+
export const REQUIRED = { openai: ["5h", "weekly"], "claude-agent": ["5h", "weekly"] }
|
|
24
|
+
const BALANCE = new Set(["deepseek"])
|
|
25
|
+
|
|
26
|
+
const sameModel = (t, selection) => !!selection && t.providerID === selection.providerID && t.modelID === selection.modelID &&
|
|
27
|
+
(t.variant ?? undefined) === (selection.variant ?? undefined)
|
|
28
|
+
export const routeModelID = (t, selection) => t.modelID ?? (selection?.providerID === t.providerID ? selection.modelID : undefined)
|
|
29
|
+
export const catalogModel = (catalog, providerID, id) => catalog?.find((m) => m.enabled && m.providerID === providerID && m.id === id)
|
|
30
|
+
|
|
31
|
+
// An omitted effort follows the same model; a different model starts at its own default.
|
|
32
|
+
function modelOf(t, selection, catalog) {
|
|
33
|
+
const modelID = routeModelID(t, selection)
|
|
34
|
+
if (!modelID) return undefined
|
|
35
|
+
const same = t.providerID === selection.providerID && modelID === selection.modelID
|
|
36
|
+
const variant = t.variant ?? (same ? selection.variant : undefined)
|
|
37
|
+
// A fixed effort on a floating model must still exist if the conversation has since changed models.
|
|
38
|
+
if (!t.modelID && t.variant && t.variant !== selection.variant &&
|
|
39
|
+
!catalogModel(catalog, t.providerID, modelID)?.variants.some((v) => v.id === t.variant)) return undefined
|
|
40
|
+
return { providerID: t.providerID, modelID, ...(variant ? { variant } : {}) }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Samples and the latest failure of one connection, with their owner IDs (the DTO leaves them out).
|
|
44
|
+
export function dataOf(integration, connection) {
|
|
45
|
+
const samples = (connection.samples ?? []).map((s) => ({ ...s, integrationID: integration.id, connectionID: connection.id }))
|
|
46
|
+
const failure = connection.failure && { ...connection.failure, integrationID: integration.id, connectionID: connection.id }
|
|
47
|
+
return { samples, failure }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// The failure that makes a source's samples undecidable: one newer than them for the same source.
|
|
51
|
+
const failed = (data, s) => (data.failure && data.failure.source === s.source ? data.failure : undefined)
|
|
52
|
+
|
|
53
|
+
// Quota of one account for one model selection: general windows plus windows scoped to that exact selection.
|
|
54
|
+
// Returns { high } when a window is at or over the threshold (fresh, or a confirmed mark whose reset is still ahead),
|
|
55
|
+
// { below } when every required window is fresh and below it, otherwise { unknown }.
|
|
56
|
+
function quota(integrationID, data, scope, threshold, now, ttl) {
|
|
57
|
+
const own = data.samples.filter((s) => s.used !== undefined)
|
|
58
|
+
.filter((s) => s.scope === "general" || s.scope === scope)
|
|
59
|
+
let high
|
|
60
|
+
let waiting
|
|
61
|
+
for (const s of own) {
|
|
62
|
+
const state = sampleState(s, failed(data, s), now, ttl)
|
|
63
|
+
if (state === "Fresh" && s.used !== undefined && s.used >= threshold && (!high || s.used > high.used)) high = s
|
|
64
|
+
// A negative mark: a confirmed high value stays a reason to skip until its known reset, though no longer a figure.
|
|
65
|
+
if (state === "Stale" && s.used !== undefined && s.used >= threshold && s.resetsAt > now) waiting = s
|
|
66
|
+
}
|
|
67
|
+
if (high) return { high: `${windowLabel(high.window, high.scope)}: ${percent(high.used)} used`, window: high }
|
|
68
|
+
if (waiting) return { waiting: `Waiting for reset (${windowLabel(waiting.window, waiting.scope)})` }
|
|
69
|
+
const required = REQUIRED[integrationID]
|
|
70
|
+
if (!required) return { unknown: "Usage unknown", reader: false }
|
|
71
|
+
for (const window of required) {
|
|
72
|
+
const s = own.find((x) => x.window === window && x.scope === "general")
|
|
73
|
+
const state = s ? sampleState(s, failed(data, s), now, ttl) : "No data"
|
|
74
|
+
if (state !== "Fresh") return { unknown: "Usage unknown", state }
|
|
75
|
+
}
|
|
76
|
+
return { below: true }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Kept apart from rules.js's: the data shapes differ ({ samples, failure } here, { own, failureOf } there).
|
|
80
|
+
const freshBalance = (data, now, ttl) => data.samples.find((s) => s.balances && sampleState(s, failed(data, s), now, ttl) === "Fresh")
|
|
81
|
+
|
|
82
|
+
// A paid key with a balance reader: available, in a currency with a configured minimum, strictly above it. USD and CNY
|
|
83
|
+
// are never added up; a currency without a minimum proves nothing.
|
|
84
|
+
function balanceFit(data, minimums, now, ttl) {
|
|
85
|
+
const configured = Object.keys(minimums ?? {}).filter((c) => isDecimal(minimums[c]))
|
|
86
|
+
if (configured.length === 0) return { reason: "No balance criterion" }
|
|
87
|
+
const sample = freshBalance(data, now, ttl)
|
|
88
|
+
if (!sample) return { unknown: "Usage unknown" }
|
|
89
|
+
if (sample.available !== true) return { reason: "Balance not available" }
|
|
90
|
+
const present = sample.balances.filter((b) => configured.includes(b.currency))
|
|
91
|
+
if (present.length === 0) return { reason: `No ${configured.join(" or ")} balance` }
|
|
92
|
+
const low = present.find((b) => compareDecimal(b.total, minimums[b.currency]) <= 0)
|
|
93
|
+
return low ? { reason: `Balance: ${low.currency} ${low.total}` } : { fit: true }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// The origin's trigger: a fresh applicable window at or over the threshold, or a fresh balance at or below its minimum.
|
|
97
|
+
function originState(integration, connection, selection, threshold, minimums, now, ttl) {
|
|
98
|
+
const data = dataOf(integration, connection)
|
|
99
|
+
if (BALANCE.has(integration.id)) {
|
|
100
|
+
const sample = freshBalance(data, now, ttl)
|
|
101
|
+
if (!sample) return { state: "unknown" }
|
|
102
|
+
const low = sample.balances.filter((b) => isDecimal(minimums?.[b.currency]) && compareDecimal(b.total, minimums[b.currency]) <= 0)
|
|
103
|
+
return low.length > 0 ? { state: "trigger", text: "Low balance: " + low.map((b) => `${b.currency} ${b.total}`).join(", ") } : { state: "below" }
|
|
104
|
+
}
|
|
105
|
+
const q = quota(integration.id, data, selectionKey(selection), threshold, now, ttl)
|
|
106
|
+
if (q.high) return { state: "trigger", text: q.high }
|
|
107
|
+
// Below needs a fresh measure of the origin; a waiting mark or missing data leave the origin unverified.
|
|
108
|
+
const fresh = data.samples.some((s) => s.used !== undefined && (s.scope === "general" || s.scope === selectionKey(selection)) &&
|
|
109
|
+
sampleState(s, failed(data, s), now, ttl) === "Fresh")
|
|
110
|
+
return fresh ? { state: "below" } : { state: "unknown" }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Where a read of one account stands: allowed now, already used in this decision, or not possible.
|
|
114
|
+
function readability(input, integration, connection, data, purpose) {
|
|
115
|
+
const key = refKey(integration.id, connection.id)
|
|
116
|
+
if (input.discarded?.has(key)) return { reason: "Account changed during the read" }
|
|
117
|
+
if (data.failure?.reason === "auth") return { reason: "Reconnect required" }
|
|
118
|
+
if (data.failure?.retryAt > input.now) return { reason: "Waiting to retry" }
|
|
119
|
+
if (!input.readable?.has(integration.id)) {
|
|
120
|
+
return { reason: integration.refreshable ? "Refresh required" : "Usage unknown" }
|
|
121
|
+
}
|
|
122
|
+
if (input.visited?.has(key)) return { reason: "Not verified" }
|
|
123
|
+
if ((input.budget?.[purpose] ?? 0) <= 0) return { reason: "Not verified (read budget used)" }
|
|
124
|
+
return { read: { integrationID: integration.id, connectionID: connection.id, purpose } }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// The account a row would use: its exact connection, or the one active natively for its provider.
|
|
128
|
+
function accountOf(integration, t) {
|
|
129
|
+
if (t.binding === "exact") return integration.connections.find((c) => c.id === t.connectionID) ?? { missing: "Account removed" }
|
|
130
|
+
if (integration.active === "connection") return integration.connections.find((c) => c.active) ?? { missing: "Usage unknown" }
|
|
131
|
+
return { missing: integration.active === "none" ? "No active account" : "Usage unknown" }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// One row: { status: "origin" | "eligible" | "skipped" | "pending", reason, read? }.
|
|
135
|
+
function evaluateRow(input, t, origin) {
|
|
136
|
+
const integration = input.integrations.find((i) => i.id === t.integrationID)
|
|
137
|
+
if (!integration) return { status: "skipped", reason: "Not in inventory" }
|
|
138
|
+
if (t.providerID !== integration.id) return { status: "skipped", reason: "Model unavailable here" }
|
|
139
|
+
const account = accountOf(integration, t)
|
|
140
|
+
if (account.missing) return { status: "skipped", reason: account.missing }
|
|
141
|
+
const model = modelOf(t, input.selection, input.catalog)
|
|
142
|
+
if (!model) return { status: "skipped", reason: routeModelID(t, input.selection) ? "Choose an effort for this model" : "Choose a model for this provider" }
|
|
143
|
+
if (origin && sameModel(model, input.selection) && origin.integrationID === integration.id && origin.connectionID === account.id) {
|
|
144
|
+
return { status: "origin", reason: "In use now" }
|
|
145
|
+
}
|
|
146
|
+
if (account.reconnectRequired) return { status: "skipped", reason: "Reconnect required" }
|
|
147
|
+
// Claude Code data belongs to its single profile only while the server can attribute it (passive flag).
|
|
148
|
+
if (integration.id === "claude-agent" && !integration.passive) return { status: "skipped", reason: "Usage unknown" }
|
|
149
|
+
const data = dataOf(integration, account)
|
|
150
|
+
if (account.method === "key") {
|
|
151
|
+
if (!input.paid) return { status: "skipped", reason: "Metered API not enabled" }
|
|
152
|
+
if (!BALANCE.has(integration.id)) return { status: "skipped", reason: "No budget reader" }
|
|
153
|
+
const fit = balanceFit(data, input.minimums, input.now, input.ttl)
|
|
154
|
+
if (fit.fit) return { status: "eligible", model }
|
|
155
|
+
if (fit.reason) return { status: "skipped", reason: fit.reason }
|
|
156
|
+
} else {
|
|
157
|
+
const q = quota(integration.id, data, selectionKey(model), input.threshold, input.now, input.ttl)
|
|
158
|
+
if (q.high) return { status: "skipped", reason: q.high }
|
|
159
|
+
if (q.waiting) return { status: "skipped", reason: q.waiting }
|
|
160
|
+
if (q.below) return { status: "eligible", model }
|
|
161
|
+
if (q.reader === false) return { status: "skipped", reason: q.unknown }
|
|
162
|
+
}
|
|
163
|
+
const readable = readability(input, integration, account, data, "candidates")
|
|
164
|
+
return readable.read ? { status: "pending", reason: "Usage unknown", read: readable.read } : { status: "skipped", reason: readable.reason }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The first eligible row as a decision, only suggested: an exact account needs a global switch (`/connect`), and this
|
|
168
|
+
// build offers no model switch.
|
|
169
|
+
function outcome(input, t, target, model) {
|
|
170
|
+
if (t.binding === "exact" || sameModel(model, input.selection)) return { kind: "suggest", target, model, manual: true, reason: "Account switch is global" }
|
|
171
|
+
return { kind: "suggest", target, model, manual: true, reason: "Model switch not enabled" }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function decideRoute(input) {
|
|
175
|
+
const targets = Array.isArray(input?.targets) ? input.targets : []
|
|
176
|
+
const blank = targets.map(() => ({ status: "not-checked", reason: "" }))
|
|
177
|
+
const selection = input?.selection
|
|
178
|
+
if (!selection?.providerID || !selection.modelID || !validThreshold(input.threshold)) return { kind: "keep", reason: "Selection unknown", origin: { state: "unknown" }, rows: blank }
|
|
179
|
+
const integration = input.integrations?.find((i) => i.id === selection.providerID)
|
|
180
|
+
const account = integration?.active === "connection" ? integration.connections.find((c) => c.active) : undefined
|
|
181
|
+
if (!integration || !account) return { kind: "keep", reason: "Usage unknown", origin: { state: "unknown" }, rows: blank }
|
|
182
|
+
const origin = { integrationID: integration.id, connectionID: account.id,
|
|
183
|
+
...originState(integration, account, selection, input.threshold, input.minimums, input.now, input.ttl) }
|
|
184
|
+
const evaluated = targets.map((t) => evaluateRow(input, t, origin))
|
|
185
|
+
const rows = evaluated.map(({ status, reason }) => ({ status, reason: reason ?? "" }))
|
|
186
|
+
if (origin.state === "below") return { kind: "keep", origin, rows }
|
|
187
|
+
if (origin.state === "unknown") {
|
|
188
|
+
// Never read reserves for a trigger that was not confirmed: at most the origin itself.
|
|
189
|
+
const r = readability(input, integration, account, dataOf(integration, account), "origin")
|
|
190
|
+
if (r.read) return { kind: "needRead", read: r.read, origin, rows }
|
|
191
|
+
return { kind: "keep", reason: r.reason === "Not verified" ? "Usage unknown" : r.reason, origin, rows }
|
|
192
|
+
}
|
|
193
|
+
for (const [index, row] of evaluated.entries()) {
|
|
194
|
+
if (row.status === "eligible") {
|
|
195
|
+
rows.slice(index + 1).forEach((r) => { r.status = "not-checked"; r.reason = "" })
|
|
196
|
+
return { ...outcome(input, targets[index], index, row.model), trigger: origin.text, origin, rows }
|
|
197
|
+
}
|
|
198
|
+
if (row.status === "pending") {
|
|
199
|
+
rows.slice(index + 1).forEach((r) => { r.status = "not-checked"; r.reason = "" })
|
|
200
|
+
return { kind: "needRead", read: row.read, trigger: origin.text, origin, rows }
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const first = rows.find((r) => r.status === "skipped")
|
|
204
|
+
return { kind: "noTarget", reason: first?.reason ?? "No destination in the route order", trigger: origin.text, origin, rows }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// The next instant at which a decision of the preview can change by the clock alone (a sample's freshness, with the
|
|
208
|
+
// snapshot's `ttl` table, or, with `resets`, a reset of a held sample).
|
|
209
|
+
export const nextChange = (integrations, now, ttl, resets = true) => {
|
|
210
|
+
let next
|
|
211
|
+
for (const integration of integrations ?? []) {
|
|
212
|
+
for (const connection of integration.connections ?? []) {
|
|
213
|
+
for (const s of dataOf(integration, connection).samples) {
|
|
214
|
+
for (const at of resets ? [expiresAt(s, ttl), s.resetsAt] : [expiresAt(s, ttl)]) if (at > now && (next === undefined || at < next)) next = at
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return next
|
|
219
|
+
}
|
package/rpc.js
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { Rpc } from "@opencode/plugin/rpc"
|
|
2
|
+
import { isAccountReference, isRecord } from "./inventory.js"
|
|
3
|
+
import { validTarget } from "./preferences.js"
|
|
4
|
+
import { MAX_USAGE_FRESHNESS } from "./rules.js"
|
|
5
|
+
|
|
6
|
+
// Shared by the server and the TUI. The host validates shapes only; server.js repeats every check that
|
|
7
|
+
// grants access, because a schema is not a permission (S08).
|
|
8
|
+
const count = { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER }
|
|
9
|
+
const ref = { type: "string", minLength: 1, maxLength: 200 }
|
|
10
|
+
const time = { type: "number" }
|
|
11
|
+
const amount = { type: "string", minLength: 1, maxLength: 40 }
|
|
12
|
+
const none = { type: "object", properties: {}, additionalProperties: false }
|
|
13
|
+
// 2.3.2 normalizes extra JSON Schema properties away. Validate the original RPC input instead.
|
|
14
|
+
const exactInput = (valid) => ({
|
|
15
|
+
"~standard": { version: 1, vendor: "account-quota", validate: value =>
|
|
16
|
+
valid(value) ? { value } : { issues: [{ message: "Invalid account request." }] } },
|
|
17
|
+
})
|
|
18
|
+
// An account reference, plus `manual: true` when the user asked for this read (a manual reader needs it).
|
|
19
|
+
const isRefresh = (value) => {
|
|
20
|
+
const { manual, ...reference } = isRecord(value) ? value : {}
|
|
21
|
+
return isAccountReference(reference) && (manual === undefined || manual === true)
|
|
22
|
+
}
|
|
23
|
+
const isProposal = (value) => isRecord(value) && Object.keys(value).length === 4 &&
|
|
24
|
+
["revision", "threshold", "minimums", "order"].every((key) => Object.hasOwn(value, key)) &&
|
|
25
|
+
Number.isSafeInteger(value.revision) && Number.isInteger(value.threshold) && isRecord(value.minimums) && isRecord(value.order)
|
|
26
|
+
|
|
27
|
+
// Route order (rotation plan R1, R4): a complete list with the revision it was based on; a session mode with nothing
|
|
28
|
+
// else (never a URL, credential, command or model to switch to).
|
|
29
|
+
const isRouting = (value) => isRecord(value) && Object.keys(value).length === 2 && Number.isSafeInteger(value.revision) &&
|
|
30
|
+
Array.isArray(value.targets) && value.targets.length <= 64 && value.targets.every(validTarget)
|
|
31
|
+
const isSessionMode = (value) => isRecord(value) && Object.keys(value).length === 3 && typeof value.sessionID === "string" &&
|
|
32
|
+
value.sessionID !== "" && value.sessionID.length <= 200 && ["off", "preview"].includes(value.mode) && typeof value.paid === "boolean"
|
|
33
|
+
const isRoutingQuery = (value) => isRecord(value) && (Object.keys(value).length === 0 ||
|
|
34
|
+
(Object.keys(value).length === 1 && typeof value.sessionID === "string" && value.sessionID !== "" && value.sessionID.length <= 200))
|
|
35
|
+
|
|
36
|
+
const target = {
|
|
37
|
+
type: "object",
|
|
38
|
+
additionalProperties: false,
|
|
39
|
+
required: ["integrationID", "providerID", "binding"],
|
|
40
|
+
properties: { integrationID: ref, providerID: ref, modelID: ref, variant: ref, binding: { enum: ["current", "exact"] }, connectionID: ref },
|
|
41
|
+
}
|
|
42
|
+
const reason = { type: "string", maxLength: 120 }
|
|
43
|
+
const decision = {
|
|
44
|
+
type: "object",
|
|
45
|
+
additionalProperties: false,
|
|
46
|
+
required: ["at", "kind", "reads", "rows"],
|
|
47
|
+
properties: {
|
|
48
|
+
at: time,
|
|
49
|
+
kind: { enum: ["keep", "suggest", "noTarget", "needRead"] },
|
|
50
|
+
reads: count,
|
|
51
|
+
target: count,
|
|
52
|
+
reason,
|
|
53
|
+
trigger: reason,
|
|
54
|
+
manual: { enum: [true] },
|
|
55
|
+
rows: {
|
|
56
|
+
type: "array",
|
|
57
|
+
maxItems: 64,
|
|
58
|
+
items: {
|
|
59
|
+
type: "object", additionalProperties: false, required: ["status"],
|
|
60
|
+
properties: { status: { enum: ["origin", "eligible", "skipped", "pending", "not-checked"] }, reason },
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const sample = {
|
|
67
|
+
type: "object",
|
|
68
|
+
additionalProperties: false,
|
|
69
|
+
required: ["source", "window", "scope", "observedAt"],
|
|
70
|
+
properties: {
|
|
71
|
+
source: ref,
|
|
72
|
+
window: ref,
|
|
73
|
+
scope: ref,
|
|
74
|
+
observedAt: time,
|
|
75
|
+
resetsAt: time,
|
|
76
|
+
used: { type: "number", minimum: 0, maximum: 100 },
|
|
77
|
+
available: { type: "boolean" },
|
|
78
|
+
balances: {
|
|
79
|
+
type: "array",
|
|
80
|
+
maxItems: 8,
|
|
81
|
+
items: {
|
|
82
|
+
type: "object",
|
|
83
|
+
additionalProperties: false,
|
|
84
|
+
required: ["currency", "total"],
|
|
85
|
+
properties: { currency: { type: "string", minLength: 3, maxLength: 3 }, total: amount },
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const failure = {
|
|
92
|
+
type: "object",
|
|
93
|
+
additionalProperties: false,
|
|
94
|
+
required: ["source", "at", "reason"],
|
|
95
|
+
properties: {
|
|
96
|
+
source: ref,
|
|
97
|
+
at: time,
|
|
98
|
+
reason: { enum: ["auth", "balance", "rate-limit", "timeout", "network", "redirect", "too-large", "invalid", "http", "login", "changed",
|
|
99
|
+
"profile", "missing", "exit", "busy", "model", "unknown"] },
|
|
100
|
+
retryAt: time,
|
|
101
|
+
},
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const connection = {
|
|
105
|
+
type: "object",
|
|
106
|
+
additionalProperties: false,
|
|
107
|
+
required: ["id", "label", "method", "active"],
|
|
108
|
+
properties: {
|
|
109
|
+
id: ref,
|
|
110
|
+
label: { type: "string", maxLength: 200 },
|
|
111
|
+
method: { enum: ["key", "oauth", "external"] },
|
|
112
|
+
active: { type: "boolean" },
|
|
113
|
+
reconnectRequired: { enum: [true] },
|
|
114
|
+
samples: { type: "array", maxItems: 16, items: sample },
|
|
115
|
+
failure,
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const integration = {
|
|
120
|
+
type: "object",
|
|
121
|
+
additionalProperties: false,
|
|
122
|
+
required: ["id", "active", "refreshable", "connections"],
|
|
123
|
+
properties: {
|
|
124
|
+
id: ref,
|
|
125
|
+
active: { enum: ["connection", "environment", "none", "unknown"] },
|
|
126
|
+
refreshable: { type: "boolean" },
|
|
127
|
+
// Read only on an explicit Refresh (r or a), never when the view opens.
|
|
128
|
+
manual: { enum: [true] },
|
|
129
|
+
// Can also receive usage from the user's own Claude Code turns (experimental E02).
|
|
130
|
+
passive: { enum: [true] },
|
|
131
|
+
// Priority order: the stored order reconciled with the native inventory (B04).
|
|
132
|
+
connections: { type: "array", maxItems: 64, items: connection },
|
|
133
|
+
},
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const preferences = {
|
|
137
|
+
type: "object",
|
|
138
|
+
additionalProperties: false,
|
|
139
|
+
required: ["state"],
|
|
140
|
+
properties: {
|
|
141
|
+
state: { enum: ["available", "unsupported", "unavailable"] },
|
|
142
|
+
revision: count,
|
|
143
|
+
mode: { enum: ["recommend"] },
|
|
144
|
+
threshold: { type: "integer", minimum: 90, maximum: 100 },
|
|
145
|
+
// Explicit keys: 2.3.2 normalizes objects to their declared properties. S09 lists only CNY and USD.
|
|
146
|
+
minimums: { type: "object", additionalProperties: false, properties: { USD: amount, CNY: amount } },
|
|
147
|
+
},
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export const contract = Rpc.define({
|
|
151
|
+
id: "account-quota",
|
|
152
|
+
methods: {
|
|
153
|
+
snapshot: {
|
|
154
|
+
input: exactInput(value => isRecord(value) && Object.keys(value).length === 0),
|
|
155
|
+
output: {
|
|
156
|
+
type: "object",
|
|
157
|
+
additionalProperties: false,
|
|
158
|
+
required: ["schema", "revision", "scope", "inventory", "preferences", "integrations"],
|
|
159
|
+
properties: {
|
|
160
|
+
schema: { enum: [2] },
|
|
161
|
+
revision: count,
|
|
162
|
+
// Recorded user decision: one trusted user, one personal server, shared inventory.
|
|
163
|
+
scope: { enum: ["personal-server"] },
|
|
164
|
+
// Seconds ChatGPT and Claude Code usage stays fresh for the location answering (plugin option
|
|
165
|
+
// `usageFreshnessSeconds`). Declared so the host keeps it; a TUI without it uses the default.
|
|
166
|
+
usageFreshnessSeconds: { type: "integer", minimum: 1, maximum: MAX_USAGE_FRESHNESS },
|
|
167
|
+
inventory: { enum: ["available", "unavailable"] },
|
|
168
|
+
preferences,
|
|
169
|
+
integrations: { type: "array", maxItems: 64, items: integration },
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
refresh: {
|
|
174
|
+
// Only a reference to pick from the server inventory; never a scope, URL or credential.
|
|
175
|
+
input: exactInput(isRefresh),
|
|
176
|
+
output: {
|
|
177
|
+
type: "object",
|
|
178
|
+
additionalProperties: false,
|
|
179
|
+
required: ["revision", "status"],
|
|
180
|
+
properties: { revision: count, status: { enum: ["read", "failed", "unsupported", "deferred"] } },
|
|
181
|
+
},
|
|
182
|
+
errors: { not_found: none },
|
|
183
|
+
},
|
|
184
|
+
savePreferences: {
|
|
185
|
+
// A complete proposal with the revision it was based on. The server checks every reference.
|
|
186
|
+
input: exactInput(isProposal),
|
|
187
|
+
output: { type: "object", additionalProperties: false, required: ["revision"], properties: { revision: count } },
|
|
188
|
+
errors: { conflict: none, invalid: none, unavailable: none },
|
|
189
|
+
},
|
|
190
|
+
// Read only: the stored route order and, for one session, its mode and last decision. Opening it reads nothing.
|
|
191
|
+
routingView: {
|
|
192
|
+
input: exactInput(isRoutingQuery),
|
|
193
|
+
output: {
|
|
194
|
+
type: "object",
|
|
195
|
+
additionalProperties: false,
|
|
196
|
+
required: ["state"],
|
|
197
|
+
properties: {
|
|
198
|
+
state: { enum: ["available", "unsupported", "unavailable"] },
|
|
199
|
+
revision: count,
|
|
200
|
+
targets: { type: "array", maxItems: 64, items: target },
|
|
201
|
+
session: {
|
|
202
|
+
type: "object",
|
|
203
|
+
additionalProperties: false,
|
|
204
|
+
required: ["mode", "paid"],
|
|
205
|
+
properties: { mode: { enum: ["off", "preview"] }, paid: { type: "boolean" }, decision },
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
// A complete route order with the revision it was based on (`routing.revision`, not the preferences' one).
|
|
211
|
+
saveRouting: {
|
|
212
|
+
input: exactInput(isRouting),
|
|
213
|
+
output: { type: "object", additionalProperties: false, required: ["revision"], properties: { revision: count } },
|
|
214
|
+
errors: { conflict: none, invalid: none, unavailable: none },
|
|
215
|
+
},
|
|
216
|
+
// In memory, per root session: `preview` evaluates its turn ends; there is no automatic mode in this build.
|
|
217
|
+
setSessionRouting: {
|
|
218
|
+
input: exactInput(isSessionMode),
|
|
219
|
+
output: { type: "object", additionalProperties: false, required: ["mode", "paid"], properties: { mode: { enum: ["off", "preview"] }, paid: { type: "boolean" } } },
|
|
220
|
+
errors: { invalid: none, not_found: none },
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
events: {
|
|
224
|
+
changed: {
|
|
225
|
+
schema: {
|
|
226
|
+
type: "object",
|
|
227
|
+
additionalProperties: false,
|
|
228
|
+
required: ["revision"],
|
|
229
|
+
properties: { revision: count },
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
})
|