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.
@@ -0,0 +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
+ }
@@ -0,0 +1,96 @@
1
+ const DYNAMIC = 'nikoapi-expression-v1'
2
+ const UNKNOWN_NOTE = 'dsh-nikoapi: unavailable rate; '
3
+ const safe = name => typeof name === 'string' && name.length > 0 && !['__proto__', 'constructor', 'prototype'].includes(name)
4
+ const keyOf = (provider, model) => `${provider}:${model}`
5
+ const splitKey = key => { const i = typeof key === 'string' ? key.indexOf(':') : -1; return i > 0 ? [key.slice(0,i), key.slice(i+1)] : [] }
6
+ const stable = value => JSON.stringify(value, (key, child) => child && typeof child === 'object' && !Array.isArray(child)
7
+ ? Object.fromEntries(Object.entries(child).sort(([a],[b])=>a.localeCompare(b))) : child)
8
+ const exactPrice = price => price?.kind === 'perMillion' && price.reference !== true && ['USD','CNY'].includes(price.currency)
9
+ && ['input','output','cacheHit'].every(key => Number.isFinite(price[key]) && price[key] >= 0)
10
+
11
+ /** Compare the fields the cost-meter normalizer retains; manual edits revoke ownership. */
12
+ export function priceSignature(entry) {
13
+ if (!entry || typeof entry !== 'object') return ''
14
+ if (entry.calculator) return stable({ calculator: entry.calculator })
15
+ if (entry.unpriced === true) return stable({ unpriced:true, notes:entry.notes, sourceUrl:entry.sourceUrl })
16
+ return stable({ ...Object.fromEntries(['currency','cacheMiss','cacheHit','output','cacheWrite','reasoning'].filter(key=>entry[key]!==undefined).map(key=>[key,entry[key]])), billingMode:entry.billingMode??'flat' })
17
+ }
18
+ function currentPrice(config, key) {
19
+ const [provider, model] = splitKey(key)
20
+ if (!safe(provider) || !safe(model)) return undefined
21
+ return config.priceOverrides?.[key] === '__custom__' ? config.prices?.custom?.[key] : config.prices?.providers?.[provider]?.models?.[model]
22
+ }
23
+ const ownedNow = (config, options, key) => typeof options.ownedPriceSnapshots?.[key] === 'string'
24
+ && priceSignature(currentPrice(config,key)) === options.ownedPriceSnapshots[key]
25
+ function mutableModels(config, changes, provider) {
26
+ if (!Object.hasOwn(changes,provider)) changes[provider] = { ...(config.prices?.providers?.[provider]??{}), models:{...(config.prices?.providers?.[provider]?.models??{})} }
27
+ return changes[provider].models
28
+ }
29
+ function removeOwned(config, overrides, custom, changes, key) {
30
+ if (overrides[key] === '__custom__') { delete overrides[key]; delete custom[key] }
31
+ else {
32
+ const [provider,model] = splitKey(key)
33
+ if (safe(provider) && safe(model)) delete mutableModels(config,changes,provider)[model]
34
+ }
35
+ }
36
+ function dynamicEntry(price, options) {
37
+ if (price?.kind === 'perCall' && price.currency === 'CNY' && Number.isFinite(price.perCall) && price.perCall >= 0) {
38
+ return { calculator: { adapter: DYNAMIC, currency: 'CNY', snapshot: JSON.stringify({ requestPriceCny: price.perCall }) } }
39
+ }
40
+ if (!['nikoExpression', 'nikoZero'].includes(price?.kind) || price.adapterSupported !== true || typeof price.expression !== 'string') return null
41
+ const quota = Number(options.quotaPerUnit ?? price.quotaPerUnit), ratio = Number(price.groupRatio)
42
+ if (!Number.isFinite(quota) || quota <= 0 || !Number.isFinite(ratio) || ratio < 0) return null
43
+ return { calculator: { adapter: DYNAMIC, currency: 'CNY', snapshot: JSON.stringify({
44
+ billingExpr: price.expression, billingQuotaPerUnit: quota, billingGroupRatio: ratio,
45
+ ...(price.kind === 'nikoZero' ? { zeroByPolicy: true } : {}),
46
+ }) } }
47
+ }
48
+
49
+ /** Only prices: balance sources are never inspected or included in this patch. */
50
+ export function planPriceBinding(current, options) {
51
+ const config = current??{}, overrides={...(config.priceOverrides??{})}, custom={...(config.prices?.custom??{})}, changes={}
52
+ const models = Array.isArray(options.models)?options.models:[]
53
+ const prior = new Set([...(options.ownedPriceKeys??[]),...(options.ownedUnpricedKeys??[])])
54
+ const expected = new Set(models.map(model=>keyOf(model.provider??'nikoapi',model.id)))
55
+ for (const key of prior) if (!expected.has(key)&&ownedNow(config,options,key)) removeOwned(config,overrides,custom,changes,key)
56
+ const priced = [], dynamic = [], zeroPolicy = [], unpriced = [], conflicts = [], ownedPriceKeys = [], ownedUnpricedKeys = [], ownedPriceSnapshots = {}
57
+ for (const model of models) {
58
+ const provider=model.provider??'nikoapi', id=model.id, key=keyOf(provider,id)
59
+ if (!/^nikoapi(?:-[1-9]\d*)?$/.test(provider)||!safe(id)) { conflicts.push({key,reason:'invalid Niko price identity'}); continue }
60
+ const table=config.prices?.providers?.[provider]?.models??{}
61
+ const hasExisting = Object.hasOwn(config.priceOverrides??{},key)||Object.hasOwn(custom,key)||Object.hasOwn(table,id)
62
+ const stillOwned = prior.has(key)&&ownedNow(config,options,key)
63
+ if (hasExisting&&!stillOwned) { conflicts.push({key,reason:'existing or manually edited user price kept'}); continue }
64
+ if (stillOwned) removeOwned(config,overrides,custom,changes,key)
65
+ const dynamicRate=dynamicEntry(model.price,options)
66
+ let written
67
+ if (dynamicRate) {
68
+ written = dynamicRate
69
+ mutableModels(config, changes, provider)[id] = written
70
+ ownedPriceKeys.push(key)
71
+ dynamic.push({ provider, id, key })
72
+ if (model.price?.kind === 'nikoZero') zeroPolicy.push({ provider, id, key, note: model.price.note ?? '' })
73
+ } else if (exactPrice(model.price)) {
74
+ overrides[key]='__custom__'
75
+ written={currency:model.price.currency,cacheMiss:model.price.input,cacheHit:model.price.cacheHit,output:model.price.output,
76
+ ...(Number.isFinite(model.price.cacheWrite)?{cacheWrite:model.price.cacheWrite}:{})}
77
+ custom[key]=written; ownedPriceKeys.push(key); priced.push({provider,id,key})
78
+ } else {
79
+ written={unpriced:true,notes:UNKNOWN_NOTE+(model.price?.note??'exact price unavailable'),sourceUrl:`${new URL(options.origin).origin}/api/pricing`}
80
+ mutableModels(config,changes,provider)[id]=written; ownedUnpricedKeys.push(key)
81
+ unpriced.push({provider,id,key,kind:model.price?.kind??'unknown',note:model.price?.note??''})
82
+ }
83
+ ownedPriceSnapshots[key]=priceSignature(written)
84
+ }
85
+ return {patch:{priceOverrides:overrides,prices:{custom,...(Object.keys(changes).length?{providers:changes}:{})}},
86
+ summary: { priced, dynamic, zeroPolicy, unpriced, conflicts, ownedPriceKeys, ownedUnpricedKeys, ownedPriceSnapshots } }
87
+ }
88
+
89
+ export function planPriceUnbind(current, ownership={}) {
90
+ const config=current??{},overrides={...(config.priceOverrides??{})},custom={...(config.prices?.custom??{})},changes={},removed=[],retained=[]
91
+ for (const key of new Set([...(ownership.ownedPriceKeys??[]),...(ownership.ownedUnpricedKeys??[])])) {
92
+ if (ownedNow(config,ownership,key)) { removeOwned(config,overrides,custom,changes,key); removed.push(key) }
93
+ else retained.push(key)
94
+ }
95
+ return {patch:{priceOverrides:overrides,prices:{custom,...(Object.keys(changes).length?{providers:changes}:{})}},removed,retained,balanceSourcesChanged:false}
96
+ }