dsh-nikoapi 0.1.0 → 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/README.en.md +1 -1
- package/README.md +1 -1
- package/index.js +15 -0
- package/lib/billing-expression.js +431 -431
- package/lib/costmeter.js +47 -0
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**English** · [简体中文](README.md)
|
|
4
4
|
|
|
5
|
-
  
|
|
6
6
|
|
|
7
7
|
## Foreword
|
|
8
8
|
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[English](README.en.md) · **简体中文**
|
|
4
4
|
|
|
5
|
-
  
|
|
6
6
|
|
|
7
7
|
## 前言
|
|
8
8
|
|
package/index.js
CHANGED
|
@@ -5,6 +5,7 @@ import { normalizeGroups } from './lib/groups.js'
|
|
|
5
5
|
import { calculatePrice, hasManualPrice, usablePrice } from './lib/price-calculator.js'
|
|
6
6
|
import { API_KEY_ENV, findProvidersNamespace, isLlmModel, keyRef, keyRoute, groupProtocolMap, modelCapabilities, modelProtocols, normalizeProtocols, planRoutes, registrationStatus, routeEntries } from './lib/models.js'
|
|
7
7
|
import { readState, writeState, emptyState, keyMetadata, directoryKeyMetadata, keyPriceIdentity } from './lib/state.js'
|
|
8
|
+
import { planBalanceBinding } from './lib/costmeter.js'
|
|
8
9
|
import { HttpError } from './lib/http.js'
|
|
9
10
|
|
|
10
11
|
export const name = 'nikoapi'
|
|
@@ -292,6 +293,20 @@ export function apply(ctx, config = {}) {
|
|
|
292
293
|
ctx.logger?.info?.('nikoapi: billion-context assistance disabled for cost-meter billing')
|
|
293
294
|
} catch { /* the switch is advisory; price calculators keep working without it */ }
|
|
294
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
|
+
}
|
|
295
310
|
const routes = new Set(registration.routes)
|
|
296
311
|
const cached = new Map(state.priceSnapshots.map(row => [pair(row.keyId, row.modelId), row]))
|
|
297
312
|
const desired = new Set(), conflicts = [], unavailable = []
|
|
@@ -1,431 +1,431 @@
|
|
|
1
|
-
const zeroUsageVars = new Set(['cc1h', 'cc12h', 'img', 'img_cr', 'img_o', 'ai', 'ao', 'image_count'])
|
|
2
|
-
const tokenVars = new Set(['p', 'c', 'len', 'cr', 'cc', ...zeroUsageVars])
|
|
3
|
-
const billedTokenVars = new Set(['p', 'c', 'cr', 'cc'])
|
|
4
|
-
const functionNames = new Set(['tier', 'fixed', 'u', 'param', 'header', 'has', 'hour', 'minute', 'weekday', 'month', 'day', 'max', 'min', 'abs', 'ceil', 'floor', 'when'])
|
|
5
|
-
const maxExpressionLength = 16_384
|
|
6
|
-
const maxTokens = 4_096
|
|
7
|
-
const maxDepth = 64
|
|
8
|
-
const compiled = new Map()
|
|
9
|
-
|
|
10
|
-
export class NikoBillingExpressionError extends Error {
|
|
11
|
-
constructor(code, message) { super(message); this.name = 'NikoBillingExpressionError'; this.code = code }
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
function fail(code, message) { throw new NikoBillingExpressionError(code, message) }
|
|
15
|
-
function finite(value) { return typeof value === 'number' && Number.isFinite(value) }
|
|
16
|
-
|
|
17
|
-
function tokenize(source) {
|
|
18
|
-
if (typeof source !== 'string' || source.length === 0 || source.length > maxExpressionLength) fail('invalid_expression', 'expression is empty or exceeds the size limit')
|
|
19
|
-
const rows = []
|
|
20
|
-
let i = 0
|
|
21
|
-
while (i < source.length) {
|
|
22
|
-
const char = source[i]
|
|
23
|
-
if (/\s/.test(char)) { i++; continue }
|
|
24
|
-
const pair = source.slice(i, i + 2)
|
|
25
|
-
const triple = source.slice(i, i + 3)
|
|
26
|
-
if (['|||', '&&', '||', '==', '!=', '<=', '>='].includes(triple) || ['&&', '||', '==', '!=', '<=', '>='].includes(pair)) {
|
|
27
|
-
rows.push(triple === '|||' ? { kind: 'separator', value: triple } : { kind: 'operator', value: triple.length === 2 ? triple : pair })
|
|
28
|
-
i += triple === '|||' ? 3 : 2
|
|
29
|
-
} else if ('+-*/%<>!?:(),'.includes(char)) {
|
|
30
|
-
rows.push({ kind: 'operator', value: char }); i++
|
|
31
|
-
} else if (char === '"') {
|
|
32
|
-
const start = i++
|
|
33
|
-
let escaped = false
|
|
34
|
-
while (i < source.length) {
|
|
35
|
-
const current = source[i++]
|
|
36
|
-
if (escaped) escaped = false
|
|
37
|
-
else if (current === '\\') escaped = true
|
|
38
|
-
else if (current === '"') break
|
|
39
|
-
}
|
|
40
|
-
if (source[i - 1] !== '"') fail('invalid_expression', 'unterminated string literal')
|
|
41
|
-
let value
|
|
42
|
-
try { value = JSON.parse(source.slice(start, i)) } catch { fail('invalid_expression', 'invalid string literal') }
|
|
43
|
-
rows.push({ kind: 'literal', value })
|
|
44
|
-
} else if (/[0-9.]/.test(char)) {
|
|
45
|
-
const match = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(source.slice(i))
|
|
46
|
-
if (!match) fail('invalid_expression', 'invalid numeric literal')
|
|
47
|
-
const value = Number(match[0])
|
|
48
|
-
if (!finite(value)) fail('invalid_expression', 'numeric literal must be finite')
|
|
49
|
-
rows.push({ kind: 'literal', value }); i += match[0].length
|
|
50
|
-
} else if (/[A-Za-z_]/.test(char)) {
|
|
51
|
-
const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i))[0]
|
|
52
|
-
rows.push({ kind: 'identifier', value: match }); i += match.length
|
|
53
|
-
} else fail('invalid_expression', `unsupported character at offset ${i}`)
|
|
54
|
-
if (rows.length > maxTokens) fail('invalid_expression', 'expression has too many tokens')
|
|
55
|
-
}
|
|
56
|
-
rows.push({ kind: 'end', value: '' })
|
|
57
|
-
return rows
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const precedence = new Map([['||', 1], ['&&', 2], ['==', 3], ['!=', 3], ['<', 4], ['<=', 4], ['>', 4], ['>=', 4], ['+', 5], ['-', 5], ['*', 6], ['/', 6], ['%', 6]])
|
|
61
|
-
|
|
62
|
-
function parsePart(source) {
|
|
63
|
-
const tokens = tokenize(source)
|
|
64
|
-
let cursor = 0, nodes = 0
|
|
65
|
-
const peek = () => tokens[cursor]
|
|
66
|
-
const take = () => tokens[cursor++]
|
|
67
|
-
const node = value => {
|
|
68
|
-
if (++nodes > maxTokens) fail('invalid_expression', 'expression has too many nodes')
|
|
69
|
-
const children = [value.left, value.right, value.test, value.yes, value.no, value.value?.type ? value.value : null, ...(value.args ?? [])].filter(Boolean)
|
|
70
|
-
value.height = 1 + Math.max(0, ...children.map(child => child.height ?? 0))
|
|
71
|
-
if (value.height > maxDepth) fail('invalid_expression', 'expression AST exceeds the nesting limit')
|
|
72
|
-
return value
|
|
73
|
-
}
|
|
74
|
-
function primary(depth) {
|
|
75
|
-
if (depth > maxDepth) fail('invalid_expression', 'expression nesting exceeds the limit')
|
|
76
|
-
const token = take()
|
|
77
|
-
if (token.kind === 'literal') return node({ type: 'literal', value: token.value })
|
|
78
|
-
if (token.kind === 'identifier') {
|
|
79
|
-
if (token.value === 'true' || token.value === 'false') return node({ type: 'literal', value: token.value === 'true' })
|
|
80
|
-
if (peek().value !== '(') {
|
|
81
|
-
if (!tokenVars.has(token.value)) fail('invalid_expression', `unknown identifier ${token.value}`)
|
|
82
|
-
return node({ type: 'variable', name: token.value })
|
|
83
|
-
}
|
|
84
|
-
if (!functionNames.has(token.value)) fail('invalid_expression', `unsupported function ${token.value}`)
|
|
85
|
-
take()
|
|
86
|
-
const args = []
|
|
87
|
-
if (peek().value !== ')') {
|
|
88
|
-
do { args.push(expression(0, depth + 1)); if (peek().value !== ',') break; take() } while (true)
|
|
89
|
-
}
|
|
90
|
-
if (take().value !== ')') fail('invalid_expression', 'expected closing parenthesis')
|
|
91
|
-
return node({ type: 'call', name: token.value, args })
|
|
92
|
-
}
|
|
93
|
-
if (token.value === '(') {
|
|
94
|
-
const result = expression(0, depth + 1)
|
|
95
|
-
if (take().value !== ')') fail('invalid_expression', 'expected closing parenthesis')
|
|
96
|
-
return result
|
|
97
|
-
}
|
|
98
|
-
if (['+', '-', '!'].includes(token.value)) return node({ type: 'unary', op: token.value, value: primary(depth + 1) })
|
|
99
|
-
fail('invalid_expression', 'expected a value')
|
|
100
|
-
}
|
|
101
|
-
function expression(min, depth) {
|
|
102
|
-
let left = primary(depth)
|
|
103
|
-
while (peek().kind === 'operator' && precedence.has(peek().value) && precedence.get(peek().value) >= min) {
|
|
104
|
-
const op = take().value, p = precedence.get(op)
|
|
105
|
-
left = node({ type: 'binary', op, left, right: expression(p + 1, depth + 1) })
|
|
106
|
-
}
|
|
107
|
-
if (min === 0 && peek().value === '?') {
|
|
108
|
-
take()
|
|
109
|
-
const yes = expression(0, depth + 1)
|
|
110
|
-
if (take().value !== ':') fail('invalid_expression', 'expected colon in conditional expression')
|
|
111
|
-
left = node({ type: 'conditional', test: left, yes, no: expression(0, depth + 1) })
|
|
112
|
-
}
|
|
113
|
-
return left
|
|
114
|
-
}
|
|
115
|
-
const tree = expression(0, 0)
|
|
116
|
-
if (peek().kind !== 'end') fail('invalid_expression', 'unexpected trailing expression content')
|
|
117
|
-
return tree
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function walk(tree, visit) {
|
|
121
|
-
visit(tree)
|
|
122
|
-
if (tree.left) { walk(tree.left, visit); walk(tree.right, visit) }
|
|
123
|
-
if (tree.value?.type) walk(tree.value, visit)
|
|
124
|
-
if (tree.test) { walk(tree.test, visit); walk(tree.yes, visit); walk(tree.no, visit) }
|
|
125
|
-
for (const child of tree.args ?? []) walk(child, visit)
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function containsCall(tree, name) {
|
|
129
|
-
let found = false
|
|
130
|
-
walk(tree, part => { if (part.type === 'call' && part.name === name) found = true })
|
|
131
|
-
return found
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
function validateFixed(tree) {
|
|
135
|
-
const hasFixed = containsCall(tree, 'fixed')
|
|
136
|
-
if (!hasFixed) return
|
|
137
|
-
const allowed = part => {
|
|
138
|
-
if (part.type === 'conditional') return allowed(part.yes) && allowed(part.no)
|
|
139
|
-
if (part.type === 'binary' && part.op === '*') {
|
|
140
|
-
const imageCount = part.left.type === 'variable' && part.left.name === 'image_count' || part.right.type === 'variable' && part.right.name === 'image_count'
|
|
141
|
-
return imageCount && allowed(part.left.type === 'variable' && part.left.name === 'image_count' ? part.right : part.left)
|
|
142
|
-
}
|
|
143
|
-
if (part.type !== 'call' || part.name !== 'tier' || part.args.length !== 2 || part.args[0].type !== 'literal' || typeof part.args[0].value !== 'string') return false
|
|
144
|
-
const price = part.args[1]
|
|
145
|
-
if (price.type === 'call' && price.name === 'fixed' && price.args.length === 1 && price.args[0].type === 'literal' && finite(price.args[0].value) && price.args[0].value >= 0) return true
|
|
146
|
-
return !containsCall(price, 'fixed')
|
|
147
|
-
}
|
|
148
|
-
if (!allowed(tree)) fail('unsupported_expression', 'fixed() must be the complete price of a tier leaf')
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function truth(value) { return value === true || typeof value === 'number' && value !== 0 || typeof value === 'string' && value.length > 0 }
|
|
152
|
-
function safeNumber(value) { if (!finite(value)) fail('unsupported_context', 'expression requires a finite numeric value'); return value }
|
|
153
|
-
|
|
154
|
-
function evalTree(tree, env, trace) {
|
|
155
|
-
if (tree.type === 'literal') return tree.value
|
|
156
|
-
if (tree.type === 'variable') {
|
|
157
|
-
if (!Object.hasOwn(env, tree.name)) fail('unsupported_context', `usage field ${tree.name} is unavailable for this request`)
|
|
158
|
-
return env[tree.name]
|
|
159
|
-
}
|
|
160
|
-
if (tree.type === 'unary') {
|
|
161
|
-
const value = evalTree(tree.value, env, trace)
|
|
162
|
-
return tree.op === '!' ? !truth(value) : tree.op === '-' ? -safeNumber(value) : safeNumber(value)
|
|
163
|
-
}
|
|
164
|
-
if (tree.type === 'conditional') return evalTree(truth(evalTree(tree.test, env, trace)) ? tree.yes : tree.no, env, trace)
|
|
165
|
-
if (tree.type === 'binary') {
|
|
166
|
-
const left = evalTree(tree.left, env, trace)
|
|
167
|
-
if (tree.op === '&&') return truth(left) && truth(evalTree(tree.right, env, trace))
|
|
168
|
-
if (tree.op === '||') return truth(left) || truth(evalTree(tree.right, env, trace))
|
|
169
|
-
const right = evalTree(tree.right, env, trace)
|
|
170
|
-
if (tree.op === '==') return left === right
|
|
171
|
-
if (tree.op === '!=') return left !== right
|
|
172
|
-
if (tree.op === '<') return left < right
|
|
173
|
-
if (tree.op === '<=') return left <= right
|
|
174
|
-
if (tree.op === '>') return left > right
|
|
175
|
-
if (tree.op === '>=') return left >= right
|
|
176
|
-
const a = safeNumber(left), b = safeNumber(right)
|
|
177
|
-
if (tree.op === '+') return a + b
|
|
178
|
-
if (tree.op === '-') return a - b
|
|
179
|
-
if (tree.op === '*') return a * b
|
|
180
|
-
if (tree.op === '/') { if (b === 0) fail('invalid_result', 'division by zero'); return a / b }
|
|
181
|
-
if (tree.op === '%') { if (b === 0) fail('invalid_result', 'modulo by zero'); return a % b }
|
|
182
|
-
}
|
|
183
|
-
if (tree.type === 'call') {
|
|
184
|
-
const args = tree.args.map(arg => evalTree(arg, env, trace))
|
|
185
|
-
switch (tree.name) {
|
|
186
|
-
case 'tier':
|
|
187
|
-
if (args.length !== 2 || typeof args[0] !== 'string') fail('invalid_expression', 'tier expects a label and a price')
|
|
188
|
-
trace.matchedTier = args[0]; return safeNumber(args[1])
|
|
189
|
-
case 'fixed':
|
|
190
|
-
if (args.length !== 1 || safeNumber(args[0]) < 0) fail('invalid_expression', 'fixed expects one non-negative amount')
|
|
191
|
-
trace.fixed = safeNumber(args[0]); return trace.fixed * 1_000_000
|
|
192
|
-
case 'max': case 'min':
|
|
193
|
-
if (args.length !== 2) fail('invalid_expression', `${tree.name} expects two arguments`)
|
|
194
|
-
return tree.name === 'max' ? Math.max(safeNumber(args[0]), safeNumber(args[1])) : Math.min(safeNumber(args[0]), safeNumber(args[1]))
|
|
195
|
-
case 'abs': case 'ceil': case 'floor':
|
|
196
|
-
if (args.length !== 1) fail('invalid_expression', `${tree.name} expects one argument`)
|
|
197
|
-
return Math[tree.name](safeNumber(args[0]))
|
|
198
|
-
case 'u': case 'param': case 'header': fail('unsupported_context', `${tree.name}() values are not available in DSH usage records`)
|
|
199
|
-
case 'has':
|
|
200
|
-
if (args.length !== 2) fail('invalid_expression', 'has expects two arguments')
|
|
201
|
-
return String(args[0] ?? '').includes(String(args[1]))
|
|
202
|
-
case 'when': if (args.length !== 1) fail('invalid_expression', 'when expects one argument'); return args[0]
|
|
203
|
-
case 'hour': case 'minute': case 'weekday': case 'month': case 'day': {
|
|
204
|
-
if (args.length > 1) fail('invalid_expression', `${tree.name} expects at most one timezone`)
|
|
205
|
-
let parts
|
|
206
|
-
try { parts = new Intl.DateTimeFormat('en', { timeZone: typeof args[0] === 'string' ? args[0] : 'UTC', weekday: 'short', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23' }).formatToParts(new Date(env.atMs)) }
|
|
207
|
-
catch { fail('unsupported_context', 'timezone in billing expression is invalid') }
|
|
208
|
-
const field = Object.fromEntries(parts.map(part => [part.type, part.value]))
|
|
209
|
-
if (tree.name === 'hour') return Number(field.hour) % 24
|
|
210
|
-
if (tree.name === 'minute') return Number(field.minute)
|
|
211
|
-
if (tree.name === 'day') return Number(field.day)
|
|
212
|
-
if (tree.name === 'month') return Number(field.month)
|
|
213
|
-
return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(field.weekday)
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
fail('invalid_expression', 'expression could not be evaluated')
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
function usesTokenValue(tree) {
|
|
221
|
-
let used = false
|
|
222
|
-
walk(tree, node => { if (node.type === 'variable' && billedTokenVars.has(node.name)) used = true })
|
|
223
|
-
return used
|
|
224
|
-
}
|
|
225
|
-
function checkedVector(vector) {
|
|
226
|
-
if (!finite(vector.constant) || vector.constant < 0 || Object.values(vector.coefficients).some(value => !finite(value) || value < 0)) fail('unsupported_expression', 'native fee components must be finite and non-negative')
|
|
227
|
-
return vector
|
|
228
|
-
}
|
|
229
|
-
function linearize(tree, env, trace) {
|
|
230
|
-
if (tree.type === 'literal') return { constant: safeNumber(tree.value), coefficients: {} }
|
|
231
|
-
if (tree.type === 'variable') {
|
|
232
|
-
if (billedTokenVars.has(tree.name)) return { constant: 0, coefficients: { [tree.name]: 1 } }
|
|
233
|
-
if (zeroUsageVars.has(tree.name)) return { constant: 0, coefficients: {} }
|
|
234
|
-
fail('unsupported_expression', 'context variables may select a tier but cannot act as a native unit price')
|
|
235
|
-
}
|
|
236
|
-
if (tree.type === 'conditional') return linearize(truth(evalTree(tree.test, env, trace)) ? tree.yes : tree.no, env, trace)
|
|
237
|
-
if (tree.type === 'call') {
|
|
238
|
-
if (tree.name === 'tier') {
|
|
239
|
-
const label = evalTree(tree.args[0], env, trace)
|
|
240
|
-
if (typeof label !== 'string') fail('invalid_expression', 'tier label must be a string')
|
|
241
|
-
trace.matchedTier = label
|
|
242
|
-
return linearize(tree.args[1], env, trace)
|
|
243
|
-
}
|
|
244
|
-
if (tree.name === 'fixed') return { constant: safeNumber(evalTree(tree, env, trace)), coefficients: {} }
|
|
245
|
-
if (usesTokenValue(tree)) fail('unsupported_expression', 'token-dependent math functions require an unavailable native fee decomposition')
|
|
246
|
-
return { constant: safeNumber(evalTree(tree, env, trace)), coefficients: {} }
|
|
247
|
-
}
|
|
248
|
-
if (tree.type === 'unary') {
|
|
249
|
-
const value = linearize(tree.value, env, trace), factor = tree.op === '-' ? -1 : tree.op === '+' ? 1 : null
|
|
250
|
-
if (factor === null) return { constant: truth(evalTree(tree, env, trace)) ? 1 : 0, coefficients: {} }
|
|
251
|
-
return scale(value, factor)
|
|
252
|
-
}
|
|
253
|
-
if (tree.type === 'binary') {
|
|
254
|
-
if (['==', '!=', '<', '<=', '>', '>=', '&&', '||', '%'].includes(tree.op)) return { constant: safeNumber(evalTree(tree, env, trace)), coefficients: {} }
|
|
255
|
-
const a = linearize(tree.left, env, trace), b = linearize(tree.right, env, trace)
|
|
256
|
-
if (tree.op === '+') return add(a, b)
|
|
257
|
-
if (tree.op === '-') return add(a, scale(b, -1))
|
|
258
|
-
if (tree.op === '*') {
|
|
259
|
-
if (Object.keys(a.coefficients).length && Object.keys(b.coefficients).length) fail('unsupported_expression', 'non-linear token pricing cannot be split into native fee rows')
|
|
260
|
-
return Object.keys(a.coefficients).length ? scale(a, b.constant) : scale(b, a.constant)
|
|
261
|
-
}
|
|
262
|
-
if (tree.op === '/') {
|
|
263
|
-
if (Object.keys(b.coefficients).length || b.constant === 0) fail('unsupported_expression', 'token pricing denominator must be a non-zero constant')
|
|
264
|
-
return scale(a, 1 / b.constant)
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
fail('unsupported_expression', 'billing expression cannot be represented by native fee rows')
|
|
268
|
-
}
|
|
269
|
-
function add(a, b) { const coefficients = { ...a.coefficients }; for (const [key, value] of Object.entries(b.coefficients)) coefficients[key] = (coefficients[key] ?? 0) + value; return { constant: a.constant + b.constant, coefficients } }
|
|
270
|
-
function scale(value, factor) { return { constant: value.constant * factor, coefficients: Object.fromEntries(Object.entries(value.coefficients).map(([key, amount]) => [key, amount * factor])) } }
|
|
271
|
-
|
|
272
|
-
function validatePriceBranch(tree, env, multiplier) {
|
|
273
|
-
const trace = { fixed: null, matchedTier: '' }
|
|
274
|
-
const vector = checkedVector(linearize(tree, env, trace))
|
|
275
|
-
if (multiplier) {
|
|
276
|
-
const value = evalTree(tree, env, trace)
|
|
277
|
-
if (!finite(value) || value < 0 || Object.keys(vector.coefficients).length) fail('unsupported_expression', 'billing multipliers must be finite non-negative scalars')
|
|
278
|
-
} else if (vector.constant !== 0 && trace.fixed === null) fail('unsupported_expression', 'constant request charges require fixed()')
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
function isScalarFactor(factor, price) {
|
|
282
|
-
return usesTokenValue(price) && !usesTokenValue(factor) && !containsCall(factor, 'fixed')
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
function validateAllBranches(tree, env, multiplier = false) {
|
|
286
|
-
if (tree.type === 'conditional') {
|
|
287
|
-
validatePriceBranch(tree.yes, env, multiplier)
|
|
288
|
-
validatePriceBranch(tree.no, env, multiplier)
|
|
289
|
-
validateAllBranches(tree.test, env)
|
|
290
|
-
validateAllBranches(tree.yes, env, multiplier)
|
|
291
|
-
validateAllBranches(tree.no, env, multiplier)
|
|
292
|
-
} else if (tree.type === 'binary') {
|
|
293
|
-
// Bare numeric branches are valid as token-price factors, not as request charges.
|
|
294
|
-
const product = tree.op === '*'
|
|
295
|
-
validateAllBranches(tree.left, env, product && (multiplier || isScalarFactor(tree.left, tree.right)))
|
|
296
|
-
validateAllBranches(tree.right, env, product && (multiplier || isScalarFactor(tree.right, tree.left)))
|
|
297
|
-
} else if (tree.type === 'unary') validateAllBranches(tree.value, env)
|
|
298
|
-
else if (tree.type === 'call') for (const arg of tree.args) validateAllBranches(arg, env)
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
export function analyzeNikoBillingExpression(expression) {
|
|
302
|
-
if (typeof expression === 'string' && compiled.has(expression)) return compiled.get(expression)
|
|
303
|
-
const result = compileExpression(expression)
|
|
304
|
-
if (typeof expression === 'string' && expression.length <= maxExpressionLength) {
|
|
305
|
-
if (compiled.size >= 128) compiled.delete(compiled.keys().next().value)
|
|
306
|
-
compiled.set(expression, result)
|
|
307
|
-
}
|
|
308
|
-
return result
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
function compileExpression(expression) {
|
|
312
|
-
try {
|
|
313
|
-
if (typeof expression !== 'string' || expression.length > maxExpressionLength) fail('invalid_expression', 'invalid expression size')
|
|
314
|
-
if (/^v\d+:/.test(expression) && !expression.startsWith('v1:')) fail('unsupported_expression', 'unknown billing expression version')
|
|
315
|
-
const parts = (expression.startsWith('v1:') ? expression.slice(3) : expression).split('|||')
|
|
316
|
-
if (parts.length > 2) fail('invalid_expression', 'only one request-rule section is allowed')
|
|
317
|
-
const tree = parsePart(parts[0].trim())
|
|
318
|
-
const rules = parts.length === 2 ? parsePart(parts[1].trim()) : null
|
|
319
|
-
validateFixed(tree)
|
|
320
|
-
if (rules && containsCall(rules, 'fixed')) fail('unsupported_expression', 'fixed() is not allowed in request-rule multipliers')
|
|
321
|
-
const variables = new Set()
|
|
322
|
-
let unsupported
|
|
323
|
-
let zeroRequestContext = false
|
|
324
|
-
walk(tree, node => {
|
|
325
|
-
if (node.type === 'variable') variables.add(node.name)
|
|
326
|
-
if (node.type === 'call' && ['u', 'param', 'header'].includes(node.name)) {
|
|
327
|
-
if (node.name === 'u') zeroRequestContext = true
|
|
328
|
-
unsupported = `${node.name}() requires request fields unavailable to the local usage ledger`
|
|
329
|
-
}
|
|
330
|
-
})
|
|
331
|
-
if (rules) walk(rules, node => {
|
|
332
|
-
if (node.type === 'variable') variables.add(node.name)
|
|
333
|
-
if (node.type === 'call' && ['u', 'param', 'header'].includes(node.name)) {
|
|
334
|
-
if (node.name === 'u') zeroRequestContext = true
|
|
335
|
-
unsupported = `${node.name}() request rules are not available to the local usage ledger`
|
|
336
|
-
}
|
|
337
|
-
})
|
|
338
|
-
const zeroByPolicy = zeroRequestContext || variables.has('image_count')
|
|
339
|
-
// DSH reports one merged cache-write total, so the long-TTL variables (`cc1h`,
|
|
340
|
-
// `cc12h`) never receive a split. Their tokens stay in the short-TTL bucket,
|
|
341
|
-
// which is the default new-api applies to an unlabelled cache-write remainder
|
|
342
|
-
// (service/tiered_settle.go: "billed as 5m writes"), never a zero charge.
|
|
343
|
-
if (!unsupported) {
|
|
344
|
-
const env = { p: 1000, c: 300, len: 1500, cr: 100, cc: 50, cc1h: 0, cc12h: 0,
|
|
345
|
-
img: 0, img_cr: 0, img_o: 0, ai: 0, ao: 0, image_count: 1, atMs: Date.UTC(2026, 0, 1, 12) }
|
|
346
|
-
const trace = { fixed: null, matchedTier: '' }
|
|
347
|
-
const initial = checkedVector(linearize(tree, env, trace))
|
|
348
|
-
if (initial.constant !== 0 && trace.fixed === null) fail('unsupported_expression', 'constant request charges require fixed()')
|
|
349
|
-
if (rules) checkedVector(linearize(rules, env, trace))
|
|
350
|
-
validateAllBranches(tree, env)
|
|
351
|
-
if (rules) validateAllBranches(rules, env)
|
|
352
|
-
}
|
|
353
|
-
return { supported: !unsupported, zeroByPolicy, reason: unsupported ?? '', tree, rules, variables, fixedPricing: containsCall(tree, 'fixed') }
|
|
354
|
-
} catch (error) { return { supported: false, zeroByPolicy: false, reason: error?.message ?? 'billing expression is not supported', error } }
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
function zeroPolicyQuote(reason = 'request uses a billing field excluded by the local policy') {
|
|
358
|
-
return { currency: 'CNY', cost: 0, matchedTier: 'zero-policy', billingUnit: 'request', zeroByPolicy: true,
|
|
359
|
-
note: reason, rows: [{ bucket: 'modelRequests', tokens: 0, requests: 1, rate: 0, cost: 0, priced: true }] }
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
function requestPriceQuote(value) {
|
|
363
|
-
const amount = Number(value)
|
|
364
|
-
if (!finite(amount) || amount < 0) return null
|
|
365
|
-
return { currency: 'CNY', cost: amount, matchedTier: 'request-price', billingUnit: 'request',
|
|
366
|
-
rows: [{ bucket: 'modelRequests', tokens: 0, requests: 1, rate: amount, cost: amount, priced: true }] }
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
export function nikoBillingBreakdown(tokens, entry, atMs = Date.now()) {
|
|
370
|
-
const requestPrice = requestPriceQuote(entry?.requestPriceCny)
|
|
371
|
-
if (requestPrice !== null) return requestPrice
|
|
372
|
-
const parsed = analyzeNikoBillingExpression(entry?.billingExpr)
|
|
373
|
-
const safeTokens = Object.fromEntries(['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning'].map(key => {
|
|
374
|
-
const value = Number(tokens?.[key] ?? 0)
|
|
375
|
-
if (!finite(value) || value < 0) fail('invalid_usage', 'usage buckets must be finite and non-negative')
|
|
376
|
-
return [key, value]
|
|
377
|
-
}))
|
|
378
|
-
if (entry?.zeroByPolicy === true || parsed.zeroByPolicy === true) return zeroPolicyQuote(parsed.reason)
|
|
379
|
-
if (!parsed.supported) return null
|
|
380
|
-
const variables = parsed.variables
|
|
381
|
-
const cacheRead = safeTokens.cacheRead
|
|
382
|
-
const cacheWrite = safeTokens.cacheWrite
|
|
383
|
-
const p = safeTokens.input + (variables.has('cr') ? 0 : cacheRead) + (variables.has('cc') ? 0 : cacheWrite)
|
|
384
|
-
const c = safeTokens.output
|
|
385
|
-
const env = { p, c, len: safeTokens.input + cacheRead + cacheWrite, cr: cacheRead, cc: cacheWrite, cc1h: 0, cc12h: 0, img: 0, img_cr: 0, img_o: 0, ai: 0, ao: 0, image_count: 1, atMs }
|
|
386
|
-
const trace = { fixed: null, matchedTier: '' }
|
|
387
|
-
try {
|
|
388
|
-
let vector = linearize(parsed.tree, env, trace)
|
|
389
|
-
let multiplier = 1
|
|
390
|
-
if (parsed.rules) multiplier = safeNumber(evalTree(parsed.rules, env, trace))
|
|
391
|
-
vector = scale(vector, multiplier)
|
|
392
|
-
const expressionValue = safeNumber(evalTree(parsed.tree, env, { fixed: null, matchedTier: '' })) * multiplier
|
|
393
|
-
if (expressionValue < 0 || !finite(expressionValue) || !finite(multiplier) || multiplier < 0) return null
|
|
394
|
-
const quotaPerUnit = Number(entry.billingQuotaPerUnit)
|
|
395
|
-
const groupRatio = Number(entry.billingGroupRatio)
|
|
396
|
-
if (!finite(quotaPerUnit) || quotaPerUnit <= 0 || !finite(groupRatio) || groupRatio < 0) return null
|
|
397
|
-
const quotaScale = quotaPerUnit * groupRatio / 1_000_000
|
|
398
|
-
if (trace.fixed !== null) {
|
|
399
|
-
const rawQuota = trace.fixed * multiplier * quotaPerUnit * groupRatio
|
|
400
|
-
if (!finite(rawQuota) || rawQuota > 2_147_483_647) return null
|
|
401
|
-
const amount = Math.round(rawQuota) / quotaPerUnit
|
|
402
|
-
return { currency: 'CNY', cost: amount, matchedTier: trace.matchedTier, billingUnit: 'request', rows: [{ bucket: 'modelRequests', tokens: 0, requests: 1, rate: amount, cost: amount, priced: true }] }
|
|
403
|
-
}
|
|
404
|
-
const rows = []
|
|
405
|
-
const addRow = (bucket, count, rate) => {
|
|
406
|
-
if (count <= 0) return
|
|
407
|
-
const cnyRate = rate * groupRatio
|
|
408
|
-
rows.push({ bucket, tokens: count, rate: cnyRate, cost: count * cnyRate / 1_000_000, priced: true })
|
|
409
|
-
}
|
|
410
|
-
const pRate = vector.coefficients.p ?? 0
|
|
411
|
-
addRow('input', safeTokens.input, pRate)
|
|
412
|
-
if (!variables.has('cr')) addRow('cacheRead', cacheRead, pRate)
|
|
413
|
-
if (!variables.has('cc')) addRow('cacheWrite', cacheWrite, pRate)
|
|
414
|
-
addRow('cacheRead', variables.has('cr') ? cacheRead : 0, vector.coefficients.cr ?? 0)
|
|
415
|
-
addRow('cacheWrite', variables.has('cc') ? cacheWrite : 0, vector.coefficients.cc ?? 0)
|
|
416
|
-
const cRate = vector.coefficients.c ?? 0
|
|
417
|
-
addRow('output', safeTokens.output, cRate)
|
|
418
|
-
const rawQuota = expressionValue * quotaScale
|
|
419
|
-
if (!finite(rawQuota) || rawQuota > 2_147_483_647) return null
|
|
420
|
-
const cost = Math.round(rawQuota) / quotaPerUnit
|
|
421
|
-
const rowCost = rows.reduce((sum, row) => sum + row.cost, 0)
|
|
422
|
-
const rounding = cost - rowCost
|
|
423
|
-
if (rows.length && rounding !== 0) {
|
|
424
|
-
const largest = rows.reduce((a,b)=>a.cost >= b.cost ? a : b)
|
|
425
|
-
largest.cost += rounding
|
|
426
|
-
if (largest.cost < 0) return null
|
|
427
|
-
}
|
|
428
|
-
else if (!rows.length && cost > 0) rows.push({ bucket: 'modelRequests', tokens: 0, requests: 1, rate: cost, cost, priced: true })
|
|
429
|
-
return { currency: 'CNY', cost, matchedTier: trace.matchedTier, billingUnit: 'token', rows }
|
|
430
|
-
} catch { return null }
|
|
431
|
-
}
|
|
1
|
+
const zeroUsageVars = new Set(['cc1h', 'cc12h', 'img', 'img_cr', 'img_o', 'ai', 'ao', 'image_count'])
|
|
2
|
+
const tokenVars = new Set(['p', 'c', 'len', 'cr', 'cc', ...zeroUsageVars])
|
|
3
|
+
const billedTokenVars = new Set(['p', 'c', 'cr', 'cc'])
|
|
4
|
+
const functionNames = new Set(['tier', 'fixed', 'u', 'param', 'header', 'has', 'hour', 'minute', 'weekday', 'month', 'day', 'max', 'min', 'abs', 'ceil', 'floor', 'when'])
|
|
5
|
+
const maxExpressionLength = 16_384
|
|
6
|
+
const maxTokens = 4_096
|
|
7
|
+
const maxDepth = 64
|
|
8
|
+
const compiled = new Map()
|
|
9
|
+
|
|
10
|
+
export class NikoBillingExpressionError extends Error {
|
|
11
|
+
constructor(code, message) { super(message); this.name = 'NikoBillingExpressionError'; this.code = code }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function fail(code, message) { throw new NikoBillingExpressionError(code, message) }
|
|
15
|
+
function finite(value) { return typeof value === 'number' && Number.isFinite(value) }
|
|
16
|
+
|
|
17
|
+
function tokenize(source) {
|
|
18
|
+
if (typeof source !== 'string' || source.length === 0 || source.length > maxExpressionLength) fail('invalid_expression', 'expression is empty or exceeds the size limit')
|
|
19
|
+
const rows = []
|
|
20
|
+
let i = 0
|
|
21
|
+
while (i < source.length) {
|
|
22
|
+
const char = source[i]
|
|
23
|
+
if (/\s/.test(char)) { i++; continue }
|
|
24
|
+
const pair = source.slice(i, i + 2)
|
|
25
|
+
const triple = source.slice(i, i + 3)
|
|
26
|
+
if (['|||', '&&', '||', '==', '!=', '<=', '>='].includes(triple) || ['&&', '||', '==', '!=', '<=', '>='].includes(pair)) {
|
|
27
|
+
rows.push(triple === '|||' ? { kind: 'separator', value: triple } : { kind: 'operator', value: triple.length === 2 ? triple : pair })
|
|
28
|
+
i += triple === '|||' ? 3 : 2
|
|
29
|
+
} else if ('+-*/%<>!?:(),'.includes(char)) {
|
|
30
|
+
rows.push({ kind: 'operator', value: char }); i++
|
|
31
|
+
} else if (char === '"') {
|
|
32
|
+
const start = i++
|
|
33
|
+
let escaped = false
|
|
34
|
+
while (i < source.length) {
|
|
35
|
+
const current = source[i++]
|
|
36
|
+
if (escaped) escaped = false
|
|
37
|
+
else if (current === '\\') escaped = true
|
|
38
|
+
else if (current === '"') break
|
|
39
|
+
}
|
|
40
|
+
if (source[i - 1] !== '"') fail('invalid_expression', 'unterminated string literal')
|
|
41
|
+
let value
|
|
42
|
+
try { value = JSON.parse(source.slice(start, i)) } catch { fail('invalid_expression', 'invalid string literal') }
|
|
43
|
+
rows.push({ kind: 'literal', value })
|
|
44
|
+
} else if (/[0-9.]/.test(char)) {
|
|
45
|
+
const match = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(source.slice(i))
|
|
46
|
+
if (!match) fail('invalid_expression', 'invalid numeric literal')
|
|
47
|
+
const value = Number(match[0])
|
|
48
|
+
if (!finite(value)) fail('invalid_expression', 'numeric literal must be finite')
|
|
49
|
+
rows.push({ kind: 'literal', value }); i += match[0].length
|
|
50
|
+
} else if (/[A-Za-z_]/.test(char)) {
|
|
51
|
+
const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i))[0]
|
|
52
|
+
rows.push({ kind: 'identifier', value: match }); i += match.length
|
|
53
|
+
} else fail('invalid_expression', `unsupported character at offset ${i}`)
|
|
54
|
+
if (rows.length > maxTokens) fail('invalid_expression', 'expression has too many tokens')
|
|
55
|
+
}
|
|
56
|
+
rows.push({ kind: 'end', value: '' })
|
|
57
|
+
return rows
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const precedence = new Map([['||', 1], ['&&', 2], ['==', 3], ['!=', 3], ['<', 4], ['<=', 4], ['>', 4], ['>=', 4], ['+', 5], ['-', 5], ['*', 6], ['/', 6], ['%', 6]])
|
|
61
|
+
|
|
62
|
+
function parsePart(source) {
|
|
63
|
+
const tokens = tokenize(source)
|
|
64
|
+
let cursor = 0, nodes = 0
|
|
65
|
+
const peek = () => tokens[cursor]
|
|
66
|
+
const take = () => tokens[cursor++]
|
|
67
|
+
const node = value => {
|
|
68
|
+
if (++nodes > maxTokens) fail('invalid_expression', 'expression has too many nodes')
|
|
69
|
+
const children = [value.left, value.right, value.test, value.yes, value.no, value.value?.type ? value.value : null, ...(value.args ?? [])].filter(Boolean)
|
|
70
|
+
value.height = 1 + Math.max(0, ...children.map(child => child.height ?? 0))
|
|
71
|
+
if (value.height > maxDepth) fail('invalid_expression', 'expression AST exceeds the nesting limit')
|
|
72
|
+
return value
|
|
73
|
+
}
|
|
74
|
+
function primary(depth) {
|
|
75
|
+
if (depth > maxDepth) fail('invalid_expression', 'expression nesting exceeds the limit')
|
|
76
|
+
const token = take()
|
|
77
|
+
if (token.kind === 'literal') return node({ type: 'literal', value: token.value })
|
|
78
|
+
if (token.kind === 'identifier') {
|
|
79
|
+
if (token.value === 'true' || token.value === 'false') return node({ type: 'literal', value: token.value === 'true' })
|
|
80
|
+
if (peek().value !== '(') {
|
|
81
|
+
if (!tokenVars.has(token.value)) fail('invalid_expression', `unknown identifier ${token.value}`)
|
|
82
|
+
return node({ type: 'variable', name: token.value })
|
|
83
|
+
}
|
|
84
|
+
if (!functionNames.has(token.value)) fail('invalid_expression', `unsupported function ${token.value}`)
|
|
85
|
+
take()
|
|
86
|
+
const args = []
|
|
87
|
+
if (peek().value !== ')') {
|
|
88
|
+
do { args.push(expression(0, depth + 1)); if (peek().value !== ',') break; take() } while (true)
|
|
89
|
+
}
|
|
90
|
+
if (take().value !== ')') fail('invalid_expression', 'expected closing parenthesis')
|
|
91
|
+
return node({ type: 'call', name: token.value, args })
|
|
92
|
+
}
|
|
93
|
+
if (token.value === '(') {
|
|
94
|
+
const result = expression(0, depth + 1)
|
|
95
|
+
if (take().value !== ')') fail('invalid_expression', 'expected closing parenthesis')
|
|
96
|
+
return result
|
|
97
|
+
}
|
|
98
|
+
if (['+', '-', '!'].includes(token.value)) return node({ type: 'unary', op: token.value, value: primary(depth + 1) })
|
|
99
|
+
fail('invalid_expression', 'expected a value')
|
|
100
|
+
}
|
|
101
|
+
function expression(min, depth) {
|
|
102
|
+
let left = primary(depth)
|
|
103
|
+
while (peek().kind === 'operator' && precedence.has(peek().value) && precedence.get(peek().value) >= min) {
|
|
104
|
+
const op = take().value, p = precedence.get(op)
|
|
105
|
+
left = node({ type: 'binary', op, left, right: expression(p + 1, depth + 1) })
|
|
106
|
+
}
|
|
107
|
+
if (min === 0 && peek().value === '?') {
|
|
108
|
+
take()
|
|
109
|
+
const yes = expression(0, depth + 1)
|
|
110
|
+
if (take().value !== ':') fail('invalid_expression', 'expected colon in conditional expression')
|
|
111
|
+
left = node({ type: 'conditional', test: left, yes, no: expression(0, depth + 1) })
|
|
112
|
+
}
|
|
113
|
+
return left
|
|
114
|
+
}
|
|
115
|
+
const tree = expression(0, 0)
|
|
116
|
+
if (peek().kind !== 'end') fail('invalid_expression', 'unexpected trailing expression content')
|
|
117
|
+
return tree
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function walk(tree, visit) {
|
|
121
|
+
visit(tree)
|
|
122
|
+
if (tree.left) { walk(tree.left, visit); walk(tree.right, visit) }
|
|
123
|
+
if (tree.value?.type) walk(tree.value, visit)
|
|
124
|
+
if (tree.test) { walk(tree.test, visit); walk(tree.yes, visit); walk(tree.no, visit) }
|
|
125
|
+
for (const child of tree.args ?? []) walk(child, visit)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function containsCall(tree, name) {
|
|
129
|
+
let found = false
|
|
130
|
+
walk(tree, part => { if (part.type === 'call' && part.name === name) found = true })
|
|
131
|
+
return found
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function validateFixed(tree) {
|
|
135
|
+
const hasFixed = containsCall(tree, 'fixed')
|
|
136
|
+
if (!hasFixed) return
|
|
137
|
+
const allowed = part => {
|
|
138
|
+
if (part.type === 'conditional') return allowed(part.yes) && allowed(part.no)
|
|
139
|
+
if (part.type === 'binary' && part.op === '*') {
|
|
140
|
+
const imageCount = part.left.type === 'variable' && part.left.name === 'image_count' || part.right.type === 'variable' && part.right.name === 'image_count'
|
|
141
|
+
return imageCount && allowed(part.left.type === 'variable' && part.left.name === 'image_count' ? part.right : part.left)
|
|
142
|
+
}
|
|
143
|
+
if (part.type !== 'call' || part.name !== 'tier' || part.args.length !== 2 || part.args[0].type !== 'literal' || typeof part.args[0].value !== 'string') return false
|
|
144
|
+
const price = part.args[1]
|
|
145
|
+
if (price.type === 'call' && price.name === 'fixed' && price.args.length === 1 && price.args[0].type === 'literal' && finite(price.args[0].value) && price.args[0].value >= 0) return true
|
|
146
|
+
return !containsCall(price, 'fixed')
|
|
147
|
+
}
|
|
148
|
+
if (!allowed(tree)) fail('unsupported_expression', 'fixed() must be the complete price of a tier leaf')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function truth(value) { return value === true || typeof value === 'number' && value !== 0 || typeof value === 'string' && value.length > 0 }
|
|
152
|
+
function safeNumber(value) { if (!finite(value)) fail('unsupported_context', 'expression requires a finite numeric value'); return value }
|
|
153
|
+
|
|
154
|
+
function evalTree(tree, env, trace) {
|
|
155
|
+
if (tree.type === 'literal') return tree.value
|
|
156
|
+
if (tree.type === 'variable') {
|
|
157
|
+
if (!Object.hasOwn(env, tree.name)) fail('unsupported_context', `usage field ${tree.name} is unavailable for this request`)
|
|
158
|
+
return env[tree.name]
|
|
159
|
+
}
|
|
160
|
+
if (tree.type === 'unary') {
|
|
161
|
+
const value = evalTree(tree.value, env, trace)
|
|
162
|
+
return tree.op === '!' ? !truth(value) : tree.op === '-' ? -safeNumber(value) : safeNumber(value)
|
|
163
|
+
}
|
|
164
|
+
if (tree.type === 'conditional') return evalTree(truth(evalTree(tree.test, env, trace)) ? tree.yes : tree.no, env, trace)
|
|
165
|
+
if (tree.type === 'binary') {
|
|
166
|
+
const left = evalTree(tree.left, env, trace)
|
|
167
|
+
if (tree.op === '&&') return truth(left) && truth(evalTree(tree.right, env, trace))
|
|
168
|
+
if (tree.op === '||') return truth(left) || truth(evalTree(tree.right, env, trace))
|
|
169
|
+
const right = evalTree(tree.right, env, trace)
|
|
170
|
+
if (tree.op === '==') return left === right
|
|
171
|
+
if (tree.op === '!=') return left !== right
|
|
172
|
+
if (tree.op === '<') return left < right
|
|
173
|
+
if (tree.op === '<=') return left <= right
|
|
174
|
+
if (tree.op === '>') return left > right
|
|
175
|
+
if (tree.op === '>=') return left >= right
|
|
176
|
+
const a = safeNumber(left), b = safeNumber(right)
|
|
177
|
+
if (tree.op === '+') return a + b
|
|
178
|
+
if (tree.op === '-') return a - b
|
|
179
|
+
if (tree.op === '*') return a * b
|
|
180
|
+
if (tree.op === '/') { if (b === 0) fail('invalid_result', 'division by zero'); return a / b }
|
|
181
|
+
if (tree.op === '%') { if (b === 0) fail('invalid_result', 'modulo by zero'); return a % b }
|
|
182
|
+
}
|
|
183
|
+
if (tree.type === 'call') {
|
|
184
|
+
const args = tree.args.map(arg => evalTree(arg, env, trace))
|
|
185
|
+
switch (tree.name) {
|
|
186
|
+
case 'tier':
|
|
187
|
+
if (args.length !== 2 || typeof args[0] !== 'string') fail('invalid_expression', 'tier expects a label and a price')
|
|
188
|
+
trace.matchedTier = args[0]; return safeNumber(args[1])
|
|
189
|
+
case 'fixed':
|
|
190
|
+
if (args.length !== 1 || safeNumber(args[0]) < 0) fail('invalid_expression', 'fixed expects one non-negative amount')
|
|
191
|
+
trace.fixed = safeNumber(args[0]); return trace.fixed * 1_000_000
|
|
192
|
+
case 'max': case 'min':
|
|
193
|
+
if (args.length !== 2) fail('invalid_expression', `${tree.name} expects two arguments`)
|
|
194
|
+
return tree.name === 'max' ? Math.max(safeNumber(args[0]), safeNumber(args[1])) : Math.min(safeNumber(args[0]), safeNumber(args[1]))
|
|
195
|
+
case 'abs': case 'ceil': case 'floor':
|
|
196
|
+
if (args.length !== 1) fail('invalid_expression', `${tree.name} expects one argument`)
|
|
197
|
+
return Math[tree.name](safeNumber(args[0]))
|
|
198
|
+
case 'u': case 'param': case 'header': fail('unsupported_context', `${tree.name}() values are not available in DSH usage records`)
|
|
199
|
+
case 'has':
|
|
200
|
+
if (args.length !== 2) fail('invalid_expression', 'has expects two arguments')
|
|
201
|
+
return String(args[0] ?? '').includes(String(args[1]))
|
|
202
|
+
case 'when': if (args.length !== 1) fail('invalid_expression', 'when expects one argument'); return args[0]
|
|
203
|
+
case 'hour': case 'minute': case 'weekday': case 'month': case 'day': {
|
|
204
|
+
if (args.length > 1) fail('invalid_expression', `${tree.name} expects at most one timezone`)
|
|
205
|
+
let parts
|
|
206
|
+
try { parts = new Intl.DateTimeFormat('en', { timeZone: typeof args[0] === 'string' ? args[0] : 'UTC', weekday: 'short', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23' }).formatToParts(new Date(env.atMs)) }
|
|
207
|
+
catch { fail('unsupported_context', 'timezone in billing expression is invalid') }
|
|
208
|
+
const field = Object.fromEntries(parts.map(part => [part.type, part.value]))
|
|
209
|
+
if (tree.name === 'hour') return Number(field.hour) % 24
|
|
210
|
+
if (tree.name === 'minute') return Number(field.minute)
|
|
211
|
+
if (tree.name === 'day') return Number(field.day)
|
|
212
|
+
if (tree.name === 'month') return Number(field.month)
|
|
213
|
+
return ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(field.weekday)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
fail('invalid_expression', 'expression could not be evaluated')
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function usesTokenValue(tree) {
|
|
221
|
+
let used = false
|
|
222
|
+
walk(tree, node => { if (node.type === 'variable' && billedTokenVars.has(node.name)) used = true })
|
|
223
|
+
return used
|
|
224
|
+
}
|
|
225
|
+
function checkedVector(vector) {
|
|
226
|
+
if (!finite(vector.constant) || vector.constant < 0 || Object.values(vector.coefficients).some(value => !finite(value) || value < 0)) fail('unsupported_expression', 'native fee components must be finite and non-negative')
|
|
227
|
+
return vector
|
|
228
|
+
}
|
|
229
|
+
function linearize(tree, env, trace) {
|
|
230
|
+
if (tree.type === 'literal') return { constant: safeNumber(tree.value), coefficients: {} }
|
|
231
|
+
if (tree.type === 'variable') {
|
|
232
|
+
if (billedTokenVars.has(tree.name)) return { constant: 0, coefficients: { [tree.name]: 1 } }
|
|
233
|
+
if (zeroUsageVars.has(tree.name)) return { constant: 0, coefficients: {} }
|
|
234
|
+
fail('unsupported_expression', 'context variables may select a tier but cannot act as a native unit price')
|
|
235
|
+
}
|
|
236
|
+
if (tree.type === 'conditional') return linearize(truth(evalTree(tree.test, env, trace)) ? tree.yes : tree.no, env, trace)
|
|
237
|
+
if (tree.type === 'call') {
|
|
238
|
+
if (tree.name === 'tier') {
|
|
239
|
+
const label = evalTree(tree.args[0], env, trace)
|
|
240
|
+
if (typeof label !== 'string') fail('invalid_expression', 'tier label must be a string')
|
|
241
|
+
trace.matchedTier = label
|
|
242
|
+
return linearize(tree.args[1], env, trace)
|
|
243
|
+
}
|
|
244
|
+
if (tree.name === 'fixed') return { constant: safeNumber(evalTree(tree, env, trace)), coefficients: {} }
|
|
245
|
+
if (usesTokenValue(tree)) fail('unsupported_expression', 'token-dependent math functions require an unavailable native fee decomposition')
|
|
246
|
+
return { constant: safeNumber(evalTree(tree, env, trace)), coefficients: {} }
|
|
247
|
+
}
|
|
248
|
+
if (tree.type === 'unary') {
|
|
249
|
+
const value = linearize(tree.value, env, trace), factor = tree.op === '-' ? -1 : tree.op === '+' ? 1 : null
|
|
250
|
+
if (factor === null) return { constant: truth(evalTree(tree, env, trace)) ? 1 : 0, coefficients: {} }
|
|
251
|
+
return scale(value, factor)
|
|
252
|
+
}
|
|
253
|
+
if (tree.type === 'binary') {
|
|
254
|
+
if (['==', '!=', '<', '<=', '>', '>=', '&&', '||', '%'].includes(tree.op)) return { constant: safeNumber(evalTree(tree, env, trace)), coefficients: {} }
|
|
255
|
+
const a = linearize(tree.left, env, trace), b = linearize(tree.right, env, trace)
|
|
256
|
+
if (tree.op === '+') return add(a, b)
|
|
257
|
+
if (tree.op === '-') return add(a, scale(b, -1))
|
|
258
|
+
if (tree.op === '*') {
|
|
259
|
+
if (Object.keys(a.coefficients).length && Object.keys(b.coefficients).length) fail('unsupported_expression', 'non-linear token pricing cannot be split into native fee rows')
|
|
260
|
+
return Object.keys(a.coefficients).length ? scale(a, b.constant) : scale(b, a.constant)
|
|
261
|
+
}
|
|
262
|
+
if (tree.op === '/') {
|
|
263
|
+
if (Object.keys(b.coefficients).length || b.constant === 0) fail('unsupported_expression', 'token pricing denominator must be a non-zero constant')
|
|
264
|
+
return scale(a, 1 / b.constant)
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
fail('unsupported_expression', 'billing expression cannot be represented by native fee rows')
|
|
268
|
+
}
|
|
269
|
+
function add(a, b) { const coefficients = { ...a.coefficients }; for (const [key, value] of Object.entries(b.coefficients)) coefficients[key] = (coefficients[key] ?? 0) + value; return { constant: a.constant + b.constant, coefficients } }
|
|
270
|
+
function scale(value, factor) { return { constant: value.constant * factor, coefficients: Object.fromEntries(Object.entries(value.coefficients).map(([key, amount]) => [key, amount * factor])) } }
|
|
271
|
+
|
|
272
|
+
function validatePriceBranch(tree, env, multiplier) {
|
|
273
|
+
const trace = { fixed: null, matchedTier: '' }
|
|
274
|
+
const vector = checkedVector(linearize(tree, env, trace))
|
|
275
|
+
if (multiplier) {
|
|
276
|
+
const value = evalTree(tree, env, trace)
|
|
277
|
+
if (!finite(value) || value < 0 || Object.keys(vector.coefficients).length) fail('unsupported_expression', 'billing multipliers must be finite non-negative scalars')
|
|
278
|
+
} else if (vector.constant !== 0 && trace.fixed === null) fail('unsupported_expression', 'constant request charges require fixed()')
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function isScalarFactor(factor, price) {
|
|
282
|
+
return usesTokenValue(price) && !usesTokenValue(factor) && !containsCall(factor, 'fixed')
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function validateAllBranches(tree, env, multiplier = false) {
|
|
286
|
+
if (tree.type === 'conditional') {
|
|
287
|
+
validatePriceBranch(tree.yes, env, multiplier)
|
|
288
|
+
validatePriceBranch(tree.no, env, multiplier)
|
|
289
|
+
validateAllBranches(tree.test, env)
|
|
290
|
+
validateAllBranches(tree.yes, env, multiplier)
|
|
291
|
+
validateAllBranches(tree.no, env, multiplier)
|
|
292
|
+
} else if (tree.type === 'binary') {
|
|
293
|
+
// Bare numeric branches are valid as token-price factors, not as request charges.
|
|
294
|
+
const product = tree.op === '*'
|
|
295
|
+
validateAllBranches(tree.left, env, product && (multiplier || isScalarFactor(tree.left, tree.right)))
|
|
296
|
+
validateAllBranches(tree.right, env, product && (multiplier || isScalarFactor(tree.right, tree.left)))
|
|
297
|
+
} else if (tree.type === 'unary') validateAllBranches(tree.value, env)
|
|
298
|
+
else if (tree.type === 'call') for (const arg of tree.args) validateAllBranches(arg, env)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export function analyzeNikoBillingExpression(expression) {
|
|
302
|
+
if (typeof expression === 'string' && compiled.has(expression)) return compiled.get(expression)
|
|
303
|
+
const result = compileExpression(expression)
|
|
304
|
+
if (typeof expression === 'string' && expression.length <= maxExpressionLength) {
|
|
305
|
+
if (compiled.size >= 128) compiled.delete(compiled.keys().next().value)
|
|
306
|
+
compiled.set(expression, result)
|
|
307
|
+
}
|
|
308
|
+
return result
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function compileExpression(expression) {
|
|
312
|
+
try {
|
|
313
|
+
if (typeof expression !== 'string' || expression.length > maxExpressionLength) fail('invalid_expression', 'invalid expression size')
|
|
314
|
+
if (/^v\d+:/.test(expression) && !expression.startsWith('v1:')) fail('unsupported_expression', 'unknown billing expression version')
|
|
315
|
+
const parts = (expression.startsWith('v1:') ? expression.slice(3) : expression).split('|||')
|
|
316
|
+
if (parts.length > 2) fail('invalid_expression', 'only one request-rule section is allowed')
|
|
317
|
+
const tree = parsePart(parts[0].trim())
|
|
318
|
+
const rules = parts.length === 2 ? parsePart(parts[1].trim()) : null
|
|
319
|
+
validateFixed(tree)
|
|
320
|
+
if (rules && containsCall(rules, 'fixed')) fail('unsupported_expression', 'fixed() is not allowed in request-rule multipliers')
|
|
321
|
+
const variables = new Set()
|
|
322
|
+
let unsupported
|
|
323
|
+
let zeroRequestContext = false
|
|
324
|
+
walk(tree, node => {
|
|
325
|
+
if (node.type === 'variable') variables.add(node.name)
|
|
326
|
+
if (node.type === 'call' && ['u', 'param', 'header'].includes(node.name)) {
|
|
327
|
+
if (node.name === 'u') zeroRequestContext = true
|
|
328
|
+
unsupported = `${node.name}() requires request fields unavailable to the local usage ledger`
|
|
329
|
+
}
|
|
330
|
+
})
|
|
331
|
+
if (rules) walk(rules, node => {
|
|
332
|
+
if (node.type === 'variable') variables.add(node.name)
|
|
333
|
+
if (node.type === 'call' && ['u', 'param', 'header'].includes(node.name)) {
|
|
334
|
+
if (node.name === 'u') zeroRequestContext = true
|
|
335
|
+
unsupported = `${node.name}() request rules are not available to the local usage ledger`
|
|
336
|
+
}
|
|
337
|
+
})
|
|
338
|
+
const zeroByPolicy = zeroRequestContext || variables.has('image_count')
|
|
339
|
+
// DSH reports one merged cache-write total, so the long-TTL variables (`cc1h`,
|
|
340
|
+
// `cc12h`) never receive a split. Their tokens stay in the short-TTL bucket,
|
|
341
|
+
// which is the default new-api applies to an unlabelled cache-write remainder
|
|
342
|
+
// (service/tiered_settle.go: "billed as 5m writes"), never a zero charge.
|
|
343
|
+
if (!unsupported) {
|
|
344
|
+
const env = { p: 1000, c: 300, len: 1500, cr: 100, cc: 50, cc1h: 0, cc12h: 0,
|
|
345
|
+
img: 0, img_cr: 0, img_o: 0, ai: 0, ao: 0, image_count: 1, atMs: Date.UTC(2026, 0, 1, 12) }
|
|
346
|
+
const trace = { fixed: null, matchedTier: '' }
|
|
347
|
+
const initial = checkedVector(linearize(tree, env, trace))
|
|
348
|
+
if (initial.constant !== 0 && trace.fixed === null) fail('unsupported_expression', 'constant request charges require fixed()')
|
|
349
|
+
if (rules) checkedVector(linearize(rules, env, trace))
|
|
350
|
+
validateAllBranches(tree, env)
|
|
351
|
+
if (rules) validateAllBranches(rules, env)
|
|
352
|
+
}
|
|
353
|
+
return { supported: !unsupported, zeroByPolicy, reason: unsupported ?? '', tree, rules, variables, fixedPricing: containsCall(tree, 'fixed') }
|
|
354
|
+
} catch (error) { return { supported: false, zeroByPolicy: false, reason: error?.message ?? 'billing expression is not supported', error } }
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function zeroPolicyQuote(reason = 'request uses a billing field excluded by the local policy') {
|
|
358
|
+
return { currency: 'CNY', cost: 0, matchedTier: 'zero-policy', billingUnit: 'request', zeroByPolicy: true,
|
|
359
|
+
note: reason, rows: [{ bucket: 'modelRequests', tokens: 0, requests: 1, rate: 0, cost: 0, priced: true }] }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function requestPriceQuote(value) {
|
|
363
|
+
const amount = Number(value)
|
|
364
|
+
if (!finite(amount) || amount < 0) return null
|
|
365
|
+
return { currency: 'CNY', cost: amount, matchedTier: 'request-price', billingUnit: 'request',
|
|
366
|
+
rows: [{ bucket: 'modelRequests', tokens: 0, requests: 1, rate: amount, cost: amount, priced: true }] }
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function nikoBillingBreakdown(tokens, entry, atMs = Date.now()) {
|
|
370
|
+
const requestPrice = requestPriceQuote(entry?.requestPriceCny)
|
|
371
|
+
if (requestPrice !== null) return requestPrice
|
|
372
|
+
const parsed = analyzeNikoBillingExpression(entry?.billingExpr)
|
|
373
|
+
const safeTokens = Object.fromEntries(['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning'].map(key => {
|
|
374
|
+
const value = Number(tokens?.[key] ?? 0)
|
|
375
|
+
if (!finite(value) || value < 0) fail('invalid_usage', 'usage buckets must be finite and non-negative')
|
|
376
|
+
return [key, value]
|
|
377
|
+
}))
|
|
378
|
+
if (entry?.zeroByPolicy === true || parsed.zeroByPolicy === true) return zeroPolicyQuote(parsed.reason)
|
|
379
|
+
if (!parsed.supported) return null
|
|
380
|
+
const variables = parsed.variables
|
|
381
|
+
const cacheRead = safeTokens.cacheRead
|
|
382
|
+
const cacheWrite = safeTokens.cacheWrite
|
|
383
|
+
const p = safeTokens.input + (variables.has('cr') ? 0 : cacheRead) + (variables.has('cc') ? 0 : cacheWrite)
|
|
384
|
+
const c = safeTokens.output
|
|
385
|
+
const env = { p, c, len: safeTokens.input + cacheRead + cacheWrite, cr: cacheRead, cc: cacheWrite, cc1h: 0, cc12h: 0, img: 0, img_cr: 0, img_o: 0, ai: 0, ao: 0, image_count: 1, atMs }
|
|
386
|
+
const trace = { fixed: null, matchedTier: '' }
|
|
387
|
+
try {
|
|
388
|
+
let vector = linearize(parsed.tree, env, trace)
|
|
389
|
+
let multiplier = 1
|
|
390
|
+
if (parsed.rules) multiplier = safeNumber(evalTree(parsed.rules, env, trace))
|
|
391
|
+
vector = scale(vector, multiplier)
|
|
392
|
+
const expressionValue = safeNumber(evalTree(parsed.tree, env, { fixed: null, matchedTier: '' })) * multiplier
|
|
393
|
+
if (expressionValue < 0 || !finite(expressionValue) || !finite(multiplier) || multiplier < 0) return null
|
|
394
|
+
const quotaPerUnit = Number(entry.billingQuotaPerUnit)
|
|
395
|
+
const groupRatio = Number(entry.billingGroupRatio)
|
|
396
|
+
if (!finite(quotaPerUnit) || quotaPerUnit <= 0 || !finite(groupRatio) || groupRatio < 0) return null
|
|
397
|
+
const quotaScale = quotaPerUnit * groupRatio / 1_000_000
|
|
398
|
+
if (trace.fixed !== null) {
|
|
399
|
+
const rawQuota = trace.fixed * multiplier * quotaPerUnit * groupRatio
|
|
400
|
+
if (!finite(rawQuota) || rawQuota > 2_147_483_647) return null
|
|
401
|
+
const amount = Math.round(rawQuota) / quotaPerUnit
|
|
402
|
+
return { currency: 'CNY', cost: amount, matchedTier: trace.matchedTier, billingUnit: 'request', rows: [{ bucket: 'modelRequests', tokens: 0, requests: 1, rate: amount, cost: amount, priced: true }] }
|
|
403
|
+
}
|
|
404
|
+
const rows = []
|
|
405
|
+
const addRow = (bucket, count, rate) => {
|
|
406
|
+
if (count <= 0) return
|
|
407
|
+
const cnyRate = rate * groupRatio
|
|
408
|
+
rows.push({ bucket, tokens: count, rate: cnyRate, cost: count * cnyRate / 1_000_000, priced: true })
|
|
409
|
+
}
|
|
410
|
+
const pRate = vector.coefficients.p ?? 0
|
|
411
|
+
addRow('input', safeTokens.input, pRate)
|
|
412
|
+
if (!variables.has('cr')) addRow('cacheRead', cacheRead, pRate)
|
|
413
|
+
if (!variables.has('cc')) addRow('cacheWrite', cacheWrite, pRate)
|
|
414
|
+
addRow('cacheRead', variables.has('cr') ? cacheRead : 0, vector.coefficients.cr ?? 0)
|
|
415
|
+
addRow('cacheWrite', variables.has('cc') ? cacheWrite : 0, vector.coefficients.cc ?? 0)
|
|
416
|
+
const cRate = vector.coefficients.c ?? 0
|
|
417
|
+
addRow('output', safeTokens.output, cRate)
|
|
418
|
+
const rawQuota = expressionValue * quotaScale
|
|
419
|
+
if (!finite(rawQuota) || rawQuota > 2_147_483_647) return null
|
|
420
|
+
const cost = Math.round(rawQuota) / quotaPerUnit
|
|
421
|
+
const rowCost = rows.reduce((sum, row) => sum + row.cost, 0)
|
|
422
|
+
const rounding = cost - rowCost
|
|
423
|
+
if (rows.length && rounding !== 0) {
|
|
424
|
+
const largest = rows.reduce((a,b)=>a.cost >= b.cost ? a : b)
|
|
425
|
+
largest.cost += rounding
|
|
426
|
+
if (largest.cost < 0) return null
|
|
427
|
+
}
|
|
428
|
+
else if (!rows.length && cost > 0) rows.push({ bucket: 'modelRequests', tokens: 0, requests: 1, rate: cost, cost, priced: true })
|
|
429
|
+
return { currency: 'CNY', cost, matchedTier: trace.matchedTier, billingUnit: 'token', rows }
|
|
430
|
+
} catch { return null }
|
|
431
|
+
}
|
package/lib/costmeter.js
CHANGED
|
@@ -144,6 +144,53 @@ export function planBinding(current, options) {
|
|
|
144
144
|
}
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
+
const ACCOUNT_PATH = '/api/user/self'
|
|
148
|
+
const TOKEN_QUOTA_PATH = '/api/usage/token/'
|
|
149
|
+
|
|
150
|
+
/** A user's own NikoAPI balance row, current or legacy shape, is already the answer. */
|
|
151
|
+
function isNikoLabelEntry(entry, site) {
|
|
152
|
+
if (entry?.label !== BALANCE_LABEL) return false
|
|
153
|
+
const url = entry?.request?.url
|
|
154
|
+
return url === `${site}${ACCOUNT_PATH}` || url === `${site}${TOKEN_QUOTA_PATH}`
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Balance-only plan: reuse whatever already answers the question, otherwise add one entry.
|
|
159
|
+
* Prices are never part of this patch, so it can run beside the price calculators.
|
|
160
|
+
* Existing rows win — a template-shaped row, a row we created earlier, or any NikoAPI-labelled
|
|
161
|
+
* row on this origin. Only a site-origin change relocates the row we created.
|
|
162
|
+
*/
|
|
163
|
+
export function planBalanceBinding(current, options = {}) {
|
|
164
|
+
const config = current ?? {}
|
|
165
|
+
let site = ''
|
|
166
|
+
try { site = new URL(options.origin).origin } catch { site = '' }
|
|
167
|
+
if (!site) return { ok: false, changed: false, created: false, reused: false, patch: null, balance: null, reason: 'a site origin is required before the account balance can be linked' }
|
|
168
|
+
const credentialVar = options.credentialVar ?? BALANCE_VAR
|
|
169
|
+
const rows = [...(config.customBalances ?? [])]
|
|
170
|
+
const owned = rows.findIndex(entry => ownedBalanceMatches(entry, options.ownedBalance, options.origin))
|
|
171
|
+
if (owned >= 0) {
|
|
172
|
+
const url = rows[owned].request?.url
|
|
173
|
+
if (url === `${site}${ACCOUNT_PATH}`) {
|
|
174
|
+
return { ok: true, changed: false, created: false, reused: true, patch: null,
|
|
175
|
+
balance: { url, credentialVar: credentialOf(rows[owned]) ?? credentialVar } }
|
|
176
|
+
}
|
|
177
|
+
const next = [...rows]
|
|
178
|
+
next[owned] = balanceEntry({ origin: site, refreshMinutes: options.refreshMinutes, credentialVar })
|
|
179
|
+
return { ok: true, changed: true, created: false, reused: false, relocated: true, patch: { customBalances: next },
|
|
180
|
+
balance: { url: next[owned].request.url, credentialVar } }
|
|
181
|
+
}
|
|
182
|
+
if (rows.some(entry => isNikoAccountBalance(entry, site) || isNikoLabelEntry(entry, site))) {
|
|
183
|
+
return { ok: true, changed: false, created: false, reused: true, retained: true, patch: null, balance: null }
|
|
184
|
+
}
|
|
185
|
+
if (rows.length >= 8) {
|
|
186
|
+
return { ok: false, changed: false, created: false, reused: false, patch: null, balance: null,
|
|
187
|
+
reason: 'cost-meter already holds 8 custom balance entries; no existing entry was changed' }
|
|
188
|
+
}
|
|
189
|
+
const entry = balanceEntry({ origin: site, refreshMinutes: options.refreshMinutes, credentialVar })
|
|
190
|
+
return { ok: true, changed: true, created: true, reused: false, patch: { customBalances: [...rows, entry] },
|
|
191
|
+
balance: { url: entry.request.url, credentialVar } }
|
|
192
|
+
}
|
|
193
|
+
|
|
147
194
|
/** Remove precisely owned generated entries; an existing working account template is never owned. */
|
|
148
195
|
export function planUnbind(current, ownership = {}) {
|
|
149
196
|
const config = current ?? {}
|