bailinghub 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -5
- package/README.md +6 -5
- package/docker-compose.images.yml +2 -2
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CHANGELOG.en.md +12 -1
- package/docs/CHANGELOG.md +12 -1
- package/docs/COMPATIBILITY.en.md +4 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/MODEL_BILLING.en.md +123 -0
- package/docs/MODEL_BILLING.md +125 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
- package/docs/README.en.md +5 -1
- package/docs/README.md +4 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
- package/docs/RELEASE_NOTES_NEXT.md +4 -2
- package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
- package/docs/UPGRADE_v0.9.0.en.md +54 -0
- package/docs/UPGRADE_v0.9.0.md +54 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
- package/package.json +1 -1
- package/scripts/check-doc-links.mjs +4 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +1 -0
- package/scripts/sdk-runtime-test.mjs +6 -0
- package/scripts/verify-billing-install-upgrade.mjs +225 -0
- package/scripts/verify-github-repo.mjs +1 -0
- package/sdk/node/README.md +17 -0
- package/sdk/node/examples/billing.mjs +21 -0
- package/sdk/node/package.json +5 -1
- package/sdk/node/src/index.mjs +2 -0
- package/sdk/node/src/usage.d.mts +74 -0
- package/sdk/node/src/usage.mjs +62 -0
- package/sdk/node/tests/usage-types.mts +23 -0
- package/sdk/node/tests/usage.test.mjs +81 -0
- package/sdk/php7/README.md +19 -2
- package/sdk/php7/examples/billing.php +27 -0
- package/sdk/php7/examples/well-known.php +1 -1
- package/sdk/php7/src/ToolSpec.php +1 -1
- package/sdk/php7/src/UsageClient.php +95 -0
- package/sdk/php7/src/UsageClientException.php +22 -0
- package/sdk/php7/tests/billing-core-http.php +59 -0
- package/sdk/php7/tests/usage-client.php +78 -0
- package/sql/063_usage_model_billing.sql +153 -0
- package/sql/064_period_plan_allowance.sql +25 -0
- package/sql/README.en.md +12 -4
- package/sql/README.md +14 -6
- package/src/app/auth.ts +2 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/infrastructure/config/configstore.ts +6 -0
- package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
- package/src/modules/usage/billing-contracts.ts +59 -0
- package/src/modules/usage/billing-decimal.test.ts +22 -0
- package/src/modules/usage/billing-decimal.ts +36 -0
- package/src/modules/usage/billing-external.ts +39 -0
- package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
- package/src/modules/usage/billing-ledger.test.ts +51 -0
- package/src/modules/usage/billing-ledger.ts +104 -0
- package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
- package/src/modules/usage/billing-presentation.test.ts +49 -0
- package/src/modules/usage/billing-presentation.ts +34 -0
- package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
- package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
- package/src/modules/usage/billing-repository.ts +463 -0
- package/src/modules/usage/contracts.ts +49 -0
- package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
- package/src/modules/usage/errors.ts +19 -0
- package/src/modules/usage/http.ts +85 -0
- package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
- package/src/modules/usage/identity.mysql.test.ts +120 -0
- package/src/modules/usage/identity.ts +303 -0
- package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
- package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
- package/src/modules/usage/model-gateway.ts +229 -0
- package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
- package/src/modules/usage/model-tool-provider.test.ts +37 -0
- package/src/modules/usage/model-tool-provider.ts +110 -0
- package/src/modules/usage/model-tools.test.ts +36 -0
- package/src/modules/usage/model-tools.ts +62 -0
- package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
- package/src/modules/usage/period.test.ts +26 -0
- package/src/modules/usage/period.ts +96 -0
- package/src/modules/usage/pricing.test.ts +178 -0
- package/src/modules/usage/pricing.ts +228 -0
- package/src/modules/usage/provider-failure.ts +37 -0
- package/src/modules/usage/provider-stream.test.ts +85 -0
- package/src/modules/usage/provider-stream.ts +77 -0
- package/src/modules/usage/provider.test.ts +67 -0
- package/src/modules/usage/provider.ts +142 -0
- package/src/modules/usage/repository.ts +539 -0
- package/src/modules/usage/service-availability.mysql.test.ts +68 -0
- package/src/modules/usage/service-availability.ts +13 -0
- package/src/modules/usage/service-delete.mysql.test.ts +87 -0
- package/src/modules/usage/stream-http.ts +32 -0
- package/src/modules/usage/test-harness.ts +108 -0
- package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
- package/src/modules/usage/usage-deletion.ts +119 -0
- package/src/modules/usage/validation.test.ts +18 -0
- package/src/modules/usage/validation.ts +33 -0
- package/src/routes/admin-billing-usage.ts +73 -0
- package/src/routes/admin-usage.ts +147 -0
- package/src/routes/admin.ts +4 -0
- package/src/routes/private.ts +8 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/Accounts-Bervi5JU.css +1 -0
- package/web/console/assets/Accounts-DnddhY6t.js +3 -0
- package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-VInbD7JS.js} +1 -1
- package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
- package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
- package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-34qUPHf0.js} +1 -1
- package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-BbVgkSm2.js} +1 -1
- package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-DgscF28e.js} +1 -1
- package/web/console/assets/{Channels-B9n4fbxg.js → Channels-Bp-yuk8d.js} +1 -1
- package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-C9Ft60TS.js} +1 -1
- package/web/console/assets/{Clients-CI3DBDHf.js → Clients-NPldD-DD.js} +1 -1
- package/web/console/assets/{Cost-JgNXQPlN.js → Cost-DZcuB-EB.js} +1 -1
- package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-RTT7N6zl.js} +1 -1
- package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-_LeK8cce.js} +1 -1
- package/web/console/assets/{Executors-CRbboOCZ.js → Executors-Bi7H8rIm.js} +1 -1
- package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
- package/web/console/assets/{Kb-CgLNGjRp.js → Kb-BHamz8NP.js} +2 -2
- package/web/console/assets/{Login-C52JmXzx.js → Login-C1rJR-6w.js} +1 -1
- package/web/console/assets/{Projects-CDOvHPVS.js → Projects-BRA4a48v.js} +1 -1
- package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
- package/web/console/assets/Routes-CyXV4Pba.css +1 -0
- package/web/console/assets/{Runs-DYNDXsqk.js → Runs-B_fa_BlD.js} +1 -1
- package/web/console/assets/{Setup-B91P6i1x.js → Setup-C1_d0mFy.js} +1 -1
- package/web/console/assets/Shell-CHEV6RGC.js +1 -0
- package/web/console/assets/Shell-ykb-tUfo.css +1 -0
- package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DlG3ojhA.js} +1 -1
- package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-DYo2gg6d.js} +1 -1
- package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-DKCoUZlq.js} +1 -1
- package/web/console/assets/{Targets-CuuIYeZO.js → Targets-CdkG6BPR.js} +1 -1
- package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DVpCt0ox.js} +1 -1
- package/web/console/assets/Usage-CAeDGjrb.css +1 -0
- package/web/console/assets/Usage-DWCpLugC.js +1 -0
- package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
- package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
- package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
- package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
- package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
- package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
- package/web/console/assets/index-H1kfa0Mj.js +2 -0
- package/web/console/assets/{request-DeGya810.js → request-DLsP1_ot.js} +1 -1
- package/web/console/assets/{schema-BqlqLw1R.js → schema-BLOHvAJQ.js} +1 -1
- package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
- package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
- package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
- package/web/console/index.html +3 -3
- package/web-admin/README.md +17 -0
- package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
- package/web-admin/src/components/UsageHelp.vue +72 -0
- package/web-admin/src/components/UsageServiceReferences.vue +169 -0
- package/web-admin/src/layout/Shell.vue +22 -5
- package/web-admin/src/pages/Accounts.vue +3 -3
- package/web-admin/src/pages/AgentTasks.vue +2 -2
- package/web-admin/src/pages/Routes.vue +5 -1
- package/web-admin/src/pages/Usage.vue +2470 -0
- package/web-admin/src/pages/UsageAccess.vue +1147 -0
- package/web-admin/src/router.ts +8 -4
- package/web-admin/src/styles/base.css +57 -0
- package/web-admin/src/table-widths.ts +16 -1
- package/web-admin/src/usage-deletion.ts +40 -0
- package/web-admin/src/usage-management.ts +13 -0
- package/web-admin/src/usage-presentation.test.ts +21 -0
- package/web-admin/src/usage-presentation.ts +107 -0
- package/web-admin/src/usage-price-preview.test.ts +60 -0
- package/web-admin/src/usage-price-preview.ts +54 -0
- package/web-admin/tests/token-usage.browser.mjs +773 -0
- package/web-admin/tests/usage-access.browser.mjs +398 -0
- package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
- package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
- package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
- package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
- package/web/console/assets/Routes-DkMIjMQA.css +0 -1
- package/web/console/assets/Routes-X9vHLpKW.js +0 -124
- package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
- package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
- package/web/console/assets/index-UGvfF3Xr.js +0 -2
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { ResolvedLlmCredential } from '../../core/runtime/credential-resolver';
|
|
2
|
+
import type { UsageServiceConfig } from './contracts';
|
|
3
|
+
import { UsageError, usageAssert } from './errors';
|
|
4
|
+
import { object, type ProviderResult } from './provider';
|
|
5
|
+
import { ProviderFailure, httpProviderFailure, safeProviderIdentifier } from './provider-failure';
|
|
6
|
+
|
|
7
|
+
/** The host supplies declared arguments only; no arbitrary endpoint, credential or provider routing. */
|
|
8
|
+
export function modelToolBody(config: UsageServiceConfig, args: unknown): Record<string, unknown> {
|
|
9
|
+
const tool = config.tool;
|
|
10
|
+
usageAssert(tool && tool.adapter !== 'pending', 'MODEL_TOOL_ADAPTER_NOT_READY', '该工具目前仅声明,尚未配置执行适配。', 400);
|
|
11
|
+
usageAssert(object(args), 'USAGE_INVALID_INPUT', '工具参数应为对象。', 400);
|
|
12
|
+
usageAssert(Object.keys(args).every(k => tool.parameters.some(p => p.name === k)), 'USAGE_INVALID_INPUT', '存在未声明的工具参数。', 400);
|
|
13
|
+
for (const p of tool.parameters) {
|
|
14
|
+
const v = args[p.name];
|
|
15
|
+
if (v === undefined) { usageAssert(!p.required, 'USAGE_INVALID_INPUT', `缺少工具参数 ${p.name}。`, 400); continue; }
|
|
16
|
+
usageAssert(typeof v === p.type && (typeof v !== 'number' || Number.isFinite(v)), 'USAGE_INVALID_INPUT', `工具参数 ${p.name} 类型错误。`, 400);
|
|
17
|
+
}
|
|
18
|
+
usageAssert(typeof args.prompt === 'string' && args.prompt.trim().length > 0, 'USAGE_INVALID_INPUT', '请提供生成提示词。', 400);
|
|
19
|
+
if (args.n !== undefined) usageAssert(Number.isInteger(args.n) && Number(args.n) >= 1 && Number(args.n) <= (tool.adapter.startsWith('aliyun-image') ? 6 : 10), 'USAGE_INVALID_INPUT','图片数量无效。',400);
|
|
20
|
+
if (args.seed !== undefined) usageAssert(Number.isSafeInteger(args.seed) && Number(args.seed) >= 0 && Number(args.seed) <= 2147483647, 'USAGE_INVALID_INPUT','seed无效。',400);
|
|
21
|
+
const body = { model:config.model,...args };
|
|
22
|
+
usageAssert(Buffer.byteLength(JSON.stringify(body)) <= config.maxInputBytes, 'USAGE_INPUT_LIMIT','生成参数超过服务传输大小限制。',400);
|
|
23
|
+
return body;
|
|
24
|
+
}
|
|
25
|
+
const count=(v:unknown):v is number=>typeof v==='number' && Number.isSafeInteger(v) && v>=0;
|
|
26
|
+
const tier=(v:unknown)=>typeof v==='string' ? v.match(/(?:^|_)(512|1k|2k|4k)$/i)?.[1]?.toLowerCase() : undefined;
|
|
27
|
+
/** A completed image response is usage evidence; missing usage is not invented Token usage. */
|
|
28
|
+
export function imageProviderResult(adapter:string, value:unknown, requestId:string|null):ProviderResult {
|
|
29
|
+
usageAssert(object(value) && Array.isArray(value.data) && value.data.length > 0 && value.data.length <= 10, 'USAGE_PROVIDER_INVALID','生成服务未返回有效图片结果。',502);
|
|
30
|
+
const outputs = value.data.map(item=> {
|
|
31
|
+
usageAssert(object(item), 'USAGE_PROVIDER_INVALID','生成结果格式异常。',502);
|
|
32
|
+
if(typeof item.url === 'string') {let url:URL; try{url=new URL(item.url);}catch{throw new UsageError('USAGE_PROVIDER_INVALID','生成结果地址无效。',502);}
|
|
33
|
+
usageAssert(['https:','http:'].includes(url.protocol) && !url.username && !url.password, 'USAGE_PROVIDER_INVALID','生成结果地址无效。',502);
|
|
34
|
+
return {type:'image',url:item.url,...(typeof item.media_type==='string'?{mime_type:item.media_type}:{})};}
|
|
35
|
+
usageAssert(typeof item.b64_json==='string' && /^[A-Za-z0-9+/]+={0,2}$/.test(item.b64_json), 'USAGE_PROVIDER_INVALID','生成结果缺少图片内容。',502);
|
|
36
|
+
return {type:'image',base64:item.b64_json,...(typeof item.media_type==='string'?{mime_type:item.media_type}:{})};
|
|
37
|
+
});
|
|
38
|
+
const u=object(value.usage)?value.usage:{};
|
|
39
|
+
const raw:Record<string,unknown>={...u,requestCount:1};
|
|
40
|
+
if(adapter.startsWith('aliyun-image')) {
|
|
41
|
+
if(count(u.input_image_count))raw.inputImageCount=u.input_image_count;
|
|
42
|
+
if(count(u.output_image_count))raw.outputImageCount=u.output_image_count;
|
|
43
|
+
if(tier(u.input_image_type))raw.inputVariant=tier(u.input_image_type);
|
|
44
|
+
if(tier(u.output_image_type))raw.outputVariant=tier(u.output_image_type);
|
|
45
|
+
if(count(u.output_width)&&count(u.output_height)&&count(u.output_image_count))raw.outputPixelCount=u.output_width*u.output_height*u.output_image_count;
|
|
46
|
+
} else {
|
|
47
|
+
// The implemented adapter is text-to-image only; output evidence supplies actual count.
|
|
48
|
+
raw.inputImageCount=0;raw.outputImageCount=outputs.length;
|
|
49
|
+
if(typeof u.resolution==='string')raw.outputVariant=tier(u.resolution);
|
|
50
|
+
// General text Tokens cannot be assumed to be image Tokens.
|
|
51
|
+
if(count(u.image_tokens))raw.outputImageTokens=u.image_tokens;
|
|
52
|
+
if(object(u.completion_tokens_details)&&count(u.completion_tokens_details.image_tokens))raw.outputImageTokens=u.completion_tokens_details.image_tokens;
|
|
53
|
+
}
|
|
54
|
+
const usage=count(u.prompt_tokens)&&count(u.completion_tokens)?{inputTokens:u.prompt_tokens,outputTokens:u.completion_tokens}:undefined;
|
|
55
|
+
return {response:{schema:'bailing.model-tool-result.v1',outputs,...(requestId?{provider_request_id:requestId}:{})},executionId:requestId,...(usage?{usage}:{}),rawUsage:raw};
|
|
56
|
+
}
|
|
57
|
+
/** Explicit adapter choice, never a retry or silent fallback to another API. */
|
|
58
|
+
export function modelToolEndpoint(credential: ResolvedLlmCredential, config: UsageServiceConfig, body: Record<string, unknown>) {
|
|
59
|
+
if (config.tool?.adapter === 'aliyun-image-native') {
|
|
60
|
+
const base = new URL(credential.base_url);
|
|
61
|
+
usageAssert(!base.username && !base.password && !base.search && !base.hash
|
|
62
|
+
&& ['','/','/api/v1','/api/v1/','/compatible-mode/v1','/compatible-mode/v1/'].includes(base.pathname),
|
|
63
|
+
'USAGE_INVALID_INPUT','原生图片接口请配置服务根地址或标准 API 基础地址。',400);
|
|
64
|
+
const {model, prompt, ...parameters} = body;
|
|
65
|
+
if (typeof parameters.size === 'string') parameters.size = parameters.size.replace(/^(\d+)x(\d+)$/, '$1*$2');
|
|
66
|
+
return {url: new URL('/api/v1/services/aigc/multimodal-generation/generation', base).href,
|
|
67
|
+
body: {model, input: {messages:[{role:'user',content:[{text:prompt}]}]}, parameters}};
|
|
68
|
+
}
|
|
69
|
+
const suffix=config.tool?.adapter==='aliyun-image'?'images/generations':'images';
|
|
70
|
+
return {url:`${credential.base_url.replace(/\/+$/,'')}/${suffix}`,body};
|
|
71
|
+
}
|
|
72
|
+
async function boundedBody(response: Response, maximum: number): Promise<string> {
|
|
73
|
+
if (!response.body) return '';
|
|
74
|
+
const reader=response.body.getReader(), chunks:Uint8Array[]=[]; let size=0;
|
|
75
|
+
try {
|
|
76
|
+
for (;;) {const {value,done}=await reader.read();if(done)break;size+=value.length;
|
|
77
|
+
if(size>maximum){await reader.cancel();throw new UsageError('USAGE_PROVIDER_INVALID','生成结果超过传输容量。',502);}chunks.push(value);}
|
|
78
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
79
|
+
} finally {reader.releaseLock();}
|
|
80
|
+
}
|
|
81
|
+
export async function executeModelTool(credential:ResolvedLlmCredential, config:UsageServiceConfig, body:Record<string,unknown>, fetcher:typeof fetch=fetch):Promise<ProviderResult> {
|
|
82
|
+
const target=modelToolEndpoint(credential,config,body);
|
|
83
|
+
let response: Response;
|
|
84
|
+
try {
|
|
85
|
+
response=await fetcher(target.url,{method:'POST',redirect:'error',signal:AbortSignal.timeout(config.timeoutMs),headers:{authorization:`Bearer ${credential.api_key}`,'content-type':'application/json'},body:JSON.stringify(target.body)});
|
|
86
|
+
} catch {
|
|
87
|
+
throw new ProviderFailure(false,{code:'USAGE_TRANSPORT_UNCERTAIN',message:'连接中断,原生成请求的结果尚无法确认。',retryable:false,next_action:'inspect_original'});
|
|
88
|
+
}
|
|
89
|
+
const secrets=[credential.api_key,credential.base_url];
|
|
90
|
+
const requestId=safeProviderIdentifier(response.headers.get('x-request-id') ?? response.headers.get('x-dashscope-request-id'),secrets);
|
|
91
|
+
if(!response.ok) {
|
|
92
|
+
let value:unknown;
|
|
93
|
+
try {value=JSON.parse(await boundedBody(response,16*1024));}catch { /* HTTP status remains authoritative; body is discarded. */ }
|
|
94
|
+
throw httpProviderFailure(response.status,value,requestId,secrets);
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
let value=JSON.parse(await boundedBody(response,24*1024*1024));
|
|
98
|
+
const id=requestId ?? safeProviderIdentifier(value.request_id ?? value.id,secrets) ?? null;
|
|
99
|
+
if(config.tool?.adapter==='aliyun-image-native') {
|
|
100
|
+
usageAssert(Array.isArray(value.output?.choices),'USAGE_PROVIDER_INVALID','生成结果格式异常。',502);
|
|
101
|
+
const images=value.output.choices.flatMap((choice:any)=>Array.isArray(choice.message?.content)?choice.message.content:[])
|
|
102
|
+
.filter((part:any)=>typeof part?.image==='string').map((part:any)=>({url:part.image}));
|
|
103
|
+
value={data:images,usage:value.usage};
|
|
104
|
+
}
|
|
105
|
+
return imageProviderResult(config.tool!.adapter,value,id);
|
|
106
|
+
} catch {
|
|
107
|
+
throw new ProviderFailure(false,{code:'USAGE_PROVIDER_INVALID',message:'生成服务已响应,但结果无法解析;请核对原请求。',http_status:response.status,
|
|
108
|
+
...(requestId?{provider_request_id:requestId}:{}),retryable:false,next_action:'inspect_original'});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { validateModelToolConfig, modelToolDescriptor, isModelTool, type ModelToolConfig } from './model-tools';
|
|
4
|
+
import type { UsageService } from './contracts';
|
|
5
|
+
const tool = (): ModelToolConfig => ({name:'create_asset',capability:'custom_media',description:'Create media for the requested campaign.',outputs:['image'],parameters:[{name:'prompt',type:'string',required:true,description:'Description of the asset'}],adapter:'pending'});
|
|
6
|
+
const service = (): UsageService => ({id:'image-service',label:'Create images',revision:2,state:'active',config:{credential:'private-credential-alias',model:'synthetic',providerScope:'private-provider-scope',maxInputBytes:1024,maxOutputTokens:100,timeoutMs:1000,purpose:'tool',tool:tool()}});
|
|
7
|
+
test('purpose separates existing chat models and configurable tools',()=>{
|
|
8
|
+
validateModelToolConfig({}); validateModelToolConfig({purpose:'chat'});
|
|
9
|
+
validateModelToolConfig({purpose:'tool',tool:tool()});
|
|
10
|
+
assert.equal(isModelTool(service()),true);
|
|
11
|
+
const chat=service(); delete chat.config.purpose;delete chat.config.tool;
|
|
12
|
+
assert.equal(isModelTool(chat),false);
|
|
13
|
+
assert.throws(()=>validateModelToolConfig({purpose:'chat',tool:tool()}));
|
|
14
|
+
assert.throws(()=>validateModelToolConfig({purpose:'tool'}));
|
|
15
|
+
});
|
|
16
|
+
test('tool schemas reject ambiguous and unsafe fields before persistence',()=>{
|
|
17
|
+
for (const bad of [
|
|
18
|
+
{...tool(),adapter:'arbitrary-url'}, {...tool(),perImage:100}, {...tool(),outputs:[]},
|
|
19
|
+
{...tool(),name:'invalid tool'}, {...tool(),parameters:[...tool().parameters,...tool().parameters]},
|
|
20
|
+
{...tool(),parameters:[{...tool().parameters[0],name:'__proto__'}]},
|
|
21
|
+
]) assert.throws(()=>validateModelToolConfig({purpose:'tool',tool:bad as ModelToolConfig}));
|
|
22
|
+
});
|
|
23
|
+
test('directory returns only declaration, explicit unavailability and shared USD multiplier',()=>{
|
|
24
|
+
const value=modelToolDescriptor(service(),2);
|
|
25
|
+
assert.equal(value.callable,false);assert.equal(value.reason,'MODEL_TOOL_ADAPTER_NOT_READY');
|
|
26
|
+
assert.equal(value.billing_scope,'shared_plan');assert.equal(value.billing_unit,'USD');
|
|
27
|
+
assert.deepEqual(value.billing_rate,{multiplier:2});
|
|
28
|
+
assert.deepEqual(value.tool.input_schema.required,['prompt']);
|
|
29
|
+
assert.equal(value.tool.input_schema.additionalProperties,false);
|
|
30
|
+
assert.equal(JSON.stringify(value).includes('private-'),false);
|
|
31
|
+
assert.equal(JSON.stringify(value).includes('synthetic'),false);
|
|
32
|
+
});
|
|
33
|
+
test('file references remain declarations, not filesystem paths or uploads',()=>{
|
|
34
|
+
const s=service(); s.config.tool!.parameters=[{name:'source',type:'file',required:true,description:'Host-owned artifact reference'}];
|
|
35
|
+
assert.deepEqual(modelToolDescriptor(s).tool.input_schema.properties.source,{type:'string',description:'Host-owned artifact reference','x-bailing-value':'artifact_ref'});
|
|
36
|
+
});
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { UsageService, UsageServiceConfig } from './contracts';
|
|
2
|
+
import { usageAssert } from './errors';
|
|
3
|
+
import { assertKnownFields } from './validation';
|
|
4
|
+
|
|
5
|
+
export interface ModelToolParameter {
|
|
6
|
+
name: string; type: 'string' | 'number' | 'boolean' | 'file'; required: boolean; description: string;
|
|
7
|
+
}
|
|
8
|
+
export interface ModelToolConfig {
|
|
9
|
+
name: string; capability: string; description: string; outputs: string[]; parameters: ModelToolParameter[];
|
|
10
|
+
adapter: 'pending' | 'aliyun-image' | 'aliyun-image-native' | 'openrouter-image';
|
|
11
|
+
}
|
|
12
|
+
const identifier = /^[a-zA-Z_][a-zA-Z0-9_]{0,63}$/;
|
|
13
|
+
const safeName = (v: unknown, max: number): v is string => typeof v === 'string' && v.trim().length > 0 && v.length <= max && !/[\x00-\x1f]/.test(v);
|
|
14
|
+
export function validateModelToolConfig(config: Pick<UsageServiceConfig, 'purpose' | 'tool'>): void {
|
|
15
|
+
usageAssert(config.purpose === undefined || config.purpose === 'chat' || config.purpose === 'tool', 'USAGE_INVALID_INPUT', '服务用途必须为对话模型或模型工具。', 400);
|
|
16
|
+
if (config.purpose !== 'tool') {
|
|
17
|
+
usageAssert(config.tool === undefined, 'USAGE_INVALID_INPUT', '对话模型不能附带工具配置。', 400); return;
|
|
18
|
+
}
|
|
19
|
+
const tool = config.tool;
|
|
20
|
+
assertKnownFields(tool, ['name','capability','description','outputs','parameters','adapter'], 'model tool');
|
|
21
|
+
usageAssert(tool && typeof tool.name === 'string' && identifier.test(tool.name) && safeName(tool.capability, 80)
|
|
22
|
+
&& typeof tool.description === 'string' && tool.description.trim().length > 0 && tool.description.length <= 1200,
|
|
23
|
+
'USAGE_INVALID_INPUT', '请填写有效的工具名称、能力类型及使用说明。', 400);
|
|
24
|
+
usageAssert(['pending','aliyun-image','aliyun-image-native','openrouter-image'].includes(tool.adapter), 'USAGE_TOOL_ADAPTER_UNSUPPORTED', '生成适配不受支持。', 400);
|
|
25
|
+
usageAssert(Array.isArray(tool.outputs) && tool.outputs.length > 0 && tool.outputs.length <= 8
|
|
26
|
+
&& tool.outputs.every(v => safeName(v, 64)) && new Set(tool.outputs).size === tool.outputs.length,
|
|
27
|
+
'USAGE_INVALID_INPUT', '工具输出类型无效。', 400);
|
|
28
|
+
usageAssert(Array.isArray(tool.parameters) && tool.parameters.length <= 32, 'USAGE_INVALID_INPUT', '工具参数声明无效。', 400);
|
|
29
|
+
const names = new Set<string>();
|
|
30
|
+
for (const p of tool.parameters) {
|
|
31
|
+
assertKnownFields(p, ['name','type','required','description'], 'tool parameter');
|
|
32
|
+
usageAssert(p && typeof p.name === 'string' && identifier.test(p.name) && !['__proto__','constructor','prototype'].includes(p.name)
|
|
33
|
+
&& !names.has(p.name) && ['string','number','boolean','file'].includes(p.type) && typeof p.required === 'boolean'
|
|
34
|
+
&& safeName(p.description, 500), 'USAGE_INVALID_INPUT', '工具参数名称、类型或说明无效。', 400);
|
|
35
|
+
names.add(p.name);
|
|
36
|
+
}
|
|
37
|
+
if (tool.adapter !== 'pending') {
|
|
38
|
+
usageAssert(tool.capability === 'image_generation' && tool.outputs.includes('image'), 'USAGE_INVALID_INPUT', '当前执行适配仅支持图片生成。', 400);
|
|
39
|
+
usageAssert(tool.parameters.some(p => p.name === 'prompt' && p.type === 'string' && p.required), 'USAGE_INVALID_INPUT', '图片工具必须声明必填的 prompt 文本。',400);
|
|
40
|
+
const supported = tool.adapter.startsWith('aliyun-image') ? ['prompt','n','size','seed','negative_prompt','watermark','prompt_extend','enable_thinking'] : ['prompt','n','size','resolution','aspect_ratio','seed'];
|
|
41
|
+
usageAssert(tool.parameters.every(p=>supported.includes(p.name) && p.type !== 'file'), 'USAGE_INVALID_INPUT','当前适配为文生图;参数须使用已支持的生成参数。',400);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export function isModelTool(service: UsageService): boolean { return service.config.purpose === 'tool'; }
|
|
45
|
+
/** Only authorized services reach this projection. Never includes credential references or provider configuration. */
|
|
46
|
+
export function modelToolDescriptor(service: UsageService, multiplier = 1) {
|
|
47
|
+
validateModelToolConfig(service.config);
|
|
48
|
+
usageAssert(isModelTool(service) && service.config.tool, 'USAGE_INVALID_INPUT', '服务不是模型工具。', 400);
|
|
49
|
+
const tool = service.config.tool;
|
|
50
|
+
return {
|
|
51
|
+
schema: 'bailing.model-tool.v1', service_id: service.id, service_revision: service.revision,
|
|
52
|
+
label: service.label, capability: tool.capability, outputs: tool.outputs,
|
|
53
|
+
state: tool.adapter === 'pending' ? 'unavailable' : 'ready', reason: tool.adapter === 'pending' ? 'MODEL_TOOL_ADAPTER_NOT_READY' : null, callable: tool.adapter !== 'pending',
|
|
54
|
+
orchestration: 'host', billing_unit: 'USD', billing_scope: 'shared_plan',
|
|
55
|
+
billing_rate: { multiplier },
|
|
56
|
+
tool: { name: tool.name, description: tool.description, input_schema: { type: 'object', additionalProperties: false,
|
|
57
|
+
properties: Object.fromEntries(tool.parameters.map(p => [p.name, {
|
|
58
|
+
type: p.type === 'file' ? 'string' : p.type, description: p.description,
|
|
59
|
+
...(p.type === 'file' ? { 'x-bailing-value': 'artifact_ref' } : {}),
|
|
60
|
+
}])), required: tool.parameters.filter(p => p.required).map(p => p.name) } },
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import test from 'node:test';
|
|
5
|
+
import { createUsageTestHarness } from './test-harness';
|
|
6
|
+
import { usageHash } from './repository';
|
|
7
|
+
import type { BillingPlanConfig, BillingRequest, PriceSnapshot } from './billing-contracts';
|
|
8
|
+
|
|
9
|
+
const enabled = process.env.BAILING_USAGE_TEST_MYSQL === '1';
|
|
10
|
+
const day = 86_400_000;
|
|
11
|
+
const price: PriceSnapshot = { source: 'openrouter', currency: 'USD', modelId: 'synthetic', endpointId: 'synthetic', fetchedAt: 1,
|
|
12
|
+
lines: [{ billable: 'prompt', unit: 'token', costUsd: '1' }, { billable: 'completion', unit: 'token', costUsd: '1' }] };
|
|
13
|
+
|
|
14
|
+
test('weekly $100 sale has $20 allowance: snapshots, late settlement, reset, short final period and expiry', { skip: !enabled }, async () => {
|
|
15
|
+
const h = await createUsageTestHarness();
|
|
16
|
+
try {
|
|
17
|
+
let now = Date.now(); const startsAt = now;
|
|
18
|
+
// Control billing time only; all accounting still runs against the isolated real DB.
|
|
19
|
+
Object.defineProperty(h.tokens, 'now', { value: async () => now });
|
|
20
|
+
const user = await h.seedUser({ grant: false });
|
|
21
|
+
const config: BillingPlanConfig = { mode: 'periodic', priceUsd: 100, periodAllowanceUsd: 20, periodUnit: 'week',
|
|
22
|
+
multiplier: 1, serviceIds: [h.service.id], duration: { unit: 'day', count: 10 } };
|
|
23
|
+
const body = { id: 'weekly', label: 'Synthetic weekly', expected_revision: 0, config };
|
|
24
|
+
assert.equal((await h.request('/admin/api/usage/billing/plans', 'synthetic-admin', 'POST', body)).status, 200);
|
|
25
|
+
const plans = await h.request('/admin/api/usage/billing/plans', 'synthetic-admin');
|
|
26
|
+
assert.equal(plans.body.period_allowance_supported, true);
|
|
27
|
+
const grant = await h.tokens.grant(user.accountId, { request_key: randomUUID(), plan_id: body.id, expected_revision: 0, starts_at: startsAt });
|
|
28
|
+
const admit = async () => { const operationId = randomUUID(); return h.tokens.admit({ actor: user.actor, operationId, serviceId: h.service.id,
|
|
29
|
+
conversationId: null, turnId: null, requestHash: usageHash(operationId), expectedServiceRevision: h.service.revision,
|
|
30
|
+
serviceConfig: h.service.config, model: h.service.config.model, priceSnapshot: price }); };
|
|
31
|
+
const dispatch = async () => h.tokens.commitDispatch((await admit()).id, user.actor);
|
|
32
|
+
const finish = (r: BillingRequest, cost: number) => h.tokens.complete(r.id, r.fence!, { response: { output: 'synthetic' }, usage: { inputTokens: cost, outputTokens: 0 } });
|
|
33
|
+
assert.equal((await h.tokens.summary(user.accountId)).availableUsd, 20);
|
|
34
|
+
const first = await finish(await dispatch(), 10);
|
|
35
|
+
assert.equal(first.billedUsd, 10); assert.equal(first.grantConfig.periodAllowanceUsd, 20);
|
|
36
|
+
const half = await h.tokens.summary(user.accountId);
|
|
37
|
+
assert.equal(half.availableUsd, 10); assert.equal(half.presentation.remaining, 50);
|
|
38
|
+
assert.equal(half.presentation.displayValue, '50'); assert.equal(half.resetAt, startsAt + 7 * day);
|
|
39
|
+
const late = await dispatch();
|
|
40
|
+
await h.tokens.putPlan({ ...body, expected_revision: 1, config: { ...config, priceUsd: 999, periodAllowanceUsd: 200, multiplier: 2 } });
|
|
41
|
+
now = startsAt + 7 * day;
|
|
42
|
+
assert.equal((await h.tokens.summary(user.accountId)).availableUsd, 20);
|
|
43
|
+
const settled = await finish(late, 15);
|
|
44
|
+
assert.equal(settled.billedUsd, 15); assert.equal(settled.overageUsd, 5);
|
|
45
|
+
const current = await h.tokens.summary(user.accountId);
|
|
46
|
+
assert.equal(current.availableUsd, 20); assert.equal(current.consumedUsd, 25);
|
|
47
|
+
assert.equal(current.currentPeriodConsumedUsd, 0); assert.equal(current.overageUsd, 0);
|
|
48
|
+
assert.equal(current.resetAt, null); assert.equal(current.expiresAt, startsAt + 10 * day);
|
|
49
|
+
assert.equal(current.grant!.config.priceUsd, 100); assert.equal(current.grant!.config.periodAllowanceUsd, 20);
|
|
50
|
+
const final = await dispatch(); assert.equal(final.periodStart, now); assert.equal(final.periodEnd, startsAt + 10 * day);
|
|
51
|
+
assert.equal((await finish(final, 10)).billedUsd, 20);
|
|
52
|
+
await assert.rejects(admit(), { code: 'QUOTA_WINDOW_EXHAUSTED' });
|
|
53
|
+
const [pools] = await h.pool.query<any[]>('SELECT allowance_usd,consumed_usd FROM bz_usage_billing_periods WHERE grant_id=? ORDER BY period_start', [grant.id]);
|
|
54
|
+
assert.deepEqual(pools.map(p => [Number(p.allowance_usd), Number(p.consumed_usd)]), [[20,25],[20,20]]);
|
|
55
|
+
now = startsAt + 10 * day;
|
|
56
|
+
const expired = await h.tokens.summary(user.accountId);
|
|
57
|
+
assert.equal(expired.availableUsd, 0); assert.equal(expired.presentation.state, 'expired');
|
|
58
|
+
await assert.rejects(admit(), { code: 'SUBSCRIPTION_EXPIRED' });
|
|
59
|
+
} finally { await h.close(); }
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('explicit migration converts each old snapshot and idempotency result without changing credits or existing allowances', { skip: !enabled }, async () => {
|
|
63
|
+
const h = await createUsageTestHarness();
|
|
64
|
+
try {
|
|
65
|
+
const user = await h.seedUser({ grant: false });
|
|
66
|
+
const config: BillingPlanConfig = { mode: 'periodic', priceUsd: 100, periodAllowanceUsd: 100, periodUnit: 'week', multiplier: 1,
|
|
67
|
+
serviceIds: [h.service.id], duration: { unit: 'day', count: 10 } };
|
|
68
|
+
await h.tokens.putPlan({ id: 'legacy', label: 'Synthetic migration', expected_revision: 0, config });
|
|
69
|
+
const body = { request_key: randomUUID(), plan_id: 'legacy', expected_revision: 0 };
|
|
70
|
+
const grant = await h.tokens.grant(user.accountId, body);
|
|
71
|
+
const operationId = randomUUID();
|
|
72
|
+
const r = await h.tokens.admit({ actor: user.actor, operationId, serviceId: h.service.id, conversationId: null, turnId: null,
|
|
73
|
+
requestHash: usageHash(operationId), expectedServiceRevision: h.service.revision, serviceConfig: h.service.config,
|
|
74
|
+
model: h.service.config.model, priceSnapshot: price });
|
|
75
|
+
const dispatched = await h.tokens.commitDispatch(r.id, user.actor);
|
|
76
|
+
// Produce a representative pre-upgrade fixture with independently edited template price.
|
|
77
|
+
await h.pool.query("UPDATE bz_usage_billing_plans SET config_json=JSON_SET(JSON_REMOVE(config_json,'$.periodAllowanceUsd'),'$.priceUsd',300) WHERE id='legacy'");
|
|
78
|
+
await h.pool.query("UPDATE bz_usage_billing_grants SET config_json=JSON_REMOVE(config_json,'$.periodAllowanceUsd')");
|
|
79
|
+
await h.pool.query("UPDATE bz_usage_billing_requests SET grant_json=JSON_REMOVE(grant_json,'$.periodAllowanceUsd')");
|
|
80
|
+
await h.pool.query("UPDATE bz_usage_changes SET result_json=JSON_REMOVE(result_json,'$.config.periodAllowanceUsd') WHERE JSON_UNQUOTE(JSON_EXTRACT(result_json,'$.config.mode'))='periodic'");
|
|
81
|
+
await h.tokens.putPlan({ id: 'explicit', label: 'Synthetic explicit', expected_revision: 0, config: { ...config, periodAllowanceUsd: 20 } });
|
|
82
|
+
await h.tokens.putPlan({ id: 'credits', label: 'Synthetic credits', expected_revision: 0, config: { mode: 'credits', priceUsd: 75, serviceIds: [], multiplier: 1, duration: { unit: 'forever', count: 0 } } });
|
|
83
|
+
const migration = await readFile(new URL('../../../sql/064_period_plan_allowance.sql', import.meta.url), 'utf8');
|
|
84
|
+
await h.pool.query(migration); await h.pool.query(migration);
|
|
85
|
+
const plans = await h.tokens.listPlans();
|
|
86
|
+
assert.equal(plans.find(p => p.id === 'legacy')!.config.periodAllowanceUsd, 300);
|
|
87
|
+
assert.equal(plans.find(p => p.id === 'explicit')!.config.periodAllowanceUsd, 20);
|
|
88
|
+
assert.equal(plans.find(p => p.id === 'credits')!.config.periodAllowanceUsd, undefined);
|
|
89
|
+
const replay = await h.tokens.grant(user.accountId, body);
|
|
90
|
+
assert.equal(replay.id, grant.id); assert.equal(replay.config.periodAllowanceUsd, 100);
|
|
91
|
+
assert.equal((await h.tokens.findRequest(user.actor, operationId))!.grantConfig.periodAllowanceUsd, 100);
|
|
92
|
+
const done = await h.tokens.complete(r.id, dispatched.fence!, { response: { output: 'synthetic' }, usage: { inputTokens: 10, outputTokens: 0 } });
|
|
93
|
+
assert.equal(done.billedUsd, 10); assert.equal(done.overageUsd, 0);
|
|
94
|
+
const summary = await h.tokens.summary(user.accountId);
|
|
95
|
+
assert.equal(summary.availableUsd, 90); assert.equal(summary.presentation.remaining, 90);
|
|
96
|
+
} finally { await h.close(); }
|
|
97
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { periodBounds } from "./period";
|
|
4
|
+
test("calendar month keeps original anchor after short month and weekly reset is stable", () => {
|
|
5
|
+
const rule = {
|
|
6
|
+
unit: "month" as const,
|
|
7
|
+
anchor: Date.parse("2026-01-31T10:00:00Z"),
|
|
8
|
+
timezone: "UTC",
|
|
9
|
+
};
|
|
10
|
+
assert.deepEqual(periodBounds(rule, Date.parse("2026-03-01T00:00:00Z")), {
|
|
11
|
+
start: Date.parse("2026-02-28T10:00:00Z"),
|
|
12
|
+
end: Date.parse("2026-03-31T10:00:00Z"),
|
|
13
|
+
});
|
|
14
|
+
assert.deepEqual(
|
|
15
|
+
periodBounds({ unit: "week", anchor: 1000, timezone: "UTC" }, 604801000),
|
|
16
|
+
{ start: 604801000, end: 1209601000 },
|
|
17
|
+
);
|
|
18
|
+
});
|
|
19
|
+
test("calendar month DST gap advances to first valid local minute", () => {
|
|
20
|
+
const anchor = Date.parse("2026-02-08T07:30:00Z");
|
|
21
|
+
const got = periodBounds(
|
|
22
|
+
{ unit: "month", anchor, timezone: "America/New_York" },
|
|
23
|
+
Date.parse("2026-03-09T00:00:00Z"),
|
|
24
|
+
);
|
|
25
|
+
assert.equal(got?.start, Date.parse("2026-03-08T07:00:00Z"));
|
|
26
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { UsageError, usageAssert } from "./errors";
|
|
2
|
+
export interface PeriodRule {
|
|
3
|
+
unit: "day" | "week" | "month";
|
|
4
|
+
anchor: number;
|
|
5
|
+
timezone: string;
|
|
6
|
+
}
|
|
7
|
+
type Parts = {
|
|
8
|
+
year: number;
|
|
9
|
+
month: number;
|
|
10
|
+
day: number;
|
|
11
|
+
hour: number;
|
|
12
|
+
minute: number;
|
|
13
|
+
second: number;
|
|
14
|
+
};
|
|
15
|
+
function parts(ms: number, zone: string): Parts {
|
|
16
|
+
const out: Record<string, number> = {};
|
|
17
|
+
for (const p of new Intl.DateTimeFormat("en-GB", {
|
|
18
|
+
timeZone: zone,
|
|
19
|
+
year: "numeric",
|
|
20
|
+
month: "2-digit",
|
|
21
|
+
day: "2-digit",
|
|
22
|
+
hour: "2-digit",
|
|
23
|
+
minute: "2-digit",
|
|
24
|
+
second: "2-digit",
|
|
25
|
+
hourCycle: "h23",
|
|
26
|
+
}).formatToParts(new Date(ms)))
|
|
27
|
+
if (p.type !== "literal") out[p.type] = Number(p.value);
|
|
28
|
+
return out as Parts;
|
|
29
|
+
}
|
|
30
|
+
function localEpoch(p: Parts): number {
|
|
31
|
+
return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second);
|
|
32
|
+
}
|
|
33
|
+
function resolveLocal(p: Parts, zone: string): number {
|
|
34
|
+
const nominal = localEpoch(p);
|
|
35
|
+
const offsets = new Set<number>();
|
|
36
|
+
for (const delta of [-36, -24, -12, 0, 12, 24, 36]) {
|
|
37
|
+
const t = nominal + delta * 3600000;
|
|
38
|
+
offsets.add(localEpoch(parts(t, zone)) - t);
|
|
39
|
+
}
|
|
40
|
+
for (let minute = 0; minute <= 180; minute++) {
|
|
41
|
+
const wanted = nominal + minute * 60000;
|
|
42
|
+
const matches = [...offsets]
|
|
43
|
+
.map((o) => wanted - o)
|
|
44
|
+
.filter((t) => localEpoch(parts(t, zone)) === wanted);
|
|
45
|
+
if (matches.length) return Math.min(...matches);
|
|
46
|
+
}
|
|
47
|
+
throw new UsageError(
|
|
48
|
+
"USAGE_UNSUPPORTED_SCHEDULE",
|
|
49
|
+
"Unable to resolve calendar boundary.",
|
|
50
|
+
400,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
export function periodBounds(
|
|
54
|
+
rule: PeriodRule,
|
|
55
|
+
now: number,
|
|
56
|
+
): { start: number; end: number } | null {
|
|
57
|
+
usageAssert(
|
|
58
|
+
Number.isSafeInteger(now) && Number.isSafeInteger(rule.anchor),
|
|
59
|
+
"USAGE_INVALID_INPUT",
|
|
60
|
+
"Invalid schedule timestamp.",
|
|
61
|
+
400,
|
|
62
|
+
);
|
|
63
|
+
if (now < rule.anchor) return null;
|
|
64
|
+
if (rule.unit === "day" || rule.unit === "week") {
|
|
65
|
+
const length = (rule.unit === "day" ? 1 : 7) * 86400000;
|
|
66
|
+
const index = Math.floor((now - rule.anchor) / length);
|
|
67
|
+
return {
|
|
68
|
+
start: rule.anchor + index * length,
|
|
69
|
+
end: rule.anchor + (index + 1) * length,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
usageAssert(
|
|
73
|
+
rule.unit === "month",
|
|
74
|
+
"USAGE_UNSUPPORTED_SCHEDULE",
|
|
75
|
+
"Unsupported period unit.",
|
|
76
|
+
400,
|
|
77
|
+
);
|
|
78
|
+
const a = parts(rule.anchor, rule.timezone),
|
|
79
|
+
n = parts(now, rule.timezone),
|
|
80
|
+
millis = rule.anchor % 1000;
|
|
81
|
+
const boundary = (i: number) => {
|
|
82
|
+
if (i === 0) return rule.anchor;
|
|
83
|
+
const monthIndex = a.year * 12 + a.month - 1 + i,
|
|
84
|
+
year = Math.floor(monthIndex / 12),
|
|
85
|
+
month = (monthIndex % 12) + 1;
|
|
86
|
+
const day = Math.min(
|
|
87
|
+
a.day,
|
|
88
|
+
new Date(Date.UTC(year, month, 0)).getUTCDate(),
|
|
89
|
+
);
|
|
90
|
+
return resolveLocal({ ...a, year, month, day }, rule.timezone) + millis;
|
|
91
|
+
};
|
|
92
|
+
let index = Math.max(0, (n.year - a.year) * 12 + n.month - a.month);
|
|
93
|
+
while (index > 0 && boundary(index) > now) index--;
|
|
94
|
+
while (boundary(index + 1) <= now) index++;
|
|
95
|
+
return { start: boundary(index), end: boundary(index + 1) };
|
|
96
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { calculateReferenceCost, ReferencePricing, validatePricingBinding } from './pricing';
|
|
4
|
+
import { UsageRepository } from './repository';
|
|
5
|
+
import type { Pool } from 'mysql2/promise';
|
|
6
|
+
import type { PriceLine, PriceSnapshot } from './billing-contracts';
|
|
7
|
+
|
|
8
|
+
const snapshot = (lines: PriceLine[]): PriceSnapshot => ({ source: 'openrouter', currency: 'USD', modelId: 'synthetic/model', endpointId: 'synthetic-provider', fetchedAt: 1, lines });
|
|
9
|
+
const chat = snapshot([{ billable: 'prompt', unit: 'token', costUsd: '0.000001' }, { billable: 'completion', unit: 'token', costUsd: '0.000004' }]);
|
|
10
|
+
|
|
11
|
+
test('reference USD uses measured input and output; supplier cost is never trusted', () => {
|
|
12
|
+
assert.equal(calculateReferenceCost(chat, { inputTokens: 100, outputTokens: 20, cost: 99999, costUsd: 99999, referenceCostUsd: 99999 }), '0.00018');
|
|
13
|
+
assert.equal(calculateReferenceCost(chat, { prompt_tokens: 100, completion_tokens: 20 }), '0.00018');
|
|
14
|
+
assert.equal(calculateReferenceCost(chat, { input_tokens: 100, output_tokens: 20 }), '0.00018');
|
|
15
|
+
assert.equal(calculateReferenceCost(chat, { cost: 0 }), null);
|
|
16
|
+
});
|
|
17
|
+
test('tiny USD prices retain twelve decimals rather than truncating to free usage', () => {
|
|
18
|
+
assert.equal(calculateReferenceCost(snapshot([{ billable: 'completion', unit: 'token', costUsd: '0.000000000001' }]), { outputTokens: 7 }), '0.000000000007');
|
|
19
|
+
assert.equal(calculateReferenceCost(snapshot([{ billable: 'output_image', unit: 'megapixel', costUsd: '0.000000000001' }]), { outputImageCount: 1, outputPixelCount: 1 }), '0.000000000001');
|
|
20
|
+
});
|
|
21
|
+
test('explicit free prices and measured zero counts are supported; absent usage remains unknown', () => {
|
|
22
|
+
const free = snapshot([{ billable: 'prompt', unit: 'token', costUsd: '0' }, { billable: 'completion', unit: 'token', costUsd: '0' }]);
|
|
23
|
+
assert.equal(calculateReferenceCost(free, { inputTokens: 100, outputTokens: 20 }), '0');
|
|
24
|
+
assert.equal(calculateReferenceCost(free, {}), null);
|
|
25
|
+
assert.equal(calculateReferenceCost(chat, { inputTokens: 0, outputTokens: 0 }), '0');
|
|
26
|
+
assert.equal(calculateReferenceCost(snapshot([]), { inputTokens: 0, outputTokens: 0 }), null);
|
|
27
|
+
});
|
|
28
|
+
test('cache hits are subtracted from full-price prompt only when separately priced', () => {
|
|
29
|
+
const cached = snapshot([...chat.lines, { billable: 'input_cache_read', unit: 'token', costUsd: '0.0000001' }, { billable: 'input_cache_write', unit: 'token', costUsd: '0.000002' }]);
|
|
30
|
+
assert.equal(calculateReferenceCost(cached, { inputTokens: 100, outputTokens: 20, cachedInputTokens: 40, cacheWriteTokens: 10 }), '0.000154');
|
|
31
|
+
assert.equal(calculateReferenceCost(chat, { inputTokens: 100, outputTokens: 20, cachedInputTokens: 40 }), '0.00018');
|
|
32
|
+
assert.equal(calculateReferenceCost(cached, { inputTokens: 20, outputTokens: 10, cachedInputTokens: 40, cacheWriteTokens: 0 }), null);
|
|
33
|
+
assert.equal(calculateReferenceCost(cached, { inputTokens: 100, outputTokens: 20 }), null, 'Missing separately priced cache counts are unknown, not zero.');
|
|
34
|
+
assert.equal(calculateReferenceCost(cached, { inputTokens: 100, outputTokens: 20, input_tokens_details: { cached_tokens: 40 }, cacheWriteTokens: 10 }), '0.000154');
|
|
35
|
+
});
|
|
36
|
+
test('image billing requires explicit matching variant; no resolution, name or count guessing', () => {
|
|
37
|
+
const price = snapshot([{ billable: 'input_image', unit: 'image', costUsd: '0.003' },
|
|
38
|
+
{ billable: 'output_image', unit: 'image', costUsd: '0.03', variant: '1k' },
|
|
39
|
+
{ billable: 'output_image', unit: 'image', costUsd: '0.05', variant: '2k' }]);
|
|
40
|
+
assert.equal(calculateReferenceCost(price, { inputImageCount: 0, outputImageCount: 2, outputVariant: '1k' }), '0.06');
|
|
41
|
+
assert.equal(calculateReferenceCost(price, { inputImageCount: 1, outputImageCount: 2, outputVariant: '2k' }), '0.103');
|
|
42
|
+
assert.equal(calculateReferenceCost(price, { outputImageCount: 1, outputVariant: '1k' }), null);
|
|
43
|
+
assert.equal(calculateReferenceCost(price, { inputImageCount: 0, outputImageCount: 1, outputWidth: 1024, outputHeight: 1024 }), null);
|
|
44
|
+
assert.equal(calculateReferenceCost(price, { inputImageCount: 0, outputImageCount: 1, outputVariant: '4k' }), null);
|
|
45
|
+
const ambiguous = snapshot([...price.lines, { billable: 'output_image', unit: 'image', costUsd: '0.01' }]);
|
|
46
|
+
assert.equal(calculateReferenceCost(ambiguous, { inputImageCount: 0, outputImageCount: 1, outputVariant: '1k' }), null);
|
|
47
|
+
});
|
|
48
|
+
test('image tokens and total measured pixel counts have distinct units', () => {
|
|
49
|
+
assert.equal(calculateReferenceCost(snapshot([{ billable: 'output_image', unit: 'token', costUsd: '0.000001' }]), { outputImageCount: 1, outputImageTokens: 1200 }), '0.0012');
|
|
50
|
+
assert.equal(calculateReferenceCost(snapshot([{ billable: 'output_image', unit: 'token', costUsd: '0.000001' }]), { outputImageCount: 1 }), null);
|
|
51
|
+
assert.equal(calculateReferenceCost(snapshot([{ billable: 'output_image', unit: 'megapixel', costUsd: '0.01' }]), { outputImageCount: 2, outputPixelCount: 2_500_000 }), '0.025');
|
|
52
|
+
});
|
|
53
|
+
test('unsupported or malformed metering never produces a fabricated charge, including zero-count cases', () => {
|
|
54
|
+
for (const raw of [{inputTokens: -1,outputTokens: 0}, {inputTokens: 1.1,outputTokens: 0}, {inputTokens: NaN,outputTokens: 0}, {inputTokens: '1',outputTokens: 0}]) assert.equal(calculateReferenceCost(chat, raw), null);
|
|
55
|
+
assert.equal(calculateReferenceCost(snapshot([{ billable: 'unknown_metric', unit: 'token', costUsd: '1' }]), { inputTokens: 1 }), null);
|
|
56
|
+
assert.equal(calculateReferenceCost(snapshot([{ billable: 'prompt', unit: 'image', costUsd: '1' }]), { inputTokens: 1 }), null);
|
|
57
|
+
assert.equal(calculateReferenceCost(snapshot([{ billable: 'prompt', unit: 'token', costUsd: '-1' }]), { inputTokens: 0 }), null);
|
|
58
|
+
assert.equal(calculateReferenceCost(snapshot([{ billable: 'prompt', unit: 'second', costUsd: '1' }]), { inputTokens: 0 }), null);
|
|
59
|
+
});
|
|
60
|
+
test('request fees require a measured request count and are added once', () => {
|
|
61
|
+
const price = snapshot([...chat.lines, { billable: 'request', unit: 'request', costUsd: '0.01' }]);
|
|
62
|
+
assert.equal(calculateReferenceCost(price, { inputTokens: 100, outputTokens: 20, requestCount: 1 }), '0.01018');
|
|
63
|
+
assert.equal(calculateReferenceCost(price, { inputTokens: 100, outputTokens: 20 }), null);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
/** Synthetic persistence and transport only: no real endpoint, account or provider key. */
|
|
67
|
+
function cacheFixture() {
|
|
68
|
+
const saved = new Map<string, any>();
|
|
69
|
+
const pool = { async query(sql: string, parameters: any[]) {
|
|
70
|
+
if (sql.startsWith('SELECT snapshot_json')) { const v = saved.get(parameters[0]); return [v ? [{ snapshot_json: structuredClone(v) }] : []]; }
|
|
71
|
+
if (sql.startsWith('INSERT INTO bz_usage_price_snapshots')) { saved.set(parameters[0], JSON.parse(parameters[1])); return [{}]; }
|
|
72
|
+
throw new Error('Unexpected synthetic query');
|
|
73
|
+
} } as unknown as Pool;
|
|
74
|
+
let calls = 0, status = 200;
|
|
75
|
+
let value: unknown = { data: { endpoints: [{ tag: 'synthetic-provider', provider_name: 'Synthetic', pricing: { prompt: '0.000001', completion: '0.000004' } }] } };
|
|
76
|
+
const fetcher = (async (url: string | URL | Request, options?: RequestInit) => {
|
|
77
|
+
calls++; assert.equal(options?.redirect, 'error'); assert(String(url).startsWith('https://openrouter.ai/api/v1/'));
|
|
78
|
+
return new Response(JSON.stringify(value), { status, headers: {'content-type': 'application/json'} });
|
|
79
|
+
}) as typeof fetch;
|
|
80
|
+
const repository = new UsageRepository(() => pool), pricing = new ReferencePricing(repository, fetcher);
|
|
81
|
+
return { pricing, saved, calls: () => calls, set(v: unknown, s = 200) { value = v; status = s; } };
|
|
82
|
+
}
|
|
83
|
+
const binding = {source:'openrouter' as const,kind:'chat' as const,modelId:'synthetic/model',endpointId:'synthetic-provider'};
|
|
84
|
+
test('binding is explicit and rejects arbitrary remote URLs and path traversal', () => {
|
|
85
|
+
validatePricingBinding(binding);
|
|
86
|
+
for (const value of [{...binding,modelId:'../secret'}, {...binding,source:'custom'}, {...binding,endpointId:''}, {...binding,url:'https://invalid.example'}]) assert.throws(() => validatePricingBinding(value));
|
|
87
|
+
});
|
|
88
|
+
test('reference snapshot requires synchronized selected endpoint and never adds a fetch before admission', async () => {
|
|
89
|
+
const h = cacheFixture();
|
|
90
|
+
await assert.rejects(h.pricing.snapshot(binding), { code:'USAGE_PRICE_UNAVAILABLE' }); assert.equal(h.calls(), 0);
|
|
91
|
+
await h.pricing.catalog('chat', binding.modelId); assert.equal(h.calls(), 1);
|
|
92
|
+
const original = await h.pricing.snapshot(binding); assert.equal(h.calls(), 1); assert.equal(original.lines[0]!.costUsd, '0.000001');
|
|
93
|
+
original.lines[0]!.costUsd = '999'; assert.equal((await h.pricing.snapshot(binding)).lines[0]!.costUsd, '0.000001');
|
|
94
|
+
await assert.rejects(h.pricing.snapshot({...binding,endpointId:'other-provider'}), {code:'USAGE_PRICE_UNAVAILABLE'});
|
|
95
|
+
await h.pricing.catalog('chat',binding.modelId); assert.equal(h.calls(),1);
|
|
96
|
+
});
|
|
97
|
+
test('catalog outage keeps the last verified price; first-time outage never invents zero price', async () => {
|
|
98
|
+
const h=cacheFixture(); await h.pricing.catalog('chat',binding.modelId);
|
|
99
|
+
h.set({error:'synthetic'},503);
|
|
100
|
+
const stale=await h.pricing.catalog('chat',binding.modelId,true); assert.equal(stale.stale,true);
|
|
101
|
+
assert.equal((await h.pricing.snapshot(binding)).lines[0]!.costUsd,'0.000001');
|
|
102
|
+
const first=cacheFixture(); first.set({},503);
|
|
103
|
+
await assert.rejects(first.pricing.catalog('chat',binding.modelId), {code:'USAGE_PRICE_UNAVAILABLE'});
|
|
104
|
+
});
|
|
105
|
+
test('ambiguous endpoint and unknown priced dimensions cannot silently select another quote', async () => {
|
|
106
|
+
const h=cacheFixture(); await h.pricing.catalog('chat',binding.modelId);
|
|
107
|
+
assert.equal((await h.pricing.snapshot(binding)).lines[0]!.costUsd,'0.000001');
|
|
108
|
+
h.set({data:{endpoints:[{tag:'synthetic-provider',pricing:{prompt:'0.1',completion:'0.2',unknown_dimension:'1'}}]}});
|
|
109
|
+
const result=await h.pricing.catalog('chat',binding.modelId,true); assert.equal(result.items[0].unavailable,true);
|
|
110
|
+
await assert.rejects(h.pricing.snapshot(binding),{code:'USAGE_PRICE_UNSUPPORTED'});
|
|
111
|
+
h.set({data:{endpoints:[{tag:'synthetic-provider',pricing:{prompt:'0.1',completion:'0.2'}},{tag:'synthetic-provider',pricing:{prompt:'0.5',completion:'0.2'}}]}});
|
|
112
|
+
assert.equal((await h.pricing.catalog('chat',binding.modelId,true)).items.length,0);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('tier selects the highest measured prompt threshold inclusively, not incremental bands or uncached tokens', () => {
|
|
116
|
+
const tiered: PriceSnapshot = { ...chat, tiers: [
|
|
117
|
+
{ minPromptTokens: 500000, lines: [{billable:'prompt',unit:'token',costUsd:'0.000004'},{billable:'completion',unit:'token',costUsd:'0.000016'}] },
|
|
118
|
+
{ minPromptTokens: 272000, lines: [{billable:'prompt',unit:'token',costUsd:'0.000002'},{billable:'completion',unit:'token',costUsd:'0.000008'}] },
|
|
119
|
+
] };
|
|
120
|
+
assert.equal(calculateReferenceCost(tiered,{inputTokens:271999,outputTokens:10}),'0.272039');
|
|
121
|
+
assert.equal(calculateReferenceCost(tiered,{inputTokens:272000,outputTokens:10}),'0.54408');
|
|
122
|
+
assert.equal(calculateReferenceCost(tiered,{inputTokens:500000,outputTokens:10}),'2.00016');
|
|
123
|
+
assert.equal(calculateReferenceCost(tiered,{outputTokens:10}),null);
|
|
124
|
+
const cached: PriceSnapshot = { ...chat, tiers:[{minPromptTokens:272000,lines:[
|
|
125
|
+
{billable:'prompt',unit:'token',costUsd:'0.000002'}, {billable:'completion',unit:'token',costUsd:'0.000008'},
|
|
126
|
+
{billable:'input_cache_read',unit:'token',costUsd:'0.0000002'}, {billable:'input_cache_write',unit:'token',costUsd:'0.000004'},
|
|
127
|
+
]}] };
|
|
128
|
+
assert.equal(calculateReferenceCost(cached,{inputTokens:300000,outputTokens:10,cachedInputTokens:200000,cacheWriteTokens:0}),'0.24008');
|
|
129
|
+
assert.equal(calculateReferenceCost(cached,{inputTokens:300000,outputTokens:10,cachedInputTokens:200000}),null);
|
|
130
|
+
assert.equal(calculateReferenceCost({...tiered,tiers:[tiered.tiers![0]!,tiered.tiers![0]!]}, {inputTokens:1,outputTokens:0}),null);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('web search is a separately measured request fee: missing is unknown, explicit zero is no fee', () => {
|
|
134
|
+
const price=snapshot([...chat.lines,{billable:'web_search',unit:'request',costUsd:'0.01'}]);
|
|
135
|
+
assert.equal(calculateReferenceCost(price,{inputTokens:100,outputTokens:20}),null);
|
|
136
|
+
assert.equal(calculateReferenceCost(price,{inputTokens:100,outputTokens:20,webSearchCount:0}),'0.00018');
|
|
137
|
+
assert.equal(calculateReferenceCost(price,{inputTokens:100,outputTokens:20,webSearchCount:2}),'0.02018');
|
|
138
|
+
assert.equal(calculateReferenceCost(price,{inputTokens:100,outputTokens:20,webSearchCount:'0'}),null);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test('catalog normalizes tier overrides into frozen complete quotes retaining base request fees', async () => {
|
|
142
|
+
const h=cacheFixture();
|
|
143
|
+
h.set({data:{endpoints:[{tag:'synthetic-provider',pricing:{prompt:'0.000001',completion:'0.000004',input_cache_read:'0.0000001',input_cache_write:'0.000002',web_search:'0.01',
|
|
144
|
+
overrides:[{min_prompt_tokens:272000,prompt:'0.000002',completion:'0.000008',input_cache_read:'0.0000002',input_cache_write:'0.000004'}]}}]}});
|
|
145
|
+
const catalog=await h.pricing.catalog('chat',binding.modelId); assert.equal(catalog.items[0].unavailable,undefined);
|
|
146
|
+
const price=await h.pricing.snapshot(binding);
|
|
147
|
+
assert.equal(price.tiers?.[0]?.minPromptTokens,272000); assert.equal(price.tiers?.[0]?.lines.length,5);
|
|
148
|
+
assert.equal(price.tiers?.[0]?.lines.find(line=>line.billable==='web_search')?.costUsd,'0.01');
|
|
149
|
+
assert.equal(calculateReferenceCost(price,{inputTokens:300000,outputTokens:10,cachedInputTokens:200000,cacheWriteTokens:0,webSearchCount:0}),'0.24008');
|
|
150
|
+
assert.equal(calculateReferenceCost(price,{inputTokens:300000,outputTokens:10,cachedInputTokens:200000,cacheWriteTokens:0}),null);
|
|
151
|
+
h.set({data:{endpoints:[{tag:'synthetic-provider',pricing:{prompt:'1',completion:'1',overrides:[{min_prompt_tokens:1,min_output_tokens:1,prompt:'2'}]}}]}});
|
|
152
|
+
const bad=await h.pricing.catalog('chat',binding.modelId,true); assert.equal(bad.items[0].unavailable,true);
|
|
153
|
+
await assert.rejects(h.pricing.snapshot(binding),{code:'USAGE_PRICE_UNSUPPORTED'});
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test('admission snapshot rejects invalid tier thresholds and invalid future-tier units before any dispatch', async () => {
|
|
157
|
+
const { tokenBillingRate } = await import('./billing-ledger');
|
|
158
|
+
const price: PriceSnapshot = {...chat,tiers:[{minPromptTokens:272000,lines:chat.lines}]};
|
|
159
|
+
assert.deepEqual(tokenBillingRate('synthetic-plan',1,1.5,price).price,price);
|
|
160
|
+
assert.throws(()=>tokenBillingRate('synthetic-plan',1,1.5,{...price,tiers:[price.tiers![0]!,price.tiers![0]!]}), /unique/);
|
|
161
|
+
assert.throws(()=>tokenBillingRate('synthetic-plan',1,1.5,{...price,tiers:[{minPromptTokens:0,lines:chat.lines}]}), /positive/);
|
|
162
|
+
assert.throws(()=>tokenBillingRate('synthetic-plan',1,1.5,{...price,tiers:[{minPromptTokens:1,lines:[{billable:'prompt',unit:'image',costUsd:'1'}]}]}), /Invalid/);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
test('readiness distinguishes unbound, unsynchronized, unsupported and ready without provider traffic', async () => {
|
|
167
|
+
const h = cacheFixture();
|
|
168
|
+
assert.equal((await h.pricing.inspect(undefined)).availability.code, 'USAGE_PRICE_NOT_CONFIGURED');
|
|
169
|
+
assert.equal((await h.pricing.inspect(binding)).availability.code, 'USAGE_PRICE_UNAVAILABLE');
|
|
170
|
+
assert.equal(h.calls(), 0);
|
|
171
|
+
await h.pricing.catalog('chat', binding.modelId);
|
|
172
|
+
assert.deepEqual((await h.pricing.inspect(binding)).availability, {state:'ready',code:null,message:null});
|
|
173
|
+
assert.equal(h.calls(), 1);
|
|
174
|
+
h.set({data:{endpoints:[{tag:binding.endpointId,pricing:{prompt:'1',completion:'2',unsupported_meter:'3'}}]}});
|
|
175
|
+
await h.pricing.catalog('chat', binding.modelId, true);
|
|
176
|
+
assert.equal((await h.pricing.inspect(binding)).availability.code, 'USAGE_PRICE_UNSUPPORTED');
|
|
177
|
+
assert.equal(h.calls(), 2);
|
|
178
|
+
});
|