dsh-model-allowance 0.0.0-stage → 1.0.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 +147 -2
- package/README.zh.md +128 -0
- package/client.js +1897 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +7 -0
- package/index.js +457 -0
- package/lib/balance.js +413 -0
- package/lib/credentials.js +174 -0
- package/lib/debug.js +70 -0
- package/lib/providers/deepseek.js +408 -0
- package/lib/providers/kimi.js +474 -0
- package/lib/providers/minimax.js +383 -0
- package/lib/providers/opencode.js +209 -0
- package/lib/providers/schedule.js +153 -0
- package/lib/providers/shared.js +324 -0
- package/lib/providers/status.js +133 -0
- package/lib/providers/zhipu.js +185 -0
- package/lib/providers.js +112 -0
- package/lib/remote.js +214 -0
- package/lib/status.js +196 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +82 -4
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Time-of-day pricing schedules.
|
|
3
|
+
*
|
|
4
|
+
* DeepSeek charges half price outside its peak windows, and its docs define
|
|
5
|
+
* those windows by wall clock in a named zone: Monday to Friday, 09:00–12:00
|
|
6
|
+
* and 14:00–18:00 Beijing time, with Chinese statutory holidays counting as
|
|
7
|
+
* off-peak all day. That is three facts a vendor file should be able to state
|
|
8
|
+
* without writing code — the browser turns them into a phase and a countdown.
|
|
9
|
+
*
|
|
10
|
+
* A schedule is data, not a clock: the Host publishes it, and the browser
|
|
11
|
+
* evaluates it against its own ticking clock, so the countdown is smooth with
|
|
12
|
+
* no extra round trips.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** HH:MM in 24-hour wall time. */
|
|
16
|
+
const TIME_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)$/
|
|
17
|
+
|
|
18
|
+
/** ISO calendar date, in the schedule's own zone. */
|
|
19
|
+
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Parse one `HH:MM` string to minutes since midnight.
|
|
23
|
+
* @param {string} value Wall-clock time.
|
|
24
|
+
* @returns {number} Minutes since midnight.
|
|
25
|
+
*/
|
|
26
|
+
export function timeToMinutes(value) {
|
|
27
|
+
const match = TIME_PATTERN.exec(value)
|
|
28
|
+
return Number(match[1]) * 60 + Number(match[2])
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @typedef {object} ScheduleWindow
|
|
33
|
+
* @property {string} from Wall-clock start, `HH:MM`.
|
|
34
|
+
* @property {string} to Wall-clock end, `HH:MM`; must be later than `from`.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @typedef {object} Schedule
|
|
39
|
+
* @property {string} timezone IANA zone the wall-clock times refer to.
|
|
40
|
+
* @property {{zh: string, en: string}} timezoneLabel The zone's name for the card.
|
|
41
|
+
* @property {readonly number[]} days Weekdays the peak windows apply to, `0` = Sunday.
|
|
42
|
+
* @property {readonly ScheduleWindow[]} windows Peak windows within those days.
|
|
43
|
+
* @property {readonly string[]} holidays Dates in that zone that are off-peak all day.
|
|
44
|
+
* @property {{zh: string, en: string}} [note] One line about what the phase means.
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The declaration a vendor file passes to {@link defineSchedule}.
|
|
49
|
+
* @typedef {object} ScheduleSpec
|
|
50
|
+
* @property {string} timezone IANA zone the wall-clock times refer to.
|
|
51
|
+
* @property {{zh: string, en: string}} timezoneLabel The zone's name for the card.
|
|
52
|
+
* @property {number[]} days Weekdays the peak windows apply to, `0` = Sunday.
|
|
53
|
+
* @property {ScheduleWindow[]} windows Peak windows within those days.
|
|
54
|
+
* @property {string[]} [holidays] Dates in that zone that are off-peak all day.
|
|
55
|
+
* @property {{zh: string, en: string}} [note] One line about what the phase means.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The calendar years a schedule's holiday list covers.
|
|
60
|
+
*
|
|
61
|
+
* A vendor that publishes a statutory holiday list changes it every year; a
|
|
62
|
+
* schedule whose list has expired silently turns every holiday into a peak
|
|
63
|
+
* day. Exposing the coverage lets startup diagnostics and tests notice that
|
|
64
|
+
* before a user reads a wrong price phase.
|
|
65
|
+
*
|
|
66
|
+
* @param {Schedule} schedule The schedule.
|
|
67
|
+
* @returns {{from: number, to: number} | undefined} Covered years, when the
|
|
68
|
+
* schedule declares holidays.
|
|
69
|
+
*/
|
|
70
|
+
export function holidayCoverage(schedule) {
|
|
71
|
+
if (!Array.isArray(schedule.holidays) || schedule.holidays.length === 0) return undefined
|
|
72
|
+
const years = schedule.holidays.map((date) => Number(date.slice(0, 4))).filter(Number.isFinite)
|
|
73
|
+
if (years.length === 0) return undefined
|
|
74
|
+
return { from: Math.min(...years), to: Math.max(...years) }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Declare one vendor's time-of-day pricing schedule, refusing an unusable one.
|
|
79
|
+
*
|
|
80
|
+
* Only same-day windows are modeled: a peak period that crosses midnight can
|
|
81
|
+
* be written as two windows, which keeps the phase test a plain comparison.
|
|
82
|
+
*
|
|
83
|
+
* @param {ScheduleSpec} spec The declaration.
|
|
84
|
+
* @returns {Schedule} The frozen schedule.
|
|
85
|
+
*/
|
|
86
|
+
export function defineSchedule(spec) {
|
|
87
|
+
const where = 'schedule'
|
|
88
|
+
if (typeof spec?.timezone !== 'string' || spec.timezone === '') {
|
|
89
|
+
throw new Error(`${where} needs an IANA time zone`)
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
// Throws on a zone this runtime cannot resolve.
|
|
93
|
+
new Intl.DateTimeFormat('en-US', { timeZone: spec.timezone })
|
|
94
|
+
} catch {
|
|
95
|
+
throw new Error(`${where} names an unknown time zone "${spec.timezone}"`)
|
|
96
|
+
}
|
|
97
|
+
for (const key of ['zh', 'en']) {
|
|
98
|
+
const label = spec?.timezoneLabel?.[key]
|
|
99
|
+
if (typeof label !== 'string' || label === '') {
|
|
100
|
+
throw new Error(`${where} needs a time-zone label for ${key}`)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const days = spec.days
|
|
104
|
+
if (!Array.isArray(days) || days.length === 0) throw new Error(`${where} declares no weekdays`)
|
|
105
|
+
for (const day of days) {
|
|
106
|
+
if (!Number.isInteger(day) || day < 0 || day > 6) {
|
|
107
|
+
throw new Error(`${where} has an invalid weekday ${String(day)}`)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (new Set(days).size !== days.length) throw new Error(`${where} repeats a weekday`)
|
|
111
|
+
|
|
112
|
+
const windows = spec.windows
|
|
113
|
+
if (!Array.isArray(windows) || windows.length === 0)
|
|
114
|
+
throw new Error(`${where} declares no window`)
|
|
115
|
+
for (const window of windows) {
|
|
116
|
+
if (!TIME_PATTERN.test(String(window?.from)) || !TIME_PATTERN.test(String(window?.to))) {
|
|
117
|
+
throw new Error(`${where} has a window that is not HH:MM`)
|
|
118
|
+
}
|
|
119
|
+
if (timeToMinutes(window.from) >= timeToMinutes(window.to)) {
|
|
120
|
+
throw new Error(`${where} has a window that does not end after it starts`)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const holidays = spec.holidays ?? []
|
|
125
|
+
if (!Array.isArray(holidays)) throw new Error(`${where} holidays must be a list`)
|
|
126
|
+
for (const holiday of holidays) {
|
|
127
|
+
if (!DATE_PATTERN.test(String(holiday))) {
|
|
128
|
+
throw new Error(`${where} has an invalid holiday date ${JSON.stringify(holiday)}`)
|
|
129
|
+
}
|
|
130
|
+
const parsed = Date.parse(`${holiday}T00:00:00Z`)
|
|
131
|
+
if (Number.isNaN(parsed)) throw new Error(`${where} has an invalid holiday date ${holiday}`)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const note = spec.note
|
|
135
|
+
if (note !== undefined) {
|
|
136
|
+
for (const key of ['zh', 'en']) {
|
|
137
|
+
if (typeof note?.[key] !== 'string' || note[key] === '') {
|
|
138
|
+
throw new Error(`${where} needs a note for ${key}`)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return Object.freeze({
|
|
144
|
+
timezone: spec.timezone,
|
|
145
|
+
timezoneLabel: Object.freeze({ zh: spec.timezoneLabel.zh, en: spec.timezoneLabel.en }),
|
|
146
|
+
days: Object.freeze([...days]),
|
|
147
|
+
windows: Object.freeze(
|
|
148
|
+
windows.map((window) => Object.freeze({ from: window.from, to: window.to })),
|
|
149
|
+
),
|
|
150
|
+
holidays: Object.freeze([...holidays]),
|
|
151
|
+
...(note === undefined ? {} : { note: Object.freeze({ zh: note.zh, en: note.en }) }),
|
|
152
|
+
})
|
|
153
|
+
}
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared machinery for provider balance adapters.
|
|
3
|
+
*
|
|
4
|
+
* An adapter declares the routes it serves, how its query is authorized, and
|
|
5
|
+
* how the provider's response is projected onto the shared `BalanceView`
|
|
6
|
+
* shape. The projection is always bespoke — every provider words its response
|
|
7
|
+
* differently — so this module owns only what every adapter repeats: the
|
|
8
|
+
* quantity dimensions, the tolerant readers for numbers and instants, the
|
|
9
|
+
* window-length naming, the HTTP request that signs and bounds one query, and
|
|
10
|
+
* the validation that keeps a newly added vendor honest about its metadata.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** A provider reports a monetary balance. */
|
|
14
|
+
export const KIND_AMOUNT = 'amount'
|
|
15
|
+
|
|
16
|
+
/** A provider reports a remaining allowance (quota, time, call count). */
|
|
17
|
+
export const KIND_QUOTA = 'quota'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* One metering window a subscription plan enforces.
|
|
21
|
+
*
|
|
22
|
+
* A coding plan usually meters the same account over several periods — a short
|
|
23
|
+
* rolling window and a long one — and each period has its own allowance and
|
|
24
|
+
* reset. A single "remaining" number cannot express that, so a reading carries
|
|
25
|
+
* one of these per window.
|
|
26
|
+
*
|
|
27
|
+
* @typedef {object} BalanceWindow
|
|
28
|
+
* @property {string} id Stable identity: `session`, `weekly`, or a positional fallback.
|
|
29
|
+
* @property {'hour'|'day'|'week'|'month'|'unknown'} unit Length unit of the window.
|
|
30
|
+
* @property {{zh?: string, en?: string}} [label] Vendor-specific display name, when the plan has several windows of one unit.
|
|
31
|
+
* @property {number} [count] How many `unit`s long the window is, e.g. 5 hours.
|
|
32
|
+
* @property {number} [used] Allowance already spent in this window.
|
|
33
|
+
* @property {number} [total] Allowance included in this window.
|
|
34
|
+
* @property {number} [remainingPercent] Share of the allowance still available.
|
|
35
|
+
* @property {number} [resetAt] Epoch milliseconds of the next reset.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
/** Signing styles a provider endpoint accepts. */
|
|
39
|
+
const AUTH_STYLES = new Set(['bearer', 'raw'])
|
|
40
|
+
|
|
41
|
+
/** The credential-reference grammar the harness credentials service accepts. */
|
|
42
|
+
const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Read a JSON body as a plain object.
|
|
46
|
+
* @param {unknown} payload Decoded response body.
|
|
47
|
+
* @returns {Record<string, unknown>} The body as a plain object.
|
|
48
|
+
*/
|
|
49
|
+
export function asObject(payload) {
|
|
50
|
+
return payload && typeof payload === 'object'
|
|
51
|
+
? /** @type {Record<string, unknown>} */ (payload)
|
|
52
|
+
: {}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Parse a numeric string the providers use for money amounts.
|
|
57
|
+
* @param {unknown} value Raw amount.
|
|
58
|
+
* @returns {number | undefined} The amount, or undefined when unparsable.
|
|
59
|
+
*/
|
|
60
|
+
export function parseAmount(value) {
|
|
61
|
+
const parsed = typeof value === 'number' ? value : Number.parseFloat(String(value ?? ''))
|
|
62
|
+
return Number.isFinite(parsed) ? parsed : undefined
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Parse an instant the providers report, as epoch milliseconds or ISO text.
|
|
67
|
+
*
|
|
68
|
+
* Reset times arrive in three shapes across the vendors: epoch milliseconds
|
|
69
|
+
* (MiniMax, Zhipu), RFC 3339 text (Kimi, OpenCode), and numeric strings. One
|
|
70
|
+
* reader keeps every adapter from inventing its own numeric-string heuristic.
|
|
71
|
+
*
|
|
72
|
+
* @param {unknown} value Raw instant.
|
|
73
|
+
* @returns {number | undefined} Epoch milliseconds, or undefined when unparsable.
|
|
74
|
+
*/
|
|
75
|
+
export function parseInstant(value) {
|
|
76
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
|
|
77
|
+
if (typeof value !== 'string') return undefined
|
|
78
|
+
const text = value.trim()
|
|
79
|
+
if (text === '') return undefined
|
|
80
|
+
if (/^\d+(?:\.\d+)?$/.test(text)) {
|
|
81
|
+
const numeric = Number(text)
|
|
82
|
+
return Number.isFinite(numeric) ? numeric : undefined
|
|
83
|
+
}
|
|
84
|
+
const parsed = Date.parse(text)
|
|
85
|
+
return Number.isFinite(parsed) ? parsed : undefined
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Name a window length from its duration.
|
|
90
|
+
*
|
|
91
|
+
* Reporting the window the provider actually enforces matters: MiniMax meters
|
|
92
|
+
* a 7-day window, not a calendar month, and saying "month" would be wrong.
|
|
93
|
+
*
|
|
94
|
+
* @param {number | undefined} ms Window length in milliseconds.
|
|
95
|
+
* @returns {{unit: 'hour'|'day'|'month'|'unknown', count?: number}} The unit and count.
|
|
96
|
+
*/
|
|
97
|
+
export function windowLength(ms) {
|
|
98
|
+
if (!Number.isFinite(ms) || ms <= 0) return { unit: 'unknown' }
|
|
99
|
+
const hours = ms / 3_600_000
|
|
100
|
+
if (hours < 24) return { unit: 'hour', count: Math.round(hours) }
|
|
101
|
+
const days = ms / 86_400_000
|
|
102
|
+
if (days < 28) return { unit: 'day', count: Math.round(days) }
|
|
103
|
+
return { unit: 'month', count: Math.round(days / 30) }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The most-constrained window of a reading.
|
|
108
|
+
*
|
|
109
|
+
* The badge speaks for the window closest to its limit; the panel breaks the
|
|
110
|
+
* rest down. A window that reports no percentage cannot constrain anything,
|
|
111
|
+
* so it sorts last.
|
|
112
|
+
*
|
|
113
|
+
* @param {Array<BalanceWindow>} windows Reported windows.
|
|
114
|
+
* @returns {BalanceWindow | undefined} The binding window, if any.
|
|
115
|
+
*/
|
|
116
|
+
export function bindingWindow(windows) {
|
|
117
|
+
return windows.reduce((current, candidate) => {
|
|
118
|
+
const a = current?.remainingPercent ?? Number.POSITIVE_INFINITY
|
|
119
|
+
const b = candidate.remainingPercent ?? Number.POSITIVE_INFINITY
|
|
120
|
+
return b < a ? candidate : current
|
|
121
|
+
}, undefined)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* @typedef {object} AdapterFixture
|
|
126
|
+
* @property {string} name Fixture identity, used in failure messages.
|
|
127
|
+
* @property {string} [route] Route to read; defaults to the adapter's first.
|
|
128
|
+
* @property {object} [response] Recorded JSON body, for an endpoint adapter.
|
|
129
|
+
* @property {number} [httpStatus] Recorded HTTP status; defaults to 200.
|
|
130
|
+
* @property {Record<string, unknown>} [services] Host services the read uses,
|
|
131
|
+
* for a `readWithEnv` adapter.
|
|
132
|
+
* @property {string} [apiKey] Credential value handed to the read.
|
|
133
|
+
* @property {string} [model] Provider-owned model id handed to the read.
|
|
134
|
+
* @property {Record<string, unknown>} expect Fields the reading must carry.
|
|
135
|
+
* @property {string[]} [absent] Dotted paths the reading must not carry.
|
|
136
|
+
*/
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Declare one provider adapter and refuse a declaration that cannot work.
|
|
140
|
+
*
|
|
141
|
+
* Two forms exist. An endpoint adapter names its URL and signing style, so the
|
|
142
|
+
* balance service is the only code that performs the request: timeout, status
|
|
143
|
+
* mapping, and JSON decoding behave the same for every provider, and the
|
|
144
|
+
* vendor file only projects the body. A `readWithEnv` adapter performs its own
|
|
145
|
+
* read, which is what a Host-service-backed route needs.
|
|
146
|
+
*
|
|
147
|
+
* @param {object} spec The declaration.
|
|
148
|
+
* @param {string} spec.id Adapter identity.
|
|
149
|
+
* @param {readonly string[]} spec.routes Provider routes this adapter serves.
|
|
150
|
+
* @param {'amount'|'quota'} spec.kind Quantity dimension of the reading.
|
|
151
|
+
* @param {boolean} [spec.modelScoped] Whether the reading is per model.
|
|
152
|
+
* @param {string} spec.consoleUrl Provider console for a manual check.
|
|
153
|
+
* @param {{name: {zh: string, en: string}, mark: {icon?: string, color: string}}} spec.display
|
|
154
|
+
* Display metadata the browser needs to name and draw the route.
|
|
155
|
+
* @param {string} [spec.service] Host service this adapter reads through.
|
|
156
|
+
* @param {string} [spec.endpoint] HTTPS endpoint, for an endpoint adapter.
|
|
157
|
+
* @param {'bearer'|'raw'} [spec.auth] How the credential signs the request.
|
|
158
|
+
* @param {readonly string[]} [spec.credentialRefs] Credential references to try
|
|
159
|
+
* when the harness cannot name one for the route.
|
|
160
|
+
* @param {{endpoint: string, url: string, parse: (env: {text?: string, json?: unknown}) => {state: string, summary?: string}}} [spec.status]
|
|
161
|
+
* Live platform status source, when the vendor publishes one.
|
|
162
|
+
* @param {import('./schedule.js').Schedule} [spec.schedule] Time-of-day pricing schedule.
|
|
163
|
+
* @param {(env: {route: string, apiKey: string, body: Record<string, unknown>, model?: string}) => import('../providers.js').BalanceView} [spec.read]
|
|
164
|
+
* Projection for an endpoint adapter.
|
|
165
|
+
* @param {(env: import('../providers.js').AdapterEnv) => Promise<import('../providers.js').BalanceView>} [spec.readWithEnv]
|
|
166
|
+
* Full read for an adapter that needs more than an API key, such as a Host service.
|
|
167
|
+
* @param {readonly AdapterFixture[]} [spec.fixtures] Recorded responses proving
|
|
168
|
+
* the projection still parses.
|
|
169
|
+
* @returns {import('../providers.js').ProviderAdapter} The normalized adapter.
|
|
170
|
+
*/
|
|
171
|
+
export function defineAdapter(spec) {
|
|
172
|
+
const where = `adapter "${String(spec?.id)}"`
|
|
173
|
+
if (typeof spec?.id !== 'string' || spec.id === '') {
|
|
174
|
+
throw new Error('a provider adapter needs a non-empty id')
|
|
175
|
+
}
|
|
176
|
+
if (!Array.isArray(spec.routes) || spec.routes.length === 0) {
|
|
177
|
+
throw new Error(`${where} declares no routes`)
|
|
178
|
+
}
|
|
179
|
+
for (const route of spec.routes) {
|
|
180
|
+
if (typeof route !== 'string' || route === '') throw new Error(`${where} has an empty route`)
|
|
181
|
+
}
|
|
182
|
+
if (spec.kind !== KIND_AMOUNT && spec.kind !== KIND_QUOTA) {
|
|
183
|
+
throw new Error(`${where} must declare kind "${KIND_AMOUNT}" or "${KIND_QUOTA}"`)
|
|
184
|
+
}
|
|
185
|
+
if (typeof spec.consoleUrl !== 'string' || !spec.consoleUrl.startsWith('https://')) {
|
|
186
|
+
throw new Error(`${where} needs an https console link`)
|
|
187
|
+
}
|
|
188
|
+
if (spec.status !== undefined) {
|
|
189
|
+
if (typeof spec.status !== 'object' || spec.status === null) {
|
|
190
|
+
throw new Error(`${where} declares an unreadable status source`)
|
|
191
|
+
}
|
|
192
|
+
if (typeof spec.status.endpoint !== 'string' || !spec.status.endpoint.startsWith('https://')) {
|
|
193
|
+
throw new Error(`${where} needs an https status endpoint`)
|
|
194
|
+
}
|
|
195
|
+
if (typeof spec.status.url !== 'string' || !spec.status.url.startsWith('https://')) {
|
|
196
|
+
throw new Error(`${where} needs an https status page link`)
|
|
197
|
+
}
|
|
198
|
+
if (typeof spec.status.parse !== 'function') {
|
|
199
|
+
throw new Error(`${where} needs a status parser`)
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const name = spec.display?.name
|
|
203
|
+
if (
|
|
204
|
+
typeof name?.zh !== 'string' ||
|
|
205
|
+
name.zh === '' ||
|
|
206
|
+
typeof name?.en !== 'string' ||
|
|
207
|
+
name.en === ''
|
|
208
|
+
) {
|
|
209
|
+
throw new Error(`${where} needs a display name for both zh and en`)
|
|
210
|
+
}
|
|
211
|
+
const color = spec.display?.mark?.color
|
|
212
|
+
if (typeof color !== 'string' || color === '') throw new Error(`${where} needs a brand colour`)
|
|
213
|
+
|
|
214
|
+
const hasEndpoint = spec.endpoint !== undefined
|
|
215
|
+
const hasEnvRead = typeof spec.readWithEnv === 'function'
|
|
216
|
+
if (hasEndpoint === hasEnvRead) {
|
|
217
|
+
throw new Error(`${where} must declare exactly one of endpoint and readWithEnv`)
|
|
218
|
+
}
|
|
219
|
+
if (hasEndpoint) {
|
|
220
|
+
if (typeof spec.endpoint !== 'string' || !spec.endpoint.startsWith('https://')) {
|
|
221
|
+
throw new Error(`${where} needs an https endpoint`)
|
|
222
|
+
}
|
|
223
|
+
if (!AUTH_STYLES.has(spec.auth)) {
|
|
224
|
+
throw new Error(`${where} needs an auth style (${[...AUTH_STYLES].join(' or ')})`)
|
|
225
|
+
}
|
|
226
|
+
if (typeof spec.read !== 'function')
|
|
227
|
+
throw new Error(`${where} needs a read() to project the response`)
|
|
228
|
+
}
|
|
229
|
+
if (spec.service !== undefined && (typeof spec.service !== 'string' || spec.service === '')) {
|
|
230
|
+
throw new Error(`${where} names an empty service`)
|
|
231
|
+
}
|
|
232
|
+
for (const ref of spec.credentialRefs ?? []) {
|
|
233
|
+
if (typeof ref !== 'string' || !REF_PATTERN.test(ref)) {
|
|
234
|
+
throw new Error(`${where} names an invalid credential reference "${String(ref)}"`)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (
|
|
238
|
+
spec.schedule !== undefined &&
|
|
239
|
+
(typeof spec.schedule !== 'object' || spec.schedule === null)
|
|
240
|
+
) {
|
|
241
|
+
throw new Error(`${where} declares an unreadable schedule`)
|
|
242
|
+
}
|
|
243
|
+
const fixtures = spec.fixtures ?? []
|
|
244
|
+
if (!Array.isArray(fixtures) || fixtures.length === 0) {
|
|
245
|
+
throw new Error(`${where} ships no fixture, so nothing would prove it still parses`)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return Object.freeze({
|
|
249
|
+
id: spec.id,
|
|
250
|
+
routes: Object.freeze([...spec.routes]),
|
|
251
|
+
kind: spec.kind,
|
|
252
|
+
...(spec.modelScoped === true ? { modelScoped: true } : {}),
|
|
253
|
+
consoleUrl: spec.consoleUrl,
|
|
254
|
+
service: spec.service,
|
|
255
|
+
http: hasEndpoint ? Object.freeze({ endpoint: spec.endpoint, auth: spec.auth }) : undefined,
|
|
256
|
+
credentialRefs: Object.freeze([...(spec.credentialRefs ?? [])]),
|
|
257
|
+
display: Object.freeze({
|
|
258
|
+
name: Object.freeze({ zh: name.zh, en: name.en }),
|
|
259
|
+
mark: Object.freeze({
|
|
260
|
+
...(typeof spec.display.mark.icon === 'string' && spec.display.mark.icon !== ''
|
|
261
|
+
? { icon: spec.display.mark.icon }
|
|
262
|
+
: {}),
|
|
263
|
+
color,
|
|
264
|
+
}),
|
|
265
|
+
}),
|
|
266
|
+
status:
|
|
267
|
+
spec.status === undefined
|
|
268
|
+
? undefined
|
|
269
|
+
: Object.freeze({
|
|
270
|
+
endpoint: spec.status.endpoint,
|
|
271
|
+
url: spec.status.url,
|
|
272
|
+
parse: spec.status.parse,
|
|
273
|
+
}),
|
|
274
|
+
schedule: spec.schedule,
|
|
275
|
+
read: spec.read,
|
|
276
|
+
readWithEnv: spec.readWithEnv,
|
|
277
|
+
fixtures: Object.freeze(fixtures.map((fixture) => Object.freeze({ ...fixture }))),
|
|
278
|
+
})
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Perform one endpoint adapter query and project its body.
|
|
283
|
+
*
|
|
284
|
+
* The service owns the transport so every provider shares one timeout, one
|
|
285
|
+
* status mapping, and one decode step; the adapter owns only the projection.
|
|
286
|
+
* Transport failures throw and are translated by the caller, exactly like a
|
|
287
|
+
* failed `response.json()`.
|
|
288
|
+
*
|
|
289
|
+
* @param {import('../providers.js').ProviderAdapter} adapter Declared adapter.
|
|
290
|
+
* @param {{route: string, apiKey: string, signal: AbortSignal, model?: string}} env Query context.
|
|
291
|
+
* @returns {Promise<import('../providers.js').BalanceView>} The reading.
|
|
292
|
+
*/
|
|
293
|
+
export async function readEndpointAdapter(adapter, { route, apiKey, signal, model }) {
|
|
294
|
+
if (adapter.http === undefined) throw new Error('adapter has no endpoint')
|
|
295
|
+
const headers =
|
|
296
|
+
adapter.http.auth === 'bearer'
|
|
297
|
+
? { authorization: `Bearer ${apiKey}` }
|
|
298
|
+
: { authorization: String(apiKey) }
|
|
299
|
+
const response = await fetch(adapter.http.endpoint, { headers, signal })
|
|
300
|
+
if (!response.ok) {
|
|
301
|
+
return {
|
|
302
|
+
provider: route,
|
|
303
|
+
status: 'failed',
|
|
304
|
+
kind: adapter.kind,
|
|
305
|
+
error: `HTTP ${response.status}`,
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const body = asObject(await response.json())
|
|
309
|
+
return await adapter.read({ route, apiKey, body, model })
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The wire metadata for one adapter: what the browser needs to name and draw
|
|
314
|
+
* the route without knowing any vendor.
|
|
315
|
+
* @param {import('../providers.js').ProviderAdapter} adapter Declared adapter.
|
|
316
|
+
* @returns {{name: {zh: string, en: string}, color: string, iconHint?: string}} The metadata.
|
|
317
|
+
*/
|
|
318
|
+
export function displayOf(adapter) {
|
|
319
|
+
return {
|
|
320
|
+
name: { ...adapter.display.name },
|
|
321
|
+
color: adapter.display.mark.color,
|
|
322
|
+
...(adapter.display.mark.icon === undefined ? {} : { iconHint: adapter.display.mark.icon }),
|
|
323
|
+
}
|
|
324
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Status-page parsing shared by the providers that publish one.
|
|
3
|
+
*
|
|
4
|
+
* Every vendor words its status differently — Statuspage's boolean-ish
|
|
5
|
+
* indicators, OpenCode's own state machine, FlashCat's impact vocabulary — so
|
|
6
|
+
* the mapping onto the plugin's shared vocabulary lives here, and each adapter
|
|
7
|
+
* names the source it reads.
|
|
8
|
+
*
|
|
9
|
+
* The plugin's own states are a small fixed set so the browser can label them
|
|
10
|
+
* without knowing any vendor:
|
|
11
|
+
*
|
|
12
|
+
* `operational` everything works
|
|
13
|
+
* `degraded` slower or partly impaired, still serving
|
|
14
|
+
* `partial-outage` some services are down
|
|
15
|
+
* `major-outage` critical services are down
|
|
16
|
+
* `maintenance` a planned maintenance window is in progress
|
|
17
|
+
* `unknown` no reading, no source, or an unparsable one
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { asObject } from './shared.js'
|
|
21
|
+
|
|
22
|
+
/** A provider reports full availability. */
|
|
23
|
+
export const STATUS_OPERATIONAL = 'operational'
|
|
24
|
+
|
|
25
|
+
/** A provider reports slowed or partly impaired service. */
|
|
26
|
+
export const STATUS_DEGRADED = 'degraded'
|
|
27
|
+
|
|
28
|
+
/** A provider reports some services down. */
|
|
29
|
+
export const STATUS_PARTIAL_OUTAGE = 'partial-outage'
|
|
30
|
+
|
|
31
|
+
/** A provider reports critical services down. */
|
|
32
|
+
export const STATUS_MAJOR_OUTAGE = 'major-outage'
|
|
33
|
+
|
|
34
|
+
/** A provider reports a maintenance window in progress. */
|
|
35
|
+
export const STATUS_MAINTENANCE = 'maintenance'
|
|
36
|
+
|
|
37
|
+
/** No reading, no source, or an unparsable one. */
|
|
38
|
+
export const STATUS_UNKNOWN = 'unknown'
|
|
39
|
+
|
|
40
|
+
/** Severity order, worst first; used to pick the state a list implies. */
|
|
41
|
+
const SEVERITY = Object.freeze({
|
|
42
|
+
[STATUS_MAJOR_OUTAGE]: 4,
|
|
43
|
+
[STATUS_PARTIAL_OUTAGE]: 3,
|
|
44
|
+
[STATUS_DEGRADED]: 2,
|
|
45
|
+
[STATUS_MAINTENANCE]: 1,
|
|
46
|
+
[STATUS_OPERATIONAL]: 0,
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The vocabulary the sources use, collapsed onto the shared states.
|
|
51
|
+
*
|
|
52
|
+
* Statuspage speaks `none`/`minor`/`major`/`critical`/`maintenance`; FlashCat
|
|
53
|
+
* pages speak `full_outage`/`partial_outage`/`degraded`/`maintenance`;
|
|
54
|
+
* OpenCode speaks `operational`/`degraded`/`down`. Incident phases such as
|
|
55
|
+
* `investigating` or `monitoring` are deliberately absent: they describe the
|
|
56
|
+
* response to an incident, not what it is doing to the service, and the impact
|
|
57
|
+
* entries beside them carry the actual state.
|
|
58
|
+
*/
|
|
59
|
+
const STATE_WORDS = Object.freeze({
|
|
60
|
+
operational: STATUS_OPERATIONAL,
|
|
61
|
+
none: STATUS_OPERATIONAL,
|
|
62
|
+
ok: STATUS_OPERATIONAL,
|
|
63
|
+
up: STATUS_OPERATIONAL,
|
|
64
|
+
degraded: STATUS_DEGRADED,
|
|
65
|
+
'degraded-performance': STATUS_DEGRADED,
|
|
66
|
+
minor: STATUS_DEGRADED,
|
|
67
|
+
'partial-outage': STATUS_PARTIAL_OUTAGE,
|
|
68
|
+
partial: STATUS_PARTIAL_OUTAGE,
|
|
69
|
+
major: STATUS_PARTIAL_OUTAGE,
|
|
70
|
+
'major-outage': STATUS_MAJOR_OUTAGE,
|
|
71
|
+
'full-outage': STATUS_MAJOR_OUTAGE,
|
|
72
|
+
critical: STATUS_MAJOR_OUTAGE,
|
|
73
|
+
outage: STATUS_MAJOR_OUTAGE,
|
|
74
|
+
down: STATUS_MAJOR_OUTAGE,
|
|
75
|
+
maintenance: STATUS_MAINTENANCE,
|
|
76
|
+
'under-maintenance': STATUS_MAINTENANCE,
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Normalize one state word onto the shared vocabulary.
|
|
81
|
+
* @param {unknown} raw State word from a source.
|
|
82
|
+
* @returns {string | undefined} The shared state, or undefined when the word
|
|
83
|
+
* is not a state this plugin knows.
|
|
84
|
+
*/
|
|
85
|
+
export function normalizeState(raw) {
|
|
86
|
+
if (typeof raw !== 'string') return undefined
|
|
87
|
+
const key = raw
|
|
88
|
+
.trim()
|
|
89
|
+
.toLowerCase()
|
|
90
|
+
.replace(/[\s_]+/g, '-')
|
|
91
|
+
if (key === '') return undefined
|
|
92
|
+
return STATE_WORDS[key]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The worst state of a list, ignoring unparsable entries.
|
|
97
|
+
* @param {Iterable<unknown>} states Candidate states.
|
|
98
|
+
* @returns {string | undefined} The worst state, or undefined when none parse.
|
|
99
|
+
*/
|
|
100
|
+
export function worstState(states) {
|
|
101
|
+
let worst
|
|
102
|
+
for (const candidate of states) {
|
|
103
|
+
const state = normalizeState(candidate)
|
|
104
|
+
if (state === undefined) continue
|
|
105
|
+
if (worst === undefined || SEVERITY[state] > SEVERITY[worst]) worst = state
|
|
106
|
+
}
|
|
107
|
+
return worst
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Project one Atlassian-Statuspage `/api/v2/status.json` body.
|
|
112
|
+
*
|
|
113
|
+
* The indicator is the whole answer; the description is its human sentence,
|
|
114
|
+
* and it is English whatever the page's locale. The plugin's own label is
|
|
115
|
+
* localized in the browser, so the sentence is only carried when something is
|
|
116
|
+
* wrong — saying "All Systems Operational" beside "运行正常" would just repeat
|
|
117
|
+
* itself.
|
|
118
|
+
*
|
|
119
|
+
* @param {{json?: unknown}} env Source payload.
|
|
120
|
+
* @returns {{state: string, summary?: string}} The projected reading.
|
|
121
|
+
*/
|
|
122
|
+
export function statuspageView({ json }) {
|
|
123
|
+
const body = asObject(json)
|
|
124
|
+
const status = asObject(body.status)
|
|
125
|
+
const state = normalizeState(status.indicator) ?? STATUS_UNKNOWN
|
|
126
|
+
const summary = typeof status.description === 'string' ? status.description.trim() : ''
|
|
127
|
+
return {
|
|
128
|
+
state,
|
|
129
|
+
...(summary === '' || state === STATUS_OPERATIONAL || state === STATUS_UNKNOWN
|
|
130
|
+
? {}
|
|
131
|
+
: { summary }),
|
|
132
|
+
}
|
|
133
|
+
}
|