dsh-nikoapi 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/index.js ADDED
@@ -0,0 +1,736 @@
1
+ /** NikoAPI Host: credentials stay server-side; exact model routes own runtime quotes. */
2
+ import { createNikoClient, NikoPermissionError } from './lib/niko.js'
3
+ import { normalizePricing, hasExpressionBilling } from './lib/pricing.js'
4
+ import { normalizeGroups } from './lib/groups.js'
5
+ import { calculatePrice, hasManualPrice, usablePrice } from './lib/price-calculator.js'
6
+ import { API_KEY_ENV, findProvidersNamespace, isLlmModel, keyRef, keyRoute, groupProtocolMap, modelCapabilities, modelProtocols, normalizeProtocols, planRoutes, registrationStatus, routeEntries } from './lib/models.js'
7
+ import { readState, writeState, emptyState, keyMetadata, directoryKeyMetadata, keyPriceIdentity } from './lib/state.js'
8
+ import { HttpError } from './lib/http.js'
9
+
10
+ export const name = 'nikoapi'
11
+ export const inject = ['credentials']
12
+ const PAT_REF = 'NIKOAPI_MANAGEMENT_TOKEN'
13
+ const DEFAULT_BASE_URL = 'https://nikoapi.xyz'
14
+ const MAX_BODY_BYTES = 256 * 1024
15
+ const fail = (code, message, extra = {}) => Object.assign(new Error(message), { code, ...extra })
16
+ const pair = (keyId, modelId) => JSON.stringify([keyId, modelId])
17
+ const safeFailure = error => {
18
+ if (error instanceof NikoPermissionError) return fail('scope_missing', error.message, { scope: error.scope })
19
+ if (error instanceof HttpError) return fail(error.code === 'UNAUTHORIZED' ? 'credential_invalid' : 'upstream', error.message)
20
+ if (typeof error?.code === 'string' && /^[a-z_]+$/.test(error.code)) return error
21
+ return fail('operation_failed', 'operation failed; existing credentials and unrelated settings were not exposed')
22
+ }
23
+ const SAFE_FAILURE_CODES = new Set([
24
+ 'bad_input', 'credential_invalid', 'disposed', 'key_missing', 'llm_unavailable', 'models_none',
25
+ 'model_preview_failed', 'no_credentials', 'operation_failed', 'pat_missing', 'registration_unverified',
26
+ 'route_conflict', 'scope_missing', 'state_unavailable', 'unknown_method', 'upstream',
27
+ 'invalid_expression', 'unsupported_expression', 'unsupported_context', 'invalid_result', 'invalid_usage',
28
+ ])
29
+ const SAFE_NATIVE_CODES = new Set([
30
+ 'EACCES', 'EBUSY', 'ECONNABORTED', 'ECONNREFUSED', 'ECONNRESET', 'EEXIST', 'EHOSTUNREACH',
31
+ 'EINTR', 'EINVAL', 'EIO', 'EISDIR', 'EMFILE', 'ENETUNREACH', 'ENFILE', 'ENOENT', 'ENOTDIR',
32
+ 'ENOMEM', 'EPIPE', 'ETIMEDOUT', 'ENOTFOUND', 'ERR_INVALID_ARG_TYPE', 'ERR_INVALID_URL',
33
+ 'BAD_URL', 'BAD_SCHEME', 'CROSS_ORIGIN', 'NO_FETCH', 'REDIRECT', 'BAD_JSON', 'TIMEOUT',
34
+ 'NETWORK', 'TOO_LARGE', 'UNAUTHORIZED', 'UPSTREAM', 'INCOMPLETE',
35
+ ])
36
+ const SAFE_ERROR_NAMES = new Set([
37
+ 'Error', 'TypeError', 'RangeError', 'ReferenceError', 'SyntaxError', 'URIError', 'EvalError',
38
+ 'AggregateError', 'AbortError', 'TimeoutError', 'HttpError', 'NikoPermissionError',
39
+ ])
40
+ export function failureDiagnosticFields(method, error, code) {
41
+ const operation = typeof method === 'string' && /^[a-z][A-Za-z0-9]{0,39}$/.test(method) ? method : 'unknown'
42
+ const failureCode = SAFE_FAILURE_CODES.has(code) ? code : 'operation_failed'
43
+ const errorName = SAFE_ERROR_NAMES.has(error?.name) ? error.name : 'Error'
44
+ const causeCode = SAFE_FAILURE_CODES.has(error?.code) || SAFE_NATIVE_CODES.has(error?.code) ? error.code : 'none'
45
+ return { operation, failureCode, errorName, causeCode, errorCode: causeCode === 'none' ? failureCode : causeCode }
46
+ }
47
+ export function formatFailureDiagnostic(method, error, code) {
48
+ const fields = failureDiagnosticFields(method, error, code)
49
+ return `nikoapi: ${fields.failureCode} method=${fields.operation} error=${fields.errorName} cause=${fields.causeCode}`
50
+ }
51
+
52
+ export function apply(ctx, config = {}) {
53
+ const origin = new URL(config.baseUrl || DEFAULT_BASE_URL).origin
54
+ let state = emptyState()
55
+ let preview = null
56
+ let disposed = false
57
+ let loadError
58
+ let meter = null
59
+ let meterEpoch = 0
60
+ let meterConfig = null
61
+ let billionContextEpoch = -1
62
+ let queue = Promise.resolve()
63
+ let syncScheduled = false
64
+ let syncRequested = false
65
+ let startupRefresh = false
66
+ let ownRouteRevision = null
67
+ const slots = new Map()
68
+ const ready = readState().then(value => {
69
+ state = value
70
+ // Registrations are process-local. A saved status is never proof of a live callback.
71
+ state.costBinding = { ...state.costBinding, enabled: true, registeredCount: 0, lastStatus: 'waiting', lastMessage: '' }
72
+ }).catch(error => { loadError = error })
73
+ const save = () => disposed ? Promise.resolve() : writeState(state)
74
+ const bump = () => { preview = null }
75
+ const credentials = () => ctx.get('credentials')
76
+ const settings = () => ctx.get('settings')
77
+ const niko = () => createNikoClient({ baseUrl: origin })
78
+
79
+ async function requirePat() {
80
+ const store = credentials()
81
+ if (!store) throw fail('no_credentials', 'credential store is unavailable')
82
+ const hit = await store.resolve(PAT_REF)
83
+ if (!hit?.value) throw fail('pat_missing', 'save a management token first')
84
+ return hit.value
85
+ }
86
+ async function requireKey(id) {
87
+ const store = credentials()
88
+ if (!store) throw fail('no_credentials', 'credential store is unavailable')
89
+ const hit = await store.resolve(keyRef(id))
90
+ if (hit?.value) return hit.value
91
+ if (state.legacyKeyId === id) {
92
+ const legacy = await store.resolve(API_KEY_ENV)
93
+ if (legacy?.value) {
94
+ await store.set(keyRef(id), legacy.value)
95
+ state.legacyKeyId = null
96
+ await save()
97
+ return legacy.value
98
+ }
99
+ }
100
+ throw fail('key_missing', `stored credential for Key #${id} is missing; select it again`)
101
+ }
102
+ function section(ns) { return settings()?.describe?.({ redactSecrets: true })?.find(row => row.ns === ns) }
103
+ function providerNamespace() { return findProvidersNamespace(ctx.get('llm')?.listConfigurableProviders?.()) }
104
+ function protocolIdentityFor(key) {
105
+ return JSON.stringify([key?.group ?? '', key?.group === 'auto' ? [...(key.autoGroups ?? [])].sort() : [], key?.crossGroupRetry === true])
106
+ }
107
+ function protocolEntries(keys = state.selectedKeys, confirmed = state.confirmed) {
108
+ return keys.filter(key => key.status === 'enabled').map(key => {
109
+ const rows = confirmed.filter(row => row.keyId === key.id)
110
+ return { keyId: key.id, name: `${key.name} · ${key.group || 'inherited'} · #${key.id}`,
111
+ modelIds: rows.map(row => row.modelId), models: rows.map(row => ({ id: row.modelId, supportedEndpoints: row.supportedEndpoints,
112
+ protocols: row.protocolIdentity === protocolIdentityFor(key) ? row.protocols : ['openai-completions'],
113
+ reasoningEffortsDeclared: row.reasoningEffortsDeclared === true,
114
+ ...modelCapabilities(row) })) }
115
+ }).filter(row => row.modelIds.length)
116
+ }
117
+ function entriesFor(keys = state.selectedKeys, confirmed = state.confirmed) {
118
+ return protocolEntries(keys, confirmed)
119
+ }
120
+ function describeRegistration() {
121
+ const ns = providerNamespace()
122
+ const entries = protocolEntries()
123
+ const status = ns ? registrationStatus(section(ns)?.value, entries, origin) : { registered: false, routes: [], missing: [] }
124
+ const routes = routeEntries(entries)
125
+ const routeByModel = new Map()
126
+ for (const route of routes) for (const modelId of route.modelIds) {
127
+ const key = pair(route.keyId, modelId)
128
+ routeByModel.set(key, [...(routeByModel.get(key) ?? []), route.providerId])
129
+ }
130
+ const registered = new Set(status.routes)
131
+ const models = state.confirmed.map(row => {
132
+ const modelRoutes = (routeByModel.get(pair(row.keyId, row.modelId)) ?? []).filter(id => registered.has(id))
133
+ return { route: modelRoutes[0] ?? keyRoute(row.keyId), routes: modelRoutes, id: row.modelId }
134
+ })
135
+ const count = models.filter(row => row.routes.length > 0).length
136
+ return { supported: ns !== null, ...status, count, routeCount: status.routes.length, models, ns: ns || '',
137
+ lastStatus: state.registration.lastStatus, lastMessage: state.registration.lastMessage }
138
+ }
139
+ /** CAS and readback protect unrelated routes and concurrent settings edits. */
140
+ async function writeRoutes(entries) {
141
+ const ns = state.registration.ns || providerNamespace()
142
+ if (!ns) {
143
+ if (entries.length === 0 && state.registration.routes.length === 0) return
144
+ throw fail('llm_unavailable', 'the pi-ai settings namespace is unavailable')
145
+ }
146
+ const service = settings()
147
+ const before = section(ns)
148
+ if (!before || typeof service?.mutate !== 'function') throw fail('llm_unavailable', 'pi-ai requires the settings mutate API')
149
+ const providers = before.value?.providers ?? {}
150
+ const owned = state.registration.routes
151
+ const plan = planRoutes(owned, entries, origin)
152
+ for (const id of Object.keys(plan.routes)) {
153
+ if (Object.hasOwn(providers, id) && !owned.includes(id)) throw fail('route_conflict', `provider ${id} already exists and is not owned by this plugin`)
154
+ }
155
+ const removed = plan.removed.filter(id => Object.hasOwn(providers, id))
156
+ const ops = removed.map(id => ({ op: 'unset', path: ['providers', id] }))
157
+ for (const [id, value] of Object.entries(plan.routes)) ops.push({ op: 'set', path: ['providers', id], value })
158
+ if (ops.length) {
159
+ ownRouteRevision = { ns, revision: before.revision + 1 }
160
+ try { await service.mutate(ns, ops, before.revision) }
161
+ catch (error) { ownRouteRevision = null; throw error }
162
+ }
163
+ state.registration = { ...state.registration, routes: Object.keys(plan.routes), ns }
164
+ await save()
165
+ const after = section(ns)?.value
166
+ const status = registrationStatus(after, entries, origin)
167
+ if ((entries.length && !status.registered) || removed.some(id => Object.hasOwn(after?.providers ?? {}, id))) {
168
+ throw fail('registration_unverified', 'provider route readback did not match; retry after refreshing settings')
169
+ }
170
+ state.registration = { routes: Object.keys(plan.routes), ns, at: new Date().toISOString(),
171
+ lastStatus: entries.length ? 'registered' : 'unregistered', lastMessage: '' }
172
+ await save()
173
+ }
174
+
175
+ function costFacts() {
176
+ const service = meter ?? ctx.get('costMeter')
177
+ return !service ? { available: false, reason: 'not-installed' }
178
+ : typeof service.registerPriceCalculator !== 'function' || typeof service.getLocalState !== 'function'
179
+ ? { available: false, reason: 'unsupported' } : { available: meter === service, reason: meter === service ? undefined : 'waiting' }
180
+ }
181
+ function costDescription() {
182
+ return { ...costFacts(), automatic: true, enabled: true, refreshMinutes: state.costBinding.refreshMinutes,
183
+ registeredCount: slots.size, confirmedCount: state.confirmed.length,
184
+ conflicts: state.costBinding.conflicts ?? [], unavailable: state.costBinding.unavailable ?? [],
185
+ status: state.costBinding.lastStatus, message: state.costBinding.lastMessage, boundAt: state.costBinding.boundAt }
186
+ }
187
+ /** Pure local read; opening Settings never lists remote Keys or starts a refresh. */
188
+ async function describe() {
189
+ const store = credentials()
190
+ const pat = await store?.describe(PAT_REF).catch(() => ({ configured: false }))
191
+ const keys = []
192
+ for (const key of state.selectedKeys) {
193
+ const info = await store?.describe(keyRef(key.id)).catch(() => ({ configured: false }))
194
+ keys.push({ ...key, credentialConfigured: info?.configured === true || state.legacyKeyId === key.id })
195
+ }
196
+ return { site: { origin, name: 'NikoAPI', version: state.site?.version ?? '', currency: state.site?.currency ?? '', quotaPerUnit: state.site?.quotaPerUnit ?? 500_000 },
197
+ connection: { managementToken: { configured: pat?.configured === true, writable: pat?.writable !== false }, keys, primaryKeyId: keys[0]?.id ?? null },
198
+ keyDirectory: { ...state.keyDirectory, selectedKeys: state.selectedKeys },
199
+ confirmed: state.confirmed, cost: costDescription(), lastSyncedAt: state.lastSyncedAt, modelRegistration: describeRegistration() }
200
+ }
201
+ function removeSlot(id) {
202
+ const slot = slots.get(id)
203
+ if (!slot) return
204
+ slot.active = false
205
+ slots.delete(id)
206
+ try { slot.dispose() } catch { ctx.logger?.warn?.('nikoapi: calculator cleanup failed') }
207
+ }
208
+ function clearCalculators() { for (const id of [...slots.keys()]) removeSlot(id) }
209
+ function validSnapshot(row) {
210
+ const key = state.selectedKeys.find(key => key.id === row.keyId)
211
+ return key?.status === 'enabled' && row.keyIdentity === keyPriceIdentity(key)
212
+ && state.confirmed.some(model => pair(model.keyId, model.modelId) === pair(row.keyId, row.modelId))
213
+ }
214
+ function prunePrices() {
215
+ state.priceSnapshots = state.priceSnapshots.filter(validSnapshot)
216
+ const wanted = new Set(routeEntries(entriesFor()).flatMap(entry => entry.models.map(model => pair(entry.keyId, model.id))))
217
+ for (const id of slots.keys()) if (!wanted.has(id)) removeSlot(id)
218
+ }
219
+ function cachePrices(snapshot) {
220
+ const old = new Map(state.priceSnapshots.filter(validSnapshot).map(row => [pair(row.keyId, row.modelId), row]))
221
+ const next = []
222
+ for (const row of state.confirmed) {
223
+ const key = state.selectedKeys.find(key => key.id === row.keyId)
224
+ if (key?.status !== 'enabled') continue
225
+ const source = snapshot.keys.find(entry => entry.id === row.keyId)
226
+ const model = source?.models.find(entry => entry.modelId === row.modelId)
227
+ // Network failure retains the last known rate only for the unchanged Key/group identity.
228
+ if (!source?.modelsLoaded || source.priceTableLoaded === false) {
229
+ if (model || !source?.modelsLoaded) {
230
+ const prior = old.get(pair(row.keyId, row.modelId))
231
+ if (prior) next.push(prior)
232
+ }
233
+ continue
234
+ }
235
+ if (model && usablePrice(model.price, Date.parse(snapshot.at))) next.push({ keyId: row.keyId, modelId: row.modelId,
236
+ keyIdentity: keyPriceIdentity(key), price: model.price, at: snapshot.at })
237
+ }
238
+ state.priceSnapshots = next
239
+ prunePrices()
240
+ }
241
+ /** Registration only. This never changes cost-meter prices, balances, or recorded bills. */
242
+ async function syncCosts({ stale = false } = {}) {
243
+ prunePrices()
244
+ // Reconcile the one-provider-per-Key route even when the cost-meter service is absent.
245
+ // This also removes legacy protocol-suffix routes recorded as plugin-owned.
246
+ const entries = entriesFor()
247
+ let registration = describeRegistration()
248
+ const wantedRouteIds = routeEntries(entries).map(entry => entry.providerId).sort()
249
+ const recordedRouteIds = [...new Set(state.registration.routes)].sort()
250
+ const ownershipNeedsReconcile = JSON.stringify(wantedRouteIds) !== JSON.stringify(recordedRouteIds)
251
+ const needsRouteWrite = registration.supported && (ownershipNeedsReconcile
252
+ || (entries.length > 0 && (!registration.registered || registration.missing.length > 0)))
253
+ if (needsRouteWrite) {
254
+ try {
255
+ await writeRoutes(entries)
256
+ registration = describeRegistration()
257
+ } catch { registration = describeRegistration() }
258
+ }
259
+ const service = meter
260
+ const epoch = meterEpoch
261
+ if (!service || !costFacts().available) {
262
+ clearCalculators()
263
+ state.costBinding = { ...state.costBinding, registeredCount: 0, conflicts: [], unavailable: [], lastStatus: 'waiting',
264
+ lastMessage: 'waiting for cost-meter 1.9.78 or later' }
265
+ await save()
266
+ return costDescription()
267
+ }
268
+ if (!state.confirmed.length) {
269
+ clearCalculators()
270
+ state.costBinding = { ...state.costBinding, registeredCount: 0, conflicts: [], unavailable: [], lastStatus: 'waiting',
271
+ lastMessage: 'select and confirm models to start automatic pricing' }
272
+ await save()
273
+ return costDescription()
274
+ }
275
+ let current
276
+ try { current = await service.getLocalState() }
277
+ catch { current = null }
278
+ if (disposed || meter !== service || meterEpoch !== epoch) return costDescription()
279
+ if (!current?.config || typeof current.config !== 'object') {
280
+ clearCalculators()
281
+ meterConfig = null
282
+ state.costBinding = { ...state.costBinding, registeredCount: 0, lastStatus: 'error', lastMessage: 'cost configuration is unavailable; user price conflicts could not be checked' }
283
+ await save()
284
+ return costDescription()
285
+ }
286
+ meterConfig = current.config
287
+ if (typeof service.updateConfig === 'function' && meterConfig.billionContextEnabled === true && billionContextEpoch !== epoch) {
288
+ billionContextEpoch = epoch
289
+ try {
290
+ await service.updateConfig({ billionContextEnabled: false })
291
+ meterConfig = { ...meterConfig, billionContextEnabled: false }
292
+ ctx.logger?.info?.('nikoapi: billion-context assistance disabled for cost-meter billing')
293
+ } catch { /* the switch is advisory; price calculators keep working without it */ }
294
+ }
295
+ const routes = new Set(registration.routes)
296
+ const cached = new Map(state.priceSnapshots.map(row => [pair(row.keyId, row.modelId), row]))
297
+ const desired = new Set(), conflicts = [], unavailable = []
298
+ for (const entry of routeEntries(entries)) {
299
+ for (const model of entry.models) {
300
+ const id = pair(entry.keyId, model.id), rate = cached.get(id)
301
+ const label = `${entry.providerId}:${model.id}`
302
+ if (!routes.has(entry.providerId) || !rate || !usablePrice(rate.price, Date.now())) { unavailable.push(label); continue }
303
+ if (hasManualPrice(meterConfig, entry.providerId, model.id, state.costBinding)) { conflicts.push(label); continue }
304
+ desired.add(id)
305
+ const existing = slots.get(id)
306
+ if (existing) { existing.rate = rate; continue }
307
+ const slot = { active: true, rate, dispose: () => {} }
308
+ try {
309
+ const dispose = service.registerPriceCalculator({ provider: entry.providerId, model: model.id, calculate({ usage, atMs }) {
310
+ if (!slot.active || disposed || meter !== service || meterEpoch !== epoch || !validSnapshot(slot.rate)
311
+ || !describeRegistration().routes.includes(entry.providerId)) return null
312
+ return calculatePrice(slot.rate.price, usage, atMs)
313
+ } })
314
+ if (typeof dispose !== 'function') throw new Error('calculator registration did not return a disposer')
315
+ slot.dispose = dispose
316
+ slots.set(id, slot)
317
+ } catch {
318
+ slot.active = false
319
+ desired.delete(id)
320
+ conflicts.push(label)
321
+ }
322
+ }
323
+ }
324
+ for (const id of [...slots.keys()]) if (!desired.has(id)) removeSlot(id)
325
+ const count = slots.size
326
+ const status = !state.confirmed.length ? 'waiting' : !count ? 'pending'
327
+ : stale ? 'bound-stale' : conflicts.length || unavailable.length ? 'bound-partial' : 'bound'
328
+ state.costBinding = { ...state.costBinding, enabled: true, registeredCount: count, conflicts, unavailable,
329
+ boundAt: count ? new Date().toISOString() : state.costBinding.boundAt, lastStatus: status,
330
+ lastMessage: [!state.confirmed.length ? 'select and confirm models to start automatic pricing' : '',
331
+ conflicts.length ? `${conflicts.length} existing user price(s) or calculator owner(s) kept` : '',
332
+ unavailable.length ? `${unavailable.length} model(s) await a valid route or exact rate` : '',
333
+ stale ? 'refresh incomplete; unchanged Keys retain their last known rates' : ''].filter(Boolean).join('; ') }
334
+ await save()
335
+ return costDescription()
336
+ }
337
+
338
+ async function listKeys() {
339
+ const pat = await requirePat(), client = niko()
340
+ const [site, result, auto, pricing] = await Promise.all([client.status(), client.allKeys(pat),
341
+ client.autoGroups(pat).catch(() => ({ groups: [], maxCount: null })),
342
+ client.pricing(pat).catch(() => ({ rows: [], groupRatio: {}, usableGroup: {}, autoGroups: [] }))])
343
+ state.site = { version: site.version, currency: site.displayCurrency, quotaPerUnit: site.quotaPerUnit, usdExchangeRate: site.usdExchangeRate }
344
+ const fresh = new Map(result.items.map(key => [key.id, key]))
345
+ let identityChanged = false
346
+ state.selectedKeys = state.selectedKeys.map(key => {
347
+ const next = fresh.get(key.id)
348
+ const metadata = next ? keyMetadata(next) : { ...key, status: 'missing' }
349
+ identityChanged ||= keyPriceIdentity(key) !== keyPriceIdentity(metadata)
350
+ return metadata
351
+ })
352
+ if (identityChanged) {
353
+ bump(); prunePrices()
354
+ await writeRoutes(entriesFor())
355
+ }
356
+ const groups = normalizeGroups({ usableGroup: pricing.usableGroup, groupRatio: pricing.groupRatio })
357
+ state.lastSyncedAt = new Date().toISOString()
358
+ state.keyDirectory = { keys: result.items.map(directoryKeyMetadata).filter(Boolean), total: result.total, complete: true,
359
+ autoGroups: auto.groups, autoGroupLimit: auto.maxCount, groups, groupDescriptions: groups.some(group => group.desc !== ''), at: state.lastSyncedAt }
360
+ await save()
361
+ if (identityChanged && state.confirmed.length) await previewModels({ force: true })
362
+ else await syncCosts()
363
+ return { site, ...state.keyDirectory, selectedKeys: state.selectedKeys }
364
+ }
365
+ async function connect({ managementToken }) {
366
+ if (typeof managementToken !== 'string' || !managementToken.trim()) throw fail('bad_input', 'management token is empty')
367
+ const token = managementToken.trim()
368
+ await niko().listKeys(token, { size: 1 })
369
+ await credentials().set(PAT_REF, token)
370
+ bump()
371
+ return listKeys()
372
+ }
373
+ async function selectKeys({ keys }) {
374
+ if (!Array.isArray(keys) || keys.some(key => !Number.isSafeInteger(key?.id) || key.id <= 0)) throw fail('bad_input', 'invalid Key selection')
375
+ const ids = [...new Set(keys.map(key => key.id))], store = credentials()
376
+ if (!ids.length) {
377
+ clearCalculators()
378
+ if (state.registration.routes.length) await writeRoutes([])
379
+ const previous = state.selectedKeys
380
+ state.selectedKeys = []; state.confirmed = []; state.priceSnapshots = []; state.legacyKeyId = null
381
+ bump()
382
+ for (const key of previous) await store?.unset(keyRef(key.id))
383
+ await store?.unset(API_KEY_ENV)
384
+ await syncCosts()
385
+ return { ...(await describe()), failed: [] }
386
+ }
387
+ const pat = await requirePat()
388
+ const result = await niko().allKeys(pat)
389
+ const known = new Map(result.items.map(key => [key.id, key]))
390
+ const invalid = ids.find(id => !known.has(id) || known.get(id).status !== 'enabled')
391
+ if (invalid !== undefined) throw fail('bad_input', `Key #${invalid} is absent or not enabled; refresh the Key list`)
392
+ const selected = [], staged = new Map(), failed = []
393
+ for (const id of ids) {
394
+ try {
395
+ const existing = state.selectedKeys.find(key => key.id === id)
396
+ const configured = await store.describe(keyRef(id)).catch(() => ({ configured: false }))
397
+ if (configured.configured === true && existing) { selected.push(keyMetadata(known.get(id))); continue }
398
+ if (state.legacyKeyId === id) {
399
+ const legacy = await store.resolve(API_KEY_ENV)
400
+ if (legacy?.value) { staged.set(id, legacy.value); selected.push(keyMetadata(known.get(id))); continue }
401
+ }
402
+ staged.set(id, await niko().revealKey(pat, id))
403
+ selected.push(keyMetadata(known.get(id)))
404
+ } catch (error) { failed.push({ id, name: known.get(id).name, message: safeFailure(error).message }) }
405
+ }
406
+ if (failed.length) throw fail('key_missing', `could not securely select every Key; selection was left unchanged (${failed.map(row => `${row.name}: ${row.message}`).join('; ')})`)
407
+ const previous = state.selectedKeys
408
+ for (const [id, secret] of staged) await store.set(keyRef(id), secret)
409
+ state.selectedKeys = selected
410
+ state.confirmed = state.confirmed.filter(row => selected.some(key => key.id === row.keyId))
411
+ state.legacyKeyId = null
412
+ bump(); prunePrices()
413
+ if (state.registration.routes.length || state.confirmed.length) await writeRoutes(entriesFor())
414
+ await save()
415
+ for (const key of previous) if (!selected.some(next => next.id === key.id)) {
416
+ await store.unset(keyRef(key.id))
417
+ }
418
+ await syncCosts()
419
+ return { ...(await describe()), failed }
420
+ }
421
+ async function setGroup({ keyId, group, autoGroups, crossGroupRetry }) {
422
+ if (!Number.isSafeInteger(keyId) || keyId <= 0 || typeof group !== 'string' || !group.trim()) throw fail('bad_input', 'invalid Key or group')
423
+ const pat = await requirePat()
424
+ const source = (await niko().allKeys(pat)).items.find(key => key.id === keyId)
425
+ if (!source) throw fail('bad_input', 'Key is no longer available')
426
+ const nextGroup = group.trim()
427
+ try {
428
+ await niko().updateGroup(pat, keyId, { group: nextGroup,
429
+ autoGroups: Array.isArray(autoGroups) ? autoGroups.filter(value => typeof value === 'string') : source.autoGroups,
430
+ crossGroupRetry: typeof crossGroupRetry === 'boolean' ? crossGroupRetry : source.crossGroupRetry })
431
+ const updated = (await niko().allKeys(pat)).items.find(key => key.id === keyId)
432
+ if (!updated || updated.group !== nextGroup) throw fail('upstream', 'updated Key metadata was not confirmed; refresh the list')
433
+ // Changing pricing identity invalidates only this Key's rates; its explicit model choices remain.
434
+ state.priceSnapshots = state.priceSnapshots.filter(row => row.keyId !== keyId)
435
+ prunePrices()
436
+ state.selectedKeys = state.selectedKeys.map(key => key.id === keyId ? keyMetadata(updated) : key)
437
+ state.keyDirectory.keys = state.keyDirectory.keys.map(key => key.id === keyId ? directoryKeyMetadata(updated) : key)
438
+ if (state.registration.routes.length) await writeRoutes(entriesFor())
439
+ bump(); await save()
440
+ await previewModels({ force: true })
441
+ return { key: directoryKeyMetadata(updated), selectedKeys: state.selectedKeys }
442
+ } catch (error) {
443
+ const refreshed = (await niko().allKeys(pat).catch(() => ({ items: [] }))).items.find(key => key.id === keyId)
444
+ if (refreshed) {
445
+ state.selectedKeys = state.selectedKeys.map(key => key.id === keyId ? keyMetadata(refreshed) : key)
446
+ state.keyDirectory.keys = state.keyDirectory.keys.map(key => key.id === keyId ? directoryKeyMetadata(refreshed) : key)
447
+ if (state.registration.routes.length) await writeRoutes(entriesFor())
448
+ bump(); await save(); await syncCosts({ stale: true })
449
+ }
450
+ throw error
451
+ }
452
+ }
453
+
454
+ async function previewModels({ force = false } = {}) {
455
+ if (!force && preview) return preview
456
+ const pat = await requirePat(), client = niko()
457
+ const freshSite = await client.status()
458
+ state.site = { version: freshSite.version, currency: freshSite.displayCurrency, quotaPerUnit: freshSite.quotaPerUnit, usdExchangeRate: freshSite.usdExchangeRate }
459
+ const table = await client.pricing(pat, { requireIdentity: true }).catch(() => null)
460
+ const currency = state.site?.currency || 'USD', keys = []
461
+ for (const key of state.selectedKeys) {
462
+ const entry = { id: key.id, name: key.name, group: key.group, usage: null, models: [], error: '', modelsLoaded: false, priceTableLoaded: table !== null }
463
+ try {
464
+ if (key.status !== 'enabled') throw fail('key_missing', `Key #${key.id} is not enabled; refresh the Key list`)
465
+ const credential = await requireKey(key.id)
466
+ const [usage, models] = await Promise.all([client.usage(credential).catch(() => null), client.listModels(credential)])
467
+ entry.usage = usage; entry.modelsLoaded = true
468
+ const autoGroups = Array.isArray(key.autoGroups) && key.autoGroups.length ? key.autoGroups : (Array.isArray(table?.autoGroups) ? table.autoGroups : [])
469
+ const candidates = key.group === 'auto' ? autoGroups : key.group ? [key.group] : []
470
+ const prices = table === null ? new Map() : normalizePricing(table.rows, { groupRatio: table.groupRatio,
471
+ quotaPerUnit: state.site?.quotaPerUnit ?? 500_000, usdExchangeRate: state.site?.usdExchangeRate ?? 1, currency,
472
+ candidateGroups: candidates, reference: key.group === 'auto', unknownGroup: !key.group || (key.group === 'auto' && !candidates.length) })
473
+ entry.models = [...new Map(models.map(model => [model.id, model])).values()].map(model => {
474
+ const prior = state.confirmed.find(row => row.keyId === key.id && row.modelId === model.id)
475
+ const pricingRows = table?.rows?.filter(row => row?.model_name === model.id) ?? []
476
+ const pricingEndpoints = [...new Set(pricingRows.flatMap(row => Array.isArray(row?.supported_endpoint_types) ? row.supported_endpoint_types : []))]
477
+ const supportedEndpoints = model.supportedEndpoints ?? (pricingEndpoints.length ? pricingEndpoints : null)
478
+ return { modelId: model.id, name: model.name, supportedEndpoints,
479
+ ...modelCapabilities({ input: model.inputModalities, reasoningEfforts: model.reasoningEfforts }),
480
+ // Preserve whether the upstream API explicitly declared a reasoning-efforts policy.
481
+ // null means "not declared"; false means "declared as unsupported". Both differ from
482
+ // an object with levels. buildProviderRoute uses this to default anthropic-messages
483
+ // routes to false only when the server never declared a policy.
484
+ reasoningEffortsDeclared: model.reasoningEfforts !== null && model.reasoningEfforts !== undefined,
485
+ price: prices.get(model.id) ?? { kind: 'unknown', currency, note: table === null ? 'price table unavailable for this Key' : 'no exact applicable price' },
486
+ confirmed: Boolean(prior) }
487
+ }).filter(isLlmModel)
488
+ } catch (error) { entry.error = safeFailure(error).message }
489
+ keys.push(entry)
490
+ }
491
+ if (disposed) throw fail('disposed', 'plugin is no longer active')
492
+
493
+ const knownGroups = [...new Set([
494
+ ...Object.keys(table?.groupRatio ?? {}),
495
+ ...keys.flatMap(entry => [entry.group, ...(state.selectedKeys.find(key => key.id === entry.id)?.autoGroups ?? [])]),
496
+ ].filter(group => typeof group === 'string' && group && group !== 'auto'))]
497
+ const modelProtocolRows = keys.flatMap(entry => {
498
+ const key = state.selectedKeys.find(row => row.id === entry.id)
499
+ if (!key || key.group === 'auto') return []
500
+ return entry.models.map(model => ({ group: key.group, supportedEndpoints: model.supportedEndpoints }))
501
+ })
502
+ const protocolGroups = groupProtocolMap([...(table?.rows ?? []), ...modelProtocolRows], knownGroups)
503
+ const groupsFor = key => key.group === 'auto'
504
+ ? (Array.isArray(key.autoGroups) && key.autoGroups.length ? key.autoGroups : table?.autoGroups ?? [])
505
+ : [key.group]
506
+ const groupSetKnown = key => {
507
+ const groups = groupsFor(key).filter(group => typeof group === 'string' && group && group !== 'auto')
508
+ return groups.length > 0 && groups.every(group => protocolGroups.has(group) && protocolGroups.get(group).length > 0)
509
+ }
510
+ const identityFor = key => protocolIdentityFor(key)
511
+ for (const entry of keys) {
512
+ const key = state.selectedKeys.find(row => row.id === entry.id)
513
+ if (!key) continue
514
+ entry.protocolGroups = Object.fromEntries([...protocolGroups].map(([group, values]) => [group, values]))
515
+ for (const model of entry.models) {
516
+ const prior = state.confirmed.find(row => row.keyId === key.id && row.modelId === model.modelId)
517
+ const sameIdentity = prior?.protocolIdentity === identityFor(key)
518
+ if (!Array.isArray(model.supportedEndpoints) && sameIdentity) model.supportedEndpoints = prior.supportedEndpoints
519
+ const known = groupSetKnown(key) && isLlmModel(model)
520
+ const reusable = sameIdentity ? normalizeProtocols(prior.protocols) : []
521
+ const routingKey = key.group === 'auto' ? { ...key, autoGroups: groupsFor(key) } : key
522
+ model.protocols = known ? modelProtocols(model, routingKey, protocolGroups) : reusable.length ? reusable : ['openai-completions']
523
+ model.protocolIdentity = identityFor(key)
524
+ }
525
+ }
526
+ const confirmedProtocolSignature = rows => JSON.stringify(rows.map(row => [row.keyId, row.modelId, normalizeProtocols(row.protocols), row.protocolIdentity]))
527
+ const previousConfirmed = confirmedProtocolSignature(state.confirmed)
528
+ const discovered = new Map(keys.flatMap(key => key.models.map(model => [pair(key.id, model.modelId), model])))
529
+ state.confirmed = state.confirmed.map(row => {
530
+ const model = discovered.get(pair(row.keyId, row.modelId))
531
+ if (!model) return row
532
+ return { ...row, name: model.name, supportedEndpoints: model.supportedEndpoints ?? [], protocols: normalizeProtocols(model.protocols),
533
+ protocolIdentity: model.protocolIdentity }
534
+ })
535
+ state.protocolGroups = Object.fromEntries([...protocolGroups].map(([group, values]) => [group, normalizeProtocols(values)]))
536
+ const protocolChanged = previousConfirmed !== confirmedProtocolSignature(state.confirmed)
537
+ if (protocolChanged && state.registration.routes.length) await writeRoutes(entriesFor())
538
+ preview = { keys, groups: normalizeGroups({ usableGroup: table?.usableGroup, groupRatio: table?.groupRatio }), confirmed: state.confirmed, site: state.site, at: new Date().toISOString() }
539
+ cachePrices(preview)
540
+ await syncCosts({ stale: table === null || keys.some(key => !key.modelsLoaded) })
541
+ return { ...preview, cost: costDescription() }
542
+ }
543
+ async function registerModels() {
544
+ if (!state.confirmed.length) throw fail('models_none', 'confirm at least one model first')
545
+ await writeRoutes(entriesFor())
546
+ await syncCosts()
547
+ return describeRegistration()
548
+ }
549
+ async function unregisterModels() {
550
+ clearCalculators()
551
+ await writeRoutes([])
552
+ state.confirmed = []; state.priceSnapshots = []
553
+ bump()
554
+ await syncCosts()
555
+ return describeRegistration()
556
+ }
557
+ async function confirmModels({ selections }) {
558
+ if (!Array.isArray(selections) || selections.some(row => !Number.isSafeInteger(row?.keyId) || !Array.isArray(row.modelIds) || row.modelIds.some(id => typeof id !== 'string' || !id))) throw fail('bad_input', 'invalid model selection')
559
+ const snapshot = await previewModels()
560
+ const errored = snapshot.keys.find(key => key.error)
561
+ if (errored) throw fail('model_preview_failed', `model preview failed for Key #${errored.id}; refresh it before changing registered models`)
562
+ const known = new Map(snapshot.keys.flatMap(key => key.models.map(model => [pair(key.id, model.modelId), model]))), rows = new Map()
563
+ for (const entry of selections) {
564
+ if (!state.selectedKeys.some(key => key.id === entry.keyId)) throw fail('bad_input', 'selection includes a Key that is not active')
565
+ for (const modelId of entry.modelIds) {
566
+ const model = known.get(pair(entry.keyId, modelId))
567
+ if (!model) throw fail('bad_input', 'a selected model is not in this Key preview; refresh the preview')
568
+ const key = state.selectedKeys.find(item => item.id === entry.keyId)
569
+ rows.set(pair(entry.keyId, modelId), { keyId: entry.keyId, modelId, name: model.name,
570
+ supportedEndpoints: Array.isArray(model.supportedEndpoints) ? model.supportedEndpoints : [],
571
+ protocols: normalizeProtocols(model.protocols).length ? normalizeProtocols(model.protocols) : ['openai-completions'],
572
+ protocolIdentity: typeof model.protocolIdentity === 'string' ? model.protocolIdentity : protocolIdentityFor(key),
573
+ reasoningEffortsDeclared: model.reasoningEffortsDeclared === true,
574
+ ...modelCapabilities(model) })
575
+ }
576
+ }
577
+ state.confirmed = [...rows.values()]
578
+ prunePrices()
579
+ await save()
580
+ try { await writeRoutes(entriesFor()) }
581
+ catch (error) { const failure = safeFailure(error); state.registration.lastStatus = 'error'; state.registration.lastMessage = failure.message; await save() }
582
+ preview = { ...snapshot, confirmed: state.confirmed }
583
+ cachePrices(preview)
584
+ await syncCosts({ stale: snapshot.keys.some(key => !key.priceTableLoaded) })
585
+ return { confirmed: state.confirmed, registration: describeRegistration(), cost: costDescription() }
586
+ }
587
+ /** Kept as a compatible endpoint name; only the interval is saved, no opt-in gate. */
588
+ async function saveCostBinding({ refreshMinutes }) {
589
+ if (refreshMinutes !== undefined && (!Number.isFinite(refreshMinutes) || refreshMinutes < 1 || refreshMinutes > 1440)) throw fail('bad_input', 'refresh interval must be between 1 and 1440 minutes')
590
+ if (refreshMinutes !== undefined) state.costBinding.refreshMinutes = Math.round(refreshMinutes)
591
+ await syncCosts()
592
+ return { cost: costDescription() }
593
+ }
594
+ async function refresh() {
595
+ const snapshot = await previewModels({ force: true })
596
+ return { ...snapshot, cost: costDescription() }
597
+ }
598
+ async function disconnect() {
599
+ clearCalculators()
600
+ await writeRoutes([])
601
+ const store = credentials()
602
+ for (const key of state.selectedKeys) await store.unset(keyRef(key.id))
603
+ await store.unset(API_KEY_ENV); await store.unset(PAT_REF)
604
+ state = emptyState(); bump()
605
+ await save()
606
+ return describe()
607
+ }
608
+
609
+ function enqueue(work) {
610
+ const result = queue.then(async () => {
611
+ await ready
612
+ if (loadError) throw fail('state_unavailable', loadError.message)
613
+ if (disposed) throw fail('disposed', 'plugin is no longer active')
614
+ return work()
615
+ })
616
+ queue = result.catch(() => {})
617
+ return result
618
+ }
619
+ function scheduleCostSync(refreshIfStale = false) {
620
+ if (disposed) return
621
+ startupRefresh ||= refreshIfStale
622
+ syncRequested = true
623
+ if (syncScheduled) return
624
+ syncScheduled = true
625
+ void enqueue(async () => {
626
+ do {
627
+ syncRequested = false
628
+ const shouldRefresh = startupRefresh
629
+ startupRefresh = false
630
+ await syncCosts()
631
+ const snapshots = new Map(state.priceSnapshots.map(row => [pair(row.keyId, row.modelId), row]))
632
+ const stale = state.confirmed.some(row => {
633
+ const at = Date.parse(snapshots.get(pair(row.keyId, row.modelId))?.at)
634
+ return !Number.isFinite(at) || Date.now() - at >= state.costBinding.refreshMinutes * 60_000
635
+ })
636
+ if (!disposed && shouldRefresh && meter && state.confirmed.length && stale) {
637
+ try { await previewModels({ force: true }) }
638
+ catch { await syncCosts({ stale: true }) }
639
+ }
640
+ } while (!disposed && syncRequested)
641
+ }).catch(() => {}).finally(() => {
642
+ syncScheduled = false
643
+ if (!disposed && syncRequested) scheduleCostSync()
644
+ })
645
+ }
646
+ const operations = { describe, connect, disconnect, listKeys, selectKeys, setGroup, previewModels, confirmModels, registerModels, unregisterModels, saveCostBinding, refresh }
647
+ function dispatch(method, params) {
648
+ if (typeof method !== 'string' || !Object.hasOwn(operations, method)) return Promise.reject(fail('unknown_method', 'unknown NikoAPI operation'))
649
+ if (params !== undefined && (params === null || typeof params !== 'object' || Array.isArray(params))) return Promise.reject(fail('bad_input', 'operation parameters must be an object'))
650
+ // Local reads do not wait behind an unrelated remote refresh.
651
+ if (method === 'describe') return ready.then(() => {
652
+ if (loadError) throw fail('state_unavailable', loadError.message)
653
+ if (disposed) throw fail('disposed', 'plugin is no longer active')
654
+ return describe()
655
+ })
656
+ return enqueue(() => operations[method](params ?? {}))
657
+ }
658
+ ctx.inject(['webServer'], web => {
659
+ web.effect(() => web.webServer.register({ kind: 'prefix', path: '/nikoapi/api', handler: async (req, res) => {
660
+ if (!isTrustedRequest(req, ctx.get('webStartup')?.trustedHosts ?? [])) return sendJson(res, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } })
661
+ if (req.method !== 'POST') { res.writeHead(405, { allow: 'POST' }); res.end(); return }
662
+ if (!String(headerOf(req.headers, 'content-type') ?? '').toLowerCase().startsWith('application/json')) return sendJson(res, 400, { ok: false, error: { code: 'bad_body', message: 'JSON content-type required' } })
663
+ let payload
664
+ try { payload = await readJsonBody(req) } catch { return sendJson(res, 400, { ok: false, error: { code: 'bad_body', message: 'request must be JSON under 256 KiB' } }) }
665
+ try { sendJson(res, 200, { ok: true, data: await dispatch(payload?.method, payload?.params) }) }
666
+ catch (error) {
667
+ const failure = safeFailure(error)
668
+ const operation = typeof payload?.method === 'string' && Object.hasOwn(operations, payload.method) ? payload.method : 'unknown'
669
+ const diagnostic = failureDiagnosticFields(operation, error, failure.code)
670
+ ctx.logger?.warn?.(formatFailureDiagnostic(operation, error, failure.code))
671
+ sendJson(res, ['unknown_method', 'bad_input'].includes(failure.code) ? 400 : 200, { ok: false, error: {
672
+ code: failure.code, message: failure.message, scope: failure.scope,
673
+ diagnostic: { method: diagnostic.operation, errorType: diagnostic.errorName, errorCode: diagnostic.errorCode },
674
+ } })
675
+ }
676
+ } }), 'nikoapi: web api')
677
+ })
678
+ ctx.inject(['costMeter'], linked => {
679
+ linked.effect(() => {
680
+ const service = linked.get('costMeter')
681
+ if (typeof service?.registerPriceCalculator !== 'function' || typeof service?.getLocalState !== 'function') return
682
+ clearCalculators()
683
+ meter = service; meterConfig = null; meterEpoch++
684
+ scheduleCostSync(true)
685
+ return () => {
686
+ if (meter !== service) return
687
+ meterEpoch++; meter = null; meterConfig = null
688
+ clearCalculators()
689
+ state.costBinding.lastStatus = 'waiting'
690
+ state.costBinding.lastMessage = 'waiting for cost-meter 1.9.78 or later'
691
+ }
692
+ }, 'nikoapi: official price calculators')
693
+ })
694
+ ctx.on?.('settings/document-updated', (ns, revision) => {
695
+ if (ownRouteRevision?.ns === ns && ownRouteRevision.revision === revision) { ownRouteRevision = null; return }
696
+ if (ns === providerNamespace()) scheduleCostSync()
697
+ })
698
+ ctx.effect(() => {
699
+ let lastTimer = Date.now(), timerPending = false
700
+ const timer = setInterval(() => {
701
+ if (disposed || timerPending || !meter || !state.confirmed.length || Date.now() - lastTimer < state.costBinding.refreshMinutes * 60_000) return
702
+ timerPending = true; lastTimer = Date.now()
703
+ void dispatch('refresh').catch(() => enqueue(() => syncCosts({ stale: true })).catch(() => {})).finally(() => { timerPending = false })
704
+ }, 30_000)
705
+ timer.unref?.()
706
+ return () => { disposed = true; clearInterval(timer); meterEpoch++; clearCalculators(); meter = null; meterConfig = null }
707
+ }, 'nikoapi: refresh timer')
708
+ }
709
+
710
+ function headerOf(headers, name) { const value = headers?.[name]; return Array.isArray(value) ? value[0] : typeof value === 'string' ? value : undefined }
711
+ function loopback(host) { return ['localhost', '127.0.0.1', '[::1]', '::1'].includes(host.toLowerCase()) }
712
+ export function isTrustedRequest(req, trustedHosts = []) {
713
+ const host = headerOf(req.headers, 'host')
714
+ if (!host || /[\s\/@?#]/.test(host)) return false
715
+ try {
716
+ const expected = new URL(`${req.socket?.encrypted ? 'https:' : 'http:'}//${host}`)
717
+ const trusted = Array.isArray(trustedHosts) && trustedHosts.some(value => typeof value === 'string' && value.toLowerCase() === expected.host.toLowerCase())
718
+ if (!loopback(expected.hostname) && !trusted) return false
719
+ if (headerOf(req.headers, 'sec-fetch-site') === 'cross-site') return false
720
+ const raw = headerOf(req.headers, 'origin')
721
+ if (!raw) return !headerOf(req.headers, 'sec-fetch-site')
722
+ const requestOrigin = new URL(raw)
723
+ return requestOrigin.origin === expected.origin && requestOrigin.href === `${requestOrigin.origin}/` && !requestOrigin.username && !requestOrigin.password
724
+ } catch { return false }
725
+ }
726
+ function sendJson(res, status, data) {
727
+ const body = JSON.stringify(data)
728
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(body) })
729
+ res.end(body)
730
+ }
731
+ async function readJsonBody(req) {
732
+ const chunks = []; let size = 0
733
+ for await (const chunk of req) { size += chunk.length; if (size > MAX_BODY_BYTES) throw new Error('body too large'); chunks.push(chunk) }
734
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
735
+ }
736
+ export { hasExpressionBilling }