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.
Files changed (184) hide show
  1. package/README.en.md +6 -5
  2. package/README.md +6 -5
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/ARCHITECTURE.md +1 -1
  5. package/docs/CHANGELOG.en.md +12 -1
  6. package/docs/CHANGELOG.md +12 -1
  7. package/docs/COMPATIBILITY.en.md +4 -0
  8. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  9. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  10. package/docs/MODEL_BILLING.en.md +123 -0
  11. package/docs/MODEL_BILLING.md +125 -0
  12. package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
  13. package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
  14. package/docs/README.en.md +5 -1
  15. package/docs/README.md +4 -0
  16. package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
  17. package/docs/RELEASE_NOTES_NEXT.md +4 -2
  18. package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
  19. package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
  20. package/docs/UPGRADE_v0.9.0.en.md +54 -0
  21. package/docs/UPGRADE_v0.9.0.md +54 -0
  22. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
  23. package/package.json +1 -1
  24. package/scripts/check-doc-links.mjs +4 -0
  25. package/scripts/check-image-tags.sh +1 -1
  26. package/scripts/check-release-consistency.test.mjs +2 -2
  27. package/scripts/install.sh +1 -1
  28. package/scripts/publish-images.sh +1 -1
  29. package/scripts/release-audit.mjs +1 -0
  30. package/scripts/sdk-runtime-test.mjs +6 -0
  31. package/scripts/verify-billing-install-upgrade.mjs +225 -0
  32. package/scripts/verify-github-repo.mjs +1 -0
  33. package/sdk/node/README.md +17 -0
  34. package/sdk/node/examples/billing.mjs +21 -0
  35. package/sdk/node/package.json +5 -1
  36. package/sdk/node/src/index.mjs +2 -0
  37. package/sdk/node/src/usage.d.mts +74 -0
  38. package/sdk/node/src/usage.mjs +62 -0
  39. package/sdk/node/tests/usage-types.mts +23 -0
  40. package/sdk/node/tests/usage.test.mjs +81 -0
  41. package/sdk/php7/README.md +19 -2
  42. package/sdk/php7/examples/billing.php +27 -0
  43. package/sdk/php7/examples/well-known.php +1 -1
  44. package/sdk/php7/src/ToolSpec.php +1 -1
  45. package/sdk/php7/src/UsageClient.php +95 -0
  46. package/sdk/php7/src/UsageClientException.php +22 -0
  47. package/sdk/php7/tests/billing-core-http.php +59 -0
  48. package/sdk/php7/tests/usage-client.php +78 -0
  49. package/sql/063_usage_model_billing.sql +153 -0
  50. package/sql/064_period_plan_allowance.sql +25 -0
  51. package/sql/README.en.md +12 -4
  52. package/sql/README.md +14 -6
  53. package/src/app/auth.ts +2 -0
  54. package/src/app/oss-edition.ts +1 -0
  55. package/src/infrastructure/config/configstore.ts +6 -0
  56. package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
  57. package/src/modules/usage/billing-contracts.ts +59 -0
  58. package/src/modules/usage/billing-decimal.test.ts +22 -0
  59. package/src/modules/usage/billing-decimal.ts +36 -0
  60. package/src/modules/usage/billing-external.ts +39 -0
  61. package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
  62. package/src/modules/usage/billing-ledger.test.ts +51 -0
  63. package/src/modules/usage/billing-ledger.ts +104 -0
  64. package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
  65. package/src/modules/usage/billing-presentation.test.ts +49 -0
  66. package/src/modules/usage/billing-presentation.ts +34 -0
  67. package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
  68. package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
  69. package/src/modules/usage/billing-repository.ts +463 -0
  70. package/src/modules/usage/contracts.ts +49 -0
  71. package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
  72. package/src/modules/usage/errors.ts +19 -0
  73. package/src/modules/usage/http.ts +85 -0
  74. package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
  75. package/src/modules/usage/identity.mysql.test.ts +120 -0
  76. package/src/modules/usage/identity.ts +303 -0
  77. package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
  78. package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
  79. package/src/modules/usage/model-gateway.ts +229 -0
  80. package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
  81. package/src/modules/usage/model-tool-provider.test.ts +37 -0
  82. package/src/modules/usage/model-tool-provider.ts +110 -0
  83. package/src/modules/usage/model-tools.test.ts +36 -0
  84. package/src/modules/usage/model-tools.ts +62 -0
  85. package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
  86. package/src/modules/usage/period.test.ts +26 -0
  87. package/src/modules/usage/period.ts +96 -0
  88. package/src/modules/usage/pricing.test.ts +178 -0
  89. package/src/modules/usage/pricing.ts +228 -0
  90. package/src/modules/usage/provider-failure.ts +37 -0
  91. package/src/modules/usage/provider-stream.test.ts +85 -0
  92. package/src/modules/usage/provider-stream.ts +77 -0
  93. package/src/modules/usage/provider.test.ts +67 -0
  94. package/src/modules/usage/provider.ts +142 -0
  95. package/src/modules/usage/repository.ts +539 -0
  96. package/src/modules/usage/service-availability.mysql.test.ts +68 -0
  97. package/src/modules/usage/service-availability.ts +13 -0
  98. package/src/modules/usage/service-delete.mysql.test.ts +87 -0
  99. package/src/modules/usage/stream-http.ts +32 -0
  100. package/src/modules/usage/test-harness.ts +108 -0
  101. package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
  102. package/src/modules/usage/usage-deletion.ts +119 -0
  103. package/src/modules/usage/validation.test.ts +18 -0
  104. package/src/modules/usage/validation.ts +33 -0
  105. package/src/routes/admin-billing-usage.ts +73 -0
  106. package/src/routes/admin-usage.ts +147 -0
  107. package/src/routes/admin.ts +4 -0
  108. package/src/routes/private.ts +8 -0
  109. package/web/connect/bailing-connect-php7.tgz +0 -0
  110. package/web/console/assets/Accounts-Bervi5JU.css +1 -0
  111. package/web/console/assets/Accounts-DnddhY6t.js +3 -0
  112. package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-VInbD7JS.js} +1 -1
  113. package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
  114. package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
  115. package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-34qUPHf0.js} +1 -1
  116. package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-BbVgkSm2.js} +1 -1
  117. package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-DgscF28e.js} +1 -1
  118. package/web/console/assets/{Channels-B9n4fbxg.js → Channels-Bp-yuk8d.js} +1 -1
  119. package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-C9Ft60TS.js} +1 -1
  120. package/web/console/assets/{Clients-CI3DBDHf.js → Clients-NPldD-DD.js} +1 -1
  121. package/web/console/assets/{Cost-JgNXQPlN.js → Cost-DZcuB-EB.js} +1 -1
  122. package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-RTT7N6zl.js} +1 -1
  123. package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-_LeK8cce.js} +1 -1
  124. package/web/console/assets/{Executors-CRbboOCZ.js → Executors-Bi7H8rIm.js} +1 -1
  125. package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
  126. package/web/console/assets/{Kb-CgLNGjRp.js → Kb-BHamz8NP.js} +2 -2
  127. package/web/console/assets/{Login-C52JmXzx.js → Login-C1rJR-6w.js} +1 -1
  128. package/web/console/assets/{Projects-CDOvHPVS.js → Projects-BRA4a48v.js} +1 -1
  129. package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
  130. package/web/console/assets/Routes-CyXV4Pba.css +1 -0
  131. package/web/console/assets/{Runs-DYNDXsqk.js → Runs-B_fa_BlD.js} +1 -1
  132. package/web/console/assets/{Setup-B91P6i1x.js → Setup-C1_d0mFy.js} +1 -1
  133. package/web/console/assets/Shell-CHEV6RGC.js +1 -0
  134. package/web/console/assets/Shell-ykb-tUfo.css +1 -0
  135. package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DlG3ojhA.js} +1 -1
  136. package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-DYo2gg6d.js} +1 -1
  137. package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-DKCoUZlq.js} +1 -1
  138. package/web/console/assets/{Targets-CuuIYeZO.js → Targets-CdkG6BPR.js} +1 -1
  139. package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DVpCt0ox.js} +1 -1
  140. package/web/console/assets/Usage-CAeDGjrb.css +1 -0
  141. package/web/console/assets/Usage-DWCpLugC.js +1 -0
  142. package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
  143. package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
  144. package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
  145. package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
  146. package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
  147. package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
  148. package/web/console/assets/index-H1kfa0Mj.js +2 -0
  149. package/web/console/assets/{request-DeGya810.js → request-DLsP1_ot.js} +1 -1
  150. package/web/console/assets/{schema-BqlqLw1R.js → schema-BLOHvAJQ.js} +1 -1
  151. package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
  152. package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
  153. package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
  154. package/web/console/index.html +3 -3
  155. package/web-admin/README.md +17 -0
  156. package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
  157. package/web-admin/src/components/UsageHelp.vue +72 -0
  158. package/web-admin/src/components/UsageServiceReferences.vue +169 -0
  159. package/web-admin/src/layout/Shell.vue +22 -5
  160. package/web-admin/src/pages/Accounts.vue +3 -3
  161. package/web-admin/src/pages/AgentTasks.vue +2 -2
  162. package/web-admin/src/pages/Routes.vue +5 -1
  163. package/web-admin/src/pages/Usage.vue +2470 -0
  164. package/web-admin/src/pages/UsageAccess.vue +1147 -0
  165. package/web-admin/src/router.ts +8 -4
  166. package/web-admin/src/styles/base.css +57 -0
  167. package/web-admin/src/table-widths.ts +16 -1
  168. package/web-admin/src/usage-deletion.ts +40 -0
  169. package/web-admin/src/usage-management.ts +13 -0
  170. package/web-admin/src/usage-presentation.test.ts +21 -0
  171. package/web-admin/src/usage-presentation.ts +107 -0
  172. package/web-admin/src/usage-price-preview.test.ts +60 -0
  173. package/web-admin/src/usage-price-preview.ts +54 -0
  174. package/web-admin/tests/token-usage.browser.mjs +773 -0
  175. package/web-admin/tests/usage-access.browser.mjs +398 -0
  176. package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
  177. package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
  178. package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
  179. package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
  180. package/web/console/assets/Routes-DkMIjMQA.css +0 -1
  181. package/web/console/assets/Routes-X9vHLpKW.js +0 -124
  182. package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
  183. package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
  184. package/web/console/assets/index-UGvfF3Xr.js +0 -2
@@ -5,7 +5,11 @@
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
7
7
  "exports": {
8
- ".": "./src/index.mjs"
8
+ ".": "./src/index.mjs",
9
+ "./usage": {
10
+ "types": "./src/usage.d.mts",
11
+ "default": "./src/usage.mjs"
12
+ }
9
13
  },
10
14
  "files": [
11
15
  "src",
@@ -248,3 +248,5 @@ export class HubClient {
248
248
  }
249
249
  }
250
250
  }
251
+
252
+ export { UsageIssuerClient, UsageIssuerError } from './usage.mjs';
@@ -0,0 +1,74 @@
1
+ /** Server-only business issuer API. USD billing and model identity are separate from business authorization. */
2
+ export interface UsageIssuerOptions {
3
+ baseUrl: string;
4
+ issuerToken: string;
5
+ fetchImpl?: typeof fetch;
6
+ timeoutMs?: number;
7
+ }
8
+ export interface UsageIdentityInput { tenant: string; subject: string; generation?: string }
9
+ export interface UsageExchangeInput extends UsageIdentityInput {
10
+ request_key: string;
11
+ service_id: string;
12
+ account_id?: string;
13
+ model_access?: 'service' | 'token_gateway';
14
+ }
15
+ export interface UsageSession {
16
+ sessionId: string; userId: string; accountId: string; issuerId: string;
17
+ serviceId: string; expiresAt: number; modelAccess?: 'service' | 'token_gateway';
18
+ }
19
+ export interface UsageExchangeResult {
20
+ schema: 'bailing.usage-session.v1'; credential: string; session: UsageSession;
21
+ }
22
+ export interface BillingAllowanceConfig {
23
+ mode: 'credits' | 'periodic';
24
+ /** Sale price; also the allowance amount for credits plans. */
25
+ priceUsd: number;
26
+ /** Required and positive for periodic plans; absent for credits plans. */
27
+ periodAllowanceUsd?: number;
28
+ periodUnit?: 'day' | 'week' | 'month';
29
+ duration: { unit: 'day' | 'month' | 'forever'; count: number };
30
+ }
31
+ export interface BillingPlanConfig extends BillingAllowanceConfig { serviceIds: string[]; multiplier: number }
32
+ export interface BillingPlan {
33
+ id: string; label: string; revision: number; state: 'active' | 'suspended';
34
+ config: BillingPlanConfig; createdAt: number; updatedAt: number;
35
+ }
36
+ export interface BillingGrantInput {
37
+ request_key: string; plan_id: string; expected_revision: number; starts_at?: number;
38
+ }
39
+ export interface BillingControlInput { request_key: string; expected_revision: number; state: 'active' | 'suspended' }
40
+ export interface BillingGrant {
41
+ id: string; accountId: string; planId: string; planRevision: number; label: string;
42
+ revision: number; state: 'active' | 'suspended'; sourceOwner: string;
43
+ startsAt: number; expiresAt: number | null; config: BillingAllowanceConfig;
44
+ }
45
+ export interface UsagePresentation {
46
+ schema: 'bailing.usage-presentation.v1'; kind: 'credits' | 'percentage' | 'none';
47
+ state: 'active' | 'depleted' | 'not_started' | 'expired' | 'suspended' | 'unavailable';
48
+ remaining: number | null; total: number | null; displayValue: string | null;
49
+ }
50
+ export interface BillingSummary {
51
+ schema: 'bailing.billing-summary.v1'; accountId: string; grant: BillingGrant | null;
52
+ plan: Pick<BillingPlan, 'id' | 'label' | 'revision'> & { serviceIds: string[]; multiplier: number } | null;
53
+ availableUsd: number; consumedUsd: number; currentPeriodConsumedUsd: number;
54
+ overageUsd: number; resetAt: number | null; expiresAt: number | null; pendingRequests: number;
55
+ presentation: UsagePresentation;
56
+ }
57
+ export interface UsageFeedback {
58
+ schema?: string; code?: string; dispatch?: string; retryable?: boolean;
59
+ next_action?: string; resetAt?: number; reset_at?: number;
60
+ }
61
+ export class UsageIssuerError extends Error {
62
+ constructor(code: string, status: number | undefined, outcome: 'rejected' | 'unknown', requestKey?: string, feedback?: UsageFeedback);
63
+ code: string; status: number | undefined; outcome: 'rejected' | 'unknown';
64
+ requestKey: string | undefined; feedback?: UsageFeedback;
65
+ }
66
+ export class UsageIssuerClient {
67
+ constructor(options: UsageIssuerOptions);
68
+ exchangeSession(input: UsageExchangeInput): Promise<UsageExchangeResult>;
69
+ revokeUser(input: UsageIdentityInput): Promise<{ revoked: true }>;
70
+ listBillingPlans(): Promise<{ items: BillingPlan[] }>;
71
+ grantBillingPlan(accountId: string, input: BillingGrantInput): Promise<BillingGrant>;
72
+ controlBillingPlan(accountId: string, input: BillingControlInput): Promise<BillingGrant>;
73
+ getBillingSummary(accountId: string): Promise<BillingSummary>;
74
+ }
@@ -0,0 +1,62 @@
1
+ const PREFIX = '/usage/v1';
2
+ function key(value, label = 'identifier') {
3
+ if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,190}$/.test(value)) throw new TypeError(`Invalid ${label}.`);
4
+ return value;
5
+ }
6
+ function object(value) { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('A request object is required.'); return value; }
7
+ function safeCode(value, fallback) { return typeof value === 'string' && /^[A-Z][A-Z0-9_]{1,90}$/.test(value) ? value : fallback; }
8
+ function publicFeedback(value) {
9
+ if (!value || typeof value !== 'object') return undefined;
10
+ return Object.fromEntries(['schema','code','dispatch','retryable','next_action','reset_at','resetAt'].filter(key =>
11
+ ['string','boolean','number'].includes(typeof value[key])).map(key => [key, value[key]]));
12
+ }
13
+ export class UsageIssuerError extends Error {
14
+ constructor(code, status, outcome, requestKey, feedback) {
15
+ super(`Usage management request failed (${code}).`);
16
+ this.name = 'UsageIssuerError'; this.code = code; this.status = status; this.outcome = outcome;
17
+ this.requestKey = requestKey; if (feedback) this.feedback = feedback;
18
+ }
19
+ }
20
+ /** Server-only issuer API. Never expose this credential or these methods as model tools. */
21
+ export class UsageIssuerClient {
22
+ #baseUrl; #token; #fetch; #timeout;
23
+ constructor({ baseUrl, issuerToken, fetchImpl = globalThis.fetch, timeoutMs = 15_000 }) {
24
+ let url;
25
+ try { url = new URL(baseUrl); } catch { throw new TypeError('A valid Hub URL is required.'); }
26
+ if (!['https:','http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash
27
+ || (url.protocol === 'http:' && !['localhost','127.0.0.1','[::1]'].includes(url.hostname))) throw new TypeError('Use HTTPS, or loopback HTTP for development.');
28
+ if (typeof issuerToken !== 'string' || !/^bhu_i_[A-Za-z0-9_-]{43}$/.test(issuerToken)) throw new TypeError('A separate Usage issuer credential is required.');
29
+ if (typeof fetchImpl !== 'function' || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60_000) throw new TypeError('Invalid transport configuration.');
30
+ this.#baseUrl = url.toString().replace(/\/+$/, ''); this.#token = issuerToken; this.#fetch = fetchImpl; this.#timeout = timeoutMs;
31
+ }
32
+ async #request(method, path, body) {
33
+ if (body !== undefined) { object(body); if (!path.endsWith('/external/users/revoke')) key(body.request_key, 'request_key'); }
34
+ const requestKey = body?.request_key;
35
+ let response;
36
+ try {
37
+ response = await this.#fetch(this.#baseUrl + path, { method,
38
+ headers: { authorization: `Bearer ${this.#token}`, accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
39
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), redirect: 'error', signal: AbortSignal.timeout(this.#timeout) });
40
+ } catch { throw new UsageIssuerError('USAGE_TRANSPORT_UNAVAILABLE', undefined, method === 'GET' ? 'rejected' : 'unknown', requestKey); }
41
+ let data;
42
+ try {
43
+ if (!response.body) throw new Error();
44
+ const reader = response.body.getReader(); const chunks = []; let bytes = 0;
45
+ try { while (true) { const part = await reader.read(); if (part.done) break; bytes += part.value.length; if (bytes > 1_048_576) throw new Error(); chunks.push(part.value); } }
46
+ finally { await reader.cancel().catch(() => {}); }
47
+ data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
48
+ object(data);
49
+ } catch { throw new UsageIssuerError(response.status === 404 ? 'USAGE_UNSUPPORTED' : 'USAGE_RESPONSE_INVALID', response.status,
50
+ method === 'GET' || response.status === 404 ? 'rejected' : 'unknown', requestKey); }
51
+ if (!response.ok) throw new UsageIssuerError(safeCode(data.code ?? data.error, response.status === 404 ? 'USAGE_UNSUPPORTED' : 'USAGE_REQUEST_REJECTED'),
52
+ response.status, response.status >= 500 && method !== 'GET' ? 'unknown' : 'rejected', requestKey, publicFeedback(data.feedback));
53
+ return data;
54
+ }
55
+ #accountPath(accountId, action) { return `${PREFIX}/external/billing/accounts/${encodeURIComponent(key(accountId))}/${action}`; }
56
+ exchangeSession(input) { return this.#request('POST', `${PREFIX}/sessions/exchange`, input); }
57
+ revokeUser(input) { return this.#request('POST', `${PREFIX}/external/users/revoke`, input); }
58
+ listBillingPlans() { return this.#request('GET', `${PREFIX}/external/billing/plans`); }
59
+ grantBillingPlan(accountId, input) { return this.#request('POST', this.#accountPath(accountId, 'grant'), input); }
60
+ controlBillingPlan(accountId, input) { return this.#request('POST', this.#accountPath(accountId, 'control'), input); }
61
+ getBillingSummary(accountId) { return this.#request('GET', this.#accountPath(accountId, 'summary')); }
62
+ }
@@ -0,0 +1,23 @@
1
+ import { UsageIssuerClient, UsageIssuerError, type BillingPlan, type BillingGrant, type BillingSummary } from '@bailinghub/connect/usage';
2
+
3
+ // Compile-only public package entrypoint check. This function is never called.
4
+ async function billingTypes(client: UsageIssuerClient) {
5
+ const plans: BillingPlan[] = (await client.listBillingPlans()).items;
6
+ const login = await client.exchangeSession({ request_key: 'login', tenant: 'example', subject: 'user', service_id: 'text', model_access: 'token_gateway' });
7
+ const grant: BillingGrant = await client.grantBillingPlan(login.session.accountId, { request_key: 'grant', plan_id: 'monthly', expected_revision: 0 });
8
+ const summary: BillingSummary = await client.getBillingSummary(grant.accountId);
9
+ await client.controlBillingPlan(grant.accountId, { request_key: 'pause', expected_revision: grant.revision, state: 'suspended' });
10
+ await client.revokeUser({ tenant: 'example', subject: 'user' });
11
+ const allowance: number | undefined = plans[0]?.config.periodAllowanceUsd;
12
+ // @ts-expect-error A billing grant requires the original request key.
13
+ await client.grantBillingPlan(grant.accountId, { plan_id: 'monthly', expected_revision: 0 });
14
+ // @ts-expect-error Old token plan methods are not compatibility aliases.
15
+ await client.listTokenPlans();
16
+ // @ts-expect-error The summary exposes dollar amounts, not an old token balance.
17
+ const obsolete = summary.availableTokens;
18
+ return { summary, allowance, obsolete };
19
+ }
20
+ void billingTypes;
21
+ const error = new UsageIssuerError('USAGE_REVISION_CONFLICT', 409, 'rejected', 'grant');
22
+ const outcome: 'unknown' | 'rejected' = error.outcome;
23
+ void outcome;
@@ -0,0 +1,81 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { UsageIssuerClient, UsageIssuerError } from '../src/index.mjs';
4
+ const issuerToken = `bhu_i_${'x'.repeat(43)}`;
5
+ const json = (data, status = 200) => new Response(JSON.stringify(data), { status });
6
+ const input = { request_key: 'order-1', plan_id: 'plan-1', expected_revision: 0 };
7
+ test('Billing issuer methods preserve scope and exact grant keys', async () => {
8
+ const calls = [];
9
+ const sdk = new UsageIssuerClient({ baseUrl: 'https://hub.example.com', issuerToken, fetchImpl: async (url, init) => {
10
+ assert.equal(new Headers(init.headers).get('authorization'), `Bearer ${issuerToken}`);
11
+ calls.push({ path: new URL(url).pathname, method: init.method, body: init.body && JSON.parse(init.body) }); return json({ ok: true });
12
+ } });
13
+ await sdk.exchangeSession({ request_key: 'login-1', tenant: 'tenant-1', subject: 'subject-1', service_id: 'text' });
14
+ await sdk.grantBillingPlan('account-1', input); await sdk.grantBillingPlan('account-1', input);
15
+ await sdk.controlBillingPlan('account-1', { request_key: 'pause-1', expected_revision: 1, state: 'suspended' });
16
+ await sdk.getBillingSummary('account-1'); await sdk.revokeUser({ tenant: 'tenant-1', subject: 'subject-1' }); await sdk.listBillingPlans();
17
+ assert.equal(calls.length, 7); assert.deepEqual(calls[1], calls[2]);
18
+ assert.equal(calls[1].path, '/usage/v1/external/billing/accounts/account-1/grant');
19
+ assert.equal(calls[4].path, '/usage/v1/external/billing/accounts/account-1/summary');
20
+ assert.equal(calls[6].path, '/usage/v1/external/billing/plans');
21
+ for (const removed of ['listTokenPlans','grantTokenPlan','controlTokenPlan','getTokenSummary','getSummary','grantCredits','putEntitlement','renewEntitlement','listLedger','listPlans']) assert.equal(sdk[removed], undefined);
22
+ assert.equal(JSON.stringify(sdk).includes(issuerToken), false);
23
+ });
24
+ test('grant acknowledgement loss preserves original wire input and only caller retry sends it again', async () => {
25
+ const original = { request_key: 'grant-1', expected_revision: 2, plan_id: 'plan-1' };
26
+ const bodies = [];
27
+ const sdk = new UsageIssuerClient({ baseUrl: 'https://hub.example.com', issuerToken, fetchImpl: async (url, init) => {
28
+ assert.ok(url.endsWith('/grant')); assert.equal(init.method, 'POST'); bodies.push(init.body);
29
+ if (bodies.length === 1) throw new Error('lost acknowledgement'); return json({ revision: 3 });
30
+ } });
31
+ await assert.rejects(sdk.grantBillingPlan('account-1', original), error => {
32
+ assert.equal(error.outcome, 'unknown'); assert.equal(error.requestKey, 'grant-1'); return true;
33
+ });
34
+ assert.equal(bodies.length, 1);
35
+ assert.equal((await sdk.grantBillingPlan('account-1', original)).revision, 3);
36
+ assert.deepEqual(JSON.parse(bodies[0]), original); assert.equal(bodies[0], bodies[1]);
37
+ });
38
+ test('issuer transport never auto-retries ambiguous mutation or exposes private cause', async () => {
39
+ let calls = 0;
40
+ const sdk = new UsageIssuerClient({ baseUrl: 'https://hub.example.com', issuerToken, fetchImpl: async () => { calls++; throw new Error('private original details'); } });
41
+ await assert.rejects(sdk.grantBillingPlan('account-1', input), error => {
42
+ assert.ok(error instanceof UsageIssuerError); assert.equal(error.requestKey, 'order-1'); assert.equal(error.outcome, 'unknown'); assert.equal(error.message.includes('private'), false); return true;
43
+ });
44
+ assert.equal(calls, 1);
45
+ });
46
+ test('wrong credential or path fails before IO and stable feedback survives error decoding', async () => {
47
+ assert.throws(() => new UsageIssuerClient({ baseUrl: 'https://hub.example.com', issuerToken: 'business-token' }), TypeError);
48
+ assert.throws(() => new UsageIssuerClient({ baseUrl: 'http://example.com', issuerToken }), TypeError);
49
+ const sdk = new UsageIssuerClient({ baseUrl: 'https://hub.example.com', issuerToken, fetchImpl: async () => json({ code: 'USAGE_REVISION_CONFLICT', message: 'private body', feedback: { code: 'USAGE_REVISION_CONFLICT', next_action: 'refresh', token: 'secret' } }, 409) });
50
+ assert.throws(() => sdk.getBillingSummary('../account'), TypeError);
51
+ await assert.rejects(sdk.grantBillingPlan('account-1',input), error => {
52
+ assert.equal(error.code, 'USAGE_REVISION_CONFLICT'); assert.equal(error.feedback.next_action, 'refresh'); assert.equal('token' in error.feedback, false); return true;
53
+ });
54
+ });
55
+ test('summary still rejects missing, invalid, oversized and error responses', async () => {
56
+ for (const [body, status] of [
57
+ [null, 200], ['', 200], [' \n\t ', 200], ['nul', 200], ['{"incomplete":', 200],
58
+ ['"null"', 200], ['false', 200], ['0', 200], [' '.repeat(1_048_576) + 'null', 200],
59
+ ['null', 201], ['null', 401], ['null', 404], ['null', 500],
60
+ ]) {
61
+ let calls = 0;
62
+ const sdk = new UsageIssuerClient({ baseUrl: 'https://hub.example.com', issuerToken, fetchImpl: async () => { calls++; return new Response(body, { status }); } });
63
+ await assert.rejects(sdk.getBillingSummary('account-1'), error => {
64
+ assert.equal(error.code, status === 404 ? 'USAGE_UNSUPPORTED' : 'USAGE_RESPONSE_INVALID');
65
+ assert.equal(error.status, status); assert.equal(error.outcome, 'rejected'); return true;
66
+ });
67
+ assert.equal(calls, 1);
68
+ }
69
+ const sdk = new UsageIssuerClient({ baseUrl: 'https://hub.example.com', issuerToken, fetchImpl: async () => json({ code: 'USAGE_IDENTITY_REVOKED' }, 403) });
70
+ await assert.rejects(sdk.getBillingSummary('account-1'), error => error.code === 'USAGE_IDENTITY_REVOKED' && error.outcome === 'rejected');
71
+ });
72
+ test('malformed or null mutation acknowledgements remain unknown and are never automatically retried', async () => {
73
+ for (const body of ['null', '', 'nul', ' '.repeat(1_048_576) + 'null']) {
74
+ let calls = 0;
75
+ const sdk = new UsageIssuerClient({ baseUrl: 'https://hub.example.com', issuerToken, fetchImpl: async () => { calls++; return new Response(body); } });
76
+ await assert.rejects(sdk.grantBillingPlan('account-1', input), error => {
77
+ assert.equal(error.code, 'USAGE_RESPONSE_INVALID'); assert.equal(error.outcome, 'unknown'); assert.equal(error.requestKey, 'order-1'); return true;
78
+ });
79
+ assert.equal(calls, 1);
80
+ }
81
+ });
@@ -22,7 +22,7 @@ curl -O https://<中枢域名>/connect/bailing-connect-php7.tgz && tar -xzf bail
22
22
  }
23
23
  ```
24
24
 
25
- 或 ③ 直接拷贝 `src/` 目录进项目——共 **7 个文件**(`ToolSpec`/`ToolDef`/`Verify`/`Ticket`/`SpecServer`/`HubClient`/`AgentAuth`)。零依赖,怎么引都行。命名空间同为 `Bailing\Connect`。
25
+ 或 ③ 直接拷贝 `src/` 目录进项目——共 **9 个文件**(`ToolSpec`/`ToolDef`/`Verify`/`Ticket`/`SpecServer`/`HubClient`/`AgentAuth`,以及可选的 `UsageClient`/`UsageClientException`)。零依赖,怎么引都行。命名空间同为 `Bailing\Connect`。
26
26
 
27
27
  ## 第一步:声明工具(builder,不动你的控制器)
28
28
 
@@ -30,7 +30,7 @@ curl -O https://<中枢域名>/connect/bailing-connect-php7.tgz && tar -xzf bail
30
30
  use Bailing\Connect\ToolSpec;
31
31
  use Bailing\Connect\ToolDef;
32
32
 
33
- $spec = ToolSpec::create('示例商城') // 标题随便填,业务系统名
33
+ $spec = ToolSpec::create('示例业务系统') // 标题随便填,业务系统名
34
34
  ->tool(
35
35
  'staff_list', // 工具名(operationId):定了就别改,改名会让 AI 认为这是另一个新工具
36
36
  'GET', // method
@@ -250,3 +250,20 @@ $session = $agentAuth->updateSubjectDisplay($sessionId, null);
250
250
 
251
251
  - `examples/build-spec.php`:完整 builder 范例(覆盖全部字段;与 8.x 版同源,跑同一个跨语言契约测试)
252
252
  - `examples/well-known.php`:裸 PHP 托管 spec 范例
253
+
254
+ ## 可选模型套餐与登录
255
+
256
+ `Bailing\Connect\UsageClient`(PHP 7.3) 使用独立的服务端 Usage issuer 凭据,提供 `exchangeSession`、`revokeUser`、`listBillingPlans`、`getBillingSummary`、`grantBillingPlan` 和 `controlBillingPlan`。不要复用业务 Client Token,也不要把 issuer 凭据或管理方法交给浏览器或模型。
257
+
258
+ 业务后端根据已验证登录提交 `request_key/tenant/subject/generation/service_id` 换取短期模型凭证。`model_access: "service"` 限定所选模型;显式 `"token_gateway"` 可在身份来源及套餐允许的模型交集中选择,不扩大业务权限。只将短期凭证和固定身份交给对应使用人。登录不依赖套餐摘要成功;未开通套餐通过摘要的 `grant=null` 表达。
259
+
260
+ `grantBillingPlan(accountId, input)` 的 input 包含原 `request_key`、`plan_id`、`expected_revision`。`controlBillingPlan(accountId, input)` 使用原请求键、当前修订和 `state: active|suspended`。`getBillingSummary(accountId)` 读取当前账户美元余额、实际费用与周期状态,不执行模型。向用户展示时只使用摘要 `presentation`:额度包显示积分,周期套餐显示剩余百分比;美元字段用于计费核账;原始 Token 用量保留在模型请求明细中。售价、收款和合同由业务系统负责。
261
+
262
+ 套餐管理统一使用 `/usage/v1/external/billing/`。套餐目录返回 `config.priceUsd`、周期套餐必填的 `config.periodAllowanceUsd`、`periodUnit`、`duration`、`serviceIds` 和 `multiplier`。周期套餐售价与每周期额度是两个独立字段;账户摘要使用 `bailing.billing-summary.v1`,美元余额为 `availableUsd`,已消费为 `consumedUsd`,客户展示使用 `presentation`。
263
+
264
+ 管理写入不会自动重试。回包丢失时沿原键、原参数核对,不能换新键重复发放。异常只包含脱敏错误码、`outcome`、`requestKey` 和安全反馈。`revokeUser` 按原 tenant/subject/generation 幂等停用,不需要 request_key。
265
+
266
+ 完整契约见 [模型服务与套餐计费](../../docs/MODEL_BILLING.md)。安装业务 SDK 本身不接管本地模型流量;客户端接入模型请求/流式入口后才会计量。
267
+
268
+
269
+ 示例将准备和发送分开:先调用 `prepareBillingPlan` 并持久化 `grantInput`,再调用 `applyBillingPlan`;回包不确定时沿用已保存的输入,不能重新计算修订。服务端开通示例见 [examples/billing.php](examples/billing.php)。
@@ -0,0 +1,27 @@
1
+ <?php
2
+ require_once __DIR__ . '/../src/UsageClientException.php';
3
+ require_once __DIR__ . '/../src/UsageClient.php';
4
+
5
+ /** Invoke after authenticating a user in your own backend. Loading this file sends no requests. */
6
+ function prepareBillingPlan($baseUrl, $issuerToken, array $identity, $loginRequestKey, $serviceId, $planId, $orderRequestKey)
7
+ {
8
+ $issuer = new \Bailing\Connect\UsageClient($baseUrl, $issuerToken);
9
+ $login = $issuer->exchangeSession(array_merge($identity, array(
10
+ 'request_key' => $loginRequestKey, 'service_id' => $serviceId, 'model_access' => 'token_gateway'
11
+ )));
12
+ $accountId = $login['session']['accountId'];
13
+ $summary = $issuer->getBillingSummary($accountId);
14
+ // Persist this exact body with your order before calling grantBillingPlan.
15
+ $grantInput = array('request_key' => $orderRequestKey, 'plan_id' => $planId,
16
+ 'expected_revision' => $summary['grant'] === null ? 0 : $summary['grant']['revision']);
17
+ return array('credential' => $login['credential'], 'session' => $login['session'], 'accountId' => $accountId, 'grantInput' => $grantInput);
18
+ }
19
+
20
+ /** Submit the saved input, including its original revision. Do not prepare it again on retry. */
21
+ function applyBillingPlan($baseUrl, $issuerToken, $accountId, array $grantInput)
22
+ {
23
+ $issuer = new \Bailing\Connect\UsageClient($baseUrl, $issuerToken);
24
+ $issuer->grantBillingPlan($accountId, $grantInput);
25
+ $summary = $issuer->getBillingSummary($accountId);
26
+ return $summary['presentation'];
27
+ }
@@ -17,7 +17,7 @@ use Bailing\Connect\SpecServer;
17
17
 
18
18
  $secret = getenv('BAILING_TOOL_SECRET') ?: '在中枢「工具源」登记的签名密钥';
19
19
 
20
- $spec = ToolSpec::create('示例商城')
20
+ $spec = ToolSpec::create('示例业务系统')
21
21
  ->authzProbe('/bailing/authz-probe')
22
22
  ->tool('staff_list', 'GET', '/openapi/staff/list', 'tenant.staff.read', '查询门店员工列表',
23
23
  function (ToolDef $t) {
@@ -13,7 +13,7 @@ use InvalidArgumentException;
13
13
  * 设计原则同 8.x 版:**会被中枢跳过/误用的问题在构建期就报错**,而不是发布后才在控制台发现。
14
14
  *
15
15
  * 用法:
16
- * $spec = ToolSpec::create('示例商城')
16
+ * $spec = ToolSpec::create('示例业务系统')
17
17
  * ->tool('staff_list', 'GET', '/openapi/staff/list', 'tenant.staff.read', '查询门店员工列表',
18
18
  * function (ToolDef $t) {
19
19
  * $t->query('dept', 'string', false, '按部门过滤');
@@ -0,0 +1,95 @@
1
+ <?php
2
+ namespace Bailing\Connect;
3
+
4
+ /** Optional, server-only Usage issuer API. This credential is not a business Client Token. */
5
+ final class UsageClient
6
+ {
7
+ private $baseUrl;
8
+ private $issuerToken;
9
+ private $timeout;
10
+ private $transport;
11
+
12
+ public function __construct($baseUrl, $issuerToken, $timeoutSeconds = 15, $transport = null)
13
+ {
14
+ $url = is_string($baseUrl) ? parse_url($baseUrl) : false;
15
+ if (!$url || !isset($url['scheme'], $url['host']) || !in_array($url['scheme'], array('https', 'http'), true)
16
+ || isset($url['user']) || isset($url['pass']) || isset($url['query']) || isset($url['fragment'])
17
+ || ($url['scheme'] === 'http' && !in_array($url['host'], array('localhost', '127.0.0.1', '[::1]'), true))) {
18
+ throw new \InvalidArgumentException('Use HTTPS, or loopback HTTP for development.');
19
+ }
20
+ if (!is_string($issuerToken) || !preg_match('/^bhu_i_[A-Za-z0-9_-]{43}$/D', $issuerToken)) {
21
+ throw new \InvalidArgumentException('A separate Usage issuer credential is required.');
22
+ }
23
+ if (!is_int($timeoutSeconds) || $timeoutSeconds < 1 || $timeoutSeconds > 60 || ($transport !== null && !is_callable($transport))) {
24
+ throw new \InvalidArgumentException('Invalid transport configuration.');
25
+ }
26
+ $this->baseUrl = rtrim($baseUrl, '/');
27
+ $this->issuerToken = $issuerToken;
28
+ $this->timeout = $timeoutSeconds;
29
+ $this->transport = $transport;
30
+ }
31
+
32
+ public function __debugInfo() { return array('credential' => '[redacted]', 'timeoutSeconds' => $this->timeout); }
33
+ private function key($value)
34
+ {
35
+ if (!is_string($value) || !preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,190}$/D', $value)) {
36
+ throw new \InvalidArgumentException('An exact identifier is required.');
37
+ }
38
+ return $value;
39
+ }
40
+ private function accountPath($accountId, $action)
41
+ {
42
+ return '/usage/v1/external/billing/accounts/' . rawurlencode($this->key($accountId)) . '/' . $action;
43
+ }
44
+ public function exchangeSession(array $input) { return $this->request('POST', '/usage/v1/sessions/exchange', $input); }
45
+ public function revokeUser(array $input) { return $this->request('POST', '/usage/v1/external/users/revoke', $input); }
46
+ public function listBillingPlans() { return $this->request('GET', '/usage/v1/external/billing/plans'); }
47
+ public function grantBillingPlan($accountId, array $input) { return $this->request('POST', $this->accountPath($accountId, 'grant'), $input); }
48
+ public function controlBillingPlan($accountId, array $input) { return $this->request('POST', $this->accountPath($accountId, 'control'), $input); }
49
+ public function getBillingSummary($accountId) { return $this->request('GET', $this->accountPath($accountId, 'summary')); }
50
+ private function request($method, $path, array $body = null)
51
+ {
52
+ $requestKey = $body === null || $path === '/usage/v1/external/users/revoke' ? null : $this->key(isset($body['request_key']) ? $body['request_key'] : null);
53
+ $encoded = $body === null ? null : json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
54
+ if ($body !== null && $encoded === false) throw new \InvalidArgumentException('The request must be JSON encodable.');
55
+ $headers = array('Authorization: Bearer ' . $this->issuerToken, 'Accept: application/json');
56
+ if ($body !== null) $headers[] = 'Content-Type: application/json';
57
+ try {
58
+ if ($this->transport !== null) {
59
+ $result = call_user_func($this->transport, $method, $this->baseUrl . $path, $headers, $encoded, $this->timeout);
60
+ $status = isset($result['status']) ? (int) $result['status'] : 0;
61
+ $raw = isset($result['body']) ? $result['body'] : false;
62
+ } else {
63
+ $http = array('method' => $method, 'header' => implode("\r\n", $headers), 'timeout' => $this->timeout,
64
+ 'ignore_errors' => true, 'follow_location' => 0, 'max_redirects' => 0);
65
+ if ($encoded !== null) $http['content'] = $encoded;
66
+ // Suppress transport warnings that otherwise embed private URLs in PHP logs.
67
+ $raw = @file_get_contents($this->baseUrl . $path, false, stream_context_create(array('http' => $http)), 0, 1048577);
68
+ $status = 0;
69
+ if (isset($http_response_header)) foreach ($http_response_header as $line) {
70
+ if (preg_match('/^HTTP\/\S+\s+(\d+)/', $line, $match)) { $status = (int) $match[1]; break; }
71
+ }
72
+ }
73
+ } catch (\Throwable $error) {
74
+ throw new UsageClientException('USAGE_TRANSPORT_UNAVAILABLE', null, $method === 'GET' ? 'rejected' : 'unknown', $requestKey);
75
+ }
76
+ if ($raw === false || $status === 0) throw new UsageClientException('USAGE_TRANSPORT_UNAVAILABLE', null, $method === 'GET' ? 'rejected' : 'unknown', $requestKey);
77
+ $data = null;
78
+ $validJson = false;
79
+ if (is_string($raw) && strlen($raw) <= 1048576) {
80
+ $data = json_decode($raw, true);
81
+ $validJson = json_last_error() === JSON_ERROR_NONE;
82
+ }
83
+ if (!$validJson || !is_array($data)) throw new UsageClientException($status === 404 ? 'USAGE_UNSUPPORTED' : 'USAGE_RESPONSE_INVALID', $status, $method === 'GET' || $status === 404 ? 'rejected' : 'unknown', $requestKey);
84
+ if ($status < 200 || $status >= 300) {
85
+ $candidate = isset($data['code']) ? $data['code'] : (isset($data['error']) ? $data['error'] : '');
86
+ $code = is_string($candidate) && preg_match('/^[A-Z][A-Z0-9_]{1,90}$/D', $candidate) ? $candidate : ($status === 404 ? 'USAGE_UNSUPPORTED' : 'USAGE_REQUEST_REJECTED');
87
+ $feedback = array();
88
+ if (isset($data['feedback']) && is_array($data['feedback'])) foreach (array('schema', 'code', 'dispatch', 'retryable', 'next_action', 'resetAt', 'reset_at') as $key) {
89
+ if (isset($data['feedback'][$key]) && is_scalar($data['feedback'][$key])) $feedback[$key] = $data['feedback'][$key];
90
+ }
91
+ throw new UsageClientException($code, $status, $status >= 500 && $method !== 'GET' ? 'unknown' : 'rejected', $requestKey, $feedback);
92
+ }
93
+ return $data;
94
+ }
95
+ }
@@ -0,0 +1,22 @@
1
+ <?php
2
+ namespace Bailing\Connect;
3
+
4
+ /** Sanitized failure; an unknown write is retried only with the exact original request key. */
5
+ final class UsageClientException extends \RuntimeException
6
+ {
7
+ public $usageCode;
8
+ public $status;
9
+ public $outcome;
10
+ public $requestKey;
11
+ public $feedback;
12
+
13
+ public function __construct($code, $status, $outcome, $requestKey = null, array $feedback = array())
14
+ {
15
+ parent::__construct('Usage management request failed (' . $code . ').');
16
+ $this->usageCode = $code;
17
+ $this->status = $status;
18
+ $this->outcome = $outcome;
19
+ $this->requestKey = $requestKey;
20
+ $this->feedback = $feedback;
21
+ }
22
+ }
@@ -0,0 +1,59 @@
1
+ <?php
2
+ // Synthetic loopback Core acceptance. Fixture credentials arrive over stdin, never command arguments.
3
+ require_once __DIR__ . '/../src/UsageClientException.php';
4
+ require_once __DIR__ . '/../src/UsageClient.php';
5
+ use Bailing\Connect\UsageClient;
6
+ use Bailing\Connect\UsageClientException;
7
+ function expectBilling($value) { if (!$value) throw new RuntimeException('Synthetic Core billing assertion failed'); }
8
+ function expectBillingError($code, $operation) {
9
+ try { $operation(); } catch (UsageClientException $error) {
10
+ expectBilling($error->usageCode === $code && $error->outcome === 'rejected'); return;
11
+ }
12
+ throw new RuntimeException('Expected synthetic Core billing rejection');
13
+ }
14
+ $fixture = json_decode(stream_get_contents(STDIN), true);
15
+ $client = new UsageClient($fixture['baseUrl'], $fixture['issuerToken']);
16
+ $identity = array('tenant' => 'synthetic-sdk', 'subject' => $fixture['subject']);
17
+ $loginInput = array_merge($identity, array('request_key' => $fixture['subject'], 'service_id' => $fixture['serviceId'], 'model_access' => 'token_gateway'));
18
+ $login = $client->exchangeSession($loginInput);
19
+ expectBilling($login['schema'] === 'bailing.usage-session.v1' && $login['session']['modelAccess'] === 'token_gateway');
20
+ expectBilling($client->exchangeSession($loginInput) == $login);
21
+ $accountId = $login['session']['accountId'];
22
+ $catalog = $client->listBillingPlans();
23
+ expectBilling(count($catalog['items']) === 2);
24
+ $byId = array(); foreach ($catalog['items'] as $plan) $byId[$plan['id']] = $plan;
25
+ expectBilling($byId[$fixture['periodPlanId']]['config']['priceUsd'] === 300);
26
+ expectBilling($byId[$fixture['periodPlanId']]['config']['periodAllowanceUsd'] === 100);
27
+ expectBilling(!isset($byId[$fixture['creditsPlanId']]['config']['periodAllowanceUsd']));
28
+ $before = $client->getBillingSummary($accountId);
29
+ expectBilling($before['grant'] === null && $before['presentation']['kind'] === 'none');
30
+ $grantInput = array('request_key' => 'grant-period', 'plan_id' => $fixture['periodPlanId'], 'expected_revision' => 0);
31
+ $grant = $client->grantBillingPlan($accountId, $grantInput);
32
+ expectBilling($client->grantBillingPlan($accountId, $grantInput) == $grant);
33
+ expectBilling($grant['sourceOwner'] === 'issuer:synthetic-product' && $grant['config']['periodAllowanceUsd'] === 100);
34
+ $summary = $client->getBillingSummary($accountId);
35
+ expectBilling($summary['schema'] === 'bailing.billing-summary.v1' && $summary['availableUsd'] === 100);
36
+ expectBilling($summary['consumedUsd'] === 0 && $summary['presentation']['kind'] === 'percentage');
37
+ expectBilling($summary['presentation']['remaining'] === 100 && $summary['plan']['multiplier'] === 1.5);
38
+ expectBillingError('USAGE_IDEMPOTENCY_CONFLICT', function () use ($client, $accountId, $grantInput) {
39
+ $changed = $grantInput; $changed['expected_revision'] = 1; $client->grantBillingPlan($accountId, $changed);
40
+ });
41
+ expectBillingError('USAGE_REVISION_CONFLICT', function () use ($client, $accountId, $fixture) {
42
+ $client->grantBillingPlan($accountId, array('request_key' => 'stale-grant', 'plan_id' => $fixture['periodPlanId'], 'expected_revision' => 0));
43
+ });
44
+ $pauseInput = array('request_key' => 'pause-period', 'expected_revision' => 1, 'state' => 'suspended');
45
+ $paused = $client->controlBillingPlan($accountId, $pauseInput);
46
+ expectBilling($paused['revision'] === 2 && $client->controlBillingPlan($accountId, $pauseInput) == $paused);
47
+ expectBilling($client->getBillingSummary($accountId)['presentation']['state'] === 'suspended');
48
+ $credits = $client->grantBillingPlan($accountId, array('request_key' => 'grant-credits', 'plan_id' => $fixture['creditsPlanId'], 'expected_revision' => 2));
49
+ expectBilling($credits['revision'] === 3);
50
+ $summary = $client->getBillingSummary($accountId);
51
+ expectBilling($summary['availableUsd'] === 12 && $summary['presentation']['displayValue'] === '12000');
52
+ $outsider = new UsageClient($fixture['baseUrl'], $fixture['outsiderToken']);
53
+ expectBillingError('USAGE_ACCOUNT_FORBIDDEN', function () use ($outsider, $accountId) { $outsider->getBillingSummary($accountId); });
54
+ expectBilling($client->revokeUser($identity)['revoked'] === true);
55
+ expectBilling($client->revokeUser($identity)['revoked'] === true);
56
+ expectBillingError('USAGE_ACCOUNT_SUSPENDED', function () use ($client, $loginInput) {
57
+ $changed = $loginInput; $changed['request_key'] = 'after-revoke'; $client->exchangeSession($changed);
58
+ });
59
+ echo json_encode(array('accountId' => $accountId, 'grantId' => $credits['id'], 'revision' => $credits['revision'], 'checks' => 'passed'));
@@ -0,0 +1,78 @@
1
+ <?php
2
+ require_once __DIR__ . '/../src/UsageClientException.php';
3
+ require_once __DIR__ . '/../src/UsageClient.php';
4
+ use Bailing\Connect\UsageClient;
5
+ use Bailing\Connect\UsageClientException;
6
+ function check($value) { if (!$value) throw new RuntimeException('Synthetic usage assertion failed'); }
7
+ $token = 'bhu_i_' . str_repeat('x', 43);
8
+ $calls = array();
9
+ $client = new UsageClient('https://hub.example.com', $token, 15, function ($method, $url, $headers, $body) use (&$calls, $token) {
10
+ check(in_array('Authorization: Bearer ' . $token, $headers, true));
11
+ $calls[] = array($method, parse_url($url, PHP_URL_PATH), $body === null ? null : json_decode($body, true));
12
+ return array('status' => 200, 'body' => '{"ok":true}');
13
+ });
14
+ $input = array('request_key' => 'order-1', 'plan_id' => 'plan-1', 'expected_revision' => 0);
15
+ $client->exchangeSession(array('request_key' => 'login-1', 'tenant' => 'tenant-1', 'subject' => 'subject-1', 'service_id' => 'text'));
16
+ $client->grantBillingPlan('account-1', $input); $client->grantBillingPlan('account-1', $input);
17
+ $client->controlBillingPlan('account-1', array('request_key' => 'pause-1', 'expected_revision' => 1, 'state' => 'suspended'));
18
+ $client->getBillingSummary('account-1'); $client->revokeUser(array('tenant' => 'tenant-1', 'subject' => 'subject-1')); $client->listBillingPlans();
19
+ check(count($calls) === 7); check($calls[1][2] === $calls[2][2]);
20
+ check($calls[1][1] === '/usage/v1/external/billing/accounts/account-1/grant');
21
+ check($calls[4][1] === '/usage/v1/external/billing/accounts/account-1/summary');
22
+ check($calls[6][1] === '/usage/v1/external/billing/plans');
23
+ foreach (array('listTokenPlans', 'grantTokenPlan', 'controlTokenPlan', 'getTokenSummary', 'getSummary', 'putEntitlement', 'grantCredits', 'listLedger', 'listPlans') as $removed) check(!method_exists($client, $removed));
24
+ $renewal = array('request_key' => 'renewal-1', 'expected_revision' => 2, 'plan_id' => 'plan-1');
25
+ try { new UsageClient('https://hub.example.com', 'business-token'); throw new RuntimeException('must reject'); } catch (InvalidArgumentException $expected) {}
26
+ $attempts = 0;
27
+ $broken = new UsageClient('https://hub.example.com', $token, 15, function () use (&$attempts) { $attempts++; throw new RuntimeException('private URL or token'); });
28
+ try { $broken->grantBillingPlan('account-1', $input); throw new RuntimeException('must reject'); } catch (UsageClientException $error) {
29
+ check($error->usageCode === 'USAGE_TRANSPORT_UNAVAILABLE'); check($error->outcome === 'unknown'); check($error->requestKey === 'order-1'); check(strpos($error->getMessage(), 'private') === false);
30
+ }
31
+ check($attempts === 1);
32
+ $renewalBodies = array();
33
+ $renewalClient = new UsageClient('https://hub.example.com', $token, 15, function ($method, $url, $headers, $body) use (&$renewalBodies) {
34
+ check($method === 'POST'); check(substr($url, -6) === '/grant'); $renewalBodies[] = $body;
35
+ if (count($renewalBodies) === 1) throw new RuntimeException('lost acknowledgement');
36
+ return array('status' => 200, 'body' => '{"revision":3}');
37
+ });
38
+ try { $renewalClient->grantBillingPlan('account-1', $renewal); throw new RuntimeException('must reject'); } catch (UsageClientException $error) {
39
+ check($error->outcome === 'unknown'); check($error->requestKey === 'renewal-1');
40
+ }
41
+ check(count($renewalBodies) === 1);
42
+ $renewed = $renewalClient->grantBillingPlan('account-1', $renewal);
43
+ check($renewed['revision'] === 3); check(json_decode($renewalBodies[0], true) === $renewal); check($renewalBodies[0] === $renewalBodies[1]);
44
+ $conflict = new UsageClient('https://hub.example.com', $token, 15, function () {
45
+ return array('status' => 409, 'body' => '{"code":"USAGE_REVISION_CONFLICT","message":"private details","feedback":{"code":"USAGE_REVISION_CONFLICT","next_action":"refresh","token":"secret"}}');
46
+ });
47
+ try { $conflict->grantBillingPlan('account-1', $input); throw new RuntimeException('must reject'); } catch (UsageClientException $error) {
48
+ check($error->usageCode === 'USAGE_REVISION_CONFLICT'); check($error->feedback['next_action'] === 'refresh'); check(!isset($error->feedback['token']));
49
+ }
50
+ $invalidResponses = array(
51
+ array('', 200), array(" \n\t ", 200), array('nul', 200), array('{"incomplete":', 200),
52
+ array('"null"', 200), array('false', 200), array('0', 200), array(str_repeat(' ', 1048576) . 'null', 200),
53
+ array('null', 201), array('null', 401), array('null', 404), array('null', 500)
54
+ );
55
+ foreach ($invalidResponses as $response) {
56
+ $attempts = 0;
57
+ $invalid = new UsageClient('https://hub.example.com', $token, 15, function () use ($response, &$attempts) {
58
+ $attempts++; return array('status' => $response[1], 'body' => $response[0]);
59
+ });
60
+ try { $invalid->getBillingSummary('account-1'); throw new RuntimeException('Invalid entitlement must reject'); } catch (UsageClientException $error) {
61
+ check($error->usageCode === ($response[1] === 404 ? 'USAGE_UNSUPPORTED' : 'USAGE_RESPONSE_INVALID'));
62
+ check($error->status === $response[1]); check($error->outcome === 'rejected');
63
+ }
64
+ check($attempts === 1);
65
+ }
66
+ $denied = new UsageClient('https://hub.example.com', $token, 15, function () { return array('status' => 403, 'body' => '{"code":"USAGE_IDENTITY_REVOKED"}'); });
67
+ try { $denied->getBillingSummary('account-1'); throw new RuntimeException('HTTP errors must reject'); } catch (UsageClientException $error) {
68
+ check($error->usageCode === 'USAGE_IDENTITY_REVOKED'); check($error->outcome === 'rejected');
69
+ }
70
+ foreach (array('null', '', 'nul', str_repeat(' ', 1048576) . 'null') as $raw) {
71
+ $attempts = 0;
72
+ $invalid = new UsageClient('https://hub.example.com', $token, 15, function () use ($raw, &$attempts) { $attempts++; return array('status' => 200, 'body' => $raw); });
73
+ try { $invalid->grantBillingPlan('account-1', $input); throw new RuntimeException('Mutation acknowledgement must reject'); } catch (UsageClientException $error) {
74
+ check($error->usageCode === 'USAGE_RESPONSE_INVALID'); check($error->outcome === 'unknown'); check($error->requestKey === 'order-1');
75
+ }
76
+ check($attempts === 1);
77
+ }
78
+ echo "Usage issuer PHP synthetic checks passed, including malformed response boundaries\n";