dsh-nikoapi 0.0.0-stage → 0.1.1
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.en.md +110 -0
- package/README.md +109 -2
- package/client.js +398 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +7 -0
- package/images/key_permissions.png +0 -0
- package/images/qrcode_main.jpg +0 -0
- package/images/qrcode_notify.jpg +0 -0
- package/index.js +751 -0
- package/lib/billing-expression.js +431 -0
- package/lib/costmeter-prices.js +96 -0
- package/lib/costmeter.js +209 -0
- package/lib/groups.js +68 -0
- package/lib/http.js +147 -0
- package/lib/models.js +192 -0
- package/lib/niko.js +254 -0
- package/lib/price-calculator.js +65 -0
- package/lib/pricing.js +174 -0
- package/lib/state.js +211 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +62 -3
package/lib/costmeter.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/** Plan cost-meter edits. Never write a partial replacement table or claim foreign configuration. */
|
|
2
|
+
export const BALANCE_LABEL = 'NikoAPI'
|
|
3
|
+
export const PRICE_PROVIDER = 'nikoapi'
|
|
4
|
+
export const BALANCE_VAR = 'NIKOAPI_MANAGEMENT_TOKEN'
|
|
5
|
+
const UNPRICED_NOTE = 'dsh-nikoapi: unavailable rate; '
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Portable account-balance template supplied by the user.
|
|
9
|
+
* The final screenshot selects CNY as the source currency (no FX conversion).
|
|
10
|
+
* extract.unit is retained verbatim; cost-meter's top-level unit takes precedence.
|
|
11
|
+
* /api/user/self requires an account credential with profile:read, not a model Key.
|
|
12
|
+
*/
|
|
13
|
+
export function balanceEntry({ origin, refreshMinutes = 15, credentialVar = BALANCE_VAR }) {
|
|
14
|
+
const site = new URL(origin)
|
|
15
|
+
return {
|
|
16
|
+
enabled: true, display: 'both', refreshMinutes,
|
|
17
|
+
label: BALANCE_LABEL, labelEn: BALANCE_LABEL,
|
|
18
|
+
unit: 'CNY', convertToDisplayCurrency: false,
|
|
19
|
+
dashboardUrl: `${site.origin}/console`, allowedHosts: [site.host], allowInsecureHttp: false,
|
|
20
|
+
request: { url: `${site.origin}/api/user/self`, method: 'GET', headers: { Authorization: `Bearer {{${credentialVar}}}` } },
|
|
21
|
+
extract: { remaining: { op: 'divide', path: 'data.quota', by: 500_000 }, maxBudget: 200, spend: 'info.spend', unit: 'USD' },
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function credentialOf(entry) {
|
|
26
|
+
const value = Object.entries(entry?.request?.headers ?? {}).find(([key]) => key.toLowerCase() === 'authorization')?.[1]
|
|
27
|
+
return typeof value === 'string' ? /^Bearer\s+\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}$/i.exec(value)?.[1] : undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** A user's working account query can be reused, but never rewritten or claimed as ours. */
|
|
31
|
+
export function isNikoAccountBalance(entry, origin) {
|
|
32
|
+
if (!entry || typeof entry !== 'object') return false
|
|
33
|
+
const extract = entry.extract ?? {}
|
|
34
|
+
return entry.request?.url === `${new URL(origin).origin}/api/user/self`
|
|
35
|
+
&& (entry.request?.method ?? 'GET').toUpperCase() === 'GET' && !!credentialOf(entry)
|
|
36
|
+
&& entry.unit === 'CNY' && entry.convertToDisplayCurrency !== true
|
|
37
|
+
&& extract.remaining?.op === 'divide' && extract.remaining.path === 'data.quota' && extract.remaining.by === 500_000
|
|
38
|
+
&& extract.maxBudget === 200 && extract.spend === 'info.spend'
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Recognize the *old generated shape* only in conjunction with the persisted ownership reference. */
|
|
42
|
+
function isLegacyShape(entry) {
|
|
43
|
+
const extract = entry?.extract ?? {}
|
|
44
|
+
return entry?.label === BALANCE_LABEL && (entry.request?.method ?? 'GET') === 'GET'
|
|
45
|
+
&& extract.remaining?.op === 'divide' && extract.remaining.path === 'data.total_available' && extract.remaining.by > 0
|
|
46
|
+
&& extract.maxBudget?.op === 'divide' && extract.maxBudget.path === 'data.total_granted' && extract.maxBudget.by === extract.remaining.by
|
|
47
|
+
&& extract.spend?.op === 'divide' && extract.spend.path === 'data.total_used' && extract.spend.by === extract.remaining.by
|
|
48
|
+
}
|
|
49
|
+
function ownedBalanceMatches(entry, ownership, origin) {
|
|
50
|
+
if (!ownership?.url || !ownership?.credentialVar || entry?.request?.url !== ownership.url || credentialOf(entry) !== ownership.credentialVar) return false
|
|
51
|
+
const site = new URL(origin ?? ownership.url).origin
|
|
52
|
+
return isNikoAccountBalance(entry, site) || (ownership.url === `${site}/api/usage/token/` && isLegacyShape(entry))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const priceKeyOf = (provider, model) => `${provider}:${model}`
|
|
56
|
+
function splitPriceKey(key) {
|
|
57
|
+
const at = typeof key === 'string' ? key.indexOf(':') : -1
|
|
58
|
+
return at > 0 ? [key.slice(0, at), key.slice(at + 1)] : []
|
|
59
|
+
}
|
|
60
|
+
function marker(entry) { return entry?.unpriced === true && entry.notes?.startsWith(UNPRICED_NOTE) === true }
|
|
61
|
+
function mutableProvider(config, changes, provider) {
|
|
62
|
+
if (!Object.hasOwn(changes, provider)) {
|
|
63
|
+
const previous = config.prices?.providers?.[provider] ?? {}
|
|
64
|
+
changes[provider] = { ...previous, models: { ...(previous.models ?? {}) } }
|
|
65
|
+
}
|
|
66
|
+
return changes[provider].models
|
|
67
|
+
}
|
|
68
|
+
function removeMarker(config, changes, key) {
|
|
69
|
+
const [provider, model] = splitPriceKey(key)
|
|
70
|
+
if (!provider) return
|
|
71
|
+
const current = (changes[provider]?.models ?? config.prices?.providers?.[provider]?.models ?? {})[model]
|
|
72
|
+
if (marker(current)) delete mutableProvider(config, changes, provider)[model]
|
|
73
|
+
}
|
|
74
|
+
function exactPrice(price) {
|
|
75
|
+
return price?.kind === 'perMillion' && price.reference !== true && ['USD', 'CNY'].includes(price.currency)
|
|
76
|
+
&& ['input', 'output', 'cacheHit'].every(key => Number.isFinite(price[key]) && price[key] >= 0)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function planBinding(current, options) {
|
|
80
|
+
const config = current ?? {}
|
|
81
|
+
let balances = [...(config.customBalances ?? [])]
|
|
82
|
+
const previousOwned = options.ownedBalance
|
|
83
|
+
const oldMatches = balances.filter(entry => ownedBalanceMatches(entry, previousOwned, options.origin))
|
|
84
|
+
// Migrate only the precisely owned wrong token-quota entry. Ambiguous/untracked entries stay untouched.
|
|
85
|
+
if (oldMatches.length === 1 && isLegacyShape(oldMatches[0])) balances = balances.filter(entry => entry !== oldMatches[0])
|
|
86
|
+
let index = balances.findIndex(entry => isNikoAccountBalance(entry, options.origin))
|
|
87
|
+
const created = index < 0
|
|
88
|
+
if (created && balances.length >= 8) return { ok: false, reason: 'cost-meter already holds 8 custom balance entries; no existing entry was changed' }
|
|
89
|
+
let ownedBalance = null
|
|
90
|
+
if (created) {
|
|
91
|
+
index = balances.length
|
|
92
|
+
balances.push(balanceEntry(options))
|
|
93
|
+
ownedBalance = { url: balances[index].request.url, credentialVar: options.credentialVar ?? BALANCE_VAR }
|
|
94
|
+
} else if (ownedBalanceMatches(balances[index], previousOwned, options.origin)) {
|
|
95
|
+
ownedBalance = previousOwned
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const overrides = { ...(config.priceOverrides ?? {}) }
|
|
99
|
+
const custom = { ...(config.prices?.custom ?? {}) }
|
|
100
|
+
const providerChanges = {}
|
|
101
|
+
const owned = new Set(options.ownedPriceKeys ?? [])
|
|
102
|
+
const ownedUnknown = new Set(options.ownedUnpricedKeys ?? [])
|
|
103
|
+
const expected = new Set(options.models.map(model => priceKeyOf(model.provider || PRICE_PROVIDER, model.id)))
|
|
104
|
+
for (const key of owned) if (!expected.has(key)) {
|
|
105
|
+
if (overrides[key] === '__custom__') { delete overrides[key]; delete custom[key] }
|
|
106
|
+
}
|
|
107
|
+
for (const key of ownedUnknown) if (!expected.has(key)) removeMarker(config, providerChanges, key)
|
|
108
|
+
|
|
109
|
+
const priced = [], unpriced = [], conflicts = [], ownedPriceKeys = [], ownedUnpricedKeys = []
|
|
110
|
+
for (const model of options.models) {
|
|
111
|
+
const provider = model.provider || PRICE_PROVIDER
|
|
112
|
+
const key = priceKeyOf(provider, model.id)
|
|
113
|
+
const oldTable = config.prices?.providers?.[provider]?.models ?? {}
|
|
114
|
+
// An explicit user mapping wins. Do not replace it, even if it uses the same provider/model name.
|
|
115
|
+
if ((Object.hasOwn(overrides, key) && !owned.has(key))
|
|
116
|
+
|| (Object.hasOwn(custom, key) && !owned.has(key))
|
|
117
|
+
|| (Object.hasOwn(oldTable, model.id) && !(ownedUnknown.has(key) && marker(oldTable[model.id])))) {
|
|
118
|
+
conflicts.push({ key, reason: 'existing user price kept' })
|
|
119
|
+
continue
|
|
120
|
+
}
|
|
121
|
+
if (exactPrice(model.price)) {
|
|
122
|
+
removeMarker(config, providerChanges, key)
|
|
123
|
+
overrides[key] = '__custom__'
|
|
124
|
+
custom[key] = { currency: model.price.currency, cacheMiss: model.price.input, cacheHit: model.price.cacheHit, output: model.price.output,
|
|
125
|
+
...(Number.isFinite(model.price.cacheWrite) ? { cacheWrite: model.price.cacheWrite } : {}) }
|
|
126
|
+
ownedPriceKeys.push(key)
|
|
127
|
+
priced.push({ provider, id: model.id, key })
|
|
128
|
+
} else {
|
|
129
|
+
if (owned.has(key) && overrides[key] === '__custom__') { delete overrides[key]; delete custom[key] }
|
|
130
|
+
// __custom__ requires three numeric buckets and CANNOT carry unpriced. Use the real provider-table contract.
|
|
131
|
+
mutableProvider(config, providerChanges, provider)[model.id] = {
|
|
132
|
+
unpriced: true, notes: UNPRICED_NOTE + (model.price?.note || 'the API does not provide an exact representable tariff'),
|
|
133
|
+
sourceUrl: `${new URL(options.origin).origin}/api/pricing`,
|
|
134
|
+
}
|
|
135
|
+
ownedUnpricedKeys.push(key)
|
|
136
|
+
unpriced.push({ provider, id: model.id, key, kind: model.price?.kind ?? 'unknown', note: model.price?.note ?? '' })
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return { ok: true,
|
|
140
|
+
patch: { customBalances: balances, priceOverrides: overrides,
|
|
141
|
+
prices: { custom, ...(Object.keys(providerChanges).length ? { providers: providerChanges } : {}) } },
|
|
142
|
+
summary: { balanceIndex: index, balance: ownedBalance, balanceCreated: created, balanceReused: !created,
|
|
143
|
+
legacyBalanceRetained: oldMatches.length > 1, priced, unpriced, conflicts, ownedPriceKeys, ownedUnpricedKeys },
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const ACCOUNT_PATH = '/api/user/self'
|
|
148
|
+
const TOKEN_QUOTA_PATH = '/api/usage/token/'
|
|
149
|
+
|
|
150
|
+
/** A user's own NikoAPI balance row, current or legacy shape, is already the answer. */
|
|
151
|
+
function isNikoLabelEntry(entry, site) {
|
|
152
|
+
if (entry?.label !== BALANCE_LABEL) return false
|
|
153
|
+
const url = entry?.request?.url
|
|
154
|
+
return url === `${site}${ACCOUNT_PATH}` || url === `${site}${TOKEN_QUOTA_PATH}`
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Balance-only plan: reuse whatever already answers the question, otherwise add one entry.
|
|
159
|
+
* Prices are never part of this patch, so it can run beside the price calculators.
|
|
160
|
+
* Existing rows win — a template-shaped row, a row we created earlier, or any NikoAPI-labelled
|
|
161
|
+
* row on this origin. Only a site-origin change relocates the row we created.
|
|
162
|
+
*/
|
|
163
|
+
export function planBalanceBinding(current, options = {}) {
|
|
164
|
+
const config = current ?? {}
|
|
165
|
+
let site = ''
|
|
166
|
+
try { site = new URL(options.origin).origin } catch { site = '' }
|
|
167
|
+
if (!site) return { ok: false, changed: false, created: false, reused: false, patch: null, balance: null, reason: 'a site origin is required before the account balance can be linked' }
|
|
168
|
+
const credentialVar = options.credentialVar ?? BALANCE_VAR
|
|
169
|
+
const rows = [...(config.customBalances ?? [])]
|
|
170
|
+
const owned = rows.findIndex(entry => ownedBalanceMatches(entry, options.ownedBalance, options.origin))
|
|
171
|
+
if (owned >= 0) {
|
|
172
|
+
const url = rows[owned].request?.url
|
|
173
|
+
if (url === `${site}${ACCOUNT_PATH}`) {
|
|
174
|
+
return { ok: true, changed: false, created: false, reused: true, patch: null,
|
|
175
|
+
balance: { url, credentialVar: credentialOf(rows[owned]) ?? credentialVar } }
|
|
176
|
+
}
|
|
177
|
+
const next = [...rows]
|
|
178
|
+
next[owned] = balanceEntry({ origin: site, refreshMinutes: options.refreshMinutes, credentialVar })
|
|
179
|
+
return { ok: true, changed: true, created: false, reused: false, relocated: true, patch: { customBalances: next },
|
|
180
|
+
balance: { url: next[owned].request.url, credentialVar } }
|
|
181
|
+
}
|
|
182
|
+
if (rows.some(entry => isNikoAccountBalance(entry, site) || isNikoLabelEntry(entry, site))) {
|
|
183
|
+
return { ok: true, changed: false, created: false, reused: true, retained: true, patch: null, balance: null }
|
|
184
|
+
}
|
|
185
|
+
if (rows.length >= 8) {
|
|
186
|
+
return { ok: false, changed: false, created: false, reused: false, patch: null, balance: null,
|
|
187
|
+
reason: 'cost-meter already holds 8 custom balance entries; no existing entry was changed' }
|
|
188
|
+
}
|
|
189
|
+
const entry = balanceEntry({ origin: site, refreshMinutes: options.refreshMinutes, credentialVar })
|
|
190
|
+
return { ok: true, changed: true, created: true, reused: false, patch: { customBalances: [...rows, entry] },
|
|
191
|
+
balance: { url: entry.request.url, credentialVar } }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Remove precisely owned generated entries; an existing working account template is never owned. */
|
|
195
|
+
export function planUnbind(current, ownership = {}) {
|
|
196
|
+
const config = current ?? {}
|
|
197
|
+
const rows = [...(config.customBalances ?? [])]
|
|
198
|
+
const matches = rows.filter(entry => ownedBalanceMatches(entry, ownership.balance))
|
|
199
|
+
const balances = matches.length === 1 ? rows.filter(entry => entry !== matches[0]) : rows
|
|
200
|
+
const overrides = { ...(config.priceOverrides ?? {}) }, custom = { ...(config.prices?.custom ?? {}) }, providerChanges = {}
|
|
201
|
+
const removed = []
|
|
202
|
+
for (const key of new Set(ownership.ownedPriceKeys ?? [])) {
|
|
203
|
+
if (overrides[key] === '__custom__') { delete overrides[key]; delete custom[key]; removed.push(key) }
|
|
204
|
+
}
|
|
205
|
+
for (const key of new Set(ownership.ownedUnpricedKeys ?? [])) removeMarker(config, providerChanges, key)
|
|
206
|
+
return { patch: { customBalances: balances, priceOverrides: overrides,
|
|
207
|
+
prices: { custom, ...(Object.keys(providerChanges).length ? { providers: providerChanges } : {}) } },
|
|
208
|
+
removed, legacyBalanceAmbiguous: false, balanceRetained: matches.length > 1 }
|
|
209
|
+
}
|
package/lib/groups.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Group options for the picker.
|
|
3
|
+
*
|
|
4
|
+
* In the deployed New API fork, `/api/pricing.usable_group` is
|
|
5
|
+
* `group id -> description`; `group_ratio` is the independent multiplier map.
|
|
6
|
+
* `/api/group/` is an admin-only endpoint, so a user's key-management PAT must
|
|
7
|
+
* not call it. Keep the upstream group id as the title, the provided value as
|
|
8
|
+
* its second line, and never synthesize a description.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {object} input
|
|
13
|
+
* @param {Record<string, unknown>} [input.usableGroup] `/api/pricing` usable_group
|
|
14
|
+
* @param {Record<string, number>} [input.groupRatio] `/api/pricing` group_ratio
|
|
15
|
+
* @param {Record<string, { name?: string, desc?: string }>} [input.groupMeta] optional extra metadata
|
|
16
|
+
* @returns {Array<{ id: string, name: string, desc: string, ratio: number | null }>}
|
|
17
|
+
*/
|
|
18
|
+
export function normalizeGroups({ usableGroup, groupRatio, groupMeta } = {}) {
|
|
19
|
+
const ratios = groupRatio !== null && typeof groupRatio === 'object' ? groupRatio : {}
|
|
20
|
+
const meta = groupMeta !== null && typeof groupMeta === 'object' ? groupMeta : {}
|
|
21
|
+
const source = usableGroup !== null && typeof usableGroup === 'object' ? usableGroup : {}
|
|
22
|
+
const ids = new Set([...Object.keys(source), ...Object.keys(meta)])
|
|
23
|
+
const rows = []
|
|
24
|
+
for (const id of ids) {
|
|
25
|
+
const raw = source[id]
|
|
26
|
+
const detailed = raw !== null && typeof raw === 'object' ? raw : undefined
|
|
27
|
+
const description = typeof raw === 'string' ? raw : ''
|
|
28
|
+
const fromMeta = meta[id]
|
|
29
|
+
rows.push({
|
|
30
|
+
id,
|
|
31
|
+
name: firstText(fromMeta?.name, detailed?.name, id),
|
|
32
|
+
desc: firstText(fromMeta?.desc, detailed?.desc, description),
|
|
33
|
+
ratio: Number.isFinite(ratios[id]) ? ratios[id] : null,
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
rows.sort((left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id))
|
|
37
|
+
return rows
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The secondary line exactly follows the API's group description. */
|
|
41
|
+
export function groupSecondary(group) {
|
|
42
|
+
if (typeof group?.desc === 'string' && group.desc.trim() !== '') return group.desc.trim()
|
|
43
|
+
return ''
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Fold extra metadata rows into an id-keyed lookup. */
|
|
47
|
+
export function groupMetaFromRows(rows) {
|
|
48
|
+
const meta = {}
|
|
49
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
50
|
+
if (row === null || typeof row !== 'object') continue
|
|
51
|
+
const id = firstText(row.id, row.group, row.name, '')
|
|
52
|
+
if (id === '') continue
|
|
53
|
+
const name = firstText(row.display_name, row.label, row.name, '')
|
|
54
|
+
const desc = firstText(row.desc, row.description, row.remark, '')
|
|
55
|
+
meta[id] = {
|
|
56
|
+
...(name === '' || name === id ? {} : { name }),
|
|
57
|
+
...(desc === '' ? {} : { desc }),
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return meta
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function firstText(...values) {
|
|
64
|
+
for (const value of values) {
|
|
65
|
+
if (typeof value === 'string' && value.trim() !== '') return value.trim()
|
|
66
|
+
}
|
|
67
|
+
return ''
|
|
68
|
+
}
|
package/lib/http.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded JSON HTTP with an exact-origin credential fence.
|
|
3
|
+
*
|
|
4
|
+
* Every authenticated request must name the origin it is allowed to reach.
|
|
5
|
+
* The comparison uses protocol + host + port, because comparing only the
|
|
6
|
+
* hostname would send a key to a different service on the same host.
|
|
7
|
+
* Redirects are never followed: a 3xx is a failure, not a hop.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export class HttpError extends Error {
|
|
11
|
+
/**
|
|
12
|
+
* @param {string} message safe diagnostic; never contains a credential or body
|
|
13
|
+
* @param {{ status?: number, code?: string }} [detail]
|
|
14
|
+
*/
|
|
15
|
+
constructor(message, detail = {}) {
|
|
16
|
+
super(message)
|
|
17
|
+
this.name = 'HttpError'
|
|
18
|
+
this.status = detail.status
|
|
19
|
+
this.code = detail.code ?? 'HTTP'
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const DEFAULT_TIMEOUT_MS = 15_000
|
|
24
|
+
const DEFAULT_MAX_BYTES = 4 * 1024 * 1024
|
|
25
|
+
|
|
26
|
+
/** Effective port for an absolute URL. */
|
|
27
|
+
export function portOf(url) {
|
|
28
|
+
if (url.port !== '') return url.port
|
|
29
|
+
if (url.protocol === 'https:') return '443'
|
|
30
|
+
if (url.protocol === 'http:') return '80'
|
|
31
|
+
return ''
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Whether `candidate` is the same origin as `base` (protocol, host, port). */
|
|
35
|
+
export function sameOrigin(candidate, base) {
|
|
36
|
+
if (candidate.protocol !== base.protocol) return false
|
|
37
|
+
if (portOf(candidate) !== portOf(base)) return false
|
|
38
|
+
return candidate.hostname.toLowerCase() === base.hostname.toLowerCase()
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Loopback hosts may use plain HTTP; everything else must be TLS. */
|
|
42
|
+
export function isLoopback(hostname) {
|
|
43
|
+
const name = hostname.toLowerCase()
|
|
44
|
+
return name === 'localhost' || name === '127.0.0.1' || name === '[::1]' || name === '::1'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Validate one absolute URL against a fixed origin.
|
|
49
|
+
* @param {string} raw URL text.
|
|
50
|
+
* @param {string} origin required origin, e.g. `https://nikoapi.xyz`.
|
|
51
|
+
* @returns {URL}
|
|
52
|
+
*/
|
|
53
|
+
export function requireUrl(raw, origin) {
|
|
54
|
+
let url
|
|
55
|
+
let base
|
|
56
|
+
try {
|
|
57
|
+
url = new URL(raw)
|
|
58
|
+
base = new URL(origin)
|
|
59
|
+
} catch {
|
|
60
|
+
throw new HttpError('invalid URL', { code: 'BAD_URL' })
|
|
61
|
+
}
|
|
62
|
+
if (url.username !== '' || url.password !== '') throw new HttpError('URL must not carry credentials', { code: 'BAD_URL' })
|
|
63
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopback(url.hostname))) {
|
|
64
|
+
throw new HttpError('only HTTPS (or loopback HTTP) is allowed', { code: 'BAD_SCHEME' })
|
|
65
|
+
}
|
|
66
|
+
if (!sameOrigin(url, base)) throw new HttpError('request left the configured origin', { code: 'CROSS_ORIGIN' })
|
|
67
|
+
return url
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One JSON request.
|
|
72
|
+
* @param {object} request
|
|
73
|
+
* @param {string} request.url absolute URL.
|
|
74
|
+
* @param {string} request.origin allowed origin.
|
|
75
|
+
* @param {string} [request.method]
|
|
76
|
+
* @param {Record<string,string>} [request.headers]
|
|
77
|
+
* @param {unknown} [request.json] JSON body.
|
|
78
|
+
* @param {number} [request.timeoutMs]
|
|
79
|
+
* @param {number} [request.maxBytes]
|
|
80
|
+
* @param {AbortSignal} [request.signal]
|
|
81
|
+
* @param {typeof fetch} [request.fetch]
|
|
82
|
+
* @returns {Promise<{ status: number, body: any, text: string, authenticated: boolean }>}
|
|
83
|
+
*/
|
|
84
|
+
export async function requestJson(request) {
|
|
85
|
+
const url = requireUrl(request.url, request.origin)
|
|
86
|
+
const fetchImpl = request.fetch ?? globalThis.fetch
|
|
87
|
+
if (typeof fetchImpl !== 'function') throw new HttpError('no fetch implementation', { code: 'NO_FETCH' })
|
|
88
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
89
|
+
const maxBytes = request.maxBytes ?? DEFAULT_MAX_BYTES
|
|
90
|
+
const controller = new AbortController()
|
|
91
|
+
const timer = setTimeout(() => { controller.abort() }, timeoutMs)
|
|
92
|
+
const onAbort = () => { controller.abort() }
|
|
93
|
+
request.signal?.addEventListener('abort', onAbort, { once: true })
|
|
94
|
+
const headers = { accept: 'application/json', ...request.headers }
|
|
95
|
+
let body
|
|
96
|
+
if (request.json !== undefined) {
|
|
97
|
+
headers['content-type'] = 'application/json'
|
|
98
|
+
body = JSON.stringify(request.json)
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const response = await fetchImpl(url, {
|
|
102
|
+
method: request.method ?? 'GET',
|
|
103
|
+
headers,
|
|
104
|
+
body,
|
|
105
|
+
redirect: 'manual',
|
|
106
|
+
signal: controller.signal,
|
|
107
|
+
})
|
|
108
|
+
if (response.status >= 300 && response.status < 400) {
|
|
109
|
+
throw new HttpError('upstream redirect refused', { status: response.status, code: 'REDIRECT' })
|
|
110
|
+
}
|
|
111
|
+
const text = await readBounded(response, maxBytes)
|
|
112
|
+
let parsed
|
|
113
|
+
if (text.trim() !== '') {
|
|
114
|
+
try {
|
|
115
|
+
parsed = JSON.parse(text)
|
|
116
|
+
} catch {
|
|
117
|
+
throw new HttpError('upstream returned non-JSON', { status: response.status, code: 'BAD_JSON' })
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return { status: response.status, body: parsed, text, authenticated: response.headers.get('auth-version') !== null }
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (error instanceof HttpError) throw error
|
|
123
|
+
if (error?.name === 'AbortError') throw new HttpError('upstream request timed out or was cancelled', { code: 'TIMEOUT' })
|
|
124
|
+
throw new HttpError('upstream request failed', { code: 'NETWORK' })
|
|
125
|
+
} finally {
|
|
126
|
+
clearTimeout(timer)
|
|
127
|
+
request.signal?.removeEventListener('abort', onAbort)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function readBounded(response, maxBytes) {
|
|
132
|
+
if (response.body === null) return ''
|
|
133
|
+
const reader = response.body.getReader()
|
|
134
|
+
const chunks = []
|
|
135
|
+
let size = 0
|
|
136
|
+
while (true) {
|
|
137
|
+
const { done, value } = await reader.read()
|
|
138
|
+
if (done) break
|
|
139
|
+
size += value.byteLength
|
|
140
|
+
if (size > maxBytes) {
|
|
141
|
+
await reader.cancel().catch(() => {})
|
|
142
|
+
throw new HttpError('upstream response exceeded the size limit', { code: 'TOO_LARGE' })
|
|
143
|
+
}
|
|
144
|
+
chunks.push(value)
|
|
145
|
+
}
|
|
146
|
+
return Buffer.concat(chunks.map(chunk => Buffer.from(chunk))).toString('utf8')
|
|
147
|
+
}
|
package/lib/models.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/** Build one owned pi-ai route per Niko Key; the route selects one shared group protocol. */
|
|
2
|
+
export const PROVIDER_PREFIX = 'nikoapi'
|
|
3
|
+
export const API_KEY_ENV = 'NIKOAPI_API_KEY' // legacy single-key reference, not used for new routes
|
|
4
|
+
export const DSH_PROTOCOLS = Object.freeze(['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai'])
|
|
5
|
+
const ENDPOINT_PROTOCOL = Object.freeze({
|
|
6
|
+
openai: 'openai-completions',
|
|
7
|
+
'openai-response': 'openai-responses',
|
|
8
|
+
anthropic: 'anthropic-messages',
|
|
9
|
+
gemini: 'google-generative-ai',
|
|
10
|
+
...Object.fromEntries(DSH_PROTOCOLS.map(protocol => [protocol, protocol])),
|
|
11
|
+
})
|
|
12
|
+
const ROUTE_PROTOCOL_PRIORITY = Object.freeze(['openai-responses', 'anthropic-messages', 'google-generative-ai', 'openai-completions'])
|
|
13
|
+
export function keyRoute(keyId) { return `${PROVIDER_PREFIX}-${Number(keyId)}` }
|
|
14
|
+
export function selectRouteProtocol(protocols) {
|
|
15
|
+
const supported = new Set(normalizeProtocols(protocols))
|
|
16
|
+
return ROUTE_PROTOCOL_PRIORITY.find(protocol => supported.has(protocol)) ?? 'openai-completions'
|
|
17
|
+
}
|
|
18
|
+
export const keyRef = keyId => `${API_KEY_ENV}_${Number(keyId)}`
|
|
19
|
+
export const isOwnedRoute = routeId => typeof routeId === 'string' && /^nikoapi(?:-[1-9]\d*(?:-(?:responses|anthropic|gemini))?)?$/.test(routeId)
|
|
20
|
+
|
|
21
|
+
/** Protocol capability is shared by a NikoAPI group, aggregated from its LLM catalogue rows. */
|
|
22
|
+
export function groupProtocolMap(rows, knownGroups = []) {
|
|
23
|
+
const source = Array.isArray(rows) ? rows : []
|
|
24
|
+
const allGroups = new Set((Array.isArray(knownGroups) ? knownGroups : []).filter(group => typeof group === 'string' && group))
|
|
25
|
+
for (const row of source) for (const group of rowGroups(row)) if (group !== 'all') allGroups.add(group)
|
|
26
|
+
const groups = new Map()
|
|
27
|
+
for (const row of source) {
|
|
28
|
+
const hasEndpoints = Array.isArray(row?.supportedEndpoints) || Array.isArray(row?.supported_endpoint_types)
|
|
29
|
+
const endpointTypes = Array.isArray(row?.supportedEndpoints) && row.supportedEndpoints.length ? row.supportedEndpoints
|
|
30
|
+
: Array.isArray(row?.supported_endpoint_types) ? row.supported_endpoint_types : []
|
|
31
|
+
// Image-only catalogue rows are not chat-route capability declarations.
|
|
32
|
+
if (endpointTypes.length && endpointTypes.every(type => type === 'image-generation')) continue
|
|
33
|
+
if (!hasEndpoints) continue
|
|
34
|
+
const supported = new Set(endpointTypes.map(type => ENDPOINT_PROTOCOL[type]).filter(Boolean))
|
|
35
|
+
if (!supported.size) continue
|
|
36
|
+
const names = rowGroups(row)
|
|
37
|
+
const targets = names.includes('all') ? [...allGroups] : names
|
|
38
|
+
for (const group of targets) {
|
|
39
|
+
if (!groups.has(group)) groups.set(group, new Set())
|
|
40
|
+
for (const protocol of supported) groups.get(group).add(protocol)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return new Map([...groups].map(([group, protocols]) => [group, DSH_PROTOCOLS.filter(protocol => protocols.has(protocol))]))
|
|
44
|
+
}
|
|
45
|
+
function rowGroups(row) {
|
|
46
|
+
if (typeof row?.group === 'string' && row.group) return [row.group]
|
|
47
|
+
const values = Array.isArray(row?.enable_groups) ? row.enable_groups : Array.isArray(row?.enable_group) ? row.enable_group : []
|
|
48
|
+
const groups = values.filter(group => typeof group === 'string' && group)
|
|
49
|
+
return groups
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Auto groups can route to any member, so expose only protocols common to all candidates. */
|
|
53
|
+
export function protocolsForKey(key, groupProtocols) {
|
|
54
|
+
const groups = key?.group === 'auto'
|
|
55
|
+
? [...new Set(Array.isArray(key.autoGroups) ? key.autoGroups.filter(group => typeof group === 'string' && group) : [])]
|
|
56
|
+
: typeof key?.group === 'string' && key.group ? [key.group] : []
|
|
57
|
+
if (!groups.length) return ['openai-completions']
|
|
58
|
+
const sets = groups.map(group => new Set(groupProtocols.get(group) ?? []))
|
|
59
|
+
const shared = DSH_PROTOCOLS.filter(protocol => sets.every(protocols => protocols.has(protocol)))
|
|
60
|
+
return shared.length ? shared : ['openai-completions']
|
|
61
|
+
}
|
|
62
|
+
export function isLlmModel(model) {
|
|
63
|
+
const endpoints = model?.supportedEndpoints
|
|
64
|
+
if (Array.isArray(endpoints) && endpoints.length > 0 && endpoints.every(endpoint => endpoint === 'image-generation')) return false
|
|
65
|
+
return isGptModel(model) || (Array.isArray(endpoints) && endpoints.some(endpoint => Object.hasOwn(ENDPOINT_PROTOCOL, endpoint)))
|
|
66
|
+
}
|
|
67
|
+
export function modelProtocols(model, key, groupProtocols) {
|
|
68
|
+
const endpoints = model?.supportedEndpoints
|
|
69
|
+
if (!Array.isArray(endpoints) || endpoints.length === 0) return ['openai-completions']
|
|
70
|
+
if (!isLlmModel(model)) return ['openai-completions']
|
|
71
|
+
return protocolsForKey(key, groupProtocols)
|
|
72
|
+
}
|
|
73
|
+
export function normalizeProtocols(protocols) {
|
|
74
|
+
const values = [...new Set(Array.isArray(protocols) ? protocols.filter(protocol => DSH_PROTOCOLS.includes(protocol)) : [])]
|
|
75
|
+
return DSH_PROTOCOLS.filter(protocol => values.includes(protocol))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Shipped pi-ai directory entries expose their actual profile entry id as settingsNs. */
|
|
79
|
+
export function findProvidersNamespace(rows) {
|
|
80
|
+
const candidates = [...new Set((Array.isArray(rows) ? rows : []).filter(row =>
|
|
81
|
+
typeof row?.settingsNs === 'string' && row.settingsNs !== '' && Array.isArray(row.settingsPath) && row.settingsPath[0] === 'providers',
|
|
82
|
+
).map(row => row.settingsNs))]
|
|
83
|
+
if (candidates.includes('llm-pi-ai')) return 'llm-pi-ai'
|
|
84
|
+
return candidates.length === 1 ? candidates[0] : null
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Missing capability metadata follows the user's explicit defaults, not a model-name guess. */
|
|
88
|
+
export function modelCapabilities(model = {}) {
|
|
89
|
+
const input = [...new Set((Array.isArray(model.input) ? model.input : []).filter(type => type === 'text' || type === 'image'))]
|
|
90
|
+
const knownEfforts = new Set(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
|
|
91
|
+
let reasoningEfforts
|
|
92
|
+
if (model.reasoningEfforts === false) {
|
|
93
|
+
reasoningEfforts = false
|
|
94
|
+
} else {
|
|
95
|
+
const source = model.reasoningEfforts
|
|
96
|
+
const entries = Array.isArray(source)
|
|
97
|
+
? source.map(level => [level, level === 'off' ? null : level])
|
|
98
|
+
: source && typeof source === 'object' ? Object.entries(source) : []
|
|
99
|
+
const valid = entries.filter(([level, value]) => knownEfforts.has(level)
|
|
100
|
+
&& ((level === 'off' && value === null) || (typeof value === 'string' && value !== '')))
|
|
101
|
+
reasoningEfforts = valid.length ? Object.fromEntries(valid) : { off: null, low: 'low', high: 'high', max: 'max' }
|
|
102
|
+
}
|
|
103
|
+
return { input: input.length ? input : ['text', 'image'], reasoningEfforts }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function buildProviderRoute({ origin, apiKeyEnv, modelIds, models, label, protocol = 'openai-completions' }) {
|
|
107
|
+
if (!DSH_PROTOCOLS.includes(protocol)) throw new TypeError('unsupported DSH protocol')
|
|
108
|
+
const ids = [...new Set((Array.isArray(modelIds) ? modelIds : []).filter(id => typeof id === 'string' && id.trim() !== ''))]
|
|
109
|
+
const metadata = new Map((Array.isArray(models) ? models : []).map(model => [model.id, model]))
|
|
110
|
+
// anthropic-messages: the Anthropic SDK appends its own path segments; omit /v1 from the base.
|
|
111
|
+
const baseURL = protocol === 'anthropic-messages' ? new URL(origin).origin : `${new URL(origin).origin}/v1`
|
|
112
|
+
return {
|
|
113
|
+
displayName: typeof label === 'string' && label.trim() !== '' ? `NikoAPI · ${label.trim()}` : 'NikoAPI',
|
|
114
|
+
apiKeyEnv,
|
|
115
|
+
api: protocol,
|
|
116
|
+
baseURL,
|
|
117
|
+
models: ids.map(id => {
|
|
118
|
+
const caps = modelCapabilities(metadata.get(id))
|
|
119
|
+
// DSH requires false (not an off-only map) to disable reasoning.
|
|
120
|
+
// Respect explicit server capabilities; apply this default only when undeclared.
|
|
121
|
+
if (protocol === 'anthropic-messages' && !metadata.get(id)?.reasoningEffortsDeclared) caps.reasoningEfforts = false
|
|
122
|
+
return { id, ...caps }
|
|
123
|
+
}),
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function isGptModel(model) {
|
|
128
|
+
const endpoints = model?.supportedEndpoints
|
|
129
|
+
if (Array.isArray(endpoints) && endpoints.length > 0 && endpoints.every(endpoint => endpoint === 'image-generation')) return false
|
|
130
|
+
return [model?.id, model?.modelId, model?.name].some(value => typeof value === 'string' && /(?:^|[^a-z0-9])gpt(?:$|[-_. ]|[0-9])/i.test(value))
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** One DSH Provider per Key: select one API shared by every confirmed model on that Key. */
|
|
134
|
+
export function routeEntries(entries) {
|
|
135
|
+
const byKey = new Map()
|
|
136
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
137
|
+
if (!Number.isSafeInteger(entry?.keyId) || entry.keyId <= 0 || !Array.isArray(entry.modelIds) || entry.modelIds.length === 0) continue
|
|
138
|
+
let target = byKey.get(entry.keyId)
|
|
139
|
+
if (!target) { target = { ...entry, modelIds: [], models: [] }; byKey.set(entry.keyId, target) }
|
|
140
|
+
const metadata = new Map((Array.isArray(entry.models) ? entry.models : []).map(model => [model.id, model]))
|
|
141
|
+
for (const modelId of entry.modelIds) {
|
|
142
|
+
if (target.modelIds.includes(modelId)) continue
|
|
143
|
+
const model = metadata.get(modelId) ?? { id: modelId }
|
|
144
|
+
target.modelIds.push(modelId)
|
|
145
|
+
target.models.push(model)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return [...byKey.values()].map(entry => {
|
|
149
|
+
const supportedByAll = entry.models.map(model => {
|
|
150
|
+
const declared = normalizeProtocols(model.protocols ?? entry.protocols)
|
|
151
|
+
return new Set(declared.length ? declared : ['openai-completions'])
|
|
152
|
+
})
|
|
153
|
+
const common = DSH_PROTOCOLS.filter(protocol => supportedByAll.every(protocols => protocols.has(protocol)))
|
|
154
|
+
const protocol = entry.models.some(isGptModel) ? 'openai-responses' : selectRouteProtocol(common)
|
|
155
|
+
return { ...entry, protocol, providerId: keyRoute(entry.keyId) }
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function planRoutes(ownedRouteIds, entries, origin) {
|
|
160
|
+
const routes = {}
|
|
161
|
+
for (const entry of routeEntries(entries)) {
|
|
162
|
+
routes[entry.providerId] = buildProviderRoute({ origin, apiKeyEnv: keyRef(entry.keyId), modelIds: entry.modelIds, models: entry.models,
|
|
163
|
+
label: entry.name, protocol: entry.protocol })
|
|
164
|
+
}
|
|
165
|
+
return { routes, removed: [...new Set((Array.isArray(ownedRouteIds) ? ownedRouteIds : []).filter(id => isOwnedRoute(id) && !Object.hasOwn(routes, id)))] }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Readback verifies one selected protocol, endpoint, credential and exact model set per Key. */
|
|
169
|
+
export function registrationStatus(section, entries, origin) {
|
|
170
|
+
const providers = section?.providers ?? {}
|
|
171
|
+
const routes = []
|
|
172
|
+
const missing = []
|
|
173
|
+
for (const entry of routeEntries(entries)) {
|
|
174
|
+
const id = entry.providerId
|
|
175
|
+
const route = Object.hasOwn(providers, id) ? providers[id] : undefined
|
|
176
|
+
const current = Array.isArray(route?.models) ? route.models.map(model => model?.id).filter(id => typeof id === 'string').sort() : []
|
|
177
|
+
const wanted = [...new Set(entry.modelIds)].sort()
|
|
178
|
+
// Capabilities (input modalities, reasoningEfforts) are user-adjustable after first write;
|
|
179
|
+
// only check the parts that must never drift: credential, protocol, endpoint, model set,
|
|
180
|
+
// and that each model entry is structurally complete (input array must exist).
|
|
181
|
+
const structureOk = wanted.every(modelId => {
|
|
182
|
+
const actual = route?.models?.find(model => model.id === modelId)
|
|
183
|
+
return Array.isArray(actual?.input)
|
|
184
|
+
})
|
|
185
|
+
const ok = current.length === wanted.length && current.every((modelId, index) => modelId === wanted[index])
|
|
186
|
+
&& structureOk
|
|
187
|
+
&& route?.apiKeyEnv === keyRef(entry.keyId) && route?.api === entry.protocol
|
|
188
|
+
&& (origin === undefined || route?.baseURL === (entry.protocol === 'anthropic-messages' ? new URL(origin).origin : `${new URL(origin).origin}/v1`))
|
|
189
|
+
;(ok ? routes : missing).push(id)
|
|
190
|
+
}
|
|
191
|
+
return { registered: missing.length === 0 && routes.length > 0, routes, missing }
|
|
192
|
+
}
|