}
@@ -63,29 +65,66 @@ export function EmptyState(props: EmptyStateProps) {
}
const hasSearch = Boolean(props.searchQuery?.trim())
+ const noVisibleModels = props.emptyReason === 'no_visible_models'
+ const emptyPublicCatalog = props.emptyReason === 'catalog_empty'
+ const catalogEmpty = noVisibleModels || emptyPublicCatalog
return (
-
+
- {t('No models found')}
+ {noVisibleModels
+ ? t('No models available to your account')
+ : emptyPublicCatalog
+ ? t('No public models listed')
+ : t('No models found')}
-
- {hasSearch
+
+ {noVisibleModels
? t(
- 'No results for "{{query}}". Try adjusting your search or filters.',
- { query: props.searchQuery }
+ 'Your account currently has no available models. Contact an administrator to request access.'
)
- : t('No models match your current filters.')}
+ : emptyPublicCatalog
+ ? t(
+ 'No models are currently listed in the public catalog. Please check again later.'
+ )
+ : hasSearch
+ ? t(
+ 'No results for "{{query}}". Try adjusting your search or filters.',
+ { query: props.searchQuery }
+ )
+ : t('No models match your current filters.')}
- {(props.hasActiveFilters || hasSearch) && (
-
- {t('Clear all filters')}
-
- )}
+
+ {noVisibleModels && props.onViewPublic ? (
+
+ {t('View public catalog')}
+
+ ) : null}
+ {catalogEmpty && props.onRetry ? (
+ void props.onRetry?.()}
+ >
+ {t('Refresh')}
+
+ ) : null}
+ {!catalogEmpty && (props.hasActiveFilters || hasSearch) ? (
+
+ {t('Clear all filters')}
+
+ ) : null}
+
)
}
diff --git a/apps/web/src/features/pricing/hooks/use-model-runtime.ts b/apps/web/src/features/pricing/hooks/use-model-runtime.ts
index ecf0541ef..788f668ca 100644
--- a/apps/web/src/features/pricing/hooks/use-model-runtime.ts
+++ b/apps/web/src/features/pricing/hooks/use-model-runtime.ts
@@ -7,8 +7,14 @@ import { useAuthStore } from '@/stores/auth-store'
import { nativeRuntimeSchema } from '../catalog-contract'
import type { ModelRuntimeState } from '../types'
-export function useModelRuntime(names: string[], enabled = true) {
+export function useModelRuntime(
+ names: string[],
+ enabled = true,
+ view?: 'public'
+) {
const { user, session } = useAuthStore((state) => state.auth)
+ const authenticated = Boolean(user) && view !== 'public'
+ const visibility = authenticated ? 'session' : 'public'
const sorted = [...new Set(names)].sort()
const batches: string[][] = []
for (let i = 0; i < sorted.length; i += 200) {
@@ -22,6 +28,7 @@ export function useModelRuntime(names: string[], enabled = true) {
session?.sid ?? null,
user?.group ?? '',
models,
+ ...(view ? [view] : []),
],
queryFn: async ({ signal }) => {
const response = await api.post
(
@@ -32,13 +39,13 @@ export function useModelRuntime(names: string[], enabled = true) {
timeout: 10_000,
skipErrorHandler: true,
skipBusinessError: true,
- skipAuthRefresh: !user,
+ skipAuthRefresh: !authenticated,
authScope: { userId: user?.id, sessionId: session?.sid },
- authMode: user ? 'session' : 'anonymous',
+ authMode: authenticated ? 'session' : 'anonymous',
}
)
const document = nativeRuntimeSchema.parse(response.data)
- if (document.visibility !== (user ? 'session' : 'public')) {
+ if (document.visibility !== visibility) {
throw new Error('Model runtime visibility did not match the request')
}
return document.data
diff --git a/apps/web/src/features/pricing/hooks/use-pricing-data-session.test.tsx b/apps/web/src/features/pricing/hooks/use-pricing-data-session.test.tsx
index 9179ddd96..e5ef20fb4 100644
--- a/apps/web/src/features/pricing/hooks/use-pricing-data-session.test.tsx
+++ b/apps/web/src/features/pricing/hooks/use-pricing-data-session.test.tsx
@@ -182,9 +182,11 @@ function response(config: InternalAxiosRequestConfig, data: unknown) {
function installAdapter(
pricing: (
config: InternalAxiosRequestConfig
- ) => Promise
+ ) => Promise,
+ observe?: (config: InternalAxiosRequestConfig) => void
) {
api.defaults.adapter = async (config) => {
+ observe?.(config)
if (config.url === '/api/status') {
return response(config, { success: true, data: {} })
}
@@ -407,7 +409,7 @@ test('the pricing page keeps unknown counts hidden and restores a verified empty
const { container } = await render(Pricing)
assert.doesNotMatch(
container.textContent ?? '',
- /This site currently has|0 models/
+ /Models in this view|0 models/
)
await act(async () => initial.resolve(pricingDocument('public', 1)))
await waitFor(
@@ -417,7 +419,7 @@ test('the pricing page keeps unknown counts hidden and restores a verified empty
)
assert.doesNotMatch(
container.textContent ?? '',
- /This site currently has|0 models|No models found|Prices always use the base price/
+ /Models in this view|0 models|No models found|Prices always use the base price/
)
assert.equal(container.querySelector('input'), null)
const retry = [...container.querySelectorAll('button')].find(
@@ -426,13 +428,10 @@ test('the pricing page keeps unknown counts hidden and restores a verified empty
assert.ok(retry)
await act(async () => retry.click())
await waitFor(
- () =>
- container.textContent?.includes(
- 'This site currently has 0 models enabled'
- ) === true,
+ () => container.textContent?.includes('Models in this view: 0') === true,
'successful empty catalogue count missing'
)
- assert.match(container.textContent ?? '', /No models found/)
+ assert.match(container.textContent ?? '', /No public models listed/)
assert.doesNotMatch(
container.textContent ?? '',
/Failed to load enabled models/
@@ -441,6 +440,236 @@ test('the pricing page keeps unknown counts hidden and restores a verified empty
assert.equal(requests, 2)
})
+function buttonWithText(container: HTMLElement, label: string) {
+ const button = [...container.querySelectorAll('button')].find(
+ (candidate) => candidate.textContent?.trim() === label
+ )
+ assert.ok(button, `Missing button: ${label}`)
+ return button
+}
+
+function emptyAccount(publicViewAvailable?: boolean): NativePricingDocument {
+ return {
+ ...pricingDocument('session', 1),
+ groups: [],
+ models: [],
+ empty_reason: 'no_visible_models',
+ public_view_available: publicViewAvailable,
+ }
+}
+
+test('an empty account offers an explicit public view with anonymous runtime and a return path', async () => {
+ setSession(7, 'session-a')
+ const requests: InternalAxiosRequestConfig[] = []
+ installAdapter(
+ async (config) =>
+ config.authMode === 'anonymous'
+ ? pricingDocument('public', 93)
+ : emptyAccount(true),
+ (config) => requests.push(config)
+ )
+ const { container } = await render(Pricing)
+ await waitFor(
+ () =>
+ container.textContent?.includes('No models available to your account') ===
+ true,
+ 'account empty guidance missing'
+ )
+ assert.match(container.textContent ?? '', /Contact an administrator/)
+ assert.doesNotMatch(
+ container.textContent ?? '',
+ /No models match your current filters|No public models listed/
+ )
+ assert.equal(
+ requests.some((config) => config.url === '/core/v1/pricing/public'),
+ false
+ )
+ await act(async () =>
+ buttonWithText(container, 'View public catalog').click()
+ )
+ await waitFor(
+ () => container.textContent?.includes('shared-model') === true,
+ 'explicit public catalogue missing'
+ )
+ assert.match(
+ container.textContent ?? '',
+ /Public catalog prices do not grant permission to use a model/
+ )
+ await waitFor(
+ () =>
+ requests.some(
+ (config) =>
+ config.url === '/core/v1/pricing/runtime' &&
+ config.authMode === 'anonymous'
+ ),
+ 'public runtime did not use anonymous scope'
+ )
+ for (const config of requests.filter(
+ (config) => config.authMode === 'anonymous'
+ )) {
+ assert.equal(config.headers.get('Authorization'), undefined)
+ assert.deepEqual(config.authScope, { userId: 7, sessionId: 'session-a' })
+ }
+ await act(async () => buttonWithText(container, 'Back to my catalog').click())
+ await waitFor(
+ () =>
+ container.textContent?.includes('No models available to your account') ===
+ true,
+ 'account view did not return'
+ )
+ assert.doesNotMatch(
+ container.textContent ?? '',
+ /shared-model|Back to my catalog/
+ )
+})
+
+for (const capability of [false, undefined]) {
+ test(`an empty account without public capability=${capability} has no public action`, async () => {
+ setSession(7, 'session-a')
+ const requests: string[] = []
+ installAdapter(async (config) => {
+ requests.push(config.url ?? '')
+ return emptyAccount(capability)
+ })
+ const { container } = await render(Pricing)
+ await waitFor(
+ () =>
+ container.textContent?.includes(
+ 'No models available to your account'
+ ) === true,
+ 'account empty guidance missing'
+ )
+ assert.doesNotMatch(
+ container.textContent ?? '',
+ /View public catalog|No models match your current filters/
+ )
+ assert.ok(buttonWithText(container, 'Refresh'))
+ assert.deepEqual(requests, ['/core/v1/pricing/session'])
+ })
+}
+
+for (const [name, nextUser, nextSession] of [
+ ['account', 8, 'session-b'],
+ ['same-account session', 7, 'session-b'],
+] as const) {
+ test(`explicit public selection is scoped to the current ${name}`, async () => {
+ setSession(7, 'session-a')
+ const next = deferred()
+ const requests: InternalAxiosRequestConfig[] = []
+ installAdapter(async (config) => {
+ requests.push(config)
+ if (config.authScope?.sessionId !== 'session-a') return next.promise
+ return config.authMode === 'anonymous'
+ ? pricingDocument('public', 93)
+ : emptyAccount(true)
+ })
+ let latest: ReturnType | undefined
+ function Probe() {
+ latest = usePricingData()
+ return {latest.models[0]?.input_price ?? 'empty'}
+ }
+ await render(Probe)
+ await waitFor(
+ () => latest?.publicViewAvailable === true,
+ 'public capability missing'
+ )
+ await act(async () => latest?.viewPublicCatalog())
+ await waitFor(
+ () => latest?.models[0]?.input_price === 93,
+ 'public rate missing'
+ )
+ await act(async () => setSession(nextUser, nextSession))
+ assert.equal(latest?.isPublicView, false)
+ assert.equal(latest?.models.length, 0)
+ await act(async () => next.resolve(pricingDocument('session', 82)))
+ await waitFor(
+ () => latest?.models[0]?.input_price === 82,
+ 'new account rate missing'
+ )
+ assert.equal(requests.at(-1)?.authMode, 'session')
+ assert.equal(latest?.catalogVisibility, 'session')
+ })
+}
+
+test('public policy changes produce an error with a return path and no further fallback', async () => {
+ setSession(7, 'session-a')
+ const requests: string[] = []
+ installAdapter(async (config) => {
+ requests.push(config.url ?? '')
+ if (config.authMode !== 'anonymous') return emptyAccount(true)
+ throw new AxiosError('Forbidden', undefined, config, undefined, {
+ data: { error: { code: 'pricing_forbidden' } },
+ status: 403,
+ statusText: 'Forbidden',
+ headers: {},
+ config,
+ })
+ })
+ const { container } = await render(Pricing)
+ await waitFor(
+ () => container.textContent?.includes('View public catalog') === true,
+ 'public action missing'
+ )
+ await act(async () =>
+ buttonWithText(container, 'View public catalog').click()
+ )
+ await waitFor(
+ () =>
+ container.textContent?.includes('Failed to load enabled models') === true,
+ 'public failure missing'
+ )
+ assert.doesNotMatch(
+ container.textContent ?? '',
+ /No public models listed|No models available to your account/
+ )
+ assert.deepEqual(requests, [
+ '/core/v1/pricing/session',
+ '/core/v1/pricing/public',
+ ])
+ await act(async () => buttonWithText(container, 'Back to my catalog').click())
+ await waitFor(
+ () =>
+ container.textContent?.includes('No models available to your account') ===
+ true,
+ 'account return missing'
+ )
+})
+
+test('searching a nonempty catalogue keeps filter-specific guidance and clearing restores models', async () => {
+ useAuthStore.getState().auth.reset('complete')
+ installAdapter(async () => pricingDocument('public', 1))
+ const { container } = await render(Pricing)
+ await waitFor(
+ () => container.textContent?.includes('shared-model') === true,
+ 'catalogue missing'
+ )
+ const input = container.querySelector('input')
+ assert.ok(input)
+ const setValue = Object.getOwnPropertyDescriptor(
+ domWindow.HTMLInputElement.prototype,
+ 'value'
+ )?.set
+ assert.ok(setValue)
+ await act(async () => {
+ setValue.call(input, 'no-such-model')
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await waitFor(
+ () => container.textContent?.includes('No models found') === true,
+ 'search empty state missing'
+ )
+ assert.match(container.textContent ?? '', /No results for "no-such-model"/)
+ assert.doesNotMatch(
+ container.textContent ?? '',
+ /No public models listed|No models available to your account/
+ )
+ await act(async () => buttonWithText(container, 'Clear all filters').click())
+ await waitFor(
+ () => container.textContent?.includes('shared-model') === true,
+ 'cleared search did not restore model'
+ )
+})
+
test('the model panel shows counts only after the catalogue is available', async () => {
useAuthStore.getState().auth.reset('complete')
const initial = deferred()
diff --git a/apps/web/src/features/pricing/hooks/use-pricing-data.ts b/apps/web/src/features/pricing/hooks/use-pricing-data.ts
index aa034bc1c..7e6c717ef 100644
--- a/apps/web/src/features/pricing/hooks/use-pricing-data.ts
+++ b/apps/web/src/features/pricing/hooks/use-pricing-data.ts
@@ -17,7 +17,7 @@ along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import { useQuery } from '@tanstack/react-query'
-import { useMemo } from 'react'
+import { useMemo, useState } from 'react'
import { useStatus } from '@/hooks/use-status'
import { useWalletCurrency } from '@/hooks/use-wallet-currency'
@@ -29,6 +29,16 @@ import { useModelRuntime } from './use-model-runtime'
export function usePricingData(options?: { enabled?: boolean }) {
useStatus()
const { user, session } = useAuthStore((state) => state.auth)
+ const [publicViewScope, setPublicViewScope] = useState<{
+ userId: number
+ sessionId: string | undefined
+ } | null>(null)
+ const isPublicView = Boolean(
+ user &&
+ publicViewScope?.userId === user.id &&
+ publicViewScope?.sessionId === session?.sid
+ )
+ const view = isPublicView ? 'public' : undefined
const {
currency: displayCurrency,
setPreference: setDisplayCurrency,
@@ -41,9 +51,9 @@ export function usePricingData(options?: { enabled?: boolean }) {
error,
refetch,
} = useQuery({
- queryKey: pricingQueryKey(user?.id, session?.sid),
+ queryKey: pricingQueryKey(user?.id, session?.sid, view),
queryFn: ({ signal }) =>
- getPricing(signal, { userId: user?.id, sessionId: session?.sid }),
+ getPricing(signal, { userId: user?.id, sessionId: session?.sid }, view),
enabled: options?.enabled ?? true,
staleTime: 5 * 60 * 1000,
retry: false,
@@ -72,7 +82,8 @@ export function usePricingData(options?: { enabled?: boolean }) {
const runtime = useModelRuntime(
models.map((model) => model.model_name),
- (options?.enabled ?? true) && data?.runtime_available === true
+ (options?.enabled ?? true) && data?.runtime_available === true,
+ view
)
const liveModels = useMemo(
() =>
@@ -92,6 +103,22 @@ export function usePricingData(options?: { enabled?: boolean }) {
performanceAvailable: data?.performance_available === true,
runtimeAvailable: data?.runtime_available === true,
catalogAvailable: data !== undefined,
+ catalogVisibility: data?.catalog_visibility,
+ emptyReason: data?.empty_reason ?? null,
+ publicViewAvailable:
+ data?.catalog_visibility === 'session' &&
+ data?.public_view_available === true,
+ isPublicView,
+ viewPublicCatalog: () => {
+ if (
+ user &&
+ data?.catalog_visibility === 'session' &&
+ data.public_view_available === true
+ ) {
+ setPublicViewScope({ userId: user.id, sessionId: session?.sid })
+ }
+ },
+ viewAccountCatalog: () => setPublicViewScope(null),
isLoading,
error,
refetch,
diff --git a/apps/web/src/features/pricing/index.tsx b/apps/web/src/features/pricing/index.tsx
index 1e399c6fc..b77609eb1 100644
--- a/apps/web/src/features/pricing/index.tsx
+++ b/apps/web/src/features/pricing/index.tsx
@@ -71,6 +71,12 @@ export function Pricing() {
endpointMap,
autoGroups,
catalogAvailable,
+ catalogVisibility,
+ emptyReason,
+ publicViewAvailable,
+ isPublicView,
+ viewPublicCatalog,
+ viewAccountCatalog,
isLoading,
error,
refetch,
@@ -161,6 +167,16 @@ export function Pricing() {
searchQuery={searchInput}
hasActiveFilters={hasActiveFilters}
onClearFilters={handleClearAll}
+ emptyReason={emptyReason}
+ onViewPublic={
+ publicViewAvailable
+ ? () => {
+ handleClearAll()
+ setVisibleCount(PAGE_SIZE)
+ viewPublicCatalog()
+ }
+ : undefined
+ }
error={error}
onRetry={refetch}
/>
@@ -237,7 +253,7 @@ export function Pricing() {
{catalogAvailable && (
- {t('This site currently has {{count}} models enabled', {
+ {t('Models in this view: {{count}}', {
count: models.length,
})}
@@ -265,6 +281,25 @@ export function Pricing() {
+ {(catalogVisibility === 'public' || isPublicView) && (
+
+
+ {t(
+ 'Public catalog prices do not grant permission to use a model.'
+ )}
+
+ {isPublicView ? (
+
+ {t('Back to my catalog')}
+
+ ) : null}
+
+ )}
+
{catalogAvailable && (
<>
diff --git a/apps/web/src/features/pricing/types.ts b/apps/web/src/features/pricing/types.ts
index f965e734b..eefa01b93 100644
--- a/apps/web/src/features/pricing/types.ts
+++ b/apps/web/src/features/pricing/types.ts
@@ -164,6 +164,9 @@ export type ModelCapability =
| 'embeddings'
export type PricingData = {
+ catalog_visibility?: 'public' | 'session'
+ empty_reason?: 'no_visible_models' | 'catalog_empty' | null
+ public_view_available?: boolean
pricing_context?: NativePricingContext
runtime_available?: boolean
performance_available?: boolean
diff --git a/apps/web/src/i18n/locales/en.json b/apps/web/src/i18n/locales/en.json
index fe842b067..c24a415a1 100644
--- a/apps/web/src/i18n/locales/en.json
+++ b/apps/web/src/i18n/locales/en.json
@@ -1398,6 +1398,7 @@
"Back to list": "Back to list",
"Back to login": "Back to login",
"Back to Models": "Back to Models",
+ "Back to my catalog": "Back to my catalog",
"Back to store": "Back to store",
"Back to subscriptions": "Back to subscriptions",
"Back to task": "Back to task",
@@ -1953,7 +1954,7 @@
"channelBalance.copied": "Copied observation",
"channelBalance.denied": "You do not have permission to access this balance operation.",
"channelBalance.disabled": "Balance queries are disabled. Configure a query first.",
- "channelBalance.error": "The provider balance is unavailable.",
+ "channelBalance.error": "Current balance unknown. The last recorded balance has not changed.",
"channelBalance.invalid": "Use a single / path without query or fragment, a valid / JSON Pointer, and a unit of at most 32 characters.",
"channelBalance.note": "Provider units are shown as reported. Copied or reset records are not a fresh balance query.",
"channelBalance.path": "Query path",
@@ -2120,6 +2121,7 @@
"Checking browser session...": "Checking browser session...",
"Checking connection": "Checking connection",
"Checking name...": "Checking name...",
+ "Checking Passkey availability...": "Checking Passkey availability...",
"Checking payment availability...": "Checking payment availability...",
"Checking promotion...": "Checking promotion...",
"Checking registration status": "Checking registration status",
@@ -6635,6 +6637,7 @@
"Models exposed by this channel": "Models exposed by this channel",
"Models fetched successfully": "Models fetched successfully",
"Models filled to form": "Models filled to form",
+ "Models in this view: {{count}}": "Models in this view: {{count}}",
"Models listed here will not automatically append or remove -thinking / -nothinking suffixes.": "Models listed here will not automatically append or remove -thinking / -nothinking suffixes.",
"Models losing positions": "Models losing positions",
"Models losing the most positions": "Models losing the most positions",
@@ -7063,8 +7066,10 @@
"No model found.": "No model found.",
"No model mappings configured. Click \"Add Mapping\" to get started.": "No model mappings configured. Click \"Add Mapping\" to get started.",
"No model price changes to save": "No model price changes to save",
+ "No models are currently listed in the public catalog. Please check again later.": "No models are currently listed in the public catalog. Please check again later.",
"No models available": "No models available",
"No models available in this category": "No models available in this category",
+ "No models available to your account": "No models available to your account",
"No models available. Create your first model to get started.": "No models available. Create your first model to get started.",
"No models configured. Use Add model to get started.": "No models configured. Use Add model to get started.",
"No models fetched from upstream": "No models fetched from upstream",
@@ -7141,6 +7146,7 @@
"No protected groups are published yet.": "No protected groups are published yet.",
"No providers available": "No providers available",
"No public bounty projects yet": "No public bounty projects yet",
+ "No public models listed": "No public models listed",
"No public reason has been provided.": "No public reason has been provided.",
"No public risk categories are available yet.": "No public risk categories are available yet.",
"No public rule summaries are available yet.": "No public rule summaries are available yet.",
@@ -7285,6 +7291,7 @@
"Not priced": "Not priced",
"Not provided": "Not provided",
"Not published": "Not published",
+ "Not queried": "Not queried",
"Not rated": "Not rated",
"Not read": "Not read",
"Not recorded": "Not recorded",
@@ -8708,6 +8715,7 @@
"Prune object items by conditions": "Prune object items by conditions",
"Prune Rule (string or JSON object)": "Prune Rule (string or JSON object)",
"Public": "Public",
+ "Public catalog prices do not grant permission to use a model.": "Public catalog prices do not grant permission to use a model.",
"Public challenges": "Public challenges",
"Public channel group": "Public channel group",
"Public contributor evaluation": "Public contributor evaluation",
@@ -9039,6 +9047,7 @@
"Read-only user management. Risk, usage, top-up, referral history and legacy trust information are unavailable in this view.": "Read-only user management. Risk, usage, top-up, referral history and legacy trust information are unavailable in this view.",
"Reading progress": "Reading progress",
"Reading the invitation confirmation status.": "Reading the invitation confirmation status.",
+ "Reads Sub2API wallet or key quota in USD. Unlimited or unrecognized balances remain unknown.": "Reads Sub2API wallet or key quota in USD. Unlimited or unrecognized balances remain unknown.",
"Ready": "Ready",
"Ready in this client. Refresh its tool list.": "Ready in this client. Refresh its tool list.",
"Ready to generate": "Ready to generate",
@@ -9216,6 +9225,7 @@
"Refresh quote": "Refresh quote",
"Refresh registration status": "Refresh registration status",
"Refresh result": "Refresh result",
+ "Refresh selected balances": "Refresh selected balances",
"Refresh Stats": "Refresh Stats",
"Refresh support status": "Refresh support status",
"Refresh the list and try again.": "Refresh the list and try again.",
@@ -10758,6 +10768,7 @@
"Signed-in users can use the assistant immediately. Registration protection remains active.": "Signed-in users can use the assistant immediately. Registration protection remains active.",
"Significant outages detected": "Significant outages detected",
"Signing in takes a moment and skips this screen entirely.": "Signing in takes a moment and skips this screen entirely.",
+ "Signing in...": "Signing in...",
"Signing key": "Signing key",
"Signing you in with {{provider}}": "Signing you in with {{provider}}",
"SiliconFlow": "SiliconFlow",
@@ -13007,6 +13018,7 @@
"View process details": "View process details",
"View products": "View products",
"View progress": "View progress",
+ "View public catalog": "View public catalog",
"View refunds or request a refund": "View refunds or request a refund",
"View related page": "View related page",
"View request details": "View request details",
@@ -13369,6 +13381,7 @@
"Your account can edit sensitive channel settings.": "Your account can edit sensitive channel settings.",
"Your account cannot edit sensitive channel settings.": "Your account cannot edit sensitive channel settings.",
"Your account changed. Refresh this page before continuing.": "Your account changed. Refresh this page before continuing.",
+ "Your account currently has no available models. Contact an administrator to request access.": "Your account currently has no available models. Contact an administrator to request access.",
"Your account does not cover this page yet.": "Your account does not cover this page yet.",
"Your account does not have permission to open this page.": "Your account does not have permission to open this page.",
"Your account has an active or future subscription entitlement.": "Your account has an active or future subscription entitlement.",
diff --git a/apps/web/src/i18n/locales/fr.json b/apps/web/src/i18n/locales/fr.json
index c0ca63444..9eb004c66 100644
--- a/apps/web/src/i18n/locales/fr.json
+++ b/apps/web/src/i18n/locales/fr.json
@@ -1398,6 +1398,7 @@
"Back to list": "Retour à la liste",
"Back to login": "Retour à la connexion",
"Back to Models": "Retour aux modèles",
+ "Back to my catalog": "Revenir à mon catalogue",
"Back to store": "Retour à la boutique",
"Back to subscriptions": "Retour aux abonnements",
"Back to task": "Revenir à la tâche",
@@ -1953,7 +1954,7 @@
"channelBalance.copied": "Observation copiée",
"channelBalance.denied": "Vous n’avez pas l’autorisation d’effectuer cette opération sur le solde.",
"channelBalance.disabled": "Les consultations du solde sont désactivées. Configurez-les d’abord.",
- "channelBalance.error": "Le solde du fournisseur est indisponible.",
+ "channelBalance.error": "Solde actuel inconnu. Le dernier solde enregistré reste inchangé.",
"channelBalance.invalid": "Utilisez un chemin commençant par un seul /, sans paramètres ni fragment, un JSON Pointer / valide et une unité de 32 caractères maximum.",
"channelBalance.note": "Les unités du fournisseur sont conservées. Une copie ou remise à zéro ne constitue pas une nouvelle consultation.",
"channelBalance.path": "Chemin de consultation",
@@ -2120,6 +2121,7 @@
"Checking browser session...": "Vérification de la session du navigateur…",
"Checking connection": "Vérification de la connexion",
"Checking name...": "Vérification du nom...",
+ "Checking Passkey availability...": "Vérification de la disponibilité des passkeys…",
"Checking payment availability...": "Vérification de la disponibilité du paiement…",
"Checking promotion...": "Vérification de la promotion…",
"Checking registration status": "Vérification de l’état d’inscription",
@@ -6635,6 +6637,7 @@
"Models exposed by this channel": "Modeles exposes par ce canal",
"Models fetched successfully": "Modèles récupérés avec succès",
"Models filled to form": "Modèles remplis pour le formulaire",
+ "Models in this view: {{count}}": "Modèles dans cette vue : {{count}}",
"Models listed here will not automatically append or remove -thinking / -nothinking suffixes.": "Les modèles listés ici n'ajouteront ni ne supprimeront automatiquement les suffixes -thinking / -nothinking.",
"Models losing positions": "Modèles perdant des positions",
"Models losing the most positions": "Modèles qui perdent le plus de places",
@@ -7063,8 +7066,10 @@
"No model found.": "Aucun modèle trouvé.",
"No model mappings configured. Click \"Add Mapping\" to get started.": "Aucun mappage de modèle configuré. Cliquez sur « Ajouter un mappage » pour commencer.",
"No model price changes to save": "Aucun changement de prix de modèle à sauvegarder",
+ "No models are currently listed in the public catalog. Please check again later.": "Le catalogue public ne contient actuellement aucun modèle. Veuillez revenir plus tard.",
"No models available": "Aucun modèle disponible",
"No models available in this category": "Aucun modèle disponible dans cette catégorie",
+ "No models available to your account": "Aucun modèle disponible pour votre compte",
"No models available. Create your first model to get started.": "Aucun modèle disponible. Créez votre premier modèle pour commencer.",
"No models configured. Use Add model to get started.": "Aucun modèle configuré. Utilisez Ajouter un modèle pour commencer.",
"No models fetched from upstream": "Aucun modèle récupéré depuis l'amont",
@@ -7141,6 +7146,7 @@
"No protected groups are published yet.": "Aucun groupe protégé publié.",
"No providers available": "Aucun fournisseur disponible",
"No public bounty projects yet": "Aucun projet de prime public pour le moment",
+ "No public models listed": "Aucun modèle dans le catalogue public",
"No public reason has been provided.": "Aucun motif public n’a été communiqué.",
"No public risk categories are available yet.": "Aucune catégorie de risque publique n'est encore disponible.",
"No public rule summaries are available yet.": "Aucun résumé de règle publique n'est encore disponible.",
@@ -7285,6 +7291,7 @@
"Not priced": "Non valorisé",
"Not provided": "Non fourni",
"Not published": "Non publié",
+ "Not queried": "Pas encore consulté",
"Not rated": "Non noté",
"Not read": "Non lu",
"Not recorded": "Non enregistré",
@@ -8708,6 +8715,7 @@
"Prune object items by conditions": "Nettoyer les éléments d'objets par conditions",
"Prune Rule (string or JSON object)": "Règle de nettoyage (chaîne ou objet JSON)",
"Public": "Public",
+ "Public catalog prices do not grant permission to use a model.": "Les prix du catalogue public ne donnent pas l’autorisation d’utiliser un modèle.",
"Public challenges": "Défis publics",
"Public channel group": "Groupe de canaux publics",
"Public contributor evaluation": "Évaluation publique du contributeur",
@@ -9039,6 +9047,7 @@
"Read-only user management. Risk, usage, top-up, referral history and legacy trust information are unavailable in this view.": "Gestion des utilisateurs en lecture seule. Les risques, l’utilisation, les recharges, l’historique de parrainage et les anciennes informations de confiance sont indisponibles dans cette vue.",
"Reading progress": "Progression de lecture",
"Reading the invitation confirmation status.": "Lecture de l’état de confirmation de l’invitation.",
+ "Reads Sub2API wallet or key quota in USD. Unlimited or unrecognized balances remain unknown.": "Lit le solde du portefeuille ou le quota de la clé Sub2API en USD. Les soldes illimités ou non reconnus restent inconnus.",
"Ready": "Prêt",
"Ready in this client. Refresh its tool list.": "Disponible dans ce client. Actualisez sa liste d’outils.",
"Ready to generate": "Prêt à générer",
@@ -9216,6 +9225,7 @@
"Refresh quote": "Actualiser le devis",
"Refresh registration status": "Actualiser l’état d’inscription",
"Refresh result": "Actualiser le résultat",
+ "Refresh selected balances": "Actualiser les soldes sélectionnés",
"Refresh Stats": "Actualiser les statistiques",
"Refresh support status": "Actualiser le statut de l’assistance",
"Refresh the list and try again.": "Actualisez la liste et réessayez.",
@@ -10758,6 +10768,7 @@
"Signed-in users can use the assistant immediately. Registration protection remains active.": "Les utilisateurs connectés peuvent utiliser l’assistant immédiatement. La protection des inscriptions reste active.",
"Significant outages detected": "Pannes significatives détectées",
"Signing in takes a moment and skips this screen entirely.": "Connectez-vous pour continuer.",
+ "Signing in...": "Connexion en cours…",
"Signing key": "Clé de signature",
"Signing you in with {{provider}}": "Connexion avec {{provider}}",
"SiliconFlow": "SiliconFlow",
@@ -13007,6 +13018,7 @@
"View process details": "Voir les étapes du processus",
"View products": "Afficher les produits",
"View progress": "Voir l’avancement",
+ "View public catalog": "Voir le catalogue public",
"View refunds or request a refund": "Consulter les remboursements ou en demander un",
"View related page": "Voir la page liée",
"View request details": "Voir les détails de la requête",
@@ -13369,6 +13381,7 @@
"Your account can edit sensitive channel settings.": "Votre compte peut modifier les paramètres sensibles des canaux.",
"Your account cannot edit sensitive channel settings.": "Votre compte ne peut pas modifier les paramètres sensibles des canaux.",
"Your account changed. Refresh this page before continuing.": "Votre compte a changé. Actualisez cette page avant de continuer.",
+ "Your account currently has no available models. Contact an administrator to request access.": "Aucun modèle n’est actuellement disponible pour votre compte. Contactez un administrateur pour demander l’accès.",
"Your account does not cover this page yet.": "Votre compte n’a pas accès à cette page.",
"Your account does not have permission to open this page.": "Votre compte n’a pas l’autorisation d’ouvrir cette page.",
"Your account has an active or future subscription entitlement.": "Votre compte bénéficie encore de droits d’abonnement actifs ou à venir.",
diff --git a/apps/web/src/i18n/locales/ja.json b/apps/web/src/i18n/locales/ja.json
index 865976011..f22196f39 100644
--- a/apps/web/src/i18n/locales/ja.json
+++ b/apps/web/src/i18n/locales/ja.json
@@ -1398,6 +1398,7 @@
"Back to list": "一覧に戻る",
"Back to login": "ログインに戻る",
"Back to Models": "モデルに戻る",
+ "Back to my catalog": "自分のカタログに戻る",
"Back to store": "ストアに戻る",
"Back to subscriptions": "サブスクリプションに戻る",
"Back to task": "作業に戻る",
@@ -1953,7 +1954,7 @@
"channelBalance.copied": "コピーされた観測値",
"channelBalance.denied": "この残高操作を実行する権限がありません。",
"channelBalance.disabled": "残高照会は無効です。先に照会を設定してください。",
- "channelBalance.error": "プロバイダー残高を取得できません。",
+ "channelBalance.error": "現在の残高は不明です。前回記録された残高は変更されていません。",
"channelBalance.invalid": "単一の / で始まりクエリやフラグメントを含まないパス、有効な / JSON Pointer、32文字以内の単位を指定してください。",
"channelBalance.note": "プロバイダーの単位で表示します。コピーやリセットは新たな残高照会を意味しません。",
"channelBalance.path": "照会パス",
@@ -2120,6 +2121,7 @@
"Checking browser session...": "ブラウザーのセッションを確認しています…",
"Checking connection": "接続を確認しています",
"Checking name...": "名前をチェック中...",
+ "Checking Passkey availability...": "パスキーの利用可否を確認中…",
"Checking payment availability...": "支払いの利用可能状況を確認中…",
"Checking promotion...": "プロモーションを確認中…",
"Checking registration status": "登録状態を確認中",
@@ -6635,6 +6637,7 @@
"Models exposed by this channel": "このチャンネルで公開するモデル",
"Models fetched successfully": "モデルが正常に取得されました",
"Models filled to form": "フォームにモデルが記入されました",
+ "Models in this view: {{count}}": "この表示のモデル数:{{count}}",
"Models listed here will not automatically append or remove -thinking / -nothinking suffixes.": "ここに記載されたモデルは、-thinking / -nothinking サフィックスの自動付与・削除を行いません。",
"Models losing positions": "順位を下げているモデル",
"Models losing the most positions": "順位を最も落としているモデル",
@@ -7063,8 +7066,10 @@
"No model found.": "モデルが見つかりません。",
"No model mappings configured. Click \"Add Mapping\" to get started.": "モデルマッピングは設定されていません。「マッピングを追加」をクリックして開始してください。",
"No model price changes to save": "保存するモデル価格の変更はありません",
+ "No models are currently listed in the public catalog. Please check again later.": "現在、公開カタログに掲載されているモデルはありません。しばらくしてから再度ご確認ください。",
"No models available": "利用可能なモデルがありません",
"No models available in this category": "このカテゴリにはモデルがありません",
+ "No models available to your account": "このアカウントで利用できるモデルはありません",
"No models available. Create your first model to get started.": "利用可能なモデルがありません。最初のモデルを作成して開始してください。",
"No models configured. Use Add model to get started.": "モデルが設定されていません。モデルを追加して開始してください。",
"No models fetched from upstream": "アップストリームからモデルを取得できませんでした",
@@ -7141,6 +7146,7 @@
"No protected groups are published yet.": "保護対象グループはまだ公開されていません。",
"No providers available": "利用可能なプロバイダーがありません",
"No public bounty projects yet": "公開された報奨金プロジェクトはまだありません",
+ "No public models listed": "公開カタログにモデルはありません",
"No public reason has been provided.": "公開された理由はありません。",
"No public risk categories are available yet.": "公開リスクカテゴリはまだありません。",
"No public rule summaries are available yet.": "公開ルール概要はまだありません。",
@@ -7285,6 +7291,7 @@
"Not priced": "金額未算出",
"Not provided": "未提供",
"Not published": "未公開",
+ "Not queried": "未照会",
"Not rated": "未評価",
"Not read": "未読",
"Not recorded": "記録なし",
@@ -8708,6 +8715,7 @@
"Prune object items by conditions": "条件に基づいてオブジェクト項目を削除",
"Prune Rule (string or JSON object)": "削除ルール(文字列またはJSONオブジェクト)",
"Public": "公開",
+ "Public catalog prices do not grant permission to use a model.": "公開カタログの価格情報は、モデルの利用権限を付与するものではありません。",
"Public challenges": "公開チャレンジ",
"Public channel group": "公開チャンネルグループ",
"Public contributor evaluation": "貢献者への公開評価",
@@ -9039,6 +9047,7 @@
"Read-only user management. Risk, usage, top-up, referral history and legacy trust information are unavailable in this view.": "読み取り専用のユーザー管理です。この画面ではリスク、使用量、チャージ、紹介履歴、旧来の信頼情報は利用できません。",
"Reading progress": "読了までの進捗",
"Reading the invitation confirmation status.": "招待の確認状態を読み込んでいます。",
+ "Reads Sub2API wallet or key quota in USD. Unlimited or unrecognized balances remain unknown.": "Sub2API のウォレット残高またはキーの残りクォータを USD で取得します。無制限または認識できない残高は不明として表示されます。",
"Ready": "準備完了",
"Ready in this client. Refresh its tool list.": "このクライアントで利用可能です。ツール一覧を更新してください。",
"Ready to generate": "生成の準備完了",
@@ -9216,6 +9225,7 @@
"Refresh quote": "見積もりを更新",
"Refresh registration status": "登録状態を更新",
"Refresh result": "結果を更新",
+ "Refresh selected balances": "選択したチャネルの残高を更新",
"Refresh Stats": "統計を更新",
"Refresh support status": "サポート状況を更新",
"Refresh the list and try again.": "一覧を更新して、もう一度お試しください。",
@@ -10758,6 +10768,7 @@
"Signed-in users can use the assistant immediately. Registration protection remains active.": "ログイン後、すぐにアシスタントを利用できます。登録時の不正利用対策は引き続き有効です。",
"Significant outages detected": "大規模な障害を検出",
"Signing in takes a moment and skips this screen entirely.": "ログインして続行してください。",
+ "Signing in...": "ログイン中…",
"Signing key": "署名キー",
"Signing you in with {{provider}}": "{{provider}} でサインイン中",
"SiliconFlow": "SiliconFlow",
@@ -13007,6 +13018,7 @@
"View process details": "手順の詳細を表示",
"View products": "商品を表示",
"View progress": "進捗を見る",
+ "View public catalog": "公開カタログを見る",
"View refunds or request a refund": "返金を確認または申請",
"View related page": "関連ページを表示",
"View request details": "リクエストの詳細を表示",
@@ -13369,6 +13381,7 @@
"Your account can edit sensitive channel settings.": "あなたのアカウントは機密チャネル設定を編集できます。",
"Your account cannot edit sensitive channel settings.": "あなたのアカウントは機密チャネル設定を編集できません。",
"Your account changed. Refresh this page before continuing.": "アカウントが変更されました。続行する前にこのページを再読み込みしてください。",
+ "Your account currently has no available models. Contact an administrator to request access.": "現在、このアカウントで利用できるモデルはありません。アクセス権限について管理者にお問い合わせください。",
"Your account does not cover this page yet.": "このページへのアクセス権がありません。",
"Your account does not have permission to open this page.": "このアカウントには、このページへのアクセス権がありません。",
"Your account has an active or future subscription entitlement.": "有効な、または今後開始するサブスクリプションの利用権が残っています。",
diff --git a/apps/web/src/i18n/locales/ru.json b/apps/web/src/i18n/locales/ru.json
index 375329297..3ba1e3a54 100644
--- a/apps/web/src/i18n/locales/ru.json
+++ b/apps/web/src/i18n/locales/ru.json
@@ -1398,6 +1398,7 @@
"Back to list": "Назад к списку",
"Back to login": "Вернуться к входу",
"Back to Models": "Вернуться к моделям",
+ "Back to my catalog": "Вернуться к моему каталогу",
"Back to store": "Назад в магазин",
"Back to subscriptions": "Назад к подпискам",
"Back to task": "Вернуться к задаче",
@@ -1953,7 +1954,7 @@
"channelBalance.copied": "Скопированное наблюдение",
"channelBalance.denied": "У вас нет права выполнять эту операцию с балансом.",
"channelBalance.disabled": "Запросы баланса отключены. Сначала настройте запрос.",
- "channelBalance.error": "Баланс поставщика недоступен.",
+ "channelBalance.error": "Текущий баланс неизвестен. Последний сохранённый баланс не изменён.",
"channelBalance.invalid": "Укажите путь с одним / без параметров и фрагмента, корректный JSON Pointer с / и единицу не длиннее 32 символов.",
"channelBalance.note": "Показаны единицы поставщика. Копия или сброс не означают новый запрос баланса.",
"channelBalance.path": "Путь запроса",
@@ -2120,6 +2121,7 @@
"Checking browser session...": "Проверка сеанса браузера…",
"Checking connection": "Проверка подключения",
"Checking name...": "Проверяю имя...",
+ "Checking Passkey availability...": "Проверяем доступность ключей доступа…",
"Checking payment availability...": "Проверка доступности платежей…",
"Checking promotion...": "Проверка акции…",
"Checking registration status": "Проверка статуса регистрации",
@@ -6635,6 +6637,7 @@
"Models exposed by this channel": "Модели, доступные через этот канал",
"Models fetched successfully": "Модели успешно получены",
"Models filled to form": "Модели заполнены в форму",
+ "Models in this view: {{count}}": "Модели в текущем представлении: {{count}}",
"Models listed here will not automatically append or remove -thinking / -nothinking suffixes.": "Модели из этого списка не будут автоматически добавлять или удалять суффиксы -thinking / -nothinking.",
"Models losing positions": "Модели, теряющие позиции",
"Models losing the most positions": "Модели, потерявшие больше всего позиций",
@@ -7063,8 +7066,10 @@
"No model found.": "Модель не найдена.",
"No model mappings configured. Click \"Add Mapping\" to get started.": "Не настроены сопоставления моделей. Нажмите \"Добавить сопоставление\", чтобы начать.",
"No model price changes to save": "Нет изменений цен моделей для сохранения",
+ "No models are currently listed in the public catalog. Please check again later.": "В публичном каталоге пока нет моделей. Пожалуйста, проверьте позже.",
"No models available": "Модели недоступны",
"No models available in this category": "В этой категории нет моделей",
+ "No models available to your account": "Для вашего аккаунта нет доступных моделей",
"No models available. Create your first model to get started.": "Нет доступных моделей. Создайте свою первую модель, чтобы начать.",
"No models configured. Use Add model to get started.": "Модели не настроены. Используйте добавление модели, чтобы начать.",
"No models fetched from upstream": "Модели не получены от upstream",
@@ -7141,6 +7146,7 @@
"No protected groups are published yet.": "Защищённые группы пока не опубликованы.",
"No providers available": "Нет доступных провайдеров",
"No public bounty projects yet": "Публичных проектов с наградами пока нет",
+ "No public models listed": "В публичном каталоге нет моделей",
"No public reason has been provided.": "Публичная причина не указана.",
"No public risk categories are available yet.": "Публичные категории риска пока недоступны.",
"No public rule summaries are available yet.": "Публичные сводки правил пока недоступны.",
@@ -7285,6 +7291,7 @@
"Not priced": "Стоимость не определена",
"Not provided": "Не указано",
"Not published": "Не опубликовано",
+ "Not queried": "Запрос ещё не выполнен",
"Not rated": "Без оценки",
"Not read": "Не прочитано",
"Not recorded": "Не записано",
@@ -8708,6 +8715,7 @@
"Prune object items by conditions": "Удалить элементы объекта по условиям",
"Prune Rule (string or JSON object)": "Правило очистки (строка или JSON-объект)",
"Public": "Публичное",
+ "Public catalog prices do not grant permission to use a model.": "Цены в публичном каталоге не предоставляют право использовать модель.",
"Public challenges": "Открытые задания",
"Public channel group": "Группа публичных каналов",
"Public contributor evaluation": "Публичная оценка вкладчика",
@@ -9039,6 +9047,7 @@
"Read-only user management. Risk, usage, top-up, referral history and legacy trust information are unavailable in this view.": "Управление пользователями только для чтения. В этом представлении недоступны данные о рисках, использовании, пополнениях, истории приглашений и прежней системе доверия.",
"Reading progress": "Прогресс чтения",
"Reading the invitation confirmation status.": "Читаем статус подтверждения приглашения.",
+ "Reads Sub2API wallet or key quota in USD. Unlimited or unrecognized balances remain unknown.": "Читает баланс кошелька или квоту ключа Sub2API в USD. Неограниченный или нераспознанный баланс остаётся неизвестным.",
"Ready": "Готово",
"Ready in this client. Refresh its tool list.": "Готово в этом клиенте. Обновите список инструментов.",
"Ready to generate": "Готово к генерации",
@@ -9216,6 +9225,7 @@
"Refresh quote": "Обновить предложение",
"Refresh registration status": "Обновить статус регистрации",
"Refresh result": "Обновить результат",
+ "Refresh selected balances": "Обновить баланс выбранных каналов",
"Refresh Stats": "Обновить статистику",
"Refresh support status": "Обновить статус поддержки",
"Refresh the list and try again.": "Обновите список и повторите попытку.",
@@ -10758,6 +10768,7 @@
"Signed-in users can use the assistant immediately. Registration protection remains active.": "После входа пользователи могут сразу пользоваться помощником. Защита регистрации остаётся активной.",
"Significant outages detected": "Обнаружены серьёзные сбои",
"Signing in takes a moment and skips this screen entirely.": "Войдите, чтобы продолжить.",
+ "Signing in...": "Выполняется вход…",
"Signing key": "Ключ подписи",
"Signing you in with {{provider}}": "Входим через {{provider}}",
"SiliconFlow": "SiliconFlow",
@@ -13007,6 +13018,7 @@
"View process details": "Показать подробности процесса",
"View products": "Показать товары",
"View progress": "Посмотреть прогресс",
+ "View public catalog": "Открыть публичный каталог",
"View refunds or request a refund": "Посмотреть возвраты или запросить возврат",
"View related page": "Посмотреть связанную страницу",
"View request details": "Открыть сведения о запросе",
@@ -13369,6 +13381,7 @@
"Your account can edit sensitive channel settings.": "Ваша учетная запись может изменять чувствительные настройки каналов.",
"Your account cannot edit sensitive channel settings.": "Ваша учетная запись не может изменять чувствительные настройки каналов.",
"Your account changed. Refresh this page before continuing.": "Ваш аккаунт изменился. Обновите страницу, прежде чем продолжить.",
+ "Your account currently has no available models. Contact an administrator to request access.": "Сейчас для вашего аккаунта нет доступных моделей. Обратитесь к администратору, чтобы запросить доступ.",
"Your account does not cover this page yet.": "У вашего аккаунта нет доступа к этой странице.",
"Your account does not have permission to open this page.": "У вашей учётной записи нет разрешения на просмотр этой страницы.",
"Your account has an active or future subscription entitlement.": "У аккаунта есть действующие или будущие права по подписке.",
diff --git a/apps/web/src/i18n/locales/vi.json b/apps/web/src/i18n/locales/vi.json
index 558dd77ba..e5626bdf4 100644
--- a/apps/web/src/i18n/locales/vi.json
+++ b/apps/web/src/i18n/locales/vi.json
@@ -1398,6 +1398,7 @@
"Back to list": "Quay lại danh sách",
"Back to login": "Quay lại đăng nhập",
"Back to Models": "Quay lại Mô hình",
+ "Back to my catalog": "Quay lại danh mục của tôi",
"Back to store": "Quay lại cửa hàng",
"Back to subscriptions": "Quay lại gói đăng ký",
"Back to task": "Quay lại tác vụ",
@@ -1953,7 +1954,7 @@
"channelBalance.copied": "Quan sát được sao chép",
"channelBalance.denied": "Bạn không có quyền thực hiện thao tác số dư này.",
"channelBalance.disabled": "Truy vấn số dư đã tắt. Hãy cấu hình truy vấn trước.",
- "channelBalance.error": "Chưa thể đọc số dư nhà cung cấp.",
+ "channelBalance.error": "Chưa xác định được số dư hiện tại. Số dư ghi nhận gần nhất không thay đổi.",
"channelBalance.invalid": "Dùng đường dẫn bắt đầu bằng một / không có tham số hay đoạn neo, JSON Pointer / hợp lệ và đơn vị tối đa 32 ký tự.",
"channelBalance.note": "Hiển thị theo đơn vị nhà cung cấp. Bản sao hoặc đặt lại không có nghĩa là đã truy vấn số dư mới.",
"channelBalance.path": "Đường dẫn truy vấn",
@@ -2120,6 +2121,7 @@
"Checking browser session...": "Đang kiểm tra phiên trình duyệt…",
"Checking connection": "Đang kiểm tra kết nối",
"Checking name...": "Đang kiểm tra tên...",
+ "Checking Passkey availability...": "Đang kiểm tra khả năng sử dụng Passkey…",
"Checking payment availability...": "Đang kiểm tra khả dụng thanh toán…",
"Checking promotion...": "Đang kiểm tra khuyến mãi…",
"Checking registration status": "Đang kiểm tra trạng thái đăng ký",
@@ -6635,6 +6637,7 @@
"Models exposed by this channel": "Các mô hình được kênh này cung cấp",
"Models fetched successfully": "Các mô hình đã được tải thành công",
"Models filled to form": "Mô hình đã được điền vào biểu mẫu",
+ "Models in this view: {{count}}": "Mô hình trong chế độ xem này: {{count}}",
"Models listed here will not automatically append or remove -thinking / -nothinking suffixes.": "Các mô hình được liệt kê ở đây sẽ không tự động thêm hoặc xóa hậu tố -thinking / -nothinking.",
"Models losing positions": "Các mô hình đang mất vị trí",
"Models losing the most positions": "Mô hình tụt hạng nhiều nhất",
@@ -7063,8 +7066,10 @@
"No model found.": "Không tìm thấy mô hình.",
"No model mappings configured. Click \"Add Mapping\" to get started.": "Chưa có ánh xạ mô hình nào được cấu hình. Nhấp vào \"Thêm ánh xạ\" để bắt đầu.",
"No model price changes to save": "Không có thay đổi giá mô hình nào cần lưu",
+ "No models are currently listed in the public catalog. Please check again later.": "Hiện chưa có mô hình nào được liệt kê trong danh mục công khai. Vui lòng kiểm tra lại sau.",
"No models available": "Không có mô hình nào khả dụng",
"No models available in this category": "Không có mô hình nào trong danh mục này",
+ "No models available to your account": "Tài khoản của bạn chưa có mô hình khả dụng",
"No models available. Create your first model to get started.": "Không có mô hình nào khả dụng. Hãy tạo mô hình đầu tiên của bạn để bắt đầu.",
"No models configured. Use Add model to get started.": "Chưa cấu hình mô hình. Dùng Thêm mô hình để bắt đầu.",
"No models fetched from upstream": "Không lấy được mô hình nào từ upstream",
@@ -7141,6 +7146,7 @@
"No protected groups are published yet.": "Chưa công bố nhóm được bảo vệ.",
"No providers available": "Không có nhà cung cấp khả dụng",
"No public bounty projects yet": "Chưa có dự án tiền thưởng công khai",
+ "No public models listed": "Chưa có mô hình trong danh mục công khai",
"No public reason has been provided.": "Chưa công bố lý do.",
"No public risk categories are available yet.": "Chưa có danh mục rủi ro công khai.",
"No public rule summaries are available yet.": "Chưa có tóm tắt quy tắc công khai.",
@@ -7285,6 +7291,7 @@
"Not priced": "Chưa định giá",
"Not provided": "Chưa cung cấp",
"Not published": "Chưa công bố",
+ "Not queried": "Chưa truy vấn",
"Not rated": "Chưa chấm điểm",
"Not read": "Chưa đọc",
"Not recorded": "Chưa ghi nhận",
@@ -8708,6 +8715,7 @@
"Prune object items by conditions": "Dọn dẹp các mục đối tượng theo điều kiện",
"Prune Rule (string or JSON object)": "Quy tắc dọn dẹp (chuỗi hoặc đối tượng JSON)",
"Public": "Công khai",
+ "Public catalog prices do not grant permission to use a model.": "Giá trong danh mục công khai không cấp quyền sử dụng mô hình.",
"Public challenges": "Thử thách công khai",
"Public channel group": "Nhóm kênh công khai",
"Public contributor evaluation": "Đánh giá công khai người đóng góp",
@@ -9039,6 +9047,7 @@
"Read-only user management. Risk, usage, top-up, referral history and legacy trust information are unavailable in this view.": "Quản lý người dùng chỉ đọc. Chế độ xem này không có dữ liệu rủi ro, mức sử dụng, nạp tiền, lịch sử giới thiệu và thông tin tin cậy cũ.",
"Reading progress": "Tiến độ đọc",
"Reading the invitation confirmation status.": "Đang đọc trạng thái xác nhận lời mời.",
+ "Reads Sub2API wallet or key quota in USD. Unlimited or unrecognized balances remain unknown.": "Đọc số dư ví hoặc hạn mức khóa Sub2API bằng USD. Số dư không giới hạn hoặc không nhận dạng được vẫn hiển thị là chưa xác định.",
"Ready": "Sẵn sàng",
"Ready in this client. Refresh its tool list.": "Đã sẵn sàng trong ứng dụng này. Làm mới danh sách công cụ.",
"Ready to generate": "Sẵn sàng tạo ảnh",
@@ -9216,6 +9225,7 @@
"Refresh quote": "Làm mới báo giá",
"Refresh registration status": "Làm mới trạng thái đăng ký",
"Refresh result": "Tải lại kết quả",
+ "Refresh selected balances": "Cập nhật số dư các kênh đã chọn",
"Refresh Stats": "Làm mới thống kê",
"Refresh support status": "Làm mới trạng thái hỗ trợ",
"Refresh the list and try again.": "Hãy làm mới danh sách và thử lại.",
@@ -10758,6 +10768,7 @@
"Signed-in users can use the assistant immediately. Registration protection remains active.": "Người dùng có thể sử dụng trợ lý ngay sau khi đăng nhập. Biện pháp bảo vệ khi đăng ký vẫn hoạt động.",
"Significant outages detected": "Phát hiện gián đoạn nghiêm trọng",
"Signing in takes a moment and skips this screen entirely.": "Đăng nhập để tiếp tục.",
+ "Signing in...": "Đang đăng nhập…",
"Signing key": "Khóa ký",
"Signing you in with {{provider}}": "Đang đăng nhập bằng {{provider}}",
"SiliconFlow": "SiliconFlow",
@@ -13007,6 +13018,7 @@
"View process details": "Xem chi tiết quy trình",
"View products": "Xem sản phẩm",
"View progress": "Xem tiến độ",
+ "View public catalog": "Xem danh mục công khai",
"View refunds or request a refund": "Xem các khoản hoàn tiền hoặc yêu cầu hoàn tiền",
"View related page": "Xem trang liên quan",
"View request details": "Xem chi tiết yêu cầu",
@@ -13369,6 +13381,7 @@
"Your account can edit sensitive channel settings.": "Tài khoản của bạn có thể chỉnh sửa cài đặt kênh nhạy cảm.",
"Your account cannot edit sensitive channel settings.": "Tài khoản của bạn không thể chỉnh sửa cài đặt kênh nhạy cảm.",
"Your account changed. Refresh this page before continuing.": "Tài khoản của bạn đã thay đổi. Hãy làm mới trang này trước khi tiếp tục.",
+ "Your account currently has no available models. Contact an administrator to request access.": "Hiện tài khoản của bạn chưa có mô hình khả dụng. Hãy liên hệ quản trị viên để yêu cầu quyền truy cập.",
"Your account does not cover this page yet.": "Tài khoản chưa có quyền xem trang này.",
"Your account does not have permission to open this page.": "Tài khoản của bạn không có quyền mở trang này.",
"Your account has an active or future subscription entitlement.": "Tài khoản còn quyền lợi gói đăng ký đang có hiệu lực hoặc sắp bắt đầu.",
diff --git a/apps/web/src/i18n/locales/zh-CN.json b/apps/web/src/i18n/locales/zh-CN.json
index a52442d04..4ec2a3bca 100644
--- a/apps/web/src/i18n/locales/zh-CN.json
+++ b/apps/web/src/i18n/locales/zh-CN.json
@@ -1398,6 +1398,7 @@
"Back to list": "返回列表",
"Back to login": "返回登录",
"Back to Models": "返回模型",
+ "Back to my catalog": "返回我的目录",
"Back to store": "返回商店",
"Back to subscriptions": "返回订阅",
"Back to task": "返回任务",
@@ -1953,7 +1954,7 @@
"channelBalance.copied": "复制的观察记录",
"channelBalance.denied": "你没有执行此余额操作的权限。",
"channelBalance.disabled": "余额查询已禁用,请先配置查询。",
- "channelBalance.error": "暂时无法读取供应商余额。",
+ "channelBalance.error": "当前余额未知。上次记录的余额保持不变。",
"channelBalance.invalid": "路径须以单个 / 开头且不含查询参数或片段;字段位置须为有效的 / JSON Pointer,单位最多32个字符。",
"channelBalance.note": "按供应商原单位显示。复制或重置记录不代表重新查询过余额。",
"channelBalance.path": "查询路径",
@@ -2120,6 +2121,7 @@
"Checking browser session...": "正在检查浏览器会话…",
"Checking connection": "检查连接",
"Checking name...": "正在检查名称...",
+ "Checking Passkey availability...": "正在检查 Passkey 是否可用…",
"Checking payment availability...": "正在检查支付可用性…",
"Checking promotion...": "正在检查促销活动…",
"Checking registration status": "正在读取核验状态",
@@ -6635,6 +6637,7 @@
"Models exposed by this channel": "此渠道暴露的模型",
"Models fetched successfully": "模型获取成功",
"Models filled to form": "模型已填充到表单",
+ "Models in this view: {{count}}": "当前视图中的模型:{{count}}",
"Models listed here will not automatically append or remove -thinking / -nothinking suffixes.": "此处列出的模型不会自动添加或移除 -thinking / -nothinking 后缀。",
"Models losing positions": "排名下滑的模型",
"Models losing the most positions": "名次下滑最多的模型",
@@ -7063,8 +7066,10 @@
"No model found.": "未找到模型。",
"No model mappings configured. Click \"Add Mapping\" to get started.": "未配置模型映射。点击“添加映射”即可开始使用。",
"No model price changes to save": "没有模型价格变更需要保存",
+ "No models are currently listed in the public catalog. Please check again later.": "公开目录当前没有列出任何模型。请稍后再来查看。",
"No models available": "没有可用的模型",
"No models available in this category": "该分类下没有可用模型",
+ "No models available to your account": "你的账户暂无可用模型",
"No models available. Create your first model to get started.": "没有可用的模型。创建您的第一个模型即可开始使用。",
"No models configured. Use Add model to get started.": "暂无模型配置。使用添加模型开始配置。",
"No models fetched from upstream": "未从上游获取模型",
@@ -7141,6 +7146,7 @@
"No protected groups are published yet.": "暂未公布受保护分组。",
"No providers available": "暂无可用提供商",
"No public bounty projects yet": "暂无公开悬赏项目",
+ "No public models listed": "暂无公开列出的模型",
"No public reason has been provided.": "尚未公布封禁原因。",
"No public risk categories are available yet.": "暂无公开风险分类。",
"No public rule summaries are available yet.": "暂无公开规则摘要。",
@@ -7285,6 +7291,7 @@
"Not priced": "尚未计价",
"Not provided": "未提供",
"Not published": "未发布",
+ "Not queried": "尚未查询",
"Not rated": "未评分",
"Not read": "未阅读",
"Not recorded": "未记录",
@@ -8708,6 +8715,7 @@
"Prune object items by conditions": "按条件清理对象中的子项",
"Prune Rule (string or JSON object)": "清理规则(字符串或 JSON 对象)",
"Public": "公开",
+ "Public catalog prices do not grant permission to use a model.": "公开目录中的价格信息不代表你有权限使用对应模型。",
"Public challenges": "公开挑战",
"Public channel group": "公开渠道分组",
"Public contributor evaluation": "公开的贡献者评价",
@@ -9039,6 +9047,7 @@
"Read-only user management. Risk, usage, top-up, referral history and legacy trust information are unavailable in this view.": "只读用户管理。此视图不提供风险、用量、充值、邀请历史和旧版信任信息。",
"Reading progress": "阅读进度",
"Reading the invitation confirmation status.": "正在读取邀请确认状态。",
+ "Reads Sub2API wallet or key quota in USD. Unlimited or unrecognized balances remain unknown.": "以 USD 读取 Sub2API 钱包余额或密钥配额。无限或无法识别的余额显示为未知。",
"Ready": "已就绪",
"Ready in this client. Refresh its tool list.": "此客户端已可使用。请刷新客户端工具列表。",
"Ready to generate": "准备生成",
@@ -9216,6 +9225,7 @@
"Refresh quote": "刷新报价",
"Refresh registration status": "刷新核验状态",
"Refresh result": "刷新结果",
+ "Refresh selected balances": "刷新所选渠道余额",
"Refresh Stats": "刷新统计",
"Refresh support status": "刷新人工支持状态",
"Refresh the list and try again.": "请刷新列表后重试。",
@@ -10758,6 +10768,7 @@
"Signed-in users can use the assistant immediately. Registration protection remains active.": "登录后即可使用助手。注册风险防护继续生效。",
"Significant outages detected": "检测到较为严重的故障",
"Signing in takes a moment and skips this screen entirely.": "登录后继续操作。",
+ "Signing in...": "正在登录…",
"Signing key": "签名密钥",
"Signing you in with {{provider}}": "正在使用 {{provider}} 登录",
"SiliconFlow": "SiliconFlow",
@@ -13007,6 +13018,7 @@
"View process details": "查看流程详情",
"View products": "查看商品",
"View progress": "查看进度",
+ "View public catalog": "查看公开目录",
"View refunds or request a refund": "查看退款记录或申请退款",
"View related page": "查看相关页面",
"View request details": "查看请求详情",
@@ -13369,6 +13381,7 @@
"Your account can edit sensitive channel settings.": "你的账号可以编辑敏感渠道设置。",
"Your account cannot edit sensitive channel settings.": "你的账号不能编辑敏感渠道设置。",
"Your account changed. Refresh this page before continuing.": "你的账号已更改。请刷新此页面后再继续。",
+ "Your account currently has no available models. Contact an administrator to request access.": "你的账户当前没有可用模型。请联系管理员申请访问权限。",
"Your account does not cover this page yet.": "当前账户没有此页面的权限。",
"Your account does not have permission to open this page.": "当前账号没有访问此页面的权限。",
"Your account has an active or future subscription entitlement.": "您的账户还有有效或尚未开始的订阅权益。",
diff --git a/apps/web/src/i18n/locales/zh-TW.json b/apps/web/src/i18n/locales/zh-TW.json
index c4ab8567a..23d5eeff4 100644
--- a/apps/web/src/i18n/locales/zh-TW.json
+++ b/apps/web/src/i18n/locales/zh-TW.json
@@ -1398,6 +1398,7 @@
"Back to list": "返回列表",
"Back to login": "返回登入",
"Back to Models": "返回模型",
+ "Back to my catalog": "返回我的目錄",
"Back to store": "返回商店",
"Back to subscriptions": "返回訂閱",
"Back to task": "返回任務",
@@ -1953,7 +1954,7 @@
"channelBalance.copied": "複製的觀察紀錄",
"channelBalance.denied": "你沒有執行此餘額操作的權限。",
"channelBalance.disabled": "餘額查詢已停用,請先設定查詢。",
- "channelBalance.error": "暫時無法讀取供應商餘額。",
+ "channelBalance.error": "目前餘額未知。上次記錄的餘額保持不變。",
"channelBalance.invalid": "路徑須以單個 / 開頭且不含查詢參數或片段;欄位位置須為有效的 / JSON Pointer,單位最多32個字元。",
"channelBalance.note": "依供應商原單位顯示。複製或重設紀錄不代表重新查詢過餘額。",
"channelBalance.path": "查詢路徑",
@@ -2120,6 +2121,7 @@
"Checking browser session...": "正在檢查瀏覽器工作階段…",
"Checking connection": "檢查連接",
"Checking name...": "正在檢查名稱...",
+ "Checking Passkey availability...": "正在檢查 Passkey 是否可用…",
"Checking payment availability...": "正在檢查付款可用性…",
"Checking promotion...": "正在檢查促銷活動…",
"Checking registration status": "正在读取核验状态",
@@ -6635,6 +6637,7 @@
"Models exposed by this channel": "此渠道暴露的模型",
"Models fetched successfully": "模型獲取成功",
"Models filled to form": "模型已填充到表單",
+ "Models in this view: {{count}}": "目前檢視中的模型:{{count}}",
"Models listed here will not automatically append or remove -thinking / -nothinking suffixes.": "此處列出的模型不會自動新增或移除 -thinking / -nothinking 後綴。",
"Models losing positions": "排名下滑的模型",
"Models losing the most positions": "名次下滑最多的模型",
@@ -7063,8 +7066,10 @@
"No model found.": "未找到模型。",
"No model mappings configured. Click \"Add Mapping\" to get started.": "未設定模型映射。點擊「新增映射」即可開始使用。",
"No model price changes to save": "沒有模型價格變更需要儲存",
+ "No models are currently listed in the public catalog. Please check again later.": "公開目錄目前沒有列出任何模型。請稍後再來查看。",
"No models available": "沒有可用的模型",
"No models available in this category": "該分類下沒有可用模型",
+ "No models available to your account": "你的帳戶暫無可用模型",
"No models available. Create your first model to get started.": "沒有可用的模型。建立您的第一個模型即可開始使用。",
"No models configured. Use Add model to get started.": "暫無模型設定。使用新增模型開始設定。",
"No models fetched from upstream": "未從上游獲取模型",
@@ -7141,6 +7146,7 @@
"No protected groups are published yet.": "尚未公布受保護分組。",
"No providers available": "暫無可用供應商",
"No public bounty projects yet": "暫無公開懸賞專案",
+ "No public models listed": "暫無公開列出的模型",
"No public reason has been provided.": "尚未公布停用原因。",
"No public risk categories are available yet.": "目前沒有公開風險分類。",
"No public rule summaries are available yet.": "目前沒有公開規則摘要。",
@@ -7285,6 +7291,7 @@
"Not priced": "尚未計價",
"Not provided": "未提供",
"Not published": "尚未發布",
+ "Not queried": "尚未查詢",
"Not rated": "未評分",
"Not read": "未閱讀",
"Not recorded": "未記錄",
@@ -8708,6 +8715,7 @@
"Prune object items by conditions": "按條件清理物件中的子項",
"Prune Rule (string or JSON object)": "清理規則(字串或 JSON 物件)",
"Public": "公開",
+ "Public catalog prices do not grant permission to use a model.": "公開目錄中的價格資訊不代表你有權限使用對應模型。",
"Public challenges": "公開挑戰",
"Public channel group": "公開渠道分組",
"Public contributor evaluation": "公開的貢獻者評價",
@@ -9039,6 +9047,7 @@
"Read-only user management. Risk, usage, top-up, referral history and legacy trust information are unavailable in this view.": "唯讀用戶管理。此檢視不提供風險、用量、儲值、邀請歷史和舊版信任資訊。",
"Reading progress": "閱讀進度",
"Reading the invitation confirmation status.": "正在讀取邀請確認狀態。",
+ "Reads Sub2API wallet or key quota in USD. Unlimited or unrecognized balances remain unknown.": "以 USD 讀取 Sub2API 錢包餘額或金鑰配額。無限或無法識別的餘額顯示為未知。",
"Ready": "已就緒",
"Ready in this client. Refresh its tool list.": "此用戶端已可使用。請重新整理用戶端工具清單。",
"Ready to generate": "準備生成",
@@ -9216,6 +9225,7 @@
"Refresh quote": "重新整理報價",
"Refresh registration status": "刷新核验状态",
"Refresh result": "重新整理結果",
+ "Refresh selected balances": "重新整理所選管道餘額",
"Refresh Stats": "重新整理統計",
"Refresh support status": "重新整理人工支援狀態",
"Refresh the list and try again.": "請重新整理清單後再試一次。",
@@ -10758,6 +10768,7 @@
"Signed-in users can use the assistant immediately. Registration protection remains active.": "登入後即可使用助理。註冊風險防護繼續生效。",
"Significant outages detected": "偵測到較為嚴重的故障",
"Signing in takes a moment and skips this screen entirely.": "登入後繼續操作。",
+ "Signing in...": "正在登入…",
"Signing key": "簽章金鑰",
"Signing you in with {{provider}}": "正在使用 {{provider}} 登入",
"SiliconFlow": "SiliconFlow",
@@ -13007,6 +13018,7 @@
"View process details": "查看流程詳細資料",
"View products": "查看商品",
"View progress": "查看進度",
+ "View public catalog": "查看公開目錄",
"View refunds or request a refund": "查看退款記錄或申請退款",
"View related page": "查看相關頁面",
"View request details": "檢視請求詳情",
@@ -13369,6 +13381,7 @@
"Your account can edit sensitive channel settings.": "你的賬號可以編輯敏感渠道設定。",
"Your account cannot edit sensitive channel settings.": "你的賬號不能編輯敏感渠道設定。",
"Your account changed. Refresh this page before continuing.": "你的帳戶已變更。請重新整理此頁面後再繼續。",
+ "Your account currently has no available models. Contact an administrator to request access.": "你的帳戶目前沒有可用模型。請聯絡管理員申請存取權限。",
"Your account does not cover this page yet.": "目前帳戶沒有此頁面的權限。",
"Your account does not have permission to open this page.": "目前帳號沒有開啟此頁面的權限。",
"Your account has an active or future subscription entitlement.": "您的帳戶仍有有效或尚未開始的訂閱權益。",
diff --git a/docs/channel-accounting.md b/docs/channel-accounting.md
index 3e4a1b12d..805e8506f 100644
--- a/docs/channel-accounting.md
+++ b/docs/channel-accounting.md
@@ -39,7 +39,7 @@ opening import, provider-cost accounting or complete legacy statistics parity.
`PUT /core/v1/admin/routing/channels/{id}/balance-config` takes
`{expected_version,probe}` under the existing sensitive-write permission.
-`probe` is null or `{path,json_pointer,unit_label,subtract_json_pointer?,require?,require_all?,auth?,cny_per_usd?,deepseek_currency_array?,openai_subscription?}`: a
+`probe` is null or `{path,json_pointer,unit_label,subtract_json_pointer?,require?,require_all?,auth?,cny_per_usd?,deepseek_currency_array?,openai_subscription?,sub2api_usage?}`: a
same-origin relative GET path, an RFC 6901 JSON pointer, an optional unit label,
and optionally a second RFC 6901 pointer. When the second pointer is present,
the observed finite number is the first selected numeric value minus the second;
@@ -61,6 +61,46 @@ discovery or complete legacy adapter parity. A publication containing these new
fields requires a Core version that understands them; older Core versions must not
be used to recover that publication.
+### Sub2API wallet and key quota
+
+Select **Sub2API** in the automatic provider settings, or publish
+`legacy: {"channel_type":59}` with `probe:null` and the current
+`expected_version`. An explicit manual probe takes precedence. The equivalent
+fixed probe is `{"path":"/v1/usage","json_pointer":"/remaining","unit_label":"USD","sub2api_usage":true}`.
+This plan cannot be combined with other selectors, conversions or auth overrides.
+
+Core sends one same-origin `GET /v1/usage` with Bearer authentication, including
+when the channel's model protocol is Anthropic or Gemini. It uses the existing
+endpoint validation, DNS/SSRF checks, response-size limit, timeout and admission
+gate. Both supported response contracts use numeric USD amounts:
+
+| Response | Accepted amount | Unit |
+| ---------------------------------- | ------------------------------------------------------------------ | -------------------------------------- |
+| Wallet, `mode: "unrestricted"` | Top-level `remaining`; older wallet responses may supply `balance` | Explicit `unit: "USD"` |
+| Key quota, `mode: "quota_limited"` | Top-level `remaining`, alongside the `quota` object | Both top-level and quota `unit: "USD"` |
+
+A present `remaining` takes precedence, including zero. A negative wallet
+balance remains a negative balance. Invalid keys, malformed amounts, missing
+amounts or units, unknown modes, provider errors and unlimited subscriptions
+produce an unavailable result. Rate-limit-only responses do not establish a
+wallet balance. None of these results replaces the previous amount or observation
+time. Reflected credentials in any response field, including escaped JSON strings
+and object keys, are rejected.
+
+The contract follows the upstream
+[Sub2API usage handler](https://github.com/Wei-Shaw/sub2api/blob/main/backend/internal/handler/gateway_handler.go)
+and the
+[New API adapter](https://github.com/QuantumNous/new-api/blob/63cecab824bad1a421d19950004c309bb2054c09/controller/channel-billing.go).
+The synthetic wallet and quota fixtures under `services/core/tests/fixtures`
+contain no production account data.
+
+**Refresh selected balances** operates on the selected current page, up to 25
+channels, one request at a time. It calls the same native single-channel endpoint
+and uses the same error messages. A failed channel is marked unknown while its
+last stored observation is preserved; other channels can finish. Closing the
+dialog or changing sessions cancels remaining browser work. Denied access stops
+the batch, and there is no background polling or automatic retry.
+
`GET /core/v1/admin/routing/channels/{id}/balance` requires ChannelOperate and
uses the channel's existing server-side credential. The request uses the normal
gateway's endpoint, timeout and body limits. No database transaction or actor
diff --git a/docs/progress.md b/docs/progress.md
index 70adc8536..f579053be 100644
--- a/docs/progress.md
+++ b/docs/progress.md
@@ -1,9 +1,29 @@
# 新架构进度
-更新于 2026-11-23。此文件只维护当前状态、剩余阻塞和证据入口;执行过程、逐轮测试及历史失败保留在 Git 历史与对应验收收据。
+更新于 2026-11-24。此文件只维护当前状态、剩余阻塞和证据入口;执行过程、逐轮测试及历史失败保留在 Git 历史与对应验收收据。
## 当前状态
+- **本地整合候选 E(未推送、未部署;2026-11-23)**:从精确 D `15bc9d989dfa67930ecf501f0e593794f16d672d` 建立隔离工作树,完整合并 Sub2API 余额 `5d5674c8bc41562ab0bb27a6aae0ec963e7547d5`、原生多 Key 日志快照 `cbc3bffcac4470354f8510a531ea4974748eaa64`、登录等待与定价空状态 `726c580c84b83ef46a18fa8a6f8a8320de5c32c3`,以及 PR17 的确切 head `7566aadbd93e17a5004284e104eeaf89f211d59c`。PR17 按完整 Git 祖先链合并,共同祖先为 `25a0fc4654465ade661178c68ff082e0a3f9d3df`;未只摘取最后一次提交,也未削减 canonical gate。七种语言分别保留两条功能分支的全部 14 个变更键,未增加 schema88 变更。
+
+ **B 追加(本地整合)**:纳入 `240f08a1fa9353ca1e438eda78eaf78c7980758f` 的故障转移与 reader 边界测试、合成 golden 和发布说明。两份 Rust 文件格式检查及 golden 的静态源码/摘要核对通过;这些检查没有执行真实 D、Rust 测试或 PostgreSQL。后文严格 forward-only 的当前 writer 边界完整保留,未引入或批准 reader-only 过渡版本。Web 输入未变,原 173 项自测沿用其原输入身份,不增加新通过计数。原功能工位的隔离库脚本仍是其私有 out 材料,不在本提交中。
+
+ **A 追加与当前组合自测**:纳入 `25426c7e80c6dad96b6894c7772b1c9eaaa438e8` 的选择快照、关闭后筛选重开和自动配置防重复请求回归,未修改生产逻辑。E 中两个受影响渠道测试文件重新执行,客户端 5 项、UI 55 项通过;其余 auth/pricing 的 115 项按未变的源码、配置及依赖锁复用原收据。当前验证矩阵为 175 项,其中 60 项在本轮执行、115 项沿用原证据。两份测试文件的 lint 为 0 error/0 warning,格式检查沿用该 A 提交的同输入通过记录。
+
+ **Web 类型与构建**:在主协调者安排的串行资源窗口内,完整 Web 类型检查退出 0(约 663 秒),`mise exec -- just build-web` 连同 bundle 门禁退出 0(约 17 秒);首屏 gzip 为 499868 字节,门槛 786432 字节。两个独立 scope 均限制为内存 3 GiB、swap 2 GiB、2 CPU,内存峰值分别约 2.17/1.39 GiB,无 OOM,结束后 scope 与进程均已清理。检查前后的源码输入树与锁文件一致,最终仅追加本进度记录;构建归属提交前的合并输入,不替代最终提交的 CI 资格。新命令、日志、输入身份及资源证据保存在 `out/integration-e-task-b/`,此前的取消与失败记录保持原样。
+
+ **初始组合自测**:7 个前端测试文件串行执行,173 项通过、0 失败;范围内 22 个 Web 文件格式检查通过,lint 为 0 error/16 warnings;20 个 Rust 文件的格式检查通过,七语言同步的 missing/extras 均为 0。类型检查曾在 `GOMAXPROCS=2`、`GOMEMLIMIT=512MiB` 下启动,但实际峰值 RSS 约 2.16 GiB,宿主可用内存降至约 569 MiB;为让 D 切换优先,已取消该检查,该次未取得成功退出码;本轮补跑结果见上述当前组合自测,原取消收据保留。Rust 格式不代表编译或测试通过。输入核对、逐命令退出码、原始日志及取消收据保存在 E 工作树的 `out/integration-e-validation/`。
+
+ **发布边界**:此处仅完成本地源码整合和已列出的开发自测,独立验收未执行。最终 E 仍须取得自身精确提交的完整 main CI;既有分支或 PR17 的旧 green 不转移给新组合。Rust 编译/测试、真实 PostgreSQL 及浏览器检查本轮未运行。**CBC 回退约束仍是发布前待决事项,本次整合没有解除或验证该约束。**未改动冻结 D、主线或其他工位工作树,未推送、部署或执行生产/真实支付操作。
+
+- **原生多 Key 日志快照([#853](https://github.com/TokenNotIncluded/lmm-api/issues/853) 局部实现,定向验证待完成;2026-11-23)**:原生模型请求在受理合同中保存当时的多 Key 标记与零基序号,并沿用已有的非秘密凭据 ID/版本。路由池重排、删除或改版后,管理员日志从持久化合同及实际发送记录读取原快照;结算差额与退款继续引用同一请求合同。普通用户日志不投影序号或凭据标识;无快照的旧合同和图片请求明确返回管理员状态 `unknown`,不按当前 Key 池推算。未新增 schema 或修改计费金额。
+
+ **兼容方向与发布边界**:新 reader 可读取省略 `credential_selection` 的 D 旧合同,并保留旧字节与摘要;D 的 `deny_unknown_fields` 会拒绝含该字段的新合同。未改 schema 不等于可回退 D 二进制。当前候选会直接写入新字段,只能按严格 forward-only 评审;如必须保留回退窗口,需另行交付 E reader-only 版本,先升级全部合同读取方,再单独批准启用 writer。写入首份新合同后,回退下限是兼容的新 reader,不能删除字段、重算既有摘要或仅更换回 D 二进制。本轮未实现或启用分阶段发布开关。
+
+ **范围与验证**:`key_snapshot` 定向回归已补充两次本地 HTTP 实际派发、首候选拒绝后最终 Key 绑定的管理员投影,以及旧/新合同固定字节、摘要和旧 D 严格解析边界。golden 由冻结 D 源码与合成值构造,未由真实 D 二进制执行产生;Rust 编译、这些测试和 PostgreSQL 自测仍未执行。修订的隔离库脚本与新报告位于私有 `out/task-key-logs-validation/r3/`,旧报告与完成收据保留。当前 `/api/task`、`/api/mj` 仍为历史读取入口,`usage/task_log.rs` 没有运行期调用;本轮没有新增供应商异步任务执行器,因此不能据此关闭 #853 或宣称完整异步链路已交付。
+
+- **Sub2API 余额协议与异步边界复核(2026-11-23,自测通过、独立验收未执行)**:以原本地候选 `5d5674c8` 为基线,对照官方固定源码 `570d59e9` 核对钱包/总额度 USD、零值、未知或无限额度、凭据反射与失败保留观测的边界;本轮未发现需要修改生产逻辑的问题。补充并执行选择快照/零值与关闭后筛选重开回归,强化自动配置下连续点击只发起一次查询:客户端 5 项、定向 Sub2API UI 2 项通过。新增内容仅含测试和本进度记录,原工位证据保存在其 `out/sub2api-836-boundary-review/`;E 的组合结果见上文。原候选的 Rust 编译/测试、真实 HTTP/PG、Web 生产构建与浏览器验证仍未运行,本轮 Web 类型检查与 lint 也未重跑;轻量结果不构成发布资格。
+
- **native 管理台与支付接入(界面候选完整 CI 已通过;配套支付后端已定向自测,等待发布及数据库升级资格;2026-11-23)**:界面候选 [fdbd9bc6](https://github.com/TokenNotIncluded/lmm-api-source/commit/fdbd9bc628545a5c33ea0f2bc5e79fa532948ba7) 的 [完整 CI](https://github.com/TokenNotIncluded/lmm-api-source/actions/runs/45130451839) 已成功,包括 Web、翻译、Rust/真实数据库、Go 和最终汇总。Web 单独按固定候选发布;这项资格不自动覆盖后续支付后端提交。
**管理台**:渠道、用户与系统设置进入权限过滤后的常驻导航;渠道增加状态和分组筛选,切换或重置时清理分页、选择、标签与路由草稿。用户列表恢复 URL 中的筛选、排序和分页,详情直达对应原生日志;日志链接保留时间、精确字符串、来源与作用域,个人范围不携带管理筛选。表格、展开状态、留白和移动端控件布局已调整。七种语言经既有工具同步;批量密钥操作使用显式能力声明,旧 Core 缺字段时保留单密钥入口,支持时仍走一次原子请求。确认链接与缺少重置券能力的旧 Core 兼容行为保持明确。
diff --git a/packaging/linux/extore-plugin-smoke.py b/packaging/linux/extore-plugin-smoke.py
index 35fc2a06b..22d97a4db 100644
--- a/packaging/linux/extore-plugin-smoke.py
+++ b/packaging/linux/extore-plugin-smoke.py
@@ -14,6 +14,34 @@
import urllib.request
+def probe_receipt(report, host_sha256, plugin_sha256):
+ """Export only reviewed acceptance facts from the private probe report."""
+ def confirmed(actual, expected):
+ for key, value in expected.items():
+ if type(actual.get(key)) is not type(value) or actual[key] != value:
+ raise ValueError(f"unconfirmed native acceptance field: {key}")
+ return {key: actual[key] for key in expected}
+
+ receipt = confirmed(report, {
+ "status": "passed", "consumer_exit_code": 0,
+ "host_library_sha256": host_sha256, "plugin_library_sha256": plugin_sha256,
+ "actual_rust_health": True, "isolated_network_namespace": True,
+ "tls_certificate_verification": True, "authorized_catalog": True,
+ "cross_shop_http_detail_denied": True, "revoked_token_denied": True,
+ "catalog_calls_did_not_issue_cards": True, "actual_sqlite_grant_usage_recorded": True,
+ })
+ receipt["consumer"] = confirmed(report["consumer"], {
+ "status": "passed", "host_abi": 1, "interface": "extore.commerce",
+ "real_extore_https_sqlite": True, "native_digest_path_binding": True,
+ "native_repeated_open_call_release_close": True, "store_sync_persisted": True,
+ "http_catalog_fallback_calls": 0, "secret_values_logged": False,
+ "production_accounts_created": False,
+ "store_repository": "transactional memory test repository",
+ "core_authority": "existing Store test double; independent CoreSession acceptance not run",
+ })
+ return receipt
+
+
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--arch", choices=("amd64", "arm64"), required=True)
@@ -104,7 +132,12 @@ def main():
time.sleep(0.1)
if not ready:
raise RuntimeError("installed extensions did not start without native configuration")
- if os.readlink(f"/proc/{process.pid}/exe") != "/usr/bin/lmm-extensions":
+ # Procfs checks credentials; container root cannot inspect another UID.
+ identity = subprocess.run(
+ ["readlink", "-n", f"/proc/{process.pid}/exe"],
+ check=True, stdout=subprocess.PIPE, timeout=5, user=account.pw_uid,
+ group=account.pw_gid, extra_groups=[])
+ if identity.stdout != b"/usr/bin/lmm-extensions":
raise RuntimeError("default process is not the installed program")
finally:
process.terminate()
@@ -127,15 +160,19 @@ def main():
"service_uid": account.pw_uid, "service_gid": account.pw_gid,
"default_process_stopped": True,
}
+ with tempfile.TemporaryDirectory(prefix="extore-private-probe-") as directory:
+ private_report = Path(directory) / "probe.json"
+ command = [sys.executable, "/work/tests/native_plugin_probe.py",
+ "--inside-netns", "--parent-netns", args.parent_netns,
+ "--binary", "/opt/extore/extore-server",
+ "--host-library", host, "--plugin-library", plugin,
+ "--report", str(private_report), "--consumer", str(args.consumer),
+ "-test.run", "^TestNativePluginCatalogStore$", "-test.v"]
+ subprocess.run(command, check=True)
+ accepted = probe_receipt(json.loads(private_report.read_text()),
+ info["files"][host]["sha256"], info["files"][plugin]["sha256"])
+ args.report.write_text(json.dumps(accepted, indent=2) + "\n")
Path(str(args.report) + ".package.json").write_text(json.dumps(receipt, indent=2) + "\n")
- command = [sys.executable, "/work/tests/native_plugin_probe.py",
- "--inside-netns", "--parent-netns", args.parent_netns,
- "--binary", "/opt/extore/extore-server",
- "--host-library", "/usr/lib/lmm/extensions/extore/libextore_plugin_host.so",
- "--plugin-library", "/usr/lib/lmm/extensions/extore/libextore_commerce_plugin.so",
- "--report", str(args.report), "--consumer", str(args.consumer),
- "-test.run", "^TestNativePluginCatalogStore$", "-test.v"]
- subprocess.run(command, check=True)
if __name__ == "__main__":
diff --git a/packaging/linux/test_extore_receipts.py b/packaging/linux/test_extore_receipts.py
new file mode 100644
index 000000000..ebb8f6c83
--- /dev/null
+++ b/packaging/linux/test_extore_receipts.py
@@ -0,0 +1,47 @@
+"""Check the upload boundary with synthetic private probe output."""
+import runpy
+import unittest
+from pathlib import Path
+
+
+probe_receipt = runpy.run_path(str(Path(__file__).with_name("extore-plugin-smoke.py")))["probe_receipt"]
+
+
+class ProbeReceiptTests(unittest.TestCase):
+ def setUp(self):
+ self.host, self.plugin = "a" * 64, "b" * 64
+ self.consumer = {
+ "status": "passed", "host_abi": 1, "interface": "extore.commerce",
+ "real_extore_https_sqlite": True, "native_digest_path_binding": True,
+ "native_repeated_open_call_release_close": True, "store_sync_persisted": True,
+ "http_catalog_fallback_calls": 0, "secret_values_logged": False,
+ "production_accounts_created": False,
+ "store_repository": "transactional memory test repository",
+ "core_authority": "existing Store test double; independent CoreSession acceptance not run",
+ }
+ self.report = {
+ "status": "passed", "consumer_exit_code": 0, "consumer": self.consumer,
+ "host_library_sha256": self.host, "plugin_library_sha256": self.plugin,
+ "actual_rust_health": True, "isolated_network_namespace": True,
+ "tls_certificate_verification": True, "authorized_catalog": True,
+ "cross_shop_http_detail_denied": True, "revoked_token_denied": True,
+ "catalog_calls_did_not_issue_cards": True, "actual_sqlite_grant_usage_recorded": True,
+ }
+
+ def test_only_reviewed_fields_cross_the_boundary(self):
+ private = dict(self.report, stdout="private fixture output",
+ consumer=dict(self.consumer, credentials={"test": "private"}))
+ self.assertEqual(probe_receipt(private, self.host, self.plugin), self.report)
+
+ def test_incomplete_failed_or_mistyped_facts_cannot_be_exported(self):
+ missing = self.report.copy()
+ del missing["consumer_exit_code"]
+ for raw in [missing, dict(self.report, status="failed"), dict(self.report, consumer_exit_code=False),
+ dict(self.report, host_library_sha256=self.plugin),
+ dict(self.report, consumer=dict(self.consumer, core_authority="unreviewed text"))]:
+ with self.subTest(raw=raw), self.assertRaises(ValueError):
+ probe_receipt(raw, self.host, self.plugin)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/workflow-topology.test.mjs b/scripts/workflow-topology.test.mjs
index d01178071..bebad6fc6 100644
--- a/scripts/workflow-topology.test.mjs
+++ b/scripts/workflow-topology.test.mjs
@@ -390,6 +390,49 @@ test('Core CI uses the same pinned PostgreSQL catalog as the RPC fixture', () =>
});
+test('native package uploads keep raw Alpine fixture output private', () => {
+ const source = workflow('linux-packages');
+ const upload = source.split(' - name: Preserve preview packages and scoped evidence, never publish\n')[1];
+ const paths = upload?.match(/ path: \|\n((?: .+\n)+)/)?.[1];
+ assert.ok(paths, 'the native package artifact must enumerate reviewed paths');
+ assert.deepEqual(paths.trim().split('\n').map((path) => path.trim()), [
+ '${{ steps.packages.outputs.paths }}',
+ 'out/evidence/revision.txt',
+ 'out/evidence/nfpm-version.txt',
+ 'out/evidence/install-matrix.txt',
+ 'out/evidence/image-digests.txt',
+ 'out/evidence/extore-fixture-image.txt',
+ 'out/evidence/extore-native-alpine.json',
+ 'out/evidence/extore-native-alpine.json.package.json',
+ ]);
+ assert.ok(source.includes('--report "/receipts/$report" > "$staging/fixture.log" 2>&1'));
+});
+
+test('automatic Core checks run both Cargo target groups on independent runners', () => {
+ const source = workflow('core-protocol');
+ for (const caller of ['ci', 'mk-01-identity']) {
+ assert.match(workflow(caller), /uses: \.\/\.github\/workflows\/core-protocol\.yml\n with:\n split_rust_targets: true/);
+ }
+ assert.match(source, /split_rust_targets:[\s\S]*?type: boolean\n default: false/);
+ assert.match(source, /fail-fast: false\n matrix:\n targets: .*inputs\.split_rust_targets && '\["unit","integration"\]' \|\| '\["all"\]'/);
+ assert.ok(source.includes('RUST_TARGET_GROUP: ${{ matrix.targets }}'));
+ assert.match(source, /timeout-minutes: 150/);
+ assert.doesNotMatch(source, /continue-on-error:/);
+ const selector = source.match(/case "\$RUST_TARGET_GROUP" in[\s\S]*?\besac\b/)?.[0];
+ assert.ok(selector);
+ function flags(group) {
+ return execFileSync('bash', ['-c', selector + '\nprintf "%s\\n" "${targets[@]}"'], {
+ env: { ...process.env, RUST_TARGET_GROUP: group },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ encoding: 'utf8',
+ }).trim().split('\n');
+ }
+ assert.deepEqual(flags('all'), ['--all-targets']);
+ assert.deepEqual(flags('unit'), ['--lib', '--bins', '--examples', '--benches']);
+ assert.deepEqual(flags('integration'), ['--test', '*']);
+ assert.throws(() => flags('unknown'), { status: 1 });
+});
+
test('Core CI freezes the process binary and private root before running all Rust tests', () => {
const source = workflow('core-protocol');
const block = source.match(/ - name: Rust checks and real database tests\n([\s\S]*?)(?= - name:)/)?.[1];
@@ -410,7 +453,7 @@ test('Core CI freezes the process binary and private root before running all Rus
const hash = block.indexOf('LMM_MODEL_PROCESS_CORE_SHA256="$(sha256sum "$LMM_MODEL_PROCESS_CORE_BIN"');
const root = block.indexOf('LMM_MODEL_PROCESS_ROOT="$(mktemp -d "$process_evidence_root/model-XXXXXXXX")"');
const exported = block.indexOf('export LMM_MODEL_PROCESS_CORE_BIN LMM_MODEL_PROCESS_CORE_SHA256 LMM_MODEL_PROCESS_ROOT');
- const execute = block.indexOf('cargo test --locked --all-targets --no-fail-fast');
+ const execute = block.indexOf('cargo test --locked "${targets[@]}" --no-fail-fast');
assert.ok(binary >= 0 && hash > binary && root > hash
&& exported > root && execute > exported, 'freeze inputs after compiling, before executing');
// The separately required owning-runner step covers exactly this one case.
@@ -424,7 +467,7 @@ test('Core CI isolates independent process evidence and cluster-wide role snapsh
assert.match(source, /RUST_TEST_THREADS: "1"/);
const block = source.match(/ - name: Rust checks and real database tests\n([\s\S]*?)(?= - name:)/)?.[1];
assert.ok(block);
- const execute = block.indexOf('cargo test --locked --all-targets --no-fail-fast');
+ const execute = block.indexOf('cargo test --locked "${targets[@]}" --no-fail-fast');
for (const name of [
'LMM_CONTINUITY_DEV_ARTIFACTS',
'COMPACT_INDEPENDENT_ARTIFACTS',
diff --git a/services/core/src/billing/charging/contract.rs b/services/core/src/billing/charging/contract.rs
index 5043d8d88..63bae60d3 100644
--- a/services/core/src/billing/charging/contract.rs
+++ b/services/core/src/billing/charging/contract.rs
@@ -28,6 +28,14 @@ struct AdmissionMarker {
}
// @context-fold begin reservation-contract-types
+/// Non-secret diagnostic facts captured alongside the admitted credential reference.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub(crate) struct CredentialSelection {
+ pub is_multi_key: bool,
+ pub multi_key_index: u32,
+}
+
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ReservationBinding {
@@ -38,6 +46,10 @@ pub(crate) struct ReservationBinding {
pub model_snapshot: String,
pub generation_url: String,
pub credential_ref: crate::routing::CredentialRef,
+ /// Absent on historical contracts; omission preserves their original digest.
+ /// D's strict reader rejects Some: this is backward reading, not binary rollback.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub credential_selection: Option,
pub payload_policy_sha256: String,
pub provider_contract_revision: String,
pub projection_revision: String,
@@ -55,6 +67,7 @@ impl ReservationBinding {
projection_revision: String,
quote_version: u64,
) -> Result {
+ let (is_multi_key, multi_key_index) = attempt.credential_selection();
Ok(Self {
route_id: attempt.route_key(),
target_id: attempt.target_id(),
@@ -63,6 +76,10 @@ impl ReservationBinding {
model_snapshot,
generation_url,
credential_ref: attempt.credential_ref(),
+ credential_selection: Some(CredentialSelection {
+ is_multi_key,
+ multi_key_index,
+ }),
payload_policy_sha256: typed_digest(&attempt.payload_policy())?,
provider_contract_revision,
projection_revision,
@@ -765,6 +782,9 @@ impl PreparedReservation {
|| binding.upstream_id > i64::MAX as u64
|| binding.credential_ref.id == 0
|| binding.credential_ref.revision == 0
+ || binding
+ .credential_selection
+ .is_some_and(|selection| !selection.is_multi_key && selection.multi_key_index != 0)
|| binding.quote_version == 0
|| !matches!(
binding.protocol.as_str(),
@@ -1157,15 +1177,24 @@ impl ReservationContract {
}
/// Both the route and dispatched wire body must match the frozen candidate.
- pub(crate) fn dispatched_channel(&self, route_id: &str, wire_sha256: &str) -> Option {
+ pub(crate) fn dispatched_binding(
+ &self,
+ route_id: &str,
+ wire_sha256: &str,
+ ) -> Option<&ReservationBinding> {
if self.fields.binding.route_id == route_id && self.fields.wire_sha256 == wire_sha256 {
- return Some(self.fields.binding.upstream_id);
+ return Some(&self.fields.binding);
}
self.fields
.fallbacks
.iter()
.find(|f| f.binding.route_id == route_id && f.wire_sha256 == wire_sha256)
- .map(|f| f.binding.upstream_id)
+ .map(|f| &f.binding)
+ }
+
+ pub(crate) fn dispatched_channel(&self, route_id: &str, wire_sha256: &str) -> Option {
+ self.dispatched_binding(route_id, wire_sha256)
+ .map(|binding| binding.upstream_id)
}
}
@@ -1249,6 +1278,7 @@ mod tests {
model_snapshot: "synthetic-model".into(),
generation_url: "https://synthetic.invalid/v1/responses".into(),
credential_ref: crate::routing::CredentialRef { id: 3, revision: 4 },
+ credential_selection: None,
payload_policy_sha256: "02".repeat(32),
provider_contract_revision: "synthetic-v1".into(),
projection_revision: "context_max_v1".into(),
@@ -1271,6 +1301,140 @@ mod tests {
.unwrap()
}
+ /// A test-only copy of D's binding shape, taken from commit 15bc9d98.
+ /// This checks the source-level serde boundary, not execution by a D binary.
+ #[derive(Debug, Serialize, Deserialize)]
+ #[serde(deny_unknown_fields)]
+ struct FrozenDBinding {
+ route_id: String,
+ target_id: u64,
+ upstream_id: u64,
+ protocol: String,
+ model_snapshot: String,
+ generation_url: String,
+ credential_ref: crate::routing::CredentialRef,
+ payload_policy_sha256: String,
+ provider_contract_revision: String,
+ projection_revision: String,
+ quote_version: u64,
+ }
+
+ #[test]
+ fn key_snapshot_fixed_golden_preserves_old_bytes_and_exposes_d_reader_boundary() {
+ let golden: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../tests/fixtures/key_snapshot_contract_v1_golden.json"
+ ))
+ .unwrap();
+ assert_eq!(golden["provenance"]["executed_by_real_d_binary"], false);
+ let legacy = prepared();
+ for (name, selection) in [
+ ("legacy", None),
+ (
+ "selected",
+ Some(CredentialSelection {
+ is_multi_key: true,
+ multi_key_index: 1,
+ }),
+ ),
+ ] {
+ let case = &golden[name];
+ let expected_bytes = case["prepared_bytes"].as_str().unwrap().as_bytes();
+ let expected_digest = case["prepared_sha256"].as_str().unwrap();
+ let mut proof = legacy.clone();
+ proof.fields.binding.credential_selection = selection;
+ assert_eq!(serde_json::to_vec(&proof.fields).unwrap(), expected_bytes);
+ assert_eq!(digest(expected_bytes), expected_digest);
+ proof.prepared_sha256 = expected_digest.to_owned();
+ proof.validate().unwrap();
+
+ let contract_bytes = case["contract_bytes"].as_str().unwrap().as_bytes();
+ let wire: serde_json::Value = serde_json::from_slice(contract_bytes).unwrap();
+ let restored = ReservationContract::from_value(wire.clone()).unwrap();
+ assert_eq!(restored.fields, proof.fields);
+ assert_eq!(restored.prepared_sha256, expected_digest);
+ assert_eq!(
+ serde_json::to_vec(&restored.to_value().unwrap()).unwrap(),
+ contract_bytes
+ );
+
+ let d_binding = serde_json::from_value::(wire["binding"].clone());
+ if selection.is_none() {
+ assert_eq!(legacy.digest(), expected_digest);
+ assert_eq!(
+ serde_json::to_value(d_binding.unwrap()).unwrap(),
+ wire["binding"]
+ );
+ } else {
+ assert!(
+ d_binding
+ .unwrap_err()
+ .to_string()
+ .contains("unknown field `credential_selection`"),
+ "D rejects a new binding even though the database schema did not change"
+ );
+ let mut stripped = proof.clone();
+ stripped.fields.binding.credential_selection = None;
+ assert!(
+ stripped.validate().is_err(),
+ "removing the field for D changes the accepted digest"
+ );
+ let mut wrong_credential = proof;
+ wrong_credential.fields.binding.credential_ref.revision += 1;
+ assert!(
+ wrong_credential.validate().is_err(),
+ "the chosen key revision and diagnostic ordinal remain bound together"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn key_snapshot_preserves_old_wire_and_binds_new_metadata_to_digest() {
+ let legacy = prepared();
+ let mut wire = serde_json::to_value(&legacy.fields).unwrap();
+ assert!(wire["binding"].get("credential_selection").is_none());
+ wire["prepared_sha256"] = legacy.digest().into();
+ wire["admission_spec_sha256"] = "04".repeat(32).into();
+ wire["frozen_price_sha256"] = "05".repeat(32).into();
+ let old = ReservationContract::from_value(wire.clone()).unwrap();
+ assert_eq!(old.fields.binding.credential_selection, None);
+ assert_eq!(old.to_value().unwrap(), wire);
+
+ let mut current = legacy.clone();
+ current.fields.binding.credential_selection = Some(CredentialSelection {
+ is_multi_key: true,
+ multi_key_index: 1,
+ });
+ assert!(current.validate().is_err());
+ current.prepared_sha256 = typed_digest(¤t.fields).unwrap();
+ current.validate().unwrap();
+ assert_ne!(current.digest(), legacy.digest());
+
+ current
+ .fields
+ .binding
+ .credential_selection
+ .as_mut()
+ .unwrap()
+ .multi_key_index = 0;
+ assert!(
+ current.validate().is_err(),
+ "ordinal is part of the accepted contract"
+ );
+ current.prepared_sha256 = typed_digest(¤t.fields).unwrap();
+ current.validate().unwrap();
+
+ current.fields.binding.credential_selection = Some(CredentialSelection {
+ is_multi_key: false,
+ multi_key_index: 1,
+ });
+ current.prepared_sha256 = typed_digest(¤t.fields).unwrap();
+ assert!(
+ current.validate().is_err(),
+ "a single key cannot have a nonzero ordinal"
+ );
+ }
+
#[test]
fn legacy_amounts_bind_to_prepared_receipt_without_changing_native_wire() {
let native = prepared();
diff --git a/services/core/src/billing/charging/legacy_wallet_tests.rs b/services/core/src/billing/charging/legacy_wallet_tests.rs
index e52322d53..0bdb98a37 100644
--- a/services/core/src/billing/charging/legacy_wallet_tests.rs
+++ b/services/core/src/billing/charging/legacy_wallet_tests.rs
@@ -41,6 +41,7 @@ fn prepared_legacy(id: &str, max: i64) -> (Request, ReservationBasis, PreparedRe
model_snapshot: spec.price.model.clone(),
generation_url: "https://example.test/v1/responses".into(),
credential_ref: crate::routing::CredentialRef { id: 1, revision: 1 },
+ credential_selection: None,
payload_policy_sha256: "02".repeat(32),
provider_contract_revision: "responses-v1".into(),
projection_revision: "responses-v1".into(),
diff --git a/services/core/src/channel_http/control/balance.rs b/services/core/src/channel_http/control/balance.rs
index 8315495ca..0e7511457 100644
--- a/services/core/src/channel_http/control/balance.rs
+++ b/services/core/src/channel_http/control/balance.rs
@@ -23,6 +23,8 @@ pub(crate) struct BalanceProbe {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub openai_subscription: Option,
#[serde(default, skip_serializing_if = "Option::is_none")]
+ pub sub2api_usage: Option,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub auth: Option,
}
@@ -66,6 +68,18 @@ impl BalanceProbe {
|| self.require_all.is_some()
|| self.cny_per_usd.is_some()
|| self.deepseek_currency_array == Some(true)
+ || self.sub2api_usage == Some(true)
+ || self.auth.is_some()))
+ || (self.sub2api_usage == Some(true)
+ && (self.path != "/v1/usage"
+ || self.json_pointer != "/remaining"
+ || self.unit_label.as_deref() != Some("USD")
+ || self.subtract_json_pointer.is_some()
+ || self.require.is_some()
+ || self.require_all.is_some()
+ || self.cny_per_usd.is_some()
+ || self.deepseek_currency_array == Some(true)
+ || self.openai_subscription == Some(true)
|| self.auth.is_some()))
|| (self.deepseek_currency_array == Some(true)
&& (self.json_pointer != "/balance_infos"
@@ -228,6 +242,7 @@ pub(in crate::channel_http) async fn configure(
cny_per_usd: probe.cny_per_usd.as_deref(),
deepseek_currency_array: probe.deepseek_currency_array == Some(true),
openai_subscription: probe.openai_subscription == Some(true),
+ sub2api_usage: probe.sub2api_usage == Some(true),
unit_label: probe.unit_label.as_deref(),
api_key_auth: matches!(probe.auth, Some(BalanceAuth::ApiKey)),
},
@@ -377,6 +392,7 @@ async fn observe(
cny_per_usd: probe.cny_per_usd.as_deref(),
deepseek_currency_array: probe.deepseek_currency_array == Some(true),
openai_subscription: probe.openai_subscription == Some(true),
+ sub2api_usage: probe.sub2api_usage == Some(true),
unit_label: probe.unit_label.as_deref(),
api_key_auth: matches!(probe.auth, Some(BalanceAuth::ApiKey)),
},
diff --git a/services/core/src/channel_http/control/balance/legacy.rs b/services/core/src/channel_http/control/balance/legacy.rs
index a870735e5..ee10c0d2b 100644
--- a/services/core/src/channel_http/control/balance/legacy.rs
+++ b/services/core/src/channel_http/control/balance/legacy.rs
@@ -43,9 +43,11 @@ pub(super) fn resolve(
return Ok(None);
};
legacy.validate()?;
- // The existing transport binds authentication to protocol. These two use
- // different headers; do not accidentally send them for a Bearer adapter.
- if matches!(protocol, Protocol::AnthropicMessages | Protocol::Gemini) {
+ // Keep the protocol-default adapters restricted. Sub2API has an explicit
+ // Bearer override independent of the model protocol.
+ if matches!(protocol, Protocol::AnthropicMessages | Protocol::Gemini)
+ && legacy.channel_type != 59
+ {
return Ok(None);
}
let (path, pointer, unit) = match legacy.channel_type {
@@ -74,6 +76,7 @@ pub(super) fn resolve(
// The frozen adapter does not establish a currency for this scalar.
40 => ("/v1/user/info", "/data/totalBalance", None),
43 => ("/user/balance", "/balance_infos", Some("USD")),
+ 59 => ("/v1/usage", "/remaining", Some("USD")),
_ => return Ok(None),
};
let mut probe = BalanceProbe {
@@ -86,6 +89,7 @@ pub(super) fn resolve(
cny_per_usd: legacy.cny_per_usd.clone(),
deepseek_currency_array: None,
openai_subscription: None,
+ sub2api_usage: None,
auth: None,
};
let requirement = |pointer: &str, equals| BalanceRequirement {
@@ -107,6 +111,7 @@ pub(super) fn resolve(
}
40 => probe.require = Some(requirement("/code", json!(20000))),
43 => probe.deepseek_currency_array = Some(true),
+ 59 => probe.sub2api_usage = Some(true),
_ => {}
}
probe.validate()?;
diff --git a/services/core/src/channel_http/control/balance/legacy/tests.rs b/services/core/src/channel_http/control/balance/legacy/tests.rs
index 4c1ad6a04..141c15973 100644
--- a/services/core/src/channel_http/control/balance/legacy/tests.rs
+++ b/services/core/src/channel_http/control/balance/legacy/tests.rs
@@ -1,5 +1,42 @@
use super::*;
+#[test]
+fn sub2api_plan_has_a_fixed_usd_contract_for_all_model_protocols() {
+ for protocol in [
+ Protocol::OpenAiChat,
+ Protocol::AnthropicMessages,
+ Protocol::Gemini,
+ ] {
+ let probe = resolve(None, Some(&config(59, None)), protocol)
+ .unwrap()
+ .unwrap();
+ assert_eq!(probe.path, "/v1/usage");
+ assert_eq!(probe.json_pointer, "/remaining");
+ assert_eq!(probe.unit_label.as_deref(), Some("USD"));
+ assert_eq!(probe.sub2api_usage, Some(true));
+ assert!(probe.validate().is_ok());
+ }
+ let base = serde_json::to_value(plan(59, None)).unwrap();
+ for (field, value) in [
+ ("path", json!("/other")),
+ ("json_pointer", json!("/balance")),
+ ("unit_label", json!("CNY")),
+ ("subtract_json_pointer", json!("/used")),
+ ("require", json!({"json_pointer":"/ok","equals":true})),
+ ("require_all", json!([{"json_pointer":"/ok","equals":true}])),
+ ("cny_per_usd", json!("7")),
+ ("deepseek_currency_array", json!(true)),
+ ("openai_subscription", json!(true)),
+ ("auth", json!("api_key")),
+ ] {
+ let mut changed = base.clone();
+ changed[field] = value;
+ let probe: BalanceProbe = serde_json::from_value(changed).unwrap();
+ assert!(probe.validate().is_err(), "{field}");
+ }
+ assert!(config(59, Some("7")).validate().is_err());
+}
+
fn config(channel_type: u32, rate: Option<&str>) -> LegacyBalance {
LegacyBalance {
channel_type,
@@ -58,6 +95,7 @@ fn legacy_balance_exact_mapping() {
),
(40, "/v1/user/info", "/data/totalBalance", None),
(43, "/user/balance", "/balance_infos", Some("USD")),
+ (59, "/v1/usage", "/remaining", Some("USD")),
] {
let probe = plan(kind, None);
assert_eq!(
@@ -97,7 +135,7 @@ fn legacy_balance_unknown_types_and_protocols_never_guess() {
let found = resolve(None, Some(&config(kind, None)), Protocol::OpenAiChat).unwrap();
assert_eq!(
found.is_some(),
- matches!(kind, 1 | 8 | 10 | 12 | 13 | 20 | 25 | 40 | 43),
+ matches!(kind, 1 | 8 | 10 | 12 | 13 | 20 | 25 | 40 | 43 | 59),
"type {kind}"
);
}
@@ -116,7 +154,7 @@ fn legacy_balance_manual_override_is_exact_and_not_fallback_on_error() {
let mut manual = plan(20, None);
manual.path = "/operator/balance".into();
manual.unit_label = Some("operator-unit".into());
- for kind in [0, 1, 25, 43, 61] {
+ for kind in [0, 1, 25, 43, 59, 61] {
assert_eq!(
resolve(
Some(&manual),
diff --git a/services/core/src/channel_http/control/balance/sub2api_tests.rs b/services/core/src/channel_http/control/balance/sub2api_tests.rs
new file mode 100644
index 000000000..048c0fc24
--- /dev/null
+++ b/services/core/src/channel_http/control/balance/sub2api_tests.rs
@@ -0,0 +1,141 @@
+//! Real GET /v1/usage and durable observation coverage, with a synthetic provider.
+use super::*;
+
+#[sqlx::test(migrations = false)]
+async fn sub2api_usage_wallet_quota_and_failed_refresh_preserve_observations(pool: PgPool) {
+ crate::core_schema::init(&pool).await.unwrap();
+ let identity = IdentityStore::from_pool(pool.clone());
+ let admin = identity.bootstrap_user(8, 6).await.unwrap();
+ let ordinary = identity.bootstrap_user(7, 1).await.unwrap();
+ let wallet = include_str!("../../../../tests/fixtures/sub2api_wallet_usage.json");
+ let quota = include_str!("../../../../tests/fixtures/sub2api_quota_usage.json");
+ let state = Arc::new(RwLock::new((StatusCode::OK, wallet.to_owned())));
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let endpoint = format!("http://{}", listener.local_addr().unwrap());
+ let upstream = Router::new()
+ .route(
+ "/v1/usage",
+ axum::routing::get(
+ |axum::extract::State(state): axum::extract::State<
+ Arc>,
+ >,
+ headers: axum::http::HeaderMap,
+ uri: axum::http::Uri| async move {
+ assert_eq!(headers["authorization"], "Bearer synthetic-channel-only");
+ assert!(!headers.contains_key("x-api-key"));
+ assert!(!headers.contains_key("x-goog-api-key"));
+ assert!(!headers.contains_key("api-key"));
+ assert!(uri.query().is_none());
+ let (status, body) = state.read().await.clone();
+ (status, [(header::CONTENT_TYPE, "application/json")], body)
+ },
+ ),
+ )
+ .with_state(state.clone());
+ let server = tokio::spawn(async move { axum::serve(listener, upstream).await.unwrap() });
+ let role = runtime::RuntimeRole::create(&pool).await;
+ role.optional("core_charging").await;
+ role.optional("core_model").await;
+ sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
+ "GRANT EXECUTE ON FUNCTION public.routing_control_balance_lock() TO {}",
+ role.name
+ )))
+ .execute(&pool)
+ .await
+ .unwrap();
+ // Model traffic uses Anthropic auth; the balance endpoint still requires Bearer.
+ let gateway = || {
+ gateway_for_protocol(
+ &role.pool,
+ Some(&endpoint),
+ None,
+ crate::routing::Protocol::AnthropicMessages,
+ )
+ .with_channel_secret_key(&[83; 32])
+ .unwrap()
+ };
+ let manager = ManagedChannels::recover(role.pool.clone(), gateway())
+ .await
+ .unwrap();
+ let app = managed_router(role.pool.clone(), manager);
+ let (status, configured) = request(
+ app.clone(),
+ "PUT",
+ CONFIG,
+ &admin.secret,
+ json!({"expected_version":{"routing":1,"pricing":1},"probe":null,"legacy":{"channel_type":59}}),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{configured}");
+ assert_eq!(configured["data"]["legacy"]["channel_type"], 59);
+ // Recovery must retain the selected adapter without turning it into a scalar pointer.
+ let manager = ManagedChannels::recover(role.pool.clone(), gateway())
+ .await
+ .unwrap();
+ let app = managed_router(role.pool.clone(), manager);
+ assert_eq!(
+ request(app.clone(), "GET", BALANCE, &ordinary.secret, Value::Null)
+ .await
+ .0,
+ StatusCode::FORBIDDEN
+ );
+ for (body, expected) in [(wallet, "42.5"), (quota, "986.17194888")] {
+ *state.write().await = (StatusCode::OK, body.to_owned());
+ let (status, result) =
+ request(app.clone(), "GET", BALANCE, &admin.secret, Value::Null).await;
+ assert_eq!(status, StatusCode::OK, "{result}");
+ assert_eq!(result["data"]["balance"], expected);
+ assert_eq!(result["data"]["unit_label"], "USD");
+ assert_eq!(result["data"]["kind"], "provider");
+ assert!(result["data"]["balance_updated_time"].as_i64().unwrap() > 0);
+ assert!(!result.to_string().contains("synthetic-channel-only"));
+ }
+ let original = row(&pool).await;
+ let escaped = "synthetic-channel-only"
+ .chars()
+ .map(|ch| format!("\\u{:04x}", ch as u32))
+ .collect::();
+ let reflected = format!(
+ r#"{{"remaining":99,"unit":"USD","isValid":true,"metadata":{{"private_key":"{escaped}"}}}}"#
+ );
+ for (status, body) in [
+ (StatusCode::OK, "{}".to_owned()),
+ (
+ StatusCode::OK,
+ r#"{"remaining":99,"unit":"USD","isValid":false}"#.to_owned(),
+ ),
+ (
+ StatusCode::OK,
+ r#"{"remaining":99,"unit":"CNY","isValid":true}"#.to_owned(),
+ ),
+ (
+ StatusCode::OK,
+ r#"{"mode":"quota_limited","rate_limits":[{"remaining":9}]}"#.to_owned(),
+ ),
+ (
+ StatusCode::OK,
+ r#"{"remaining":-1,"unit":"USD","subscription":{"daily_limit_usd":null}}"#.to_owned(),
+ ),
+ (StatusCode::OK, reflected),
+ (StatusCode::OK, "{".to_owned()),
+ (StatusCode::BAD_GATEWAY, wallet.to_owned()),
+ (
+ StatusCode::UNAUTHORIZED,
+ "synthetic-channel-only".to_owned(),
+ ),
+ ] {
+ *state.write().await = (status, body);
+ // Native single requests used by the bounded batch and the compatibility
+ // single route must both fail without changing the persisted observation.
+ for path in [BALANCE, "/api/channel/update_balance/1"] {
+ let (status, failure) =
+ request(app.clone(), "GET", path, &admin.secret, Value::Null).await;
+ assert_eq!(status, StatusCode::BAD_GATEWAY, "{failure}");
+ assert!(!failure.to_string().contains("synthetic-channel-only"));
+ assert!(!failure.to_string().contains(&escaped));
+ assert_eq!(row(&pool).await, original);
+ }
+ }
+ server.abort();
+ role.cleanup().await;
+}
diff --git a/services/core/src/channel_http/control/balance/tests.rs b/services/core/src/channel_http/control/balance/tests.rs
index 7cbd00426..b7172f76a 100644
--- a/services/core/src/channel_http/control/balance/tests.rs
+++ b/services/core/src/channel_http/control/balance/tests.rs
@@ -1,6 +1,8 @@
//! Synthetic-provider business acceptance: real loopback HTTP, disposable PG,
//! restricted runtime roles and real router handlers. This is not full TLS proof;
//! published routing stays HTTPS and only the cfg(test) transport is mapped.
+#[path = "sub2api_tests.rs"]
+mod sub2api_tests;
use crate::test_runtime as runtime;
use crate::{
channel_http::{ManagedChannels, managed_router},
@@ -55,11 +57,26 @@ fn gateway_fixture(
pool: &PgPool,
loopback: Option<&str>,
missing_binding: Option,
+) -> ModelGateway {
+ gateway_for_protocol(
+ pool,
+ loopback,
+ missing_binding,
+ crate::routing::Protocol::OpenAiChat,
+ )
+}
+fn gateway_for_protocol(
+ pool: &PgPool,
+ loopback: Option<&str>,
+ missing_binding: Option,
+ protocol: crate::routing::Protocol,
) -> ModelGateway {
let document = fixture();
let mut config = document.routing;
+ config.upstreams[0].protocol = protocol;
let prices = document.pricing;
let mut contexts:Vec=serde_json::from_value(json!([{"upstream_id":1,"upstream_model":"model-a","protocol":"openai_chat","endpoint":"https://provider.example/v1/","max_input_tokens":1000,"max_output_tokens":100,"contract_revision":"synthetic-v1","missing_cached_tokens_is_zero":true,"missing_cache_creation_tokens_is_zero":true}])).unwrap();
+ contexts[0].protocol = protocol;
if let Some(missing_secret) = missing_binding {
config.upstreams[0].enabled = false;
config.routes[0].enabled = false;
diff --git a/services/core/src/model_http/audio/http_tests.rs b/services/core/src/model_http/audio/http_tests.rs
index dcd9e797b..7d6abe25d 100644
--- a/services/core/src/model_http/audio/http_tests.rs
+++ b/services/core/src/model_http/audio/http_tests.rs
@@ -461,6 +461,7 @@ async fn recovery_with_format(pool: PgPool, format: AudioUsageFormat) {
model_snapshot: "synthetic-audio-upstream".into(),
generation_url: format!("{}/chat/completions", supplier.endpoint),
credential_ref: CredentialRef { id: 7, revision: 1 },
+ credential_selection: None,
payload_policy_sha256: "06".repeat(32),
provider_contract_revision: audio.provider_contract_revision.clone(),
projection_revision: if format == AudioUsageFormat::OpenAiChatV2 {
diff --git a/services/core/src/model_http/audio/legacy_journal_tests.rs b/services/core/src/model_http/audio/legacy_journal_tests.rs
index 299d54ba7..ffb2c2361 100644
--- a/services/core/src/model_http/audio/legacy_journal_tests.rs
+++ b/services/core/src/model_http/audio/legacy_journal_tests.rs
@@ -49,6 +49,7 @@ async fn legacy_fixture(pool: PgPool, corrupt: bool) {
model_snapshot: "synthetic-audio-upstream".into(),
generation_url: format!("{}/chat/completions", supplier.endpoint),
credential_ref: CredentialRef { id: 7, revision: 1 },
+ credential_selection: None,
payload_policy_sha256: "06".repeat(32),
provider_contract_revision: audio.provider_contract_revision.clone(),
projection_revision: "audio-chat-stream-raw-v1".into(),
diff --git a/services/core/src/model_http/channel_balance_sub2api.rs b/services/core/src/model_http/channel_balance_sub2api.rs
new file mode 100644
index 000000000..7cdf513ba
--- /dev/null
+++ b/services/core/src/model_http/channel_balance_sub2api.rs
@@ -0,0 +1,98 @@
+//! Sub2API /v1/usage uses USD for wallet and key quota balances.
+//! Contract: Wei-Shaw/sub2api gateway_handler.go (Usage), and
+//! QuantumNous/new-api 63cecab824bad1a421d19950004c309bb2054c09.
+use serde::Deserialize;
+use serde_json::Value;
+
+#[derive(Deserialize)]
+struct Usage {
+ #[serde(default)]
+ remaining: Option,
+ #[serde(default)]
+ balance: Option,
+ #[serde(default, rename = "isValid")]
+ is_valid: Option,
+ unit: String,
+ #[serde(default)]
+ mode: Option,
+ #[serde(default)]
+ quota: Option,
+ #[serde(default)]
+ subscription: Option,
+ #[serde(default)]
+ error: Option,
+}
+
+#[derive(Deserialize)]
+struct Quota {
+ unit: String,
+}
+
+#[derive(Deserialize)]
+struct Subscription {
+ #[serde(default)]
+ daily_limit_usd: Option,
+ #[serde(default)]
+ weekly_limit_usd: Option,
+ #[serde(default)]
+ monthly_limit_usd: Option,
+}
+
+// Inspect decoded strings and object keys, including ignored provider metadata.
+// A credential escaped as JSON must not be accepted as a successful observation.
+fn contains_secret(value: &Value, secret: &str) -> bool {
+ match value {
+ Value::String(text) => text.contains(secret),
+ Value::Array(items) => items.iter().any(|value| contains_secret(value, secret)),
+ Value::Object(fields) => fields
+ .iter()
+ .any(|(key, value)| key.contains(secret) || contains_secret(value, secret)),
+ _ => value.to_string().contains(secret),
+ }
+}
+
+pub(super) fn balance(value: &Value, secret: &str) -> Option {
+ if !value.is_object() || (!secret.is_empty() && contains_secret(value, secret)) {
+ return None;
+ }
+ let usage: Usage = serde_json::from_value(value.clone()).ok()?;
+ if usage.is_valid == Some(false)
+ || usage.error.is_some()
+ || usage.unit != "USD"
+ || usage
+ .mode
+ .as_deref()
+ .is_some_and(|mode| !matches!(mode, "unrestricted" | "quota_limited"))
+ || usage
+ .quota
+ .as_ref()
+ .is_some_and(|quota| quota.unit != "USD")
+ || (usage.mode.as_deref() == Some("quota_limited") && usage.quota.is_none())
+ {
+ return None;
+ }
+ // Both official modes publish remaining. Older wallet responses use balance.
+ // Missing, malformed or unlimited amounts never become a synthetic zero.
+ let amount = if usage.quota.is_some() {
+ usage.remaining?
+ } else {
+ usage.remaining.or(usage.balance)?
+ };
+ if !amount.is_finite() || (usage.quota.is_some() && amount < 0.0) {
+ return None;
+ }
+ if let Some(subscription) = usage.subscription {
+ let finite_limit = [
+ subscription.daily_limit_usd,
+ subscription.weekly_limit_usd,
+ subscription.monthly_limit_usd,
+ ]
+ .into_iter()
+ .flatten()
+ .any(|limit| limit.is_finite() && limit > 0.0);
+ if !finite_limit || amount < 0.0 {
+ return None;
+ }
+ }
+ Some(amount)
+}
diff --git a/services/core/src/model_http/channel_balance_sub2api_tests.rs b/services/core/src/model_http/channel_balance_sub2api_tests.rs
new file mode 100644
index 000000000..40467c552
--- /dev/null
+++ b/services/core/src/model_http/channel_balance_sub2api_tests.rs
@@ -0,0 +1,106 @@
+use super::*;
+
+const SECRET: &str = "synthetic-sub2api-only";
+
+fn read(body: &[u8]) -> Result {
+ parse_balance(
+ body,
+ "/remaining",
+ None,
+ &[],
+ None,
+ BalanceFormat::Sub2Api,
+ SECRET,
+ )
+}
+
+#[test]
+fn sub2api_wallet_and_quota_fixtures_keep_usd_amounts() {
+ assert_eq!(
+ read(include_bytes!(
+ "../../tests/fixtures/sub2api_wallet_usage.json"
+ ))
+ .unwrap(),
+ 42.5
+ );
+ assert_eq!(
+ read(include_bytes!(
+ "../../tests/fixtures/sub2api_quota_usage.json"
+ ))
+ .unwrap(),
+ 986.17194888
+ );
+ for (body, expected) in [
+ (
+ serde_json::json!({"remaining":0,"balance":20,"unit":"USD","isValid":true}),
+ 0.0,
+ ),
+ (
+ serde_json::json!({"balance":42.5,"unit":"USD","isValid":true}),
+ 42.5,
+ ),
+ (
+ serde_json::json!({"remaining":-1,"balance":-1,"unit":"USD","isValid":true,"mode":"unrestricted"}),
+ -1.0,
+ ),
+ (
+ serde_json::json!({"remaining":0,"unit":"USD","isValid":true,"mode":"quota_limited","quota":{"limit":10,"used":10,"remaining":0,"unit":"USD"}}),
+ 0.0,
+ ),
+ (
+ serde_json::json!({"remaining":2,"unit":"USD","isValid":true,"subscription":{"daily_limit_usd":10}}),
+ 2.0,
+ ),
+ ] {
+ assert_eq!(read(body.to_string().as_bytes()).unwrap(), expected);
+ }
+}
+
+#[test]
+fn sub2api_unknown_invalid_and_unlimited_results_are_unavailable() {
+ for body in [
+ serde_json::json!({}),
+ serde_json::json!({"balance":null,"remaining":null,"unit":"USD","isValid":true}),
+ serde_json::json!({"remaining":"12.5","unit":"USD","isValid":true}),
+ serde_json::json!({"remaining":true,"unit":"USD","isValid":true}),
+ serde_json::json!({"remaining":5,"unit":"USD","isValid":false}),
+ serde_json::json!({"remaining":5,"unit":"USD","isValid":"true"}),
+ serde_json::json!({"remaining":5,"unit":"USD","error":{"message":"unavailable"}}),
+ serde_json::json!({"remaining":5,"unit":"CNY","isValid":true}),
+ serde_json::json!({"remaining":5,"isValid":true}),
+ serde_json::json!({"remaining":5,"unit":"USD","mode":"unknown"}),
+ serde_json::json!({"mode":"quota_limited","unit":"USD","isValid":true,"rate_limits":[{"window":"5h","remaining":5}]}),
+ serde_json::json!({"remaining":5,"unit":"USD","mode":"quota_limited"}),
+ serde_json::json!({"balance":5,"unit":"USD","mode":"quota_limited","quota":{"unit":"USD"}}),
+ serde_json::json!({"remaining":5,"unit":"USD","quota":{"unit":"CNY"}}),
+ serde_json::json!({"remaining":-1,"unit":"USD","quota":{"unit":"USD"}}),
+ serde_json::json!({"remaining":-1,"unit":"USD","subscription":{"daily_limit_usd":null,"weekly_limit_usd":null,"monthly_limit_usd":null}}),
+ serde_json::json!({"remaining":-1,"unit":"USD","subscription":{"daily_limit_usd":0}}),
+ ] {
+ assert!(read(body.to_string().as_bytes()).is_err(), "{body}");
+ }
+ for body in [
+ b"{".as_slice(),
+ br#"{"remaining":1e999,"unit":"USD"}"#,
+ br#"[]"#,
+ ] {
+ assert!(read(body).is_err());
+ }
+}
+
+#[test]
+fn sub2api_rejects_reflected_credentials_in_ignored_and_escaped_fields() {
+ let escaped = SECRET
+ .chars()
+ .map(|ch| format!("\\u{:04x}", ch as u32))
+ .collect::();
+ for field in [
+ format!(r#""metadata":{{"private_key":"{SECRET}"}}"#),
+ format!(r#""metadata":{{"private_key":"{escaped}"}}"#),
+ format!(r#""{escaped}":"ignored""#),
+ format!(r#""metadata":["{escaped}"]"#),
+ ] {
+ let body = format!(r#"{{"remaining":42.5,"unit":"USD","isValid":true,{field}}}"#);
+ assert!(read(body.as_bytes()).is_err());
+ }
+}
diff --git a/services/core/src/model_http/channel_operations.rs b/services/core/src/model_http/channel_operations.rs
index 26b37e12e..a2c66eafd 100644
--- a/services/core/src/model_http/channel_operations.rs
+++ b/services/core/src/model_http/channel_operations.rs
@@ -557,6 +557,12 @@ impl ModelGateway {
}
}
+#[cfg(test)]
+#[path = "channel_balance_sub2api_tests.rs"]
+mod channel_balance_sub2api_tests;
+#[path = "channel_balance_sub2api.rs"]
+mod sub2api;
+
/// A frozen provider GET. The credential never leaves the gateway or enters a URL.
pub(crate) struct BalanceRequest {
url: reqwest::Url,
@@ -568,6 +574,7 @@ pub(crate) struct BalanceRequest {
cny_per_usd: Option,
deepseek_currency_array: bool,
openai_subscription: bool,
+ sub2api_usage: bool,
api_key_auth: bool,
}
@@ -679,13 +686,19 @@ fn deepseek_balance(value: &Value, rate: Option, secret: &str) -> Option= 0.0 && !result.to_string().contains(secret)).then_some(result)
}
+enum BalanceFormat {
+ Scalar,
+ DeepSeek,
+ Sub2Api,
+}
+
fn parse_balance(
bytes: &[u8],
pointer: &str,
subtract_pointer: Option<&str>,
requirements: &[(String, Value)],
cny_per_usd: Option,
- deepseek_currency_array: bool,
+ format: BalanceFormat,
secret: &str,
) -> Result {
// Do not return even a numeric-looking credential reflected by a provider.
@@ -699,8 +712,15 @@ fn parse_balance(
{
return Err(RelayError::RouteUnavailable);
}
- if deepseek_currency_array {
- return deepseek_balance(&value, cny_per_usd, secret).ok_or(RelayError::RouteUnavailable);
+ match format {
+ BalanceFormat::Sub2Api => {
+ return sub2api::balance(&value, secret).ok_or(RelayError::RouteUnavailable);
+ }
+ BalanceFormat::DeepSeek => {
+ return deepseek_balance(&value, cny_per_usd, secret)
+ .ok_or(RelayError::RouteUnavailable);
+ }
+ BalanceFormat::Scalar => {}
}
let number = |pointer: &str| -> Result {
let selected = value.pointer(pointer).ok_or(RelayError::RouteUnavailable)?;
@@ -734,6 +754,7 @@ pub(crate) struct BalanceProbeInput<'a> {
pub(crate) cny_per_usd: Option<&'a str>,
pub(crate) deepseek_currency_array: bool,
pub(crate) openai_subscription: bool,
+ pub(crate) sub2api_usage: bool,
pub(crate) unit_label: Option<&'a str>,
pub(crate) api_key_auth: bool,
}
@@ -751,6 +772,7 @@ impl ModelGateway {
cny_per_usd,
deepseek_currency_array,
openai_subscription,
+ sub2api_usage,
unit_label,
api_key_auth,
} = input;
@@ -800,6 +822,7 @@ impl ModelGateway {
.map_err(|_| RelayError::RouteUnavailable)?,
deepseek_currency_array,
openai_subscription,
+ sub2api_usage,
api_key_auth,
})
}
@@ -851,7 +874,7 @@ impl ModelGateway {
.get(url)
.header(header::ACCEPT, "application/json");
let get = match (
- request.openai_subscription,
+ request.openai_subscription || request.sub2api_usage,
request.api_key_auth,
request.protocol,
) {
@@ -929,7 +952,13 @@ impl ModelGateway {
request.subtract_pointer.as_deref(),
&request.requirements,
request.cny_per_usd,
- request.deepseek_currency_array,
+ if request.sub2api_usage {
+ BalanceFormat::Sub2Api
+ } else if request.deepseek_currency_array {
+ BalanceFormat::DeepSeek
+ } else {
+ BalanceFormat::Scalar
+ },
&request.credential,
)
})
diff --git a/services/core/src/model_http/key_snapshot_tests.rs b/services/core/src/model_http/key_snapshot_tests.rs
new file mode 100644
index 000000000..ca0618d10
--- /dev/null
+++ b/services/core/src/model_http/key_snapshot_tests.rs
@@ -0,0 +1,284 @@
+//! Real native admission, durable charging and authorized log projections.
+//! Usage is synthetic test evidence. No provider, payment or production DB is used.
+use super::*;
+use axum::{body::Body, http::StatusCode};
+use serde_json::Value;
+use tower::ServiceExt;
+
+async fn read_log(pool: &PgPool, path: &str, secret: &str) -> (StatusCode, Value) {
+ let response = crate::usage::router(crate::usage::UsageStore::new(pool.clone()))
+ .oneshot(
+ axum::http::Request::get(path)
+ .header("authorization", format!("Bearer {secret}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let status = response.status();
+ let bytes = axum::body::to_bytes(response.into_body(), 1 << 20)
+ .await
+ .unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap())
+}
+
+async fn admin_snapshot(pool: &PgPool, id: &str, secret: &str) -> Value {
+ let (status, response) = read_log(
+ pool,
+ &format!("/core/v1/usage/admin/request?request_id={id}"),
+ secret,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{response}");
+ let encoded = response.to_string();
+ for forbidden in [
+ "credential_ref",
+ "credential_selection",
+ "generation_url",
+ "synthetic-selected-bound-provider-key",
+ "synthetic-secondary-provider-key",
+ ] {
+ assert!(!encoded.contains(forbidden), "{forbidden}");
+ }
+ let other: Value = serde_json::from_str(response["data"]["other"].as_str().unwrap()).unwrap();
+ other["admin_info"].clone()
+}
+
+async fn persisted_contract(pool: &PgPool, id: &str) -> Value {
+ sqlx::query_scalar(
+ "SELECT detail FROM core_charging.usage_events WHERE request_id=$1 AND event_id='reservation-contract:v1'",
+ ).bind(id).fetch_one(pool).await.unwrap()
+}
+
+fn publish_pool(g: &ModelGateway, references: Vec) {
+ let mut release = g.bridge.routing.catalog_document().unwrap();
+ release.routing.version += 1;
+ release.routing.upstreams[0].credential = references[0];
+ g.bridge
+ .routing
+ .publish_with_credential_pools(
+ g.bridge.routing.version().unwrap(),
+ release.routing,
+ Arc::new(PriceSnapshot::compile(release.pricing).unwrap()),
+ &BTreeMap::from([(1, references)]),
+ )
+ .unwrap();
+}
+
+async fn accept(g: &ModelGateway, f: &Fixture, id: &str) -> [u8; 32] {
+ let (context, request) = admit(g, f, id, "small-model", 16).await;
+ let route = g.bridge.select(&context, &request).await.unwrap();
+ let body = request.upstream_body(&route).unwrap();
+ g.bridge
+ .reserve_prepared(&context, &route, &request, &body, None)
+ .await
+ .unwrap();
+ let worker = g.bridge.active.lock().unwrap()[id].worker;
+ g.bridge
+ .charging
+ .record_route_dispatch(id, &worker, 1, &route.id, "allowed", &digest(&body))
+ .await
+ .unwrap();
+ worker
+}
+
+#[sqlx::test(migrations = false)]
+async fn key_snapshot_survives_settlement_refund_and_is_admin_only(pool: PgPool) {
+ let f = fixture(pool, 10_000_000).await;
+ let g = gateway(&f, EXTERNAL_BASE, contexts(SMALL_INPUT));
+ let primary = CredentialRef { id: 7, revision: 1 };
+ let secondary = CredentialRef { id: 8, revision: 2 };
+ g.bridge
+ .credentials
+ .append(vec![UpstreamCredential {
+ reference: secondary,
+ secret: "synthetic-secondary-provider-key".into(),
+ }])
+ .unwrap();
+ g.bridge
+ .routing
+ .install_credential_pools(
+ g.bridge.routing.version().unwrap(),
+ &BTreeMap::from([(1, vec![primary, secondary])]),
+ )
+ .unwrap();
+ // Advance the real pool once so admission selects ordinal 1.
+ let _first = g
+ .bridge
+ .routing
+ .route(routing::RouteRequest {
+ model: "small-model",
+ group: "allowed",
+ speed: None,
+ protocol: Protocol::OpenAiChat,
+ replay: routing::ReplayPermission::Denied,
+ })
+ .unwrap();
+ let id = "key-snapshot-multi";
+ let worker = accept(&g, &f, id).await;
+ let frozen = persisted_contract(&f.pool, id).await;
+ assert_eq!(
+ frozen["binding"]["credential_ref"],
+ json!({"id":8,"revision":2})
+ );
+ assert_eq!(
+ frozen["binding"]["credential_selection"],
+ json!({"is_multi_key":true,"multi_key_index":1})
+ );
+
+ publish_pool(&g, vec![secondary, primary]);
+ let actual = charging::Usage {
+ input: 10,
+ cached: 0,
+ output: 1,
+ ..Default::default()
+ };
+ let settled = g
+ .bridge
+ .charging
+ .settle(id, &worker, actual, charging::Outcome::Completed)
+ .await
+ .unwrap();
+ assert_eq!((settled.state.as_str(), settled.settled), ("settled", 10));
+ assert!(
+ settled.reserved > settled.settled,
+ "the unused reservation difference was released"
+ );
+ let admin = IdentityStore::from_pool(f.pool.clone())
+ .bootstrap_user(9, 5)
+ .await
+ .unwrap();
+ let terminal = admin_snapshot(&f.pool, id, &admin.secret).await;
+ assert_eq!(terminal["key_snapshot_status"], "recorded");
+ assert_eq!(terminal["is_multi_key"], true);
+ assert_eq!(terminal["multi_key_index"], 1);
+ assert_eq!(terminal["route_attempts"][0]["multi_key_index"], 1);
+
+ publish_pool(&g, vec![primary]);
+ let refunded = g
+ .bridge
+ .charging
+ .refund(
+ id,
+ "synthetic-refund",
+ 4,
+ "isolated key snapshot regression",
+ )
+ .await
+ .unwrap();
+ assert_eq!(refunded.refunded, 4);
+ assert_eq!(admin_snapshot(&f.pool, id, &admin.secret).await, terminal);
+ assert_eq!(persisted_contract(&f.pool, id).await, frozen);
+ assert_balance(&f, 10_000_000 - 6, 0).await;
+
+ for path in [
+ format!("/core/v1/usage/self/request?request_id={id}"),
+ format!("/api/log/self?request_id={id}"),
+ ] {
+ let (status, response) = read_log(&f.pool, &path, &f.session).await;
+ assert_eq!(status, StatusCode::OK, "{response}");
+ let encoded = response.to_string();
+ for forbidden in [
+ "admin_info",
+ "route_attempts",
+ "credential_ref",
+ "credential_selection",
+ "is_multi_key",
+ "multi_key_index",
+ "key_snapshot_status",
+ ] {
+ assert!(!encoded.contains(forbidden), "{forbidden}");
+ }
+ }
+ assert_eq!(
+ read_log(
+ &f.pool,
+ &format!("/core/v1/usage/admin/request?request_id={id}"),
+ &f.session
+ )
+ .await
+ .0,
+ StatusCode::FORBIDDEN,
+ );
+
+ let single_id = "key-snapshot-single";
+ let single_worker = accept(&g, &f, single_id).await;
+ g.bridge
+ .charging
+ .settle(
+ single_id,
+ &single_worker,
+ actual,
+ charging::Outcome::Completed,
+ )
+ .await
+ .unwrap();
+ let single = admin_snapshot(&f.pool, single_id, &admin.secret).await;
+ assert_eq!(single["key_snapshot_status"], "recorded");
+ assert_eq!(single["is_multi_key"], false);
+ assert_eq!(single["multi_key_index"], 0);
+}
+
+#[sqlx::test(migrations = false)]
+async fn key_snapshot_historical_contract_remains_unknown_after_refund(pool: PgPool) {
+ let f = fixture(pool, 1000).await;
+ let charging = charging(&f);
+ let id = "key-snapshot-historical";
+ let wire = b"synthetic-historical-wire";
+ let (spec, basis, proof) = preparation(id, 24, 8, price(), wire);
+ reserve(&charging, &f.key, &spec, basis, &proof)
+ .await
+ .unwrap();
+ charging.start(id, &WORKER).await.unwrap();
+ charging
+ .record_route_dispatch(
+ id,
+ &WORKER,
+ 1,
+ "synthetic-prepared-route",
+ "allowed",
+ &digest(wire),
+ )
+ .await
+ .unwrap();
+ charging
+ .settle(
+ id,
+ &WORKER,
+ charging::Usage {
+ input: 10,
+ cached: 0,
+ output: 2,
+ ..Default::default()
+ },
+ charging::Outcome::Completed,
+ )
+ .await
+ .unwrap();
+ let frozen = persisted_contract(&f.pool, id).await;
+ assert!(frozen["binding"].get("credential_selection").is_none());
+ let admin = IdentityStore::from_pool(f.pool.clone())
+ .bootstrap_user(9, 5)
+ .await
+ .unwrap();
+ let terminal = admin_snapshot(&f.pool, id, &admin.secret).await;
+ assert_eq!(terminal["key_snapshot_status"], "unknown");
+ assert!(terminal["is_multi_key"].is_null());
+ assert!(terminal["multi_key_index"].is_null());
+ assert_eq!(
+ terminal["route_attempts"][0]["key_snapshot_status"],
+ "unknown"
+ );
+ charging
+ .refund(
+ id,
+ "synthetic-old-refund",
+ 4,
+ "isolated historical regression",
+ )
+ .await
+ .unwrap();
+ assert_eq!(admin_snapshot(&f.pool, id, &admin.secret).await, terminal);
+ assert_eq!(persisted_contract(&f.pool, id).await, frozen);
+ assert_balance(&f, 992, 0).await;
+}
diff --git a/services/core/src/model_http/prepared_financial_tests.rs b/services/core/src/model_http/prepared_financial_tests.rs
index 9f210e177..908973564 100644
--- a/services/core/src/model_http/prepared_financial_tests.rs
+++ b/services/core/src/model_http/prepared_financial_tests.rs
@@ -57,6 +57,7 @@ fn preparation(
model_snapshot: "synthetic-model-2026-10-01".into(),
generation_url: "https://synthetic.invalid/v1/responses".into(),
credential_ref: CredentialRef { id: 7, revision: 1 },
+ credential_selection: None,
payload_policy_sha256: digest(b"adapt"),
provider_contract_revision: "synthetic-financial-fixture-v1".into(),
projection_revision: "context-max-v1".into(),
@@ -1276,3 +1277,6 @@ async fn prepared_contract_damaged_live_proof_keeps_raw_terminal_audit_without_c
}
assert_balance(&f, 936, 64).await;
}
+
+#[path = "key_snapshot_tests.rs"]
+mod key_snapshot_tests;
diff --git a/services/core/src/model_http/route_failover_tests.rs b/services/core/src/model_http/route_failover_tests.rs
index ca53a2adc..d009250d5 100644
--- a/services/core/src/model_http/route_failover_tests.rs
+++ b/services/core/src/model_http/route_failover_tests.rs
@@ -360,6 +360,186 @@ async fn route_failover_pg_safe_failures_keep_one_frozen_bill(pool: PgPool) {
assert_balance(&f, 9_999_996, 0).await;
}
+#[sqlx::test(migrations = false)]
+async fn key_snapshot_failover_admin_uses_last_dispatched_binding(pool: PgPool) {
+ use axum::extract::OriginalUri;
+ type Dispatches = Arc>>;
+
+ async fn reply(
+ State(keys): State,
+ OriginalUri(uri): OriginalUri,
+ headers: HeaderMap,
+ Json(_): Json,
+ ) -> axum::response::Response {
+ keys.lock().unwrap().push((
+ uri.path().to_owned(),
+ headers[header::AUTHORIZATION].to_str().unwrap().to_owned(),
+ ));
+ if uri.path() == "/first/chat/completions" {
+ return (
+ axum::http::StatusCode::SERVICE_UNAVAILABLE,
+ Json(json!({"error":{"message":"synthetic pre-acceptance rejection"}})),
+ )
+ .into_response();
+ }
+ Json(json!({
+ "id":"synthetic-key-failover","object":"chat.completion",
+ "choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],
+ "usage":{"prompt_tokens":2,"completion_tokens":3,"prompt_tokens_details":{"cached_tokens":0}}
+ }))
+ .into_response()
+ }
+
+ let f = fixture(pool, 10_000_000).await;
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let keys = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let app = Router::new()
+ .route("/first/chat/completions", post(reply))
+ .route("/second/chat/completions", post(reply))
+ .with_state(keys.clone());
+ let supplier = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ let g = failover_gateway(
+ &f,
+ &format!("{base}/first"),
+ &format!("{base}/second"),
+ true,
+ false,
+ false,
+ );
+ let primary = CredentialRef { id: 7, revision: 1 };
+ let secondary = CredentialRef { id: 8, revision: 2 };
+ g.bridge
+ .credentials
+ .append(vec![UpstreamCredential {
+ reference: secondary,
+ secret: "synthetic-secondary-provider-key".into(),
+ }])
+ .unwrap();
+ g.bridge
+ .routing
+ .install_credential_pools(
+ g.bridge.routing.version().unwrap(),
+ &BTreeMap::from([(1, vec![primary, secondary]), (2, vec![primary])]),
+ )
+ .unwrap();
+ // The large-model route only visits upstream 1. Advance its pool so the
+ // failing primary uses index 1; the actual fallback uses a single key at 0.
+ let _first = g
+ .bridge
+ .routing
+ .route(routing::RouteRequest {
+ model: "large-model",
+ group: "allowed",
+ speed: None,
+ protocol: Protocol::OpenAiChat,
+ replay: routing::ReplayPermission::Denied,
+ })
+ .unwrap();
+
+ let (status, body, id) = call(&g, &f, "key-snapshot-two-dispatches", false, None).await;
+ assert_eq!(status, 200, "{body}");
+ assert_eq!(
+ *keys.lock().unwrap(),
+ [
+ (
+ "/first/chat/completions".to_owned(),
+ "Bearer synthetic-secondary-provider-key".to_owned(),
+ ),
+ (
+ "/second/chat/completions".to_owned(),
+ "Bearer synthetic-selected-bound-provider-key".to_owned(),
+ ),
+ ],
+ "both attempts must actually reach the local supplier with different credentials"
+ );
+ supplier.abort();
+
+ let events = evidence(&f, &id).await;
+ let contract = events
+ .iter()
+ .find(|event| event["kind"] == "model_reservation_contract")
+ .unwrap();
+ let first = &contract["binding"];
+ let last = &contract["fallbacks"][0]["binding"];
+ assert_eq!(first["credential_ref"], json!(secondary));
+ assert_eq!(
+ first["credential_selection"],
+ json!({"is_multi_key":true,"multi_key_index":1})
+ );
+ assert_eq!(last["credential_ref"], json!(primary));
+ assert_eq!(
+ last["credential_selection"],
+ json!({"is_multi_key":false,"multi_key_index":0})
+ );
+ let dispatches: Vec<_> = events
+ .iter()
+ .filter(|event| event["kind"] == "model_route_dispatch")
+ .collect();
+ assert_eq!(dispatches.len(), 2);
+ assert_eq!(dispatches[0]["number"], 1);
+ assert_eq!(dispatches[0]["route_id"], first["route_id"]);
+ assert_eq!(dispatches[0]["wire_sha256"], contract["wire_sha256"]);
+ assert_eq!(dispatches[1]["number"], 2);
+ assert_eq!(dispatches[1]["route_id"], last["route_id"]);
+ assert_eq!(
+ dispatches[1]["wire_sha256"],
+ contract["fallbacks"][0]["wire_sha256"]
+ );
+ let failure = events
+ .iter()
+ .find(|event| event["kind"] == "model_route_failure")
+ .unwrap();
+ assert_eq!(failure["number"], 1);
+ assert_eq!(failure["route_id"], first["route_id"]);
+ assert_eq!(failure["failure"]["http_status"], 503);
+ assert_eq!(failure["failure"]["failure"]["delivery"], "rejected");
+
+ let admin = IdentityStore::from_pool(f.pool.clone())
+ .bootstrap_user(9, 5)
+ .await
+ .unwrap();
+ let response = crate::usage::router(crate::usage::UsageStore::new(f.pool.clone()))
+ .oneshot(
+ axum::http::Request::get(format!("/core/v1/usage/admin/request?request_id={id}"))
+ .header("authorization", format!("Bearer {}", admin.secret))
+ .body(axum::body::Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), axum::http::StatusCode::OK);
+ let bytes = axum::body::to_bytes(response.into_body(), 1 << 20)
+ .await
+ .unwrap();
+ let response: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ let other: serde_json::Value =
+ serde_json::from_str(response["data"]["other"].as_str().unwrap()).unwrap();
+ let summary = &other["admin_info"];
+ assert_eq!(response["data"]["channel"], 2);
+ assert_eq!(summary["key_snapshot_status"], "recorded");
+ assert_eq!(summary["is_multi_key"], false);
+ assert_eq!(summary["multi_key_index"], 0);
+ assert_eq!(summary["route_attempts"].as_array().unwrap().len(), 2);
+ assert_eq!(summary["route_attempts"][0]["is_multi_key"], true);
+ assert_eq!(summary["route_attempts"][0]["multi_key_index"], 1);
+ assert_eq!(summary["route_attempts"][1]["is_multi_key"], false);
+ assert_eq!(summary["route_attempts"][1]["multi_key_index"], 0);
+ let encoded = response.to_string();
+ for forbidden in [
+ "credential_ref",
+ "credential_selection",
+ "synthetic-secondary-provider-key",
+ "synthetic-selected-bound-provider-key",
+ ] {
+ assert!(!encoded.contains(forbidden), "{forbidden}");
+ }
+ let charge = receipt(&g, &id).await;
+ assert_eq!((charge.state.as_str(), charge.settled), ("settled", 2));
+ assert_eq!(requests(&f.pool).await, 1);
+ assert_balance(&f, 9_999_998, 0).await;
+}
+
#[sqlx::test(migrations = false)]
async fn route_failover_pg_unknown_and_partial_tool_results_never_replay(pool: PgPool) {
let f = fixture(pool, 10_000_000).await;
diff --git a/services/core/src/pricing_http.rs b/services/core/src/pricing_http.rs
index fcbec52b6..3c8844819 100644
--- a/services/core/src/pricing_http.rs
+++ b/services/core/src/pricing_http.rs
@@ -70,6 +70,8 @@ pub struct PricingResponse {
pub credits_per_usd: i64,
pub rate_basis: &'static str,
pub invocation_authorized: bool,
+ pub empty_reason: Option<&'static str>,
+ pub public_view_available: bool,
#[serde(flatten)]
pub catalog: PricingProjection,
}
@@ -204,9 +206,10 @@ impl PricingHttp {
Some(None) => return Err(Error::Unavailable),
};
let policy = visibility(raw.as_deref());
+ let public_view_available = policy.enabled && !policy.require_auth;
// Closed square: no Authorization is forbidden before any credential lookup.
// A presented secret is authenticated first, so an unknown token is 401.
- if secret.is_none() && (!policy.enabled || policy.require_auth) {
+ if secret.is_none() && !public_view_available {
return Err(Error::Forbidden);
}
let (allowed, model_filter) = if let Some(secret) = secret {
@@ -258,6 +261,12 @@ impl PricingHttp {
credits_per_usd: crate::billing::CREDITS_PER_USD,
rate_basis,
invocation_authorized: false,
+ empty_reason: catalog.models.is_empty().then_some(if secret.is_some() {
+ "no_visible_models"
+ } else {
+ "catalog_empty"
+ }),
+ public_view_available,
catalog,
})
}
diff --git a/services/core/src/pricing_http_tests.rs b/services/core/src/pricing_http_tests.rs
index 609528ae4..c29985e2b 100644
--- a/services/core/src/pricing_http_tests.rs
+++ b/services/core/src/pricing_http_tests.rs
@@ -69,6 +69,8 @@ async fn pricing_pg_readonly_role_public_session_mark_and_revocation(pool: PgPoo
let (status, public) = call(&router, "/core/v1/pricing/public", None, None).await;
assert_eq!(status, StatusCode::OK, "{public}");
assert_eq!(public["visibility"], "public");
+ assert_eq!(public["empty_reason"], Value::Null);
+ assert_eq!(public["public_view_available"], true);
assert_eq!(public["groups"], json!(["allowed", "private"]));
assert_eq!(public["routing_version"], 9);
assert_eq!(public["pricing_version"], 11);
@@ -82,6 +84,8 @@ async fn pricing_pg_readonly_role_public_session_mark_and_revocation(pool: PgPoo
.await;
assert_eq!(status, StatusCode::OK, "{own}");
assert_eq!(own["visibility"], "session");
+ assert_eq!(own["empty_reason"], Value::Null);
+ assert_eq!(own["public_view_available"], true);
assert_eq!(own["groups"], json!(["allowed"]));
assert!(!own.to_string().contains("provider-model"));
let key = identity
@@ -248,6 +252,145 @@ async fn pricing_pg_header_nav_policy_bounds_and_public_runtime_unknown(pool: Pg
assert_eq!(counts(&pool).await, before);
}
+#[sqlx::test(migrations = false)]
+async fn pricing_pg_empty_session_metadata_uses_only_visible_permissions(pool: PgPool) {
+ crate::core_schema::init(&pool).await.unwrap();
+ let session = IdentityStore::from_pool(pool.clone())
+ .bootstrap_user(7, 1)
+ .await
+ .unwrap();
+ let surface = Arc::new(PricingSurface::from_gateway(&gateway(pool.clone())).unwrap());
+ let router = PricingHttp::new(pool.clone(), surface).router();
+ // Start without assignments: deleting an existing grant revokes the session.
+ // The default group remains valid, but this catalogue has no default routes.
+ let before = counts(&pool).await;
+ for (raw, public_available) in [
+ (r#"{"pricing":true}"#, true),
+ (r#"{"pricing":{"enabled":true,"requireAuth":true}}"#, false),
+ ] {
+ sqlx::query("INSERT INTO core_console.options(key,value) VALUES('HeaderNavModules',$1) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value")
+ .bind(raw).execute(&pool).await.unwrap();
+ let (status, empty) = call(
+ &router,
+ "/core/v1/pricing/session",
+ Some(&session.secret),
+ None,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{empty}");
+ assert_eq!(empty["visibility"], "session");
+ assert_eq!(empty["empty_reason"], "no_visible_models");
+ assert_eq!(empty["public_view_available"], public_available);
+ assert_eq!(empty["invocation_authorized"], false);
+ assert_eq!(empty["models"], json!([]));
+ assert_eq!(empty["groups"], json!([]));
+ assert!(!empty.to_string().contains("private"));
+ assert!(!empty.to_string().contains("claude"));
+ let (status, public) = call(&router, "/core/v1/pricing/public", None, None).await;
+ assert_eq!(
+ status,
+ if public_available {
+ StatusCode::OK
+ } else {
+ StatusCode::FORBIDDEN
+ }
+ );
+ if public_available {
+ assert_eq!(public["empty_reason"], Value::Null);
+ assert_eq!(public["public_view_available"], true);
+ assert!(!public["models"].as_array().unwrap().is_empty());
+ } else {
+ assert!(public.get("empty_reason").is_none());
+ assert!(public.get("public_view_available").is_none());
+ }
+ }
+ // A valid group can still have no visible models after the model restriction.
+ sqlx::query("INSERT INTO core_identity.user_routing_groups(user_id,group_name,enabled,source_reference) VALUES(7,'allowed',TRUE,'pricing-empty-model-test')")
+ .execute(&pool).await.unwrap();
+ let policy = json!({"version":1,"policies":[{"id":"marked","name":"pricing policy","mode":"fixed_text","fixed_text":"bounded","public_models":["synthetic-not-listed"],"clients":{},"limits":{"requests_per_minute_per_user":10,"requests_per_minute_global":10,"max_concurrent_per_user":1,"max_concurrent_global":1,"max_input_bytes":4096,"max_output_bytes":4096,"max_output_tokens":1024,"output_bytes_per_second":0,"total_timeout_seconds":5}}]});
+ sqlx::query("UPDATE core_abuse.settings SET revision=1,document=$1 WHERE singleton")
+ .bind(policy)
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query("INSERT INTO core_abuse.user_marks(user_id,marked,policy_id,revision) VALUES(7,TRUE,'marked',1)")
+ .execute(&pool).await.unwrap();
+ let (status, empty) = call(
+ &router,
+ "/core/v1/pricing/session",
+ Some(&session.secret),
+ None,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{empty}");
+ assert_eq!(empty["empty_reason"], "no_visible_models");
+ assert_eq!(empty["models"], json!([]));
+ assert_eq!(empty["groups"], json!([]));
+ assert!(!empty.to_string().contains("synthetic-not-listed"));
+ let (status, error) = call(
+ &router,
+ "/core/v1/pricing/session",
+ Some("lmms_not_a_real_session"),
+ None,
+ )
+ .await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED, "{error}");
+ assert!(error.get("empty_reason").is_none());
+ assert!(error.get("public_view_available").is_none());
+ assert_eq!(counts(&pool).await, before);
+}
+
+#[sqlx::test(migrations = false)]
+async fn pricing_pg_empty_public_catalog_is_distinct_from_an_empty_account(pool: PgPool) {
+ use crate::routing::{PriceConfig, PriceSnapshot, RoutingConfig};
+ crate::core_schema::init(&pool).await.unwrap();
+ let routing = crate::routing::Router::new(
+ RoutingConfig {
+ version: 1,
+ groups: vec![],
+ upstreams: vec![],
+ routes: vec![],
+ aliases: vec![],
+ },
+ Arc::new(
+ PriceSnapshot::compile(PriceConfig {
+ version: 1,
+ rules: vec![],
+ })
+ .unwrap(),
+ ),
+ )
+ .unwrap();
+ let gateway = crate::model_http::ModelGateway::new(
+ pool.clone(),
+ Arc::new(routing),
+ vec![],
+ std::collections::BTreeMap::new(),
+ crate::relay::Limits {
+ total_timeout: std::time::Duration::from_secs(1),
+ hook_timeout: std::time::Duration::from_millis(100),
+ ..Default::default()
+ },
+ crate::model_http::ChargePolicy {
+ input_token_ceiling: 65536,
+ lease_seconds: 10,
+ },
+ )
+ .unwrap();
+ let surface = Arc::new(PricingSurface::from_gateway(&gateway).unwrap());
+ let router = PricingHttp::new(pool.clone(), surface).router();
+ let before = counts(&pool).await;
+ let (status, public) = call(&router, "/core/v1/pricing/public", None, None).await;
+ assert_eq!(status, StatusCode::OK, "{public}");
+ assert_eq!(public["visibility"], "public");
+ assert_eq!(public["empty_reason"], "catalog_empty");
+ assert_eq!(public["public_view_available"], true);
+ assert_eq!(public["invocation_authorized"], false);
+ assert_eq!(public["models"], json!([]));
+ assert_eq!(public["groups"], json!([]));
+ assert_eq!(counts(&pool).await, before);
+}
+
#[sqlx::test(migrations = false)]
async fn pricing_pg_configured_group_rates_ignore_legacy_trust_state(pool: PgPool) {
let (_, session, surface) = setup(&pool).await;
@@ -463,6 +606,7 @@ async fn pricing_pg_disabled_module_allows_only_root_session(pool: PgPool) {
.await;
assert_eq!(status, StatusCode::OK, "{raw} {own}");
assert_eq!(own["visibility"], "session");
+ assert_eq!(own["public_view_available"], false);
assert_eq!(own["invocation_authorized"], false);
assert_eq!(own["groups"], json!(["allowed"]));
let (status, runtime) = call(
diff --git a/services/core/src/routing/engine.rs b/services/core/src/routing/engine.rs
index 33a66d464..c4108c3d1 100644
--- a/services/core/src/routing/engine.rs
+++ b/services/core/src/routing/engine.rs
@@ -1179,6 +1179,15 @@ impl Attempt {
pub fn credential_ref(&self) -> CredentialRef {
self.credential
}
+ /// Zero-based ordinal in this attempt's original pool, never the live release.
+ pub(crate) fn credential_selection(&self) -> (bool, u32) {
+ let references = &self.target.upstream.credentials.references;
+ let index = references
+ .iter()
+ .position(|reference| *reference == self.credential)
+ .expect("selected credential belongs to the frozen pool");
+ (references.len() > 1, index as u32)
+ }
pub fn timeout_ms(&self) -> u32 {
self.target.config.timeout_ms
}
diff --git a/services/core/src/routing/key_pool_tests.rs b/services/core/src/routing/key_pool_tests.rs
index 225fef820..1734bee9d 100644
--- a/services/core/src/routing/key_pool_tests.rs
+++ b/services/core/src/routing/key_pool_tests.rs
@@ -238,3 +238,87 @@ fn key_pool_group_alternatives_advance_each_channel_once_per_request() {
}
}
}
+
+#[test]
+fn key_snapshot_keeps_admission_ordinal_after_reorder_and_removal() {
+ use crate::billing::charging::contract::{CredentialSelection, ReservationBinding};
+
+ fn binding(attempt: &Attempt) -> ReservationBinding {
+ ReservationBinding::for_attempt(
+ attempt,
+ "chat".into(),
+ attempt.upstream_model().into(),
+ attempt.endpoint().into(),
+ "synthetic-key-snapshot-v1".into(),
+ "context-max-v1".into(),
+ attempt.quote().version(),
+ )
+ .unwrap()
+ }
+
+ let (mut config, prices) = fixture(1);
+ config.routes[0].targets.truncate(1);
+ let primary = config.upstreams[0].credential;
+ let secondary = CredentialRef {
+ id: 101,
+ revision: 2,
+ };
+ let router = build(config.clone(), prices.clone());
+ router
+ .install_credential_pools(
+ router.version().unwrap(),
+ &BTreeMap::from([(1, vec![primary, secondary])]),
+ )
+ .unwrap();
+ let _first = router.route(request()).unwrap();
+ let mut accepted = router.route(request()).unwrap();
+ let original = binding(&accepted.planned_attempts()[0]);
+ assert_eq!(original.credential_ref, secondary);
+ assert_eq!(
+ original.credential_selection,
+ Some(CredentialSelection {
+ is_multi_key: true,
+ multi_key_index: 1,
+ })
+ );
+
+ config.version += 1;
+ config.upstreams[0].credential = secondary;
+ router
+ .publish_with_credential_pools(
+ router.version().unwrap(),
+ config.clone(),
+ Arc::new(PriceSnapshot::compile(prices.clone()).unwrap()),
+ &BTreeMap::from([(1, vec![secondary, primary])]),
+ )
+ .unwrap();
+ let reordered = binding(&router.route(request()).unwrap().start().unwrap());
+ assert_eq!(reordered.credential_ref, secondary);
+ assert_eq!(reordered.credential_selection.unwrap().multi_key_index, 0);
+
+ config.version += 1;
+ config.upstreams[0].credential = primary;
+ router
+ .publish_with_credential_pools(
+ router.version().unwrap(),
+ config,
+ Arc::new(PriceSnapshot::compile(prices).unwrap()),
+ &BTreeMap::new(),
+ )
+ .unwrap();
+ let single = binding(&router.route(request()).unwrap().start().unwrap());
+ assert_eq!(
+ single.credential_selection,
+ Some(CredentialSelection {
+ is_multi_key: false,
+ multi_key_index: 0,
+ })
+ );
+ // Dispatch can happen after both releases; its source is the accepted plan.
+ assert_eq!(binding(&accepted.start().unwrap()), original);
+ let persisted = serde_json::to_value(&original).unwrap();
+ assert_eq!(
+ serde_json::from_value::(persisted).unwrap(),
+ original,
+ );
+}
diff --git a/services/core/src/usage/channel_projection.rs b/services/core/src/usage/channel_projection.rs
index 5a1e88a0e..7e76dbe7c 100644
--- a/services/core/src/usage/channel_projection.rs
+++ b/services/core/src/usage/channel_projection.rs
@@ -462,6 +462,13 @@ pub(super) fn final_channel(
proof: &contract::ReservationContract,
events: &[AttemptEvent],
) -> Option {
+ final_binding(proof, events).map(|binding| binding.upstream_id)
+}
+
+pub(super) fn final_binding<'a>(
+ proof: &'a contract::ReservationContract,
+ events: &[AttemptEvent],
+) -> Option<&'a contract::ReservationBinding> {
let mut dispatches = BTreeMap::new();
let mut failures = BTreeMap::new();
for event in events {
@@ -507,5 +514,5 @@ pub(super) fn final_channel(
}
}
let d = dispatches.get(&last)?;
- proof.dispatched_channel(&d.route_id, &d.wire_sha256)
+ proof.dispatched_binding(&d.route_id, &d.wire_sha256)
}
diff --git a/services/core/src/usage/log_details.rs b/services/core/src/usage/log_details.rs
index 2da078e3d..6c07c99d4 100644
--- a/services/core/src/usage/log_details.rs
+++ b/services/core/src/usage/log_details.rs
@@ -11,6 +11,7 @@ pub(super) struct LogDetails {
pub(super) username: Option,
pub(super) channel: Option,
pub(super) attempts: Vec,
+ pub(super) credential_selection: Option,
}
impl LogDetails {
@@ -60,7 +61,12 @@ impl LogDetails {
item["channel"] = json!(self.channel);
item["channel_name"] = Value::Null;
item["route_attempts"] = json!(self.attempts);
- other["admin_info"] = json!({"route_attempts":self.attempts});
+ other["admin_info"] = json!({
+ "route_attempts":self.attempts,
+ "key_snapshot_status":if self.credential_selection.is_some() {"recorded"} else {"unknown"},
+ "is_multi_key":self.credential_selection.map(|selection| selection.is_multi_key),
+ "multi_key_index":self.credential_selection.map(|selection| selection.multi_key_index),
+ });
}
item["other"] = json!(other.to_string());
item
@@ -140,8 +146,10 @@ pub(super) async fn load(
.upstream_id as i64,
);
} else if let Some(proof) = &proof {
- details.channel =
- channel_projection::final_channel(proof, &events).map(|id| id as i64);
+ let binding = channel_projection::final_binding(proof, &events);
+ details.channel = binding.map(|binding| binding.upstream_id as i64);
+ details.credential_selection =
+ binding.and_then(|binding| binding.credential_selection);
let failures: BTreeMap<_, _> = events
.iter()
.filter(|event| event.event_id.starts_with("route-failure:"))
@@ -170,12 +178,16 @@ pub(super) async fn load(
) else {
continue;
};
- let Some(channel) = proof.dispatched_channel(route, wire) else {
+ let Some(binding) = proof.dispatched_binding(route, wire) else {
continue;
};
+ let channel = binding.upstream_id;
let failure = failures.get(&number);
details.attempts.push(json!({
"attempt":number,"channel_id":channel,"route_id":route,
+ "key_snapshot_status":if binding.credential_selection.is_some() {"recorded"} else {"unknown"},
+ "is_multi_key":binding.credential_selection.map(|selection| selection.is_multi_key),
+ "multi_key_index":binding.credential_selection.map(|selection| selection.multi_key_index),
"status_code":failure.and_then(|failure| failure.http_status),
"error_kind":failure.map(|failure| failure.failure.kind),
"delivery":failure.map(|failure| failure.failure.delivery),
diff --git a/services/core/tests/fixtures/key_snapshot_contract_v1_golden.json b/services/core/tests/fixtures/key_snapshot_contract_v1_golden.json
new file mode 100644
index 000000000..80e0bb13b
--- /dev/null
+++ b/services/core/tests/fixtures/key_snapshot_contract_v1_golden.json
@@ -0,0 +1,21 @@
+{
+ "provenance": {
+ "source_commit": "15bc9d989dfa67930ecf501f0e593794f16d672d",
+ "source_path": "services/core/src/billing/charging/contract.rs",
+ "source_sha256": "52da6d5733fb07ff66384d2e055a864cb978b8b2dbdd08cc3048e23f5517e31f",
+ "executed_by_real_d_binary": false,
+ "method": "Constructed from frozen D Rust field order and ASCII synthetic values; SHA-256 calculated with Python hashlib. Rust assertions and a copied D serde binding shape are supplied but have not been executed. This is not a D runtime-produced artifact.",
+ "prepared_encoding": "UTF-8 compact JSON in Rust struct declaration order; excludes prepared/admission/price digests, omits empty fallbacks and None legacy_precharge/credential_selection.",
+ "contract_encoding": "UTF-8 compact JSON with lexically sorted object keys, matching serde_json Value without preserve_order; includes prepared/admission/price digests."
+ },
+ "legacy": {
+ "prepared_bytes": "{\"kind\":\"model_reservation_contract\",\"version\":1,\"mode\":\"context_max\",\"request_fingerprint\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"binding\":{\"route_id\":\"synthetic-route\",\"target_id\":1,\"upstream_id\":2,\"protocol\":\"responses\",\"model_snapshot\":\"synthetic-model\",\"generation_url\":\"https://synthetic.invalid/v1/responses\",\"credential_ref\":{\"id\":3,\"revision\":4},\"payload_policy_sha256\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"provider_contract_revision\":\"synthetic-v1\",\"projection_revision\":\"context_max_v1\",\"quote_version\":1},\"wire_sha256\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"counter\":null,\"bounds\":{\"model_input_max\":100,\"input\":100,\"requested_output\":8,\"output\":8},\"semantics\":{\"input\":\"inclusive\",\"output\":\"includes_reasoning\",\"missing_cached_tokens_is_zero\":true,\"missing_cache_creation_tokens_is_zero\":false}}",
+ "prepared_sha256": "d872c635f7e0482772c9984f8c658845e1da0acf28482e2d81c4bc0a99715254",
+ "contract_bytes": "{\"admission_spec_sha256\":\"0404040404040404040404040404040404040404040404040404040404040404\",\"binding\":{\"credential_ref\":{\"id\":3,\"revision\":4},\"generation_url\":\"https://synthetic.invalid/v1/responses\",\"model_snapshot\":\"synthetic-model\",\"payload_policy_sha256\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"projection_revision\":\"context_max_v1\",\"protocol\":\"responses\",\"provider_contract_revision\":\"synthetic-v1\",\"quote_version\":1,\"route_id\":\"synthetic-route\",\"target_id\":1,\"upstream_id\":2},\"bounds\":{\"input\":100,\"model_input_max\":100,\"output\":8,\"requested_output\":8},\"counter\":null,\"frozen_price_sha256\":\"0505050505050505050505050505050505050505050505050505050505050505\",\"kind\":\"model_reservation_contract\",\"mode\":\"context_max\",\"prepared_sha256\":\"d872c635f7e0482772c9984f8c658845e1da0acf28482e2d81c4bc0a99715254\",\"request_fingerprint\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"semantics\":{\"input\":\"inclusive\",\"missing_cache_creation_tokens_is_zero\":false,\"missing_cached_tokens_is_zero\":true,\"output\":\"includes_reasoning\"},\"version\":1,\"wire_sha256\":\"0303030303030303030303030303030303030303030303030303030303030303\"}"
+ },
+ "selected": {
+ "prepared_bytes": "{\"kind\":\"model_reservation_contract\",\"version\":1,\"mode\":\"context_max\",\"request_fingerprint\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"binding\":{\"route_id\":\"synthetic-route\",\"target_id\":1,\"upstream_id\":2,\"protocol\":\"responses\",\"model_snapshot\":\"synthetic-model\",\"generation_url\":\"https://synthetic.invalid/v1/responses\",\"credential_ref\":{\"id\":3,\"revision\":4},\"credential_selection\":{\"is_multi_key\":true,\"multi_key_index\":1},\"payload_policy_sha256\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"provider_contract_revision\":\"synthetic-v1\",\"projection_revision\":\"context_max_v1\",\"quote_version\":1},\"wire_sha256\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"counter\":null,\"bounds\":{\"model_input_max\":100,\"input\":100,\"requested_output\":8,\"output\":8},\"semantics\":{\"input\":\"inclusive\",\"output\":\"includes_reasoning\",\"missing_cached_tokens_is_zero\":true,\"missing_cache_creation_tokens_is_zero\":false}}",
+ "prepared_sha256": "259f2724db561c66df449a44010f0777f2da686b0ff9b6e9ac842000c23b587f",
+ "contract_bytes": "{\"admission_spec_sha256\":\"0404040404040404040404040404040404040404040404040404040404040404\",\"binding\":{\"credential_ref\":{\"id\":3,\"revision\":4},\"credential_selection\":{\"is_multi_key\":true,\"multi_key_index\":1},\"generation_url\":\"https://synthetic.invalid/v1/responses\",\"model_snapshot\":\"synthetic-model\",\"payload_policy_sha256\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"projection_revision\":\"context_max_v1\",\"protocol\":\"responses\",\"provider_contract_revision\":\"synthetic-v1\",\"quote_version\":1,\"route_id\":\"synthetic-route\",\"target_id\":1,\"upstream_id\":2},\"bounds\":{\"input\":100,\"model_input_max\":100,\"output\":8,\"requested_output\":8},\"counter\":null,\"frozen_price_sha256\":\"0505050505050505050505050505050505050505050505050505050505050505\",\"kind\":\"model_reservation_contract\",\"mode\":\"context_max\",\"prepared_sha256\":\"259f2724db561c66df449a44010f0777f2da686b0ff9b6e9ac842000c23b587f\",\"request_fingerprint\":\"0101010101010101010101010101010101010101010101010101010101010101\",\"semantics\":{\"input\":\"inclusive\",\"missing_cache_creation_tokens_is_zero\":false,\"missing_cached_tokens_is_zero\":true,\"output\":\"includes_reasoning\"},\"version\":1,\"wire_sha256\":\"0303030303030303030303030303030303030303030303030303030303030303\"}"
+ }
+}
diff --git a/services/core/tests/fixtures/sub2api_quota_usage.json b/services/core/tests/fixtures/sub2api_quota_usage.json
new file mode 100644
index 000000000..030cbcaf1
--- /dev/null
+++ b/services/core/tests/fixtures/sub2api_quota_usage.json
@@ -0,0 +1,8 @@
+{
+ "mode": "quota_limited",
+ "isValid": true,
+ "status": "active",
+ "quota": { "limit": 1000, "used": 13.82805112, "remaining": 986.17194888, "unit": "USD" },
+ "remaining": 986.17194888,
+ "unit": "USD"
+}
diff --git a/services/core/tests/fixtures/sub2api_wallet_usage.json b/services/core/tests/fixtures/sub2api_wallet_usage.json
new file mode 100644
index 000000000..cf75936d3
--- /dev/null
+++ b/services/core/tests/fixtures/sub2api_wallet_usage.json
@@ -0,0 +1,9 @@
+{
+ "mode": "unrestricted",
+ "isValid": true,
+ "planName": "Wallet balance",
+ "remaining": 42.5,
+ "unit": "USD",
+ "balance": 42.5,
+ "usage": { "total": { "cost": 7.5 } }
+}