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/state.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/** Non-secret plugin state. Credentials are kept only in DSH's credential store. */
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { dirname, join, resolve } from 'node:path'
|
|
5
|
+
import { isOwnedRoute, modelCapabilities } from './models.js'
|
|
6
|
+
|
|
7
|
+
export function statePath() {
|
|
8
|
+
return join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'storages', 'dsh-nikoapi', 'state.json')
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function emptyState() {
|
|
12
|
+
return {
|
|
13
|
+
version: 4,
|
|
14
|
+
selectedKeys: [],
|
|
15
|
+
keyDirectory: { keys: [], total: 0, complete: false, autoGroups: [], autoGroupLimit: null, groups: [], groupDescriptions: false },
|
|
16
|
+
confirmed: [],
|
|
17
|
+
priceSnapshots: [],
|
|
18
|
+
protocolGroups: {},
|
|
19
|
+
protocolIdentity: '',
|
|
20
|
+
legacyKeyId: null,
|
|
21
|
+
costBinding: { enabled: true, refreshMinutes: 15, registeredCount: 0, conflicts: [], boundAt: null, lastStatus: 'waiting', lastMessage: '' },
|
|
22
|
+
registration: { routes: [], ns: '', at: null, lastStatus: 'unregistered', lastMessage: '' },
|
|
23
|
+
lastSyncedAt: null,
|
|
24
|
+
site: null,
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Only a missing file means empty state; corrupt/unreadable state fails closed. */
|
|
29
|
+
export async function readState(path = statePath()) {
|
|
30
|
+
let text
|
|
31
|
+
try { text = await readFile(path, 'utf8') }
|
|
32
|
+
catch (error) { if (error?.code === 'ENOENT') return emptyState(); throw new Error('NikoAPI state could not be read; the existing file was not changed') }
|
|
33
|
+
let raw
|
|
34
|
+
try { raw = JSON.parse(text.replace(/^\uFEFF/, '')) }
|
|
35
|
+
catch { throw new Error('NikoAPI state is not valid JSON; the existing file was not changed') }
|
|
36
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('NikoAPI state has an invalid shape; the existing file was not changed')
|
|
37
|
+
return mergeState(raw)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const writes = new Map()
|
|
41
|
+
/** Serialize same-file writes and capture the value before any async work. */
|
|
42
|
+
export function writeState(state, path = statePath()) {
|
|
43
|
+
const target = resolve(path)
|
|
44
|
+
const text = `${JSON.stringify(mergeState(state), null, 2)}\n`
|
|
45
|
+
const next = (writes.get(target) ?? Promise.resolve()).then(async () => {
|
|
46
|
+
await mkdir(dirname(target), { recursive: true })
|
|
47
|
+
const temporary = `${target}.tmp`
|
|
48
|
+
await writeFile(temporary, text, 'utf8')
|
|
49
|
+
await rename(temporary, target)
|
|
50
|
+
})
|
|
51
|
+
const settled = next.catch(() => {})
|
|
52
|
+
writes.set(target, settled)
|
|
53
|
+
void settled.then(() => { if (writes.get(target) === settled) writes.delete(target) })
|
|
54
|
+
return next
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const strings = (value, cap = 256) => [...new Set((Array.isArray(value) ? value : []).filter(item => typeof item === 'string' && item !== '').map(item => item.slice(0, 512)))].slice(0, cap)
|
|
58
|
+
const protocols = value => [...new Set((Array.isArray(value) ? value : []).filter(item => ['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai'].includes(item)))]
|
|
59
|
+
const endpoints = value => Array.isArray(value)
|
|
60
|
+
? [...new Set(value.filter(item => ['openai', 'openai-response', 'anthropic', 'gemini', 'image-generation', 'openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai'].includes(item)))]
|
|
61
|
+
: null
|
|
62
|
+
function protocolGroupState(value) {
|
|
63
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return {}
|
|
64
|
+
return Object.fromEntries(Object.entries(value).slice(0, 2000).map(([group, value]) => [group.slice(0, 512), protocols(value)]).filter(([, value]) => value.length))
|
|
65
|
+
}
|
|
66
|
+
const finite = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1e12 ? value : null
|
|
67
|
+
export function keyPriceIdentity(key) {
|
|
68
|
+
return JSON.stringify([key?.group ?? '', key?.autoGroups ?? null, key?.crossGroupRetry === true, key?.status ?? 'unknown'])
|
|
69
|
+
}
|
|
70
|
+
function cachedPrice(row) {
|
|
71
|
+
const price = row?.price
|
|
72
|
+
if (!Number.isSafeInteger(row?.keyId) || row.keyId <= 0 || typeof row.modelId !== 'string' || !row.modelId || row.modelId.length > 512 || !price || typeof price !== 'object') return null
|
|
73
|
+
if (price.reference === true || !['CNY', 'USD', 'EUR'].includes(price.currency)) return null
|
|
74
|
+
if (price.kind === 'perMillion' && ['input', 'output', 'cacheHit', 'cacheWrite'].every(key => finite(price[key]) !== null)) {
|
|
75
|
+
return { keyId: row.keyId, modelId: row.modelId, price: { kind: 'perMillion', currency: price.currency,
|
|
76
|
+
input: finite(price.input), output: finite(price.output), cacheHit: finite(price.cacheHit), cacheWrite: finite(price.cacheWrite), reference: false } }
|
|
77
|
+
}
|
|
78
|
+
if (price.kind === 'perCall' && price.currency === 'CNY' && finite(price.perCall) !== null) {
|
|
79
|
+
return { keyId: row.keyId, modelId: row.modelId, price: { kind: 'perCall', currency: 'CNY', perCall: finite(price.perCall), reference: false } }
|
|
80
|
+
}
|
|
81
|
+
if (['nikoExpression', 'nikoZero'].includes(price.kind) && price.currency === 'CNY'
|
|
82
|
+
&& typeof price.expression === 'string' && price.expression.length <= 8192
|
|
83
|
+
&& finite(price.groupRatio) !== null && finite(price.quotaPerUnit) > 0) {
|
|
84
|
+
return { keyId: row.keyId, modelId: row.modelId, price: { kind: price.kind, currency: 'CNY', expression: price.expression,
|
|
85
|
+
groupRatio: finite(price.groupRatio), quotaPerUnit: finite(price.quotaPerUnit), ...(price.kind === 'nikoZero' ? { zeroByPolicy: true } : {}) } }
|
|
86
|
+
}
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function directoryKeyMetadata(key) {
|
|
91
|
+
if (!Number.isSafeInteger(key?.id) || key.id <= 0) return null
|
|
92
|
+
return {
|
|
93
|
+
...keyMetadata(key),
|
|
94
|
+
maskedKey: '••••',
|
|
95
|
+
unlimitedQuota: key.unlimitedQuota === true,
|
|
96
|
+
remainQuota: finite(key.remainQuota),
|
|
97
|
+
usedQuota: finite(key.usedQuota),
|
|
98
|
+
modelLimitsEnabled: key.modelLimitsEnabled === true,
|
|
99
|
+
expiresAt: finite(key.expiresAt),
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function directoryGroup(group) {
|
|
104
|
+
if (typeof group?.id !== 'string' || group.id === '') return null
|
|
105
|
+
return { id: group.id.slice(0, 512), name: typeof group.name === 'string' ? group.name.slice(0, 512) : group.id.slice(0, 512),
|
|
106
|
+
desc: typeof group.desc === 'string' ? group.desc.slice(0, 2048) : '', ratio: finite(group.ratio) }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function keyMetadata(key) {
|
|
110
|
+
return {
|
|
111
|
+
id: key.id,
|
|
112
|
+
name: typeof key.name === 'string' ? key.name : `#${key.id}`,
|
|
113
|
+
group: typeof key.group === 'string' ? key.group : '',
|
|
114
|
+
autoGroups: Array.isArray(key.autoGroups) ? strings(key.autoGroups) : null,
|
|
115
|
+
crossGroupRetry: key.crossGroupRetry === true,
|
|
116
|
+
status: typeof key.status === 'string' ? key.status : 'unknown',
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Migrate the original single-key state without letting another id adopt its secret. */
|
|
121
|
+
export function mergeState(raw) {
|
|
122
|
+
const base = emptyState()
|
|
123
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return base
|
|
124
|
+
const binding = raw.costBinding ?? {}
|
|
125
|
+
const directory = raw.keyDirectory ?? {}
|
|
126
|
+
const registration = raw.registration ?? {}
|
|
127
|
+
const keys = new Map()
|
|
128
|
+
for (const key of Array.isArray(raw.selectedKeys) ? raw.selectedKeys : []) {
|
|
129
|
+
if (Number.isSafeInteger(key?.id) && key.id > 0) keys.set(key.id, keyMetadata(key))
|
|
130
|
+
}
|
|
131
|
+
let legacyKeyId = Number.isSafeInteger(raw.legacyKeyId) && raw.legacyKeyId > 0 ? raw.legacyKeyId : null
|
|
132
|
+
if (keys.size === 0 && Number.isSafeInteger(raw.selectedKeyId) && raw.selectedKeyId > 0) {
|
|
133
|
+
legacyKeyId = raw.selectedKeyId
|
|
134
|
+
keys.set(raw.selectedKeyId, keyMetadata({ id: raw.selectedKeyId, name: raw.selectedKeyName }))
|
|
135
|
+
}
|
|
136
|
+
const selectedKeys = [...keys.values()]
|
|
137
|
+
const confirmed = new Map()
|
|
138
|
+
const source = Array.isArray(raw.confirmed) && raw.confirmed.length
|
|
139
|
+
? raw.confirmed
|
|
140
|
+
: keys.size === 1 && Array.isArray(raw.confirmedModels)
|
|
141
|
+
? raw.confirmedModels.map(row => ({ ...row, keyId: legacyKeyId ?? selectedKeys[0]?.id, modelId: row?.id })) : []
|
|
142
|
+
for (const row of source) {
|
|
143
|
+
if (keys.has(row?.keyId) && typeof row?.modelId === 'string' && row.modelId !== '') {
|
|
144
|
+
confirmed.set(JSON.stringify([row.keyId, row.modelId]), { keyId: row.keyId, modelId: row.modelId, name: typeof row.name === 'string' ? row.name : row.modelId,
|
|
145
|
+
supportedEndpoints: endpoints(row.supportedEndpoints), protocols: raw.version >= 4 ? protocols(row.protocols) : ['openai-completions'],
|
|
146
|
+
protocolIdentity: raw.version >= 4 && typeof row.protocolIdentity === 'string' ? row.protocolIdentity.slice(0, 2048) : '',
|
|
147
|
+
reasoningEffortsDeclared: row.reasoningEffortsDeclared === true,
|
|
148
|
+
...modelCapabilities(row) })
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const snapshots = new Map()
|
|
152
|
+
for (const row of Array.isArray(raw.priceSnapshots) ? raw.priceSnapshots.slice(0, 5000) : []) {
|
|
153
|
+
const value = cachedPrice(row)
|
|
154
|
+
const key = keys.get(row?.keyId)
|
|
155
|
+
if (!value || !key || !confirmed.has(JSON.stringify([value.keyId, value.modelId])) || row.keyIdentity !== keyPriceIdentity(key)) continue
|
|
156
|
+
snapshots.set(JSON.stringify([value.keyId, value.modelId]), { ...value, keyIdentity: row.keyIdentity,
|
|
157
|
+
at: typeof row.at === 'string' && Number.isFinite(Date.parse(row.at)) ? row.at : null })
|
|
158
|
+
}
|
|
159
|
+
const legacyRoutes = registration.lastStatus === 'registered' && raw.registration?.routes === undefined ? ['nikoapi'] : []
|
|
160
|
+
return {
|
|
161
|
+
...base,
|
|
162
|
+
selectedKeys,
|
|
163
|
+
keyDirectory: {
|
|
164
|
+
keys: Array.isArray(directory.keys) ? directory.keys.filter(key => Number.isSafeInteger(key?.id) && key.id > 0).slice(0, 5000).map(directoryKeyMetadata).filter(Boolean) : [],
|
|
165
|
+
total: Number.isSafeInteger(directory.total) && directory.total >= 0 ? directory.total : 0,
|
|
166
|
+
complete: directory.complete === true,
|
|
167
|
+
autoGroups: strings(directory.autoGroups).slice(0, 256),
|
|
168
|
+
autoGroupLimit: Number.isSafeInteger(directory.autoGroupLimit) && directory.autoGroupLimit >= 0 ? directory.autoGroupLimit : null,
|
|
169
|
+
groups: Array.isArray(directory.groups) ? directory.groups.slice(0, 2000).map(directoryGroup).filter(Boolean) : [],
|
|
170
|
+
at: typeof directory.at === 'string' && Number.isFinite(Date.parse(directory.at)) ? directory.at : null,
|
|
171
|
+
groupDescriptions: directory.groupDescriptions === true,
|
|
172
|
+
},
|
|
173
|
+
confirmed: [...confirmed.values()],
|
|
174
|
+
priceSnapshots: [...snapshots.values()],
|
|
175
|
+
protocolGroups: protocolGroupState(raw.protocolGroups),
|
|
176
|
+
legacyKeyId,
|
|
177
|
+
costBinding: {
|
|
178
|
+
enabled: true,
|
|
179
|
+
registeredCount: Number.isSafeInteger(binding.registeredCount) && binding.registeredCount >= 0 ? binding.registeredCount : 0,
|
|
180
|
+
conflicts: strings(binding.conflicts, 5000),
|
|
181
|
+
unavailable: strings(binding.unavailable, 5000),
|
|
182
|
+
refreshMinutes: Number.isFinite(binding.refreshMinutes) && binding.refreshMinutes >= 1 ? Math.min(1440, Math.round(binding.refreshMinutes)) : 15,
|
|
183
|
+
ownedPriceKeys: strings(binding.ownedPriceKeys),
|
|
184
|
+
ownedUnpricedKeys: strings(binding.ownedUnpricedKeys),
|
|
185
|
+
ownedPriceSnapshots: Object.fromEntries(Object.entries(binding.ownedPriceSnapshots ?? {}).filter(([key,value]) => !['__proto__','constructor','prototype'].includes(key) && typeof value === 'string' && value.length <= 32768)),
|
|
186
|
+
balance: typeof binding.balance?.url === 'string' && typeof binding.balance?.credentialVar === 'string'
|
|
187
|
+
? { url: binding.balance.url, credentialVar: binding.balance.credentialVar }
|
|
188
|
+
: null,
|
|
189
|
+
legacyBalance: typeof binding.balance?.url !== 'string' && binding.enabled === true,
|
|
190
|
+
boundAt: typeof binding.boundAt === 'string' ? binding.boundAt : null,
|
|
191
|
+
lastStatus: typeof binding.lastStatus === 'string' ? binding.lastStatus : 'waiting',
|
|
192
|
+
lastMessage: typeof binding.lastMessage === 'string' ? binding.lastMessage : '',
|
|
193
|
+
},
|
|
194
|
+
registration: {
|
|
195
|
+
// The route list is the ownership ledger; keep owned stale routes so a crash during key changes cannot orphan them.
|
|
196
|
+
routes: strings(Array.isArray(registration.routes) ? registration.routes : legacyRoutes)
|
|
197
|
+
.filter(isOwnedRoute),
|
|
198
|
+
ns: typeof registration.ns === 'string' ? registration.ns : '',
|
|
199
|
+
at: typeof registration.at === 'string' ? registration.at : null,
|
|
200
|
+
lastStatus: typeof registration.lastStatus === 'string' ? registration.lastStatus : 'unregistered',
|
|
201
|
+
lastMessage: typeof registration.lastMessage === 'string' ? registration.lastMessage : '',
|
|
202
|
+
},
|
|
203
|
+
lastSyncedAt: typeof raw.lastSyncedAt === 'string' ? raw.lastSyncedAt : null,
|
|
204
|
+
site: raw.site !== null && typeof raw.site === 'object' ? {
|
|
205
|
+
version: typeof raw.site.version === 'string' ? raw.site.version : '',
|
|
206
|
+
currency: typeof raw.site.currency === 'string' ? raw.site.currency : '',
|
|
207
|
+
quotaPerUnit: Number.isFinite(raw.site.quotaPerUnit) && raw.site.quotaPerUnit > 0 ? raw.site.quotaPerUnit : 500_000,
|
|
208
|
+
usdExchangeRate: Number.isFinite(raw.site.usdExchangeRate) && raw.site.usdExchangeRate > 0 ? raw.site.usdExchangeRate : 1,
|
|
209
|
+
} : null,
|
|
210
|
+
}
|
|
211
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "NikoAPI",
|
|
4
|
+
"description": "Connect a NikoAPI (New API relay) account, add models by Key group, and automatically register confirmed model price calculators when a compatible dsh-cost-meter is available. Credentials remain in DSH's local credential store and are not shown again.",
|
|
5
|
+
"detail": "README.en.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-nikoapi",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Connect NikoAPI (New API relay) keys and grouped models to DeepSeek Harness, with automatic cost-meter price linking.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"dsh",
|
|
7
|
+
"dsh-plugin",
|
|
8
|
+
"deepseek-harness",
|
|
9
|
+
"nikoapi",
|
|
10
|
+
"new-api"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"author": {
|
|
14
|
+
"name": "SnowNight777",
|
|
15
|
+
"email": "318125535+SnowNight777@users.noreply.github.com"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/SnowNight777/dsh-nikoapi.git"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/SnowNight777/dsh-nikoapi/issues"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/SnowNight777/dsh-nikoapi#readme",
|
|
25
|
+
"type": "module",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": "./index.js",
|
|
28
|
+
"./client": "./client.js",
|
|
29
|
+
"./locale/*.json": "./locale/*.json",
|
|
30
|
+
"./icon": "./icon.svg"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"index.js",
|
|
34
|
+
"client.js",
|
|
35
|
+
"lib",
|
|
36
|
+
"cordis.patch.yml",
|
|
37
|
+
"locale/*.json",
|
|
38
|
+
"images",
|
|
39
|
+
"icon.svg"
|
|
40
|
+
],
|
|
41
|
+
"scripts": {
|
|
42
|
+
"test": "node test/run.mjs"
|
|
43
|
+
},
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=20"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"dsh": {
|
|
51
|
+
"bundle": {
|
|
52
|
+
"patch": "./cordis.patch.yml"
|
|
53
|
+
},
|
|
54
|
+
"client": {
|
|
55
|
+
"platform": "web",
|
|
56
|
+
"immediately": true,
|
|
57
|
+
"inject": [
|
|
58
|
+
"@deepseek-ai/dsh-client-ui-settings"
|
|
59
|
+
]
|
|
60
|
+
},
|
|
61
|
+
"compatibility": {
|
|
62
|
+
"dsh": ">=0.2.2-rc.1 <0.3.0-0"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
6
65
|
}
|