feat(runner): add safe agent quota query infrastructure (#1787)

* feat: add runner-side quota query infrastructure

* test: cover usage query protocol contract

* fix: close quota query redirect and in-flight races

* fix: harden quota query cache and timestamps

* fix: restrict quota templates to read-only requests

* fix: harden quota credential and request boundaries

* fix: bind quota cache to credentials

* fix: retry quota failures after cooldown

* fix: require an active Codex provider

* fix: harden quota value parsing and redaction

* fix: close quota provider selection boundaries

* fix: resolve qualified Kimi provider defaults

* fix: continue Kimi config fallback when current is incomplete

* fix: isolate explicit Kimi profile fallback

* fix: bind provider credentials and URL safety

* fix: isolate Codex profiles and abort quota responses

* fix(usage-query): preserve case-sensitive Codex providers
This commit is contained in:
Ananovo
2026-11-13 18:50:59 +08:00
committed by GitHub
parent f0ab4ba79d
commit 80a5b94f8f
19 changed files with 2856 additions and 3 deletions
+362
View File
@@ -0,0 +1,362 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { parseCodexBaseUrl, resolveUsageCredentials } from './credentials'
describe('usage query credential resolution', () => {
it('selects the active Codex provider and ignores comments', () => {
expect(parseCodexBaseUrl(`
model_provider = "OpenAI" # active provider
[model_providers.Other]
base_url = "https://other.example"
[model_providers.OpenAI]
base_url = "https://openai.example/v1"
`)).toBe('https://openai.example/v1')
expect(parseCodexBaseUrl(`
model_provider = "Missing"
[model_providers.Other]
base_url = "https://other.example"
`)).toBeNull()
expect(parseCodexBaseUrl(`
[model_providers.Other]
base_url = "https://other.example"
`)).toBeNull()
expect(parseCodexBaseUrl(`
model_provider = "Gateway"
[profiles.unused]
model_provider = "Other"
[model_providers.Gateway]
base_url = "https://gateway.example"
[model_providers.Other]
base_url = "https://other.example"
`)).toBe('https://gateway.example')
})
it('prefers environment credentials and does not read config when they are complete', async () => {
const result = await resolveUsageCredentials('claude', {
ANTHROPIC_BASE_URL: 'https://env.example',
ANTHROPIC_API_KEY: 'env-secret',
CLAUDE_CONFIG_DIR: join(tmpdir(), 'missing-claude-config')
})
expect(result).toMatchObject({
baseUrl: 'https://env.example',
apiKey: 'env-secret',
baseUrlSource: 'environment',
apiKeySource: 'environment'
})
})
it('prefers the Claude Code OAuth token environment credential', async () => {
const result = await resolveUsageCredentials('claude', {
CLAUDE_CODE_OAUTH_TOKEN: 'oauth-secret',
ANTHROPIC_AUTH_TOKEN: 'anthropic-secret',
ANTHROPIC_API_KEY: 'api-secret'
})
expect(result).toMatchObject({
apiKey: 'oauth-secret',
apiKeySource: 'environment'
})
})
it('reads Claude env entries and Codex config files without returning them to callers', async () => {
const root = await mkdtemp(join(tmpdir(), 'hapi-usage-credentials-'))
try {
const claudeDir = join(root, 'claude')
const codexDir = join(root, 'codex')
await mkdir(claudeDir)
await mkdir(codexDir)
await writeFile(join(claudeDir, 'settings.json'), JSON.stringify({
env: {
ANTHROPIC_BASE_URL: 'https://claude.example/',
ANTHROPIC_AUTH_TOKEN: 'claude-secret'
}
}))
await writeFile(join(codexDir, 'config.toml'), [
'model_provider = "Gateway"',
'[model_providers.Gateway]',
'base_url = "https://codex.example/v1"',
'env_key = "CODEX_GATEWAY_API_KEY"'
].join('\n'))
await writeFile(join(codexDir, 'auth.json'), JSON.stringify({ OPENAI_API_KEY: 'unrelated-openai-secret' }))
const claude = await resolveUsageCredentials('claude', { CLAUDE_CONFIG_DIR: claudeDir })
expect(claude).toMatchObject({ baseUrl: 'https://claude.example/', apiKey: 'claude-secret', baseUrlSource: 'config', apiKeySource: 'config' })
const codex = await resolveUsageCredentials('codex', {
CODEX_HOME: codexDir,
CODEX_GATEWAY_API_KEY: 'codex-secret',
OPENAI_API_KEY: 'unrelated-openai-secret',
OPENAI_BASE_URL: 'https://api.openai.example/v1'
})
expect(codex).toMatchObject({ baseUrl: 'https://codex.example/v1', apiKey: 'codex-secret', baseUrlSource: 'config', apiKeySource: 'environment' })
} finally {
await rm(root, { recursive: true, force: true })
}
})
it('uses OpenAI credentials only for the OpenAI Codex provider', async () => {
const root = await mkdtemp(join(tmpdir(), 'hapi-codex-openai-credentials-'))
try {
await writeFile(join(root, 'config.toml'), 'model_provider = "openai"\n')
await writeFile(join(root, 'auth.json'), JSON.stringify({ OPENAI_API_KEY: 'config-openai-secret' }))
const resolved = await resolveUsageCredentials('codex', {
CODEX_HOME: root,
OPENAI_BASE_URL: 'https://api.openai.example/v1'
})
expect(resolved).toMatchObject({
baseUrl: 'https://api.openai.example/v1',
apiKey: 'config-openai-secret',
baseUrlSource: 'environment',
apiKeySource: 'config'
})
} finally {
await rm(root, { recursive: true, force: true })
}
})
it('treats an OpenAI-named custom provider as case-sensitive', async () => {
const root = await mkdtemp(join(tmpdir(), 'hapi-codex-openai-named-custom-'))
try {
await writeFile(join(root, 'config.toml'), [
'model_provider = "OpenAI"',
'[model_providers.OpenAI]',
'base_url = "https://custom-openai.example/v1"',
'env_key = "CUSTOM_OPENAI_API_KEY"'
].join('\n'))
const resolved = await resolveUsageCredentials('codex', {
CODEX_HOME: root,
CUSTOM_OPENAI_API_KEY: 'custom-provider-secret',
OPENAI_API_KEY: 'unrelated-openai-secret',
OPENAI_BASE_URL: 'https://api.openai.example/v1'
})
expect(resolved).toMatchObject({
baseUrl: 'https://custom-openai.example/v1',
apiKey: 'custom-provider-secret',
baseUrlSource: 'config',
apiKeySource: 'environment'
})
} finally {
await rm(root, { recursive: true, force: true })
}
})
it('reads the active Kimi provider from config.toml and environment overrides', async () => {
const root = await mkdtemp(join(tmpdir(), 'hapi-kimi-credentials-'))
try {
await mkdir(root, { recursive: true })
await writeFile(join(root, 'config.toml'), [
'default_model = "kimi-for-coding"',
'[providers.kimi-for-coding]',
'type = "kimi"',
'base_url = "https://api.kimi.com/coding/v1"',
'api_key = "config-kimi-secret"',
'[models.kimi-for-coding]',
'provider = "kimi-for-coding"'
].join('\n'))
const configured = await resolveUsageCredentials('kimi', { KIMI_CODE_HOME: root })
expect(configured).toMatchObject({
baseUrl: 'https://api.kimi.com/coding/v1',
apiKey: 'config-kimi-secret',
baseUrlSource: 'config',
apiKeySource: 'config'
})
const environment = await resolveUsageCredentials('kimi', {
KIMI_CODE_HOME: root,
KIMI_BASE_URL: 'https://env.kimi.example/v1',
KIMI_API_KEY: 'env-kimi-secret'
})
expect(environment).toMatchObject({
baseUrl: 'https://env.kimi.example/v1',
apiKey: 'env-kimi-secret',
baseUrlSource: 'environment',
apiKeySource: 'environment'
})
} finally {
await rm(root, { recursive: true, force: true })
}
})
it('resolves a provider-qualified Kimi default without a model alias table', async () => {
const root = await mkdtemp(join(tmpdir(), 'hapi-kimi-qualified-default-'))
try {
await writeFile(join(root, 'config.toml'), [
'default_model = "kimi-code/k3"',
'[providers.kimi-code]',
'type = "kimi"',
'base_url = "https://qualified.kimi.example/coding/v1"',
'api_key = "qualified-kimi-secret"'
].join('\n'))
const resolved = await resolveUsageCredentials('kimi', { KIMI_CODE_HOME: root })
expect(resolved).toMatchObject({
baseUrl: 'https://qualified.kimi.example/coding/v1',
apiKey: 'qualified-kimi-secret',
baseUrlSource: 'config',
apiKeySource: 'config'
})
} finally {
await rm(root, { recursive: true, force: true })
}
})
it('prefers the current Kimi Code home over the legacy home', async () => {
const root = await mkdtemp(join(tmpdir(), 'hapi-kimi-home-precedence-'))
try {
const currentHome = join(root, '.kimi-code')
const legacyHome = join(root, '.kimi')
await mkdir(currentHome, { recursive: true })
await mkdir(legacyHome, { recursive: true })
const config = (model: string, baseUrl: string, apiKey: string) => [
`default_model = "${model}"`,
`[providers.${model}]`,
'type = "kimi"',
`base_url = "${baseUrl}"`,
`api_key = "${apiKey}"`,
`[models.${model}]`,
`provider = "${model}"`
].join('\n')
await writeFile(join(currentHome, 'config.toml'), config('current', 'https://current.kimi.example', 'current-secret'))
await writeFile(join(legacyHome, 'config.toml'), config('legacy', 'https://legacy.kimi.example', 'legacy-secret'))
const resolved = await resolveUsageCredentials('kimi', {}, root)
expect(resolved).toMatchObject({
baseUrl: 'https://current.kimi.example',
apiKey: 'current-secret',
baseUrlSource: 'config',
apiKeySource: 'config'
})
} finally {
await rm(root, { recursive: true, force: true })
}
})
it('falls back to legacy Kimi credentials when the current config is incomplete', async () => {
const root = await mkdtemp(join(tmpdir(), 'hapi-kimi-incomplete-current-'))
try {
const currentHome = join(root, '.kimi-code')
const legacyHome = join(root, '.kimi')
await mkdir(currentHome, { recursive: true })
await mkdir(legacyHome, { recursive: true })
const legacyConfig = [
'default_model = "legacy"',
'[providers.legacy]',
'type = "kimi"',
'base_url = "https://legacy.kimi.example/coding/v1"',
'api_key = "legacy-secret"',
'[models.legacy]',
'provider = "legacy"'
].join('\n')
await writeFile(join(legacyHome, 'config.toml'), legacyConfig)
await writeFile(join(currentHome, 'config.toml'), [
'default_model = "current"',
'[providers.current]',
'type = "kimi"',
'api_key = "partial-current-secret"',
'[models.current]',
'provider = "current"'
].join('\n'))
const resolved = await resolveUsageCredentials('kimi', {}, root)
expect(resolved).toMatchObject({
baseUrl: 'https://legacy.kimi.example/coding/v1',
apiKey: 'legacy-secret',
baseUrlSource: 'config',
apiKeySource: 'config'
})
await writeFile(join(currentHome, 'config.toml'), [
'default_model = "current"',
'[providers.current]',
'type = "kimi"',
'base_url = "https://partial-current.kimi.example/coding/v1"',
'[models.current]',
'provider = "current"'
].join('\n'))
const baseOnly = await resolveUsageCredentials('kimi', {}, root)
expect(baseOnly).toMatchObject({
baseUrl: 'https://legacy.kimi.example/coding/v1',
apiKey: 'legacy-secret',
baseUrlSource: 'config',
apiKeySource: 'config'
})
} finally {
await rm(root, { recursive: true, force: true })
}
})
it('does not fall through an explicit Kimi home to the default current home', async () => {
const root = await mkdtemp(join(tmpdir(), 'hapi-kimi-explicit-home-'))
try {
const explicitHome = join(root, 'explicit')
const defaultHome = join(root, '.kimi-code')
await mkdir(explicitHome, { recursive: true })
await mkdir(defaultHome, { recursive: true })
await writeFile(join(explicitHome, 'config.toml'), 'default_model = "explicit/k3"\n')
await writeFile(join(defaultHome, 'config.toml'), [
'default_model = "default"',
'[providers.default]',
'type = "kimi"',
'base_url = "https://default.kimi.example/coding/v1"',
'api_key = "default-secret"',
'[models.default]',
'provider = "default"'
].join('\n'))
const resolved = await resolveUsageCredentials('kimi', {
KIMI_CODE_HOME: explicitHome,
KIMI_API_KEY: 'explicit-secret'
}, root)
expect(resolved).toMatchObject({
baseUrl: '',
apiKey: 'explicit-secret',
baseUrlSource: 'none',
apiKeySource: 'environment'
})
} finally {
await rm(root, { recursive: true, force: true })
}
})
it('does not infer an inactive Kimi provider without an active model selection', async () => {
const root = await mkdtemp(join(tmpdir(), 'hapi-kimi-inactive-provider-'))
try {
const providerConfig = [
'[providers.inactive]',
'type = "kimi"',
'base_url = "https://inactive.kimi.example"',
'api_key = "config-secret"'
].join('\n')
await writeFile(join(root, 'config.toml'), providerConfig)
const noDefault = await resolveUsageCredentials('kimi', {
KIMI_CODE_HOME: root,
KIMI_API_KEY: 'environment-secret'
})
expect(noDefault).toMatchObject({
baseUrl: '',
apiKey: 'environment-secret',
baseUrlSource: 'none',
apiKeySource: 'environment'
})
await writeFile(join(root, 'config.toml'), [
'default_model = "missing-model"',
providerConfig
].join('\n'))
const unmapped = await resolveUsageCredentials('kimi', {
KIMI_CODE_HOME: root,
KIMI_API_KEY: 'environment-secret'
})
expect(unmapped).toMatchObject({
baseUrl: '',
apiKey: 'environment-secret',
baseUrlSource: 'none',
apiKeySource: 'environment'
})
} finally {
await rm(root, { recursive: true, force: true })
}
})
})
+367
View File
@@ -0,0 +1,367 @@
import { readFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join } from 'node:path'
import type { UsageQueryAgent, UsageQueryCredentialStatus } from '@hapi/protocol/usageQuery'
export type ResolvedUsageCredentials = {
baseUrl: string
apiKey: string
baseUrlSource: UsageQueryCredentialStatus['source']
apiKeySource: UsageQueryCredentialStatus['source']
}
type JsonObject = Record<string, unknown>
function nonEmptyString(value: unknown): string | null {
if (typeof value !== 'string') return null
const trimmed = value.trim()
return trimmed ? trimmed : null
}
async function readJsonObject(path: string): Promise<JsonObject | null> {
try {
const parsed: unknown = JSON.parse(await readFile(path, 'utf8'))
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed as JsonObject
: null
} catch {
return null
}
}
function firstObjectString(object: JsonObject | null, keys: readonly string[]): string | null {
if (!object) return null
for (const key of keys) {
const value = nonEmptyString(object[key])
if (value) return value
}
return null
}
function stripTomlComment(line: string): string {
let quote: '"' | "'" | null = null
let escaped = false
for (let index = 0; index < line.length; index += 1) {
const char = line[index]
if (quote === '"' && escaped) {
escaped = false
continue
}
if (quote === '"' && char === '\\') {
escaped = true
continue
}
if ((char === '"' || char === "'") && (quote === null || quote === char)) {
quote = quote === null ? char : null
continue
}
if (char === '#' && quote === null) return line.slice(0, index)
}
return line
}
function unquoteTomlString(value: string): string | null {
const trimmed = value.trim()
if (trimmed.length < 2) return null
const quote = trimmed[0]
if ((quote !== '"' && quote !== "'") || trimmed.at(-1) !== quote) return null
if (quote === "'") return trimmed.slice(1, -1)
try {
return JSON.parse(trimmed) as string
} catch {
return trimmed.slice(1, -1)
}
}
type KimiProviderConfig = {
baseUrl?: string
apiKey?: string
}
type KimiConfigSnapshot = {
defaultModel: string | null
providers: Map<string, KimiProviderConfig>
modelProviders: Map<string, string>
}
function parseKimiToml(configText: string): KimiConfigSnapshot {
let sectionType: 'root' | 'providers' | 'models' | null = 'root'
let sectionName: string | null = null
let defaultModel: string | null = null
const providers = new Map<string, KimiProviderConfig>()
const modelProviders = new Map<string, string>()
for (const rawLine of configText.split(/\r?\n/)) {
const line = stripTomlComment(rawLine).trim()
if (!line) continue
const section = /^\[(providers|models)(?:\."([^"]+)"|\.'([^']+)'|\.([A-Za-z0-9_.-]+))\]$/.exec(line)
if (section) {
sectionType = section[1] as 'providers' | 'models'
sectionName = section[2] ?? section[3] ?? section[4] ?? null
continue
}
if (line.startsWith('[')) {
sectionType = null
sectionName = null
continue
}
const match = /^([A-Za-z0-9_-]+)\s*=\s*(.+)$/.exec(line)
if (!match) continue
const key = match[1]
const value = unquoteTomlString(match[2])
if (sectionType === 'root' && key === 'default_model') {
defaultModel = value
continue
}
if (!sectionName || value === null) continue
if (sectionType === 'providers') {
const current = providers.get(sectionName) ?? {}
if (key === 'base_url') current.baseUrl = value
if (key === 'api_key') current.apiKey = value
providers.set(sectionName, current)
} else if (sectionType === 'models' && key === 'provider') {
modelProviders.set(sectionName, value)
}
}
return { defaultModel, providers, modelProviders }
}
function parseKimiJson(config: JsonObject): KimiConfigSnapshot {
const defaultModel = nonEmptyString(config.default_model)
const providers = new Map<string, KimiProviderConfig>()
const modelProviders = new Map<string, string>()
const rawProviders = config.providers
if (rawProviders && typeof rawProviders === 'object' && !Array.isArray(rawProviders)) {
for (const [name, value] of Object.entries(rawProviders as JsonObject)) {
if (!value || typeof value !== 'object' || Array.isArray(value)) continue
const provider = value as JsonObject
providers.set(name, {
baseUrl: nonEmptyString(provider.base_url) ?? undefined,
apiKey: nonEmptyString(provider.api_key) ?? undefined
})
}
}
const rawModels = config.models
if (rawModels && typeof rawModels === 'object' && !Array.isArray(rawModels)) {
for (const [name, value] of Object.entries(rawModels as JsonObject)) {
if (!value || typeof value !== 'object' || Array.isArray(value)) continue
const provider = nonEmptyString((value as JsonObject).provider)
if (provider) modelProviders.set(name, provider)
}
}
return { defaultModel, providers, modelProviders }
}
function chooseKimiProvider(snapshot: KimiConfigSnapshot): KimiProviderConfig | null {
const model = snapshot.defaultModel
if (!model) return null
const slash = model.indexOf('/')
const providerName = snapshot.modelProviders.get(model)
?? (slash > 0 ? model.slice(0, slash) : undefined)
return providerName ? snapshot.providers.get(providerName) ?? null : null
}
function hasKimiCredentialPair(snapshot: KimiConfigSnapshot, env: NodeJS.ProcessEnv): boolean {
const provider = chooseKimiProvider(snapshot)
const baseUrl = nonEmptyString(env.KIMI_BASE_URL) ?? provider?.baseUrl
const apiKey = nonEmptyString(env.KIMI_API_KEY) ?? provider?.apiKey
return Boolean(baseUrl && apiKey)
}
async function readKimiConfig(env: NodeJS.ProcessEnv, userHome = homedir()): Promise<KimiConfigSnapshot> {
const explicitHome = nonEmptyString(env.KIMI_CODE_HOME) ?? nonEmptyString(env.KIMI_SHARE_DIR)
const homes = (explicitHome
? [explicitHome]
: [join(userHome, '.kimi-code'), join(userHome, '.kimi')]
).filter((value, index, values): value is string => Boolean(value) && values.indexOf(value) === index)
for (const home of homes) {
const tomlPath = join(home, 'config.toml')
try {
const snapshot = parseKimiToml(await readFile(tomlPath, 'utf8'))
if (hasKimiCredentialPair(snapshot, env)) return snapshot
} catch {
// Try the JSON migration format below.
}
const json = await readJsonObject(join(home, 'config.json'))
if (json) {
const snapshot = parseKimiJson(json)
if (hasKimiCredentialPair(snapshot, env)) return snapshot
}
}
return { defaultModel: null, providers: new Map(), modelProviders: new Map() }
}
type CodexProviderConfig = {
baseUrl?: string
envKey?: string
}
type CodexConfigSnapshot = {
activeProvider: string | null
providers: Map<string, CodexProviderConfig>
}
/** Read the active Codex provider and its credential selector. */
function parseCodexConfig(configText: string): CodexConfigSnapshot {
let activeProvider: string | null = null
let currentProvider: string | null = null
let inRootTable = true
const providers = new Map<string, CodexProviderConfig>()
for (const rawLine of configText.split(/\r?\n/)) {
const line = stripTomlComment(rawLine).trim()
if (!line) continue
const section = /^\[model_providers(?:\."([^"]+)"|\.'([^']+)'|\.([A-Za-z0-9_-]+))\]$/.exec(line)
if (section) {
inRootTable = false
currentProvider = section[1] ?? section[2] ?? section[3] ?? null
continue
}
if (line.startsWith('[')) {
inRootTable = false
currentProvider = null
continue
}
const providerMatch = /^model_provider\s*=\s*(.+)$/.exec(line)
if (providerMatch && inRootTable) {
activeProvider = unquoteTomlString(providerMatch[1])
continue
}
if (currentProvider === null) continue
const fieldMatch = /^([A-Za-z0-9_-]+)\s*=\s*(.+)$/.exec(line)
if (!fieldMatch) continue
const value = unquoteTomlString(fieldMatch[2])
if (value === null) continue
const provider = providers.get(currentProvider) ?? {}
if (fieldMatch[1] === 'base_url') provider.baseUrl = nonEmptyString(value) ?? undefined
if (fieldMatch[1] === 'env_key') provider.envKey = nonEmptyString(value) ?? undefined
providers.set(currentProvider, provider)
}
return { activeProvider, providers }
}
/**
* Read the active Codex model provider's base URL without a TOML dependency.
* This intentionally supports the small stable subset needed for credentials:
* `model_provider` and `[model_providers.<name>] base_url`.
*/
export function parseCodexBaseUrl(configText: string): string | null {
const config = parseCodexConfig(configText)
return config.activeProvider ? config.providers.get(config.activeProvider)?.baseUrl ?? null : null
}
async function resolveClaudeCredentials(env: NodeJS.ProcessEnv): Promise<ResolvedUsageCredentials> {
let baseUrl = nonEmptyString(env.ANTHROPIC_BASE_URL)
let apiKey = nonEmptyString(env.CLAUDE_CODE_OAUTH_TOKEN)
?? nonEmptyString(env.ANTHROPIC_AUTH_TOKEN)
?? nonEmptyString(env.ANTHROPIC_API_KEY)
let baseUrlSource: UsageQueryCredentialStatus['source'] = baseUrl ? 'environment' : 'none'
let apiKeySource: UsageQueryCredentialStatus['source'] = apiKey ? 'environment' : 'none'
const configDir = nonEmptyString(env.CLAUDE_CONFIG_DIR) ?? join(homedir(), '.claude')
const settings = await readJsonObject(join(configDir, 'settings.json'))
const settingsEnv = settings?.env && typeof settings.env === 'object' && !Array.isArray(settings.env)
? settings.env as JsonObject
: settings
if (!baseUrl) {
baseUrl = firstObjectString(settingsEnv, ['ANTHROPIC_BASE_URL']) ?? ''
if (baseUrl) baseUrlSource = 'config'
}
if (!apiKey) {
apiKey = firstObjectString(settingsEnv, ['CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY']) ?? ''
if (apiKey) apiKeySource = 'config'
}
return {
baseUrl: baseUrl ?? '',
apiKey: apiKey ?? '',
baseUrlSource,
apiKeySource
}
}
async function resolveCodexCredentials(env: NodeJS.ProcessEnv): Promise<ResolvedUsageCredentials> {
const codexHome = nonEmptyString(env.CODEX_HOME) ?? join(homedir(), '.codex')
let config: CodexConfigSnapshot = { activeProvider: null, providers: new Map() }
try {
config = parseCodexConfig(await readFile(join(codexHome, 'config.toml'), 'utf8'))
} catch {
// Missing Codex config uses the default OpenAI credential path.
}
const activeProvider = config.activeProvider
const selected = activeProvider ? config.providers.get(activeProvider) : undefined
const isOpenAiProvider = !activeProvider || activeProvider === 'openai'
let baseUrl = ''
let apiKey = ''
let baseUrlSource: UsageQueryCredentialStatus['source'] = 'none'
let apiKeySource: UsageQueryCredentialStatus['source'] = 'none'
if (!isOpenAiProvider) {
baseUrl = selected?.baseUrl ?? ''
if (baseUrl) baseUrlSource = 'config'
if (selected?.envKey) {
apiKey = nonEmptyString(env[selected.envKey]) ?? ''
if (apiKey) apiKeySource = 'environment'
}
} else {
baseUrl = nonEmptyString(env.OPENAI_BASE_URL) ?? selected?.baseUrl ?? ''
if (baseUrl) baseUrlSource = env.OPENAI_BASE_URL ? 'environment' : 'config'
apiKey = nonEmptyString(env.OPENAI_API_KEY) ?? ''
if (apiKey) apiKeySource = 'environment'
if (!apiKey) {
const auth = await readJsonObject(join(codexHome, 'auth.json'))
apiKey = firstObjectString(auth, ['OPENAI_API_KEY', 'openai_api_key', 'api_key', 'apiKey']) ?? ''
if (apiKey) apiKeySource = 'config'
}
}
return {
baseUrl,
apiKey,
baseUrlSource,
apiKeySource
}
}
async function resolveKimiCredentials(env: NodeJS.ProcessEnv, userHome = homedir()): Promise<ResolvedUsageCredentials> {
let baseUrl = nonEmptyString(env.KIMI_BASE_URL)
let apiKey = nonEmptyString(env.KIMI_API_KEY)
let baseUrlSource: UsageQueryCredentialStatus['source'] = baseUrl ? 'environment' : 'none'
let apiKeySource: UsageQueryCredentialStatus['source'] = apiKey ? 'environment' : 'none'
const provider = chooseKimiProvider(await readKimiConfig(env, userHome))
if (!baseUrl) {
baseUrl = provider?.baseUrl ?? ''
if (baseUrl) baseUrlSource = 'config'
}
if (!apiKey) {
apiKey = provider?.apiKey ?? ''
if (apiKey) apiKeySource = 'config'
}
return {
baseUrl: baseUrl ?? '',
apiKey: apiKey ?? '',
baseUrlSource,
apiKeySource
}
}
export async function resolveUsageCredentials(
agent: UsageQueryAgent,
env: NodeJS.ProcessEnv = process.env,
userHome = homedir()
): Promise<ResolvedUsageCredentials> {
if (agent === 'claude') return await resolveClaudeCredentials(env)
if (agent === 'codex') return await resolveCodexCredentials(env)
return await resolveKimiCredentials(env, userHome)
}
+246
View File
@@ -0,0 +1,246 @@
import { describe, expect, it } from 'vitest'
import {
DEFAULT_USAGE_QUERY_TEMPLATE,
DEFAULT_USAGE_QUERY_TEMPLATES,
USAGE_QUERY_MAX_RESPONSE_BYTES,
UsageQueryTemplateSchema,
type UsageQueryTemplate
} from '@hapi/protocol/usageQuery'
import {
executeUsageQueryTemplate,
getUsageJsonPath,
normalizeUsageWindow,
parseResetTimestamp,
type UsageQueryFetch
} from './execute'
import type { ResolvedUsageCredentials } from './credentials'
const credentials: ResolvedUsageCredentials = {
baseUrl: 'https://provider.example/api',
apiKey: 'secret-value',
baseUrlSource: 'config',
apiKeySource: 'config'
}
function response(body: unknown, init: { ok?: boolean; status?: number; contentLength?: string } = {}) {
return {
ok: init.ok ?? true,
status: init.status ?? 200,
headers: { get: (name: string) => name.toLowerCase() === 'content-length' ? (init.contentLength ?? null) : null },
text: async () => JSON.stringify(body)
}
}
function makeTemplate(overrides: Partial<UsageQueryTemplate> = {}): UsageQueryTemplate {
return UsageQueryTemplateSchema.parse({
...DEFAULT_USAGE_QUERY_TEMPLATE,
...overrides
})
}
describe('usage query executor', () => {
it('resolves the restricted dot and numeric bracket path syntax', () => {
const body = { limits: [{ detail: { remaining: '24' } }] }
expect(getUsageJsonPath(body, 'limits[0].detail.remaining')).toBe('24')
expect(getUsageJsonPath(body, 'limits[1].detail.remaining')).toBeUndefined()
expect(getUsageJsonPath(body, 'limits[0].detail[0]')).toBeUndefined()
expect(getUsageJsonPath(body, 'limits[0].detail.remaining; evil')).toBeUndefined()
})
it('normalizes the built-in Kimi-style remaining/limit windows', async () => {
const template = DEFAULT_USAGE_QUERY_TEMPLATES.find((item) => item.id === 'kimi-coding-plan')!
const reset = '2026-09-07T00:00:00.000Z'
const fetchImpl: UsageQueryFetch = async (url, init) => {
expect(url).toBe('https://provider.example/coding/v1/usages')
expect(init.method).toBe('GET')
expect(init.headers.Authorization).toBe('Bearer secret-value')
return response({
limits: [{ detail: { remaining: 25, limit: 100, resetTime: reset } }],
usage: { remaining: 900, limit: 1000, resetTime: reset }
})
}
const result = await executeUsageQueryTemplate('claude', template, credentials, { fetchImpl, now: 123 })
expect(result).toMatchObject({
agent: 'claude',
templateId: template.id,
status: 'success',
fiveHour: { usedPercent: 75, resetsAt: Date.parse(reset) },
sevenDay: { usedPercent: 10, resetsAt: Date.parse(reset) },
queriedAt: 123,
stale: false
})
})
it('normalizes a configured base URL before appending the template path', async () => {
const template = DEFAULT_USAGE_QUERY_TEMPLATES.find((item) => item.id === 'kimi-coding-plan')!
const fetchImpl: UsageQueryFetch = async (url) => {
expect(url).toBe('https://provider.example/coding/v1/usages')
return response({ usage: { remaining: 1, limit: 2 } })
}
const result = await executeUsageQueryTemplate('claude', template, {
...credentials,
baseUrl: 'https://provider.example/api/?ignored=query#fragment'
}, { fetchImpl })
expect(result.sevenDay?.usedPercent).toBe(50)
})
it('supports direct ratio percentages and clamps them to the normalized range', () => {
const window = normalizeUsageWindow(
{ value: 1.4, reset: 1_780_000_000 },
{ percentPath: 'value', percentScale: 'ratio', resetPath: 'reset', resetUnit: 'seconds' }
)
expect(window).toEqual({ usedPercent: 100, resetsAt: 1_780_000_000_000 })
expect(normalizeUsageWindow(
{ value: 0.4, reset: 1_780_000_000_000 },
{ percentPath: 'value', percentScale: 'ratio', resetPath: 'reset', resetUnit: 'iso' }
)?.resetsAt).toBe(1_780_000_000_000)
})
it('does not coerce blank or non-scalar quota values to numbers', () => {
const spec = { percentPath: 'value', resetUnit: 'iso' as const }
expect(normalizeUsageWindow({ value: ' ' }, spec)).toBeNull()
expect(normalizeUsageWindow({ value: [] }, spec)).toBeNull()
})
it('honors explicit units for numeric epoch strings', () => {
expect(parseResetTimestamp('1780000000', 'seconds')).toBe(1_780_000_000_000)
expect(parseResetTimestamp('1780000000000', 'milliseconds')).toBe(1_780_000_000_000)
})
it('normalizes ZenMux, Zhipu, and MiniMax reviewed adapters', async () => {
const run = async (adapter: UsageQueryTemplate['adapter'], body: unknown) => {
const template = UsageQueryTemplateSchema.parse({
...DEFAULT_USAGE_QUERY_TEMPLATE,
id: `adapter-${adapter}`,
adapter,
request: { ...DEFAULT_USAGE_QUERY_TEMPLATE.request, url: '{{baseOrigin}}/quota' },
fiveHour: {},
sevenDay: {}
})
return await executeUsageQueryTemplate('claude', template, credentials, {
fetchImpl: async () => response(body)
})
}
const zenmux = await run('zenmux-subscription', {
data: {
quota_5_hour: { usage_percentage: 0.25, resets_at: '2026-09-10T00:00:00Z' },
quota_7_day: { usage_percentage: 0.4, resets_at: '2026-09-11T00:00:00Z' }
}
})
expect(zenmux.fiveHour?.usedPercent).toBe(25)
expect(zenmux.sevenDay?.usedPercent).toBe(40)
const zhipu = await run('zhipu-coding', {
data: { limits: [
{ type: 'TOKENS_LIMIT', unit: 6, percentage: 60, nextResetTime: 1_780_100_000_000 },
{ type: 'TOKENS_LIMIT', unit: 3, percentage: 20, nextResetTime: 1_780_050_000_000 }
] }
})
expect(zhipu.fiveHour?.usedPercent).toBe(20)
expect(zhipu.sevenDay?.usedPercent).toBe(60)
const minimax = await run('minimax-coding', {
model_remains: [{
model_name: 'general',
current_interval_remaining_percent: 75,
end_time: 1_780_050_000_000,
current_weekly_status: 1,
current_weekly_remaining_percent: 50,
weekly_end_time: 1_780_100_000_000
}]
})
expect(minimax.fiveHour?.usedPercent).toBe(25)
expect(minimax.sevenDay?.usedPercent).toBe(50)
})
it('rejects cross-origin URLs and API keys embedded in URLs', async () => {
const crossOrigin = makeTemplate({ request: { ...DEFAULT_USAGE_QUERY_TEMPLATE.request, url: 'https://other.example/usage' } })
await expect(executeUsageQueryTemplate('codex', crossOrigin, credentials, { fetchImpl: async () => response({}) }))
.rejects.toThrow('configured base URL origin')
const keyInUrl = makeTemplate({ request: { ...DEFAULT_USAGE_QUERY_TEMPLATE.request, url: '{{baseUrl}}/usage?key={{apiKey}}' } })
await expect(executeUsageQueryTemplate('codex', keyInUrl, credentials, { fetchImpl: async () => response({}) }))
.rejects.toThrow('API key cannot appear')
const literalKeyInUrl = makeTemplate({ request: { ...DEFAULT_USAGE_QUERY_TEMPLATE.request, url: 'https://provider.example/usage?key=secret-value' } })
await expect(executeUsageQueryTemplate('codex', literalKeyInUrl, credentials, { fetchImpl: async () => response({}) }))
.rejects.toThrow('API key cannot appear')
const embeddedCredentials = makeTemplate({ request: { ...DEFAULT_USAGE_QUERY_TEMPLATE.request, url: 'https://user:pass@provider.example/usage' } })
await expect(executeUsageQueryTemplate('codex', embeddedCredentials, credentials, { fetchImpl: async () => response({}) }))
.rejects.toThrow('embedded credentials')
const redirectTemplate = DEFAULT_USAGE_QUERY_TEMPLATES.find((item) => item.id === 'kimi-coding-plan')!
const redirected = executeUsageQueryTemplate('claude', redirectTemplate, credentials, {
fetchImpl: async (_url, init) => {
expect(init.redirect).toBe('error')
return response({}, { ok: false, status: 302 })
}
})
await expect(redirected).rejects.toThrow('HTTP 302')
})
it('rejects non-success and oversized responses without exposing the body', async () => {
const template = makeTemplate()
await expect(executeUsageQueryTemplate('claude', template, credentials, {
fetchImpl: async () => response({ secret: 'must-not-be-returned' }, { ok: false, status: 401 })
})).rejects.toThrow('HTTP 401')
await expect(executeUsageQueryTemplate('claude', template, credentials, {
fetchImpl: async () => response({}, { contentLength: String(3 * 1024 * 1024) })
})).rejects.toThrow('too large')
const encoder = new TextEncoder()
const oversizedChunk = encoder.encode(JSON.stringify({ data: 'x'.repeat(USAGE_QUERY_MAX_RESPONSE_BYTES + 1) }))
const streamTemplate = makeTemplate()
await expect(executeUsageQueryTemplate('claude', streamTemplate, credentials, {
fetchImpl: async () => ({
ok: true,
status: 200,
headers: { get: () => null },
body: new ReadableStream<Uint8Array>({ start(controller) { controller.enqueue(oversizedChunk); controller.close() } }) as unknown as { getReader(): ReadableStreamDefaultReader<Uint8Array> },
text: async () => ''
})
})).rejects.toThrow('too large')
})
it('aborts unread responses when rejecting early', async () => {
let errorSignal: AbortSignal | undefined
await expect(executeUsageQueryTemplate('claude', makeTemplate(), credentials, {
fetchImpl: async (_url, init) => {
errorSignal = init.signal
return response({}, { ok: false, status: 502 })
}
})).rejects.toThrow('HTTP 502')
expect(errorSignal?.aborted).toBe(true)
let oversizedSignal: AbortSignal | undefined
await expect(executeUsageQueryTemplate('claude', makeTemplate(), credentials, {
fetchImpl: async (_url, init) => {
oversizedSignal = init.signal
return response({}, { contentLength: String(USAGE_QUERY_MAX_RESPONSE_BYTES + 1) })
}
})).rejects.toThrow('too large')
expect(oversizedSignal?.aborted).toBe(true)
let networkSignal: AbortSignal | undefined
await expect(executeUsageQueryTemplate('claude', makeTemplate(), credentials, {
fetchImpl: async (_url, init) => {
networkSignal = init.signal
throw new Error('network unavailable')
}
})).rejects.toThrow('network unavailable')
expect(networkSignal?.aborted).toBe(true)
})
it('aborts a request at the ten-second default timeout boundary', async () => {
const template = makeTemplate()
await expect(executeUsageQueryTemplate('claude', template, credentials, {
timeoutMs: 5,
fetchImpl: async (_url, init) => await new Promise((_resolve, reject) => {
init.signal.addEventListener('abort', () => reject(new Error('aborted by timeout')), { once: true })
})
})).rejects.toThrow('timed out')
})
})
+427
View File
@@ -0,0 +1,427 @@
import type {
UsageQueryAgent,
UsageQueryAdapter,
UsageQueryResult,
UsageQueryTemplate,
UsageQueryWindow,
UsageQueryWindowSpec
} from '@hapi/protocol/usageQuery'
import {
USAGE_QUERY_MAX_RESPONSE_BYTES,
USAGE_QUERY_TIMEOUT_MS
} from '@hapi/protocol/usageQuery'
import type { ResolvedUsageCredentials } from './credentials'
type FetchResponseLike = {
ok: boolean
status: number
headers?: { get(name: string): string | null }
body?: { getReader(): ReadableStreamDefaultReader<Uint8Array> }
text(): Promise<string>
}
export type UsageQueryFetch = (
input: string,
init: {
method: string
headers: Record<string, string>
signal: AbortSignal
redirect: 'error'
}
) => Promise<FetchResponseLike>
export class UsageQueryExecutionError extends Error {
constructor(message: string) {
super(message)
this.name = 'UsageQueryExecutionError'
}
}
function parseNumber(value: unknown): number | null {
if (typeof value === 'number') return Number.isFinite(value) ? value : null
if (typeof value !== 'string') return null
const trimmed = value.trim()
if (!trimmed) return null
const number = Number(trimmed)
return Number.isFinite(number) ? number : null
}
function isLoopbackHostname(hostname: string): boolean {
const normalized = hostname.toLowerCase()
return normalized === 'localhost'
|| normalized === '127.0.0.1'
|| normalized === '[::1]'
|| normalized === '::1'
}
function normalizeBaseUrl(value: string): URL {
let parsed: URL
try {
parsed = new URL(value)
} catch {
throw new UsageQueryExecutionError('Base URL is invalid')
}
if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && isLoopbackHostname(parsed.hostname))) {
throw new UsageQueryExecutionError('Base URL must use HTTPS (loopback HTTP is allowed)')
}
if (parsed.username || parsed.password) {
throw new UsageQueryExecutionError('Base URL must not contain embedded credentials')
}
parsed.hash = ''
parsed.search = ''
parsed.pathname = parsed.pathname.replace(/\/+$/, '') || '/'
return parsed
}
function substitute(value: string, credentials: ResolvedUsageCredentials, baseOrigin: string): string {
return value
.replaceAll('{{baseUrl}}', credentials.baseUrl.replace(/\/+$/, ''))
.replaceAll('{{baseOrigin}}', baseOrigin)
.replaceAll('{{apiKey}}', credentials.apiKey)
}
function resolveRequestUrl(rawUrl: string, credentials: ResolvedUsageCredentials, baseOrigin: string): URL {
if (rawUrl.includes('{{apiKey}}') || (credentials.apiKey && rawUrl.includes(credentials.apiKey))) {
throw new UsageQueryExecutionError('API key cannot appear in the request URL')
}
const baseUrl = normalizeBaseUrl(credentials.baseUrl)
const substituted = substitute(rawUrl, credentials, baseOrigin)
let requestUrl: URL
try {
requestUrl = new URL(substituted, baseUrl)
} catch {
throw new UsageQueryExecutionError('Request URL is invalid')
}
if (requestUrl.origin !== baseUrl.origin) {
throw new UsageQueryExecutionError('Request URL must use the configured base URL origin')
}
if (requestUrl.username || requestUrl.password) {
throw new UsageQueryExecutionError('Request URL must not contain embedded credentials')
}
if (requestUrl.protocol !== 'https:' && !(requestUrl.protocol === 'http:' && isLoopbackHostname(requestUrl.hostname))) {
throw new UsageQueryExecutionError('Request URL must use HTTPS (loopback HTTP is allowed)')
}
return requestUrl
}
function tokenizePath(path: string): string[] | null {
const tokens: string[] = []
let cursor = 0
while (cursor < path.length) {
if (path[cursor] === '.') {
cursor += 1
continue
}
if (path[cursor] === '[') {
const end = path.indexOf(']', cursor + 1)
if (end < 0 || !/^\d+$/.test(path.slice(cursor + 1, end))) return null
tokens.push(path.slice(cursor + 1, end))
cursor = end + 1
continue
}
const start = cursor
while (cursor < path.length && path[cursor] !== '.' && path[cursor] !== '[') cursor += 1
if (start === cursor) return null
tokens.push(path.slice(start, cursor))
}
return tokens.length > 0 ? tokens : null
}
/** Resolve the small dot/bracket path syntax used by the safe templates. */
export function getUsageJsonPath(value: unknown, path: string | undefined): unknown {
if (!path) return undefined
const tokens = tokenizePath(path.trim())
if (!tokens) return undefined
let current: unknown = value
for (const token of tokens) {
if (current === null || current === undefined || typeof current !== 'object') return undefined
if (Array.isArray(current)) {
const index = Number(token)
if (!Number.isSafeInteger(index) || index < 0 || index >= current.length) return undefined
current = current[index]
} else {
current = (current as Record<string, unknown>)[token]
}
}
return current
}
export function parseResetTimestamp(value: unknown, unit: UsageQueryWindowSpec['resetUnit']): number | null {
if (unit === 'seconds' || unit === 'milliseconds') {
const number = parseNumber(value)
if (number === null || number <= 0) return null
return unit === 'milliseconds' ? Math.round(number) : Math.round(number * 1000)
}
if (typeof value === 'string') {
const timestamp = Date.parse(value)
return Number.isFinite(timestamp) ? timestamp : null
}
const number = parseNumber(value)
if (number === null || number <= 0) return null
if (number >= 1_000_000_000_000) return Math.round(number)
return Math.round(number * 1000)
}
function clampPercent(value: number): number {
return Math.min(100, Math.max(0, Math.round(value)))
}
async function readBoundedResponseText(response: FetchResponseLike): Promise<string> {
const reader = response.body?.getReader()
if (!reader) {
// Test doubles and non-streaming fetch implementations may only expose
// text(). Production Fetch Responses provide a body stream, so the
// bounded path is used for real requests.
const raw = await response.text()
if (new TextEncoder().encode(raw).byteLength > USAGE_QUERY_MAX_RESPONSE_BYTES) {
throw new UsageQueryExecutionError('Usage response is too large')
}
return raw
}
const chunks: Uint8Array[] = []
let totalBytes = 0
try {
while (true) {
const next = await reader.read()
if (next.done) break
if (!next.value) continue
totalBytes += next.value.byteLength
if (totalBytes > USAGE_QUERY_MAX_RESPONSE_BYTES) {
await reader.cancel()
throw new UsageQueryExecutionError('Usage response is too large')
}
chunks.push(next.value)
}
} finally {
reader.releaseLock()
}
const bytes = new Uint8Array(totalBytes)
let offset = 0
for (const chunk of chunks) {
bytes.set(chunk, offset)
offset += chunk.byteLength
}
return new TextDecoder().decode(bytes)
}
/** Convert one response window into the normalized Hapi shape. */
export function normalizeUsageWindow(body: unknown, spec: UsageQueryWindowSpec): UsageQueryWindow | null {
let percent: number | null = null
const direct = parseNumber(getUsageJsonPath(body, spec.percentPath))
if (direct !== null) {
percent = (spec.percentScale ?? 'percent') === 'ratio' ? direct * 100 : direct
}
const limit = parseNumber(getUsageJsonPath(body, spec.limitPath))
if (percent === null && limit !== null && limit > 0) {
const used = parseNumber(getUsageJsonPath(body, spec.usedPath))
const remaining = parseNumber(getUsageJsonPath(body, spec.remainingPath))
if (used !== null) percent = (used / limit) * 100
else if (remaining !== null) percent = ((limit - remaining) / limit) * 100
}
if (percent === null) return null
return {
usedPercent: clampPercent(percent),
resetsAt: parseResetTimestamp(getUsageJsonPath(body, spec.resetPath), spec.resetUnit)
}
}
function emptyUsageWindows(): { fiveHour: UsageQueryWindow | null; sevenDay: UsageQueryWindow | null } {
return { fiveHour: null, sevenDay: null }
}
function normalizeKimiWindows(body: unknown): { fiveHour: UsageQueryWindow | null; sevenDay: UsageQueryWindow | null } {
return {
fiveHour: normalizeUsageWindow(body, {
remainingPath: 'limits[0].detail.remaining',
limitPath: 'limits[0].detail.limit',
resetPath: 'limits[0].detail.resetTime',
resetUnit: 'iso'
}),
sevenDay: normalizeUsageWindow(body, {
remainingPath: 'usage.remaining',
limitPath: 'usage.limit',
resetPath: 'usage.resetTime',
resetUnit: 'iso'
})
}
}
function normalizeZenMuxWindows(body: unknown): { fiveHour: UsageQueryWindow | null; sevenDay: UsageQueryWindow | null } {
return {
fiveHour: normalizeUsageWindow(body, {
percentPath: 'data.quota_5_hour.usage_percentage',
percentScale: 'ratio',
resetPath: 'data.quota_5_hour.resets_at',
resetUnit: 'iso'
}),
sevenDay: normalizeUsageWindow(body, {
percentPath: 'data.quota_7_day.usage_percentage',
percentScale: 'ratio',
resetPath: 'data.quota_7_day.resets_at',
resetUnit: 'iso'
})
}
}
function normalizeZhipuWindows(body: unknown): { fiveHour: UsageQueryWindow | null; sevenDay: UsageQueryWindow | null } {
const limits = getUsageJsonPath(body, 'data.limits')
if (!Array.isArray(limits)) return emptyUsageWindows()
const candidates = limits.filter((item): item is Record<string, unknown> => Boolean(item) && typeof item === 'object')
.filter((item) => {
const type = String(item.type ?? '').toLowerCase()
return type === 'tokens_limit' || type === 'credit_limit'
})
.map((item) => ({
item,
window: normalizeUsageWindow(item, {
percentPath: 'percentage',
percentScale: 'percent',
resetPath: 'nextResetTime',
resetUnit: 'milliseconds'
}),
unit: Number(item.unit)
}))
.filter((candidate): candidate is { item: Record<string, unknown>; window: UsageQueryWindow; unit: number } => candidate.window !== null)
let fiveHour = candidates.find((candidate) => candidate.unit === 3)?.window ?? null
let sevenDay = candidates.find((candidate) => candidate.unit === 6)?.window ?? null
const remaining = candidates.filter((candidate) => candidate.window !== fiveHour && candidate.window !== sevenDay)
.sort((left, right) => Number(left.window.resetsAt !== null) - Number(right.window.resetsAt !== null)
|| (left.window.resetsAt ?? Number.MIN_SAFE_INTEGER) - (right.window.resetsAt ?? Number.MIN_SAFE_INTEGER))
if (!fiveHour) fiveHour = remaining.shift()?.window ?? null
if (!sevenDay) sevenDay = remaining.shift()?.window ?? null
return { fiveHour, sevenDay }
}
function normalizeMiniMaxWindows(body: unknown): { fiveHour: UsageQueryWindow | null; sevenDay: UsageQueryWindow | null } {
const remains = getUsageJsonPath(body, 'model_remains')
if (!Array.isArray(remains)) return emptyUsageWindows()
const general = remains.find((item) => item && typeof item === 'object' && (item as Record<string, unknown>).model_name === 'general')
if (!general || typeof general !== 'object') return emptyUsageWindows()
const item = general as Record<string, unknown>
const fiveRemaining = parseNumber(item.current_interval_remaining_percent)
const fiveHour = fiveRemaining === null ? null : {
usedPercent: clampPercent(100 - fiveRemaining),
resetsAt: parseResetTimestamp(item.end_time, 'milliseconds')
}
const weeklyStatus = parseNumber(item.current_weekly_status)
const weeklyRemaining = parseNumber(item.current_weekly_remaining_percent)
const sevenDay = weeklyStatus === 1 && weeklyRemaining !== null ? {
usedPercent: clampPercent(100 - weeklyRemaining),
resetsAt: parseResetTimestamp(item.weekly_end_time, 'milliseconds')
} : null
return { fiveHour, sevenDay }
}
function normalizeAdapterWindows(
body: unknown,
adapter: UsageQueryAdapter,
template: UsageQueryTemplate
): { fiveHour: UsageQueryWindow | null; sevenDay: UsageQueryWindow | null } {
switch (adapter) {
case 'kimi-coding': return normalizeKimiWindows(body)
case 'zenmux-subscription': return normalizeZenMuxWindows(body)
case 'zhipu-coding': return normalizeZhipuWindows(body)
case 'minimax-coding': return normalizeMiniMaxWindows(body)
case 'json-path':
default:
return {
fiveHour: normalizeUsageWindow(body, template.fiveHour),
sevenDay: normalizeUsageWindow(body, template.sevenDay)
}
}
}
function createAbortSignal(signal: AbortSignal | undefined, timeoutMs: number): {
signal: AbortSignal
dispose: () => void
} {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), timeoutMs)
const abort = () => controller.abort()
signal?.addEventListener('abort', abort, { once: true })
return {
signal: controller.signal,
dispose: () => {
clearTimeout(timeout)
signal?.removeEventListener('abort', abort)
controller.abort()
}
}
}
export async function executeUsageQueryTemplate(
agent: UsageQueryAgent,
template: UsageQueryTemplate,
credentials: ResolvedUsageCredentials,
options: {
fetchImpl?: UsageQueryFetch
timeoutMs?: number
now?: number
} = {}
): Promise<UsageQueryResult> {
if (!credentials.baseUrl) throw new UsageQueryExecutionError('Base URL is not configured')
if (!credentials.apiKey) throw new UsageQueryExecutionError('API key is not configured')
const fetchImpl = options.fetchImpl ?? (fetch as unknown as UsageQueryFetch)
const normalizedBase = normalizeBaseUrl(credentials.baseUrl)
const normalizedCredentials: ResolvedUsageCredentials = {
...credentials,
baseUrl: normalizedBase.toString().replace(/\/+$/, '')
}
const requestUrl = resolveRequestUrl(template.request.url, normalizedCredentials, normalizedBase.origin)
const headers = Object.fromEntries(
Object.entries(template.request.headers).map(([name, value]) => [name, substitute(value, normalizedCredentials, normalizedBase.origin)])
)
const { signal, dispose } = createAbortSignal(undefined, options.timeoutMs ?? USAGE_QUERY_TIMEOUT_MS)
let response: FetchResponseLike
try {
response = await fetchImpl(requestUrl.toString(), {
method: template.request.method,
headers,
redirect: 'error',
signal
})
} catch (error) {
const timedOut = signal.aborted
dispose()
if (timedOut) throw new UsageQueryExecutionError('Usage request timed out')
throw new UsageQueryExecutionError(error instanceof Error ? error.message : 'Usage request failed')
}
try {
if (!response.ok) throw new UsageQueryExecutionError(`Usage request failed (HTTP ${response.status})`)
const length = response.headers?.get('content-length')
if (length && Number(length) > USAGE_QUERY_MAX_RESPONSE_BYTES) {
throw new UsageQueryExecutionError('Usage response is too large')
}
const raw = await readBoundedResponseText(response)
let body: unknown
try {
body = JSON.parse(raw) as unknown
} catch {
throw new UsageQueryExecutionError('Usage response was not valid JSON')
}
const { fiveHour, sevenDay } = normalizeAdapterWindows(body, template.adapter, template)
if (!fiveHour && !sevenDay) throw new UsageQueryExecutionError('Usage response contained no configured quota windows')
return {
agent,
templateId: template.id,
status: 'success',
fiveHour,
sevenDay,
queriedAt: options.now ?? Date.now(),
stale: false
}
} finally {
dispose()
}
}
+356
View File
@@ -0,0 +1,356 @@
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
DEFAULT_USAGE_QUERY_TEMPLATES,
type UsageQueryTemplate
} from '@hapi/protocol/usageQuery'
import type { ResolvedUsageCredentials } from './credentials'
import { UsageQueryService } from './service'
import type { UsageQueryFetch } from './execute'
const credentials: ResolvedUsageCredentials = {
baseUrl: 'https://provider.example',
apiKey: 'test-key',
baseUrlSource: 'config',
apiKeySource: 'config'
}
function makeResponse(remaining: number) {
return {
ok: true,
status: 200,
headers: { get: () => null },
text: async () => JSON.stringify({
limits: [{ detail: { remaining, limit: 100, resetTime: '2026-09-07T00:00:00.000Z' } }],
usage: { remaining: 800, limit: 1000, resetTime: '2026-09-08T00:00:00.000Z' }
})
}
}
describe('UsageQueryService', () => {
let root: string | undefined
afterEach(async () => {
if (root) await rm(root, { recursive: true, force: true })
root = undefined
})
it('persists settings and caches successful queries for five minutes', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
let now = 1_780_000_000_000
let calls = 0
const fetchImpl: UsageQueryFetch = async () => {
calls += 1
return makeResponse(25)
}
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
now: () => now,
fetchImpl,
resolveCredentials: async () => credentials
})
const template = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await service.saveSettings('claude', { enabled: true, templateId: template.id, template })
const first = await service.query('claude')
expect(first.status).toBe('success')
expect(first.fiveHour?.usedPercent).toBe(75)
expect(calls).toBe(1)
now += 4 * 60_000
await service.query('claude')
expect(calls).toBe(1)
now += 2 * 60_000
await service.query('claude')
expect(calls).toBe(2)
})
it('does not reuse cached data after credential rotation', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
let now = 1_780_000_000_000
let activeCredentials = credentials
let calls = 0
const fetchImpl: UsageQueryFetch = async (_url, init) => {
calls += 1
expect(init.headers.Authorization).toBe(`Bearer ${activeCredentials.apiKey}`)
return makeResponse(calls === 1 ? 25 : 50)
}
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
now: () => now,
fetchImpl,
resolveCredentials: async () => activeCredentials
})
const template = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await service.saveSettings('claude', { enabled: true, templateId: template.id, template })
const first = await service.query('claude')
expect(first.fiveHour?.usedPercent).toBe(75)
activeCredentials = { ...credentials, apiKey: 'rotated-key' }
now += 60_000
const rotated = await service.query('claude')
expect(rotated.fiveHour?.usedPercent).toBe(50)
expect(calls).toBe(2)
})
it('retries a forced failure after cooldown even when the prior success is fresh', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
let now = 1_780_000_000_000
let calls = 0
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
now: () => now,
fetchImpl: async () => {
calls += 1
if (calls === 1) return makeResponse(25)
throw new Error('provider unavailable')
},
resolveCredentials: async () => credentials
})
const template = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await service.saveSettings('claude', { enabled: true, templateId: template.id, template })
await service.query('claude')
now += 60_000
const forced = await service.query('claude', true)
expect(forced).toMatchObject({ status: 'error', stale: true, fiveHour: { usedPercent: 75 } })
expect(calls).toBe(2)
now += 10_000
await service.query('claude')
expect(calls).toBe(2)
now += 21_000
const retried = await service.query('claude')
expect(retried.status).toBe('error')
expect(calls).toBe(3)
})
it('keeps stale windows after an error and suppresses automatic retries for 30 seconds', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
let now = 1_780_000_000_000
let calls = 0
const fetchImpl: UsageQueryFetch = async () => {
calls += 1
if (calls === 1) return makeResponse(10)
throw new Error('provider unavailable')
}
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
now: () => now,
fetchImpl,
resolveCredentials: async () => credentials
})
const template = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await service.saveSettings('claude', { enabled: true, templateId: template.id, template })
await service.query('claude')
now += 5 * 60_000
const failed = await service.query('claude')
expect(failed).toMatchObject({ status: 'error', stale: true, fiveHour: { usedPercent: 90 } })
expect(failed.error).toContain('provider unavailable')
expect(calls).toBe(2)
now += 10_000
await service.query('claude')
expect(calls).toBe(2)
const forced = await service.query('claude', true)
expect(forced.status).toBe('error')
expect(calls).toBe(3)
})
it('does not reuse stale data after switching templates', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
let now = 1_780_000_000_000
let calls = 0
let fail = false
const fetchImpl: UsageQueryFetch = async () => {
calls += 1
if (fail) throw new Error('new template unavailable')
return makeResponse(0)
}
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
now: () => now,
fetchImpl,
resolveCredentials: async () => credentials
})
const first = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await service.saveSettings('claude', { enabled: true, templateId: first.id, template: first })
await service.query('claude')
const second: UsageQueryTemplate = {
...first,
name: 'Changed template'
}
fail = true
await service.saveSettings('claude', { enabled: true, templateId: second.id, template: second })
const result = await service.query('claude')
expect(result).toMatchObject({ status: 'error', templateId: second.id, fiveHour: null, sevenDay: null, stale: false })
expect(calls).toBe(2)
})
it('does not reuse an in-flight request after switching templates', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
let calls = 0
let releaseFirst!: () => void
let firstStarted!: () => void
const firstStartedPromise = new Promise<void>((resolve) => { firstStarted = resolve })
const fetchImpl: UsageQueryFetch = async () => {
calls += 1
if (calls === 1) {
firstStarted()
return await new Promise((resolve) => { releaseFirst = () => resolve(makeResponse(10)) })
}
return makeResponse(50)
}
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
fetchImpl,
resolveCredentials: async () => credentials
})
const first = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await service.saveSettings('claude', { enabled: true, templateId: first.id, template: first })
const firstRequest = service.query('claude')
await firstStartedPromise
const second: UsageQueryTemplate = { ...first, name: 'Changed while querying' }
await service.saveSettings('claude', { enabled: true, templateId: second.id, template: second })
const secondResult = await service.query('claude')
expect(secondResult.fiveHour?.usedPercent).toBe(50)
expect(calls).toBe(2)
releaseFirst()
const firstResult = await firstRequest
expect(firstResult.fiveHour?.usedPercent).toBe(90)
const thirdResult = await service.query('claude')
expect(thirdResult.fiveHour?.usedPercent).toBe(50)
expect(calls).toBe(2)
})
it('does not join an in-flight request after credential rotation', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
let activeCredentials = credentials
let calls = 0
let releaseFirst!: () => void
let firstStarted!: () => void
const firstStartedPromise = new Promise<void>((resolve) => { firstStarted = resolve })
const fetchImpl: UsageQueryFetch = async (_url, init) => {
calls += 1
expect(init.headers.Authorization).toBe(`Bearer ${activeCredentials.apiKey}`)
if (calls === 1) {
firstStarted()
return await new Promise((resolve) => { releaseFirst = () => resolve(makeResponse(10)) })
}
return makeResponse(50)
}
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
fetchImpl,
resolveCredentials: async () => activeCredentials
})
const template = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await service.saveSettings('claude', { enabled: true, templateId: template.id, template })
const firstRequest = service.query('claude')
await firstStartedPromise
activeCredentials = { ...credentials, apiKey: 'rotated-key' }
const rotatedResult = await service.query('claude')
expect(rotatedResult.fiveHour?.usedPercent).toBe(50)
expect(calls).toBe(2)
releaseFirst()
const firstResult = await firstRequest
expect(firstResult.fiveHour?.usedPercent).toBe(90)
const cachedRotated = await service.query('claude')
expect(cachedRotated.fiveHour?.usedPercent).toBe(50)
expect(calls).toBe(2)
})
it('redacts credentials from provider error messages', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
fetchImpl: async () => { throw new Error(`request failed for ${credentials.apiKey}`) },
resolveCredentials: async () => credentials
})
const template = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await service.saveSettings('claude', { enabled: true, templateId: template.id, template })
const result = await service.query('claude')
expect(result.error).toBe('request failed for [redacted]')
})
it('redacts literal credentials from templates returned to Web', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
resolveCredentials: async () => credentials
})
const template = {
...DEFAULT_USAGE_QUERY_TEMPLATES[0],
request: {
...DEFAULT_USAGE_QUERY_TEMPLATES[0].request,
url: `${credentials.baseUrl}/usage`,
headers: { Authorization: `Bearer ${credentials.apiKey}` }
}
}
await service.saveSettings('claude', { enabled: false, templateId: template.id, template })
const returned = await service.getSettings('claude')
expect(returned.template.request.url).toBe('{{baseUrl}}/usage')
expect(returned.template.request.headers.Authorization).toBe('Bearer {{apiKey}}')
expect(await readFile(join(root, 'usage-query.json'), 'utf8')).not.toContain(credentials.apiKey)
})
it('preserves the separator when redacting slash-terminated base URLs', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
const slashCredentials = { ...credentials, baseUrl: 'https://provider.example/' }
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
resolveCredentials: async () => slashCredentials
})
const template = {
...DEFAULT_USAGE_QUERY_TEMPLATES[0],
request: {
...DEFAULT_USAGE_QUERY_TEMPLATES[0].request,
url: 'https://provider.example/usage'
}
}
await service.saveSettings('claude', { enabled: false, templateId: template.id, template })
expect((await service.getSettings('claude')).template.request.url).toBe('{{baseUrl}}/usage')
})
it('serializes concurrent Claude and Codex settings writes', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
resolveCredentials: async () => credentials
})
const template = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await Promise.all([
service.saveSettings('claude', { enabled: true, templateId: template.id, template }),
service.saveSettings('codex', { enabled: true, templateId: template.id, template })
])
expect((await service.getSettings('claude')).enabled).toBe(true)
expect((await service.getSettings('codex')).enabled).toBe(true)
})
it('migrates a v1 settings file without dropping Claude and Codex entries', async () => {
root = await mkdtemp(join(tmpdir(), 'hapi-usage-service-'))
const template = DEFAULT_USAGE_QUERY_TEMPLATES[0]
await writeFile(join(root, 'usage-query.json'), JSON.stringify({
claude: { enabled: true, templateId: template.id, template },
codex: { enabled: false, templateId: template.id, template }
}))
const service = new UsageQueryService({
settingsFile: join(root, 'usage-query.json'),
resolveCredentials: async () => credentials
})
expect((await service.getSettings('claude')).enabled).toBe(true)
expect((await service.getSettings('kimi')).enabled).toBe(false)
})
})
+343
View File
@@ -0,0 +1,343 @@
import { chmod, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
import { dirname } from 'node:path'
import { createHash, randomUUID } from 'node:crypto'
import {
DEFAULT_USAGE_QUERY_TEMPLATE,
USAGE_QUERY_CACHE_TTL_MS,
USAGE_QUERY_RETRY_COOLDOWN_MS,
UsageQueryAgentSettingsSchema,
UsageQuerySettingsSchema,
UsageQueryTemplateSchema,
type UsageQueryAgent,
type UsageQueryAgentSettings,
type UsageQueryResult,
type UsageQuerySettings,
type UsageQuerySettingsResponse,
type UsageQueryTemplate
} from '@hapi/protocol/usageQuery'
import { z } from 'zod'
import { resolveUsageCredentials, type ResolvedUsageCredentials } from './credentials'
import { executeUsageQueryTemplate, type UsageQueryFetch, UsageQueryExecutionError } from './execute'
type UsageQueryServiceOptions = {
settingsFile: string
now?: () => number
fetchImpl?: UsageQueryFetch
resolveCredentials?: (agent: UsageQueryAgent) => Promise<ResolvedUsageCredentials>
}
type CachedResult = {
templateId: string
queryFingerprint: string
result: UsageQueryResult
cachedAt: number
lastAttemptAt: number
lastError: string | null
}
type InFlightRequest = {
fingerprint: string
request: Promise<UsageQueryResult>
}
function queryFingerprint(template: UsageQueryTemplate, credentials: ResolvedUsageCredentials): string {
// Keep credentials in the in-memory identity so a long-lived Runner cannot
// reuse or join quota data after an Agent account/configuration changes.
return createHash('sha256')
.update(JSON.stringify(template))
.update('\0')
.update(credentials.baseUrl)
.update('\0')
.update(credentials.apiKey)
.digest('hex')
}
function cloneTemplate(template: UsageQueryTemplate): UsageQueryTemplate {
return {
...template,
request: {
...template.request,
headers: { ...template.request.headers }
},
fiveHour: { ...template.fiveHour },
sevenDay: { ...template.sevenDay }
}
}
function redactTemplateCredentials(template: UsageQueryTemplate, credentials: ResolvedUsageCredentials): UsageQueryTemplate {
const replacements: Array<[string, string]> = []
if (credentials.apiKey) replacements.push([credentials.apiKey, '{{apiKey}}'])
if (credentials.baseUrl) {
const normalizedBaseUrl = credentials.baseUrl.replace(/\/+$/, '')
if (normalizedBaseUrl) replacements.push([normalizedBaseUrl, '{{baseUrl}}'])
}
if (replacements.length === 0) return cloneTemplate(template)
const redact = (value: string): string => replacements.reduce((result, [secret, placeholder]) => result.replaceAll(secret, placeholder), value)
const cloned = cloneTemplate(template)
cloned.request.url = redact(cloned.request.url)
cloned.request.headers = Object.fromEntries(
Object.entries(cloned.request.headers).map(([name, value]) => [name, redact(value)])
)
return cloned
}
function defaultAgentSettings(): UsageQueryAgentSettings {
const template = cloneTemplate(DEFAULT_USAGE_QUERY_TEMPLATE)
return {
enabled: false,
templateId: template.id,
template
}
}
function defaultSettings(): UsageQuerySettings {
const agent = defaultAgentSettings()
return {
claude: agent,
codex: cloneAgentSettings(agent),
kimi: cloneAgentSettings(agent)
}
}
function cloneAgentSettings(settings: UsageQueryAgentSettings): UsageQueryAgentSettings {
return {
enabled: settings.enabled,
templateId: settings.templateId,
template: cloneTemplate(settings.template)
}
}
function sanitizeError(error: unknown, credentials?: ResolvedUsageCredentials): string {
let message = error instanceof UsageQueryExecutionError
? error.message
: error instanceof Error ? error.message : 'Usage query failed'
const normalizedBaseUrl = credentials?.baseUrl?.replace(/\/+$/, '')
for (const secret of [credentials?.apiKey, credentials?.baseUrl, normalizedBaseUrl]) {
if (secret) message = message.replaceAll(secret, '[redacted]')
}
return message.length > 500 ? message.slice(0, 500) : message
}
function emptyResult(agent: UsageQueryAgent, templateId: string, now: number, error: string, previous?: UsageQueryResult): UsageQueryResult {
return {
agent,
templateId,
status: 'error',
fiveHour: previous?.fiveHour ?? null,
sevenDay: previous?.sevenDay ?? null,
queriedAt: now,
stale: Boolean(previous),
error
}
}
export class UsageQueryService {
private readonly now: () => number
private readonly fetchImpl?: UsageQueryFetch
private readonly resolveCredentials: (agent: UsageQueryAgent) => Promise<ResolvedUsageCredentials>
private readonly settingsFile: string
private readonly cache = new Map<UsageQueryAgent, CachedResult>()
private readonly inFlight = new Map<UsageQueryAgent, InFlightRequest>()
private settingsWriteQueue: Promise<void> = Promise.resolve()
constructor(options: UsageQueryServiceOptions) {
this.settingsFile = options.settingsFile
this.now = options.now ?? Date.now
this.fetchImpl = options.fetchImpl
this.resolveCredentials = options.resolveCredentials ?? ((agent) => resolveUsageCredentials(agent))
}
async getSettings(agent: UsageQueryAgent): Promise<UsageQuerySettingsResponse> {
const settings = await this.readSettings()
const configured = settings[agent]
const credentials = await this.resolveCredentials(agent)
return {
agent,
enabled: configured.enabled,
templateId: configured.templateId,
template: redactTemplateCredentials(configured.template, credentials),
credentials: {
baseUrl: {
configured: Boolean(credentials.baseUrl),
source: credentials.baseUrl ? credentials.baseUrlSource : 'none'
},
apiKey: {
configured: Boolean(credentials.apiKey),
source: credentials.apiKey ? credentials.apiKeySource : 'none'
}
}
}
}
async saveSettings(
agent: UsageQueryAgent,
input: Omit<UsageQueryAgentSettings, 'templateId'> & { templateId: string }
): Promise<UsageQuerySettingsResponse> {
const parsedTemplate = UsageQueryTemplateSchema.parse(input.template)
if (parsedTemplate.id !== input.templateId) {
throw new UsageQueryExecutionError('Template ID does not match template content')
}
const credentials = await this.resolveCredentials(agent)
const template = redactTemplateCredentials(parsedTemplate, credentials)
return await this.withSettingsWrite(async () => {
const settings = await this.readSettings()
settings[agent] = UsageQueryAgentSettingsSchema.parse({
enabled: input.enabled,
templateId: input.templateId,
template
})
await this.writeSettings(settings)
this.cache.delete(agent)
return await this.getSettings(agent)
})
}
async test(agent: UsageQueryAgent, template: UsageQueryTemplate): Promise<UsageQueryResult> {
const parsedTemplate = UsageQueryTemplateSchema.parse(template)
let credentials: ResolvedUsageCredentials | undefined
try {
credentials = await this.resolveCredentials(agent)
return await executeUsageQueryTemplate(agent, parsedTemplate, credentials, {
fetchImpl: this.fetchImpl,
now: this.now()
})
} catch (error) {
return emptyResult(agent, parsedTemplate.id, this.now(), sanitizeError(error, credentials))
}
}
async query(agent: UsageQueryAgent, force = false): Promise<UsageQueryResult> {
const settings = await this.readSettings()
const configured = settings[agent]
const now = this.now()
const cached = this.cache.get(agent)
if (!configured.enabled) {
return emptyResult(agent, configured.templateId, now, 'Usage query is disabled')
}
let credentials: ResolvedUsageCredentials
try {
credentials = await this.resolveCredentials(agent)
} catch (error) {
return emptyResult(agent, configured.templateId, now, sanitizeError(error))
}
// A saved template change invalidates the old value semantically even
// before the in-memory cache entry is cleared (for example, when a
// settings write races an already-running query). Credential changes
// use the same rule, so never present another account's stale data.
const fingerprint = queryFingerprint(configured.template, credentials)
const usableCached = cached !== undefined
&& cached.templateId === configured.templateId
&& cached.queryFingerprint === fingerprint
? cached
: undefined
if (!force && usableCached) {
if (usableCached.lastError) {
if (now - usableCached.lastAttemptAt < USAGE_QUERY_RETRY_COOLDOWN_MS) return usableCached.result
} else if (now - usableCached.cachedAt < USAGE_QUERY_CACHE_TTL_MS) {
return usableCached.result
}
}
const existing = this.inFlight.get(agent)
if (existing?.fingerprint === fingerprint) return await existing.request
const request = this.runQuery(agent, configured, credentials, usableCached, now, fingerprint)
this.inFlight.set(agent, { fingerprint, request })
try {
return await request
} finally {
if (this.inFlight.get(agent)?.request === request) this.inFlight.delete(agent)
}
}
private async runQuery(
agent: UsageQueryAgent,
configured: UsageQueryAgentSettings,
credentials: ResolvedUsageCredentials,
cached: CachedResult | undefined,
startedAt: number,
fingerprint: string
): Promise<UsageQueryResult> {
try {
const result = await executeUsageQueryTemplate(agent, configured.template, credentials, {
fetchImpl: this.fetchImpl,
now: startedAt
})
if (this.inFlight.get(agent)?.fingerprint === fingerprint) {
this.cache.set(agent, {
templateId: configured.templateId,
queryFingerprint: fingerprint,
result,
cachedAt: startedAt,
lastAttemptAt: startedAt,
lastError: null
})
}
return result
} catch (error) {
const message = sanitizeError(error, credentials)
const result = emptyResult(agent, configured.templateId, startedAt, message, cached?.result)
if (this.inFlight.get(agent)?.fingerprint === fingerprint) {
this.cache.set(agent, {
templateId: configured.templateId,
queryFingerprint: fingerprint,
result,
cachedAt: cached?.cachedAt ?? 0,
lastAttemptAt: startedAt,
lastError: message
})
}
return result
}
}
private async readSettings(): Promise<UsageQuerySettings> {
try {
const parsed: unknown = JSON.parse(await readFile(this.settingsFile, 'utf8'))
const result = UsageQuerySettingsSchema.safeParse(parsed)
if (result.success) return result.data
// Migrate the two-agent v1 settings file without dropping the
// user's existing Claude/Codex templates when Kimi support is
// added.
const legacy = z.object({
claude: UsageQueryAgentSettingsSchema,
codex: UsageQueryAgentSettingsSchema
}).strict().safeParse(parsed)
if (legacy.success) {
return {
...legacy.data,
kimi: defaultAgentSettings()
}
}
return defaultSettings()
} catch {
return defaultSettings()
}
}
private async writeSettings(settings: UsageQuerySettings): Promise<void> {
const parsed = UsageQuerySettingsSchema.parse(settings)
await mkdir(dirname(this.settingsFile), { recursive: true })
await chmod(dirname(this.settingsFile), 0o700).catch(() => {})
const temporary = `${this.settingsFile}.${randomUUID()}.tmp`
try {
await writeFile(temporary, `${JSON.stringify(parsed, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
await rename(temporary, this.settingsFile)
} finally {
await unlink(temporary).catch(() => {})
}
}
/** Serialize read-modify-write settings updates within this Runner. */
private async withSettingsWrite<T>(work: () => Promise<T>): Promise<T> {
const previous = this.settingsWriteQueue
let release!: () => void
this.settingsWriteQueue = new Promise<void>((resolve) => { release = resolve })
await previous
try {
return await work()
} finally {
release()
}
}
}