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