@hex4c59/pi-ext-qoder 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE +9 -0
- package/README.md +151 -2
- package/THIRD_PARTY.md +13 -0
- package/extensions/qoder.ts +960 -0
- package/lib/account.ts +129 -0
- package/lib/catalog.ts +228 -0
- package/lib/credit-report.ts +112 -0
- package/lib/model-report.ts +107 -0
- package/lib/qoder-core.mjs +864 -0
- package/lib/relay-registry.ts +34 -0
- package/lib/report-overlay.ts +175 -0
- package/lib/request-body.ts +48 -0
- package/lib/sse.ts +63 -0
- package/lib/types.ts +100 -0
- package/lib/usage-ui.ts +354 -0
- package/lib/web-search.ts +171 -0
- package/package.json +51 -4
- package/scripts/prepare-signing.mjs +51 -0
- package/vendor/LICENSE.qoder +202 -0
- package/vendor/PROVENANCE.md +42 -0
- package/vendor/auth_glue.mjs +14 -0
- package/vendor/auth_wasm.wasm +0 -0
package/lib/account.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/** 账号额度只使用 Qoder 的积分池,不把倍率或美元价格换算成积分。 */
|
|
2
|
+
import { CONFIG, withTimeout } from './qoder-core.mjs'
|
|
3
|
+
import { accountKey, cleanText, finiteNumber, isRecord } from './catalog.ts'
|
|
4
|
+
import type { QoderCredential } from './types.ts'
|
|
5
|
+
|
|
6
|
+
export const QUOTA_TTL_MS = 60_000
|
|
7
|
+
export interface CreditPool {
|
|
8
|
+
name: string
|
|
9
|
+
total: number
|
|
10
|
+
used: number
|
|
11
|
+
remaining: number
|
|
12
|
+
}
|
|
13
|
+
export interface AccountQuota {
|
|
14
|
+
total: number
|
|
15
|
+
used: number
|
|
16
|
+
remaining: number
|
|
17
|
+
pools: CreditPool[]
|
|
18
|
+
plan: string
|
|
19
|
+
resetAt?: number
|
|
20
|
+
fetchedAt: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 只加总额度池中的明确数值,接口结构异常时保留旧快照并报告错误。 */
|
|
24
|
+
export function normalizeQuota(usage: unknown, plan: unknown, now = Date.now()): AccountQuota {
|
|
25
|
+
if (!isRecord(usage)) throw new Error('Qoder quota response is not an object')
|
|
26
|
+
const candidates: [string, unknown][] = [
|
|
27
|
+
['Plan', usage.userQuota], ['Add-on', usage.addOnQuota], ['Organization', usage.orgResourcePackage],
|
|
28
|
+
...(Array.isArray(usage.dedicatedResourcePackages)
|
|
29
|
+
? usage.dedicatedResourcePackages.map((pool, index): [string, unknown] => [`Dedicated ${index + 1}`, pool]) : []),
|
|
30
|
+
]
|
|
31
|
+
const pools: CreditPool[] = []
|
|
32
|
+
for (const [name, pool] of candidates) {
|
|
33
|
+
if (pool === undefined || pool === null) continue
|
|
34
|
+
if (!isRecord(pool) || (pool.unit !== undefined && pool.unit !== 'credits')) {
|
|
35
|
+
throw new Error('Qoder quota response contains an unsupported credit pool')
|
|
36
|
+
}
|
|
37
|
+
const total = finiteNumber(pool.total)
|
|
38
|
+
const used = finiteNumber(pool.used)
|
|
39
|
+
const remaining = finiteNumber(pool.remaining)
|
|
40
|
+
if (total === undefined || used === undefined || remaining === undefined) {
|
|
41
|
+
throw new Error('Qoder quota response has incomplete credit totals')
|
|
42
|
+
}
|
|
43
|
+
pools.push({ name, total, used, remaining })
|
|
44
|
+
}
|
|
45
|
+
if (!pools.length) throw new Error('Qoder quota response has no credit pools')
|
|
46
|
+
const reset = finiteNumber(usage.expiresAt)
|
|
47
|
+
return {
|
|
48
|
+
total: pools.reduce((sum, pool) => sum + pool.total, 0),
|
|
49
|
+
used: pools.reduce((sum, pool) => sum + pool.used, 0),
|
|
50
|
+
remaining: pools.reduce((sum, pool) => sum + pool.remaining, 0),
|
|
51
|
+
pools,
|
|
52
|
+
plan: (isRecord(plan) && cleanText(plan.plan_tier_name)) || cleanText(usage.userType) || 'Qoder',
|
|
53
|
+
...(reset ? { resetAt: reset < 1_000_000_000_000 ? reset * 1000 : reset } : {}),
|
|
54
|
+
fetchedAt: now,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function fetchDocument(token: string, pathname: string, signal: AbortSignal, fetchImpl: typeof fetch): Promise<unknown> {
|
|
59
|
+
const response = await fetchImpl(CONFIG.openapi + pathname, {
|
|
60
|
+
headers: { accept: 'application/json', authorization: `Bearer ${token}` },
|
|
61
|
+
signal: withTimeout(signal, CONFIG.authRequestTimeoutMs),
|
|
62
|
+
})
|
|
63
|
+
if (!response.ok) {
|
|
64
|
+
await response.body?.cancel()
|
|
65
|
+
throw new Error(`Qoder account lookup returned HTTP ${response.status}`)
|
|
66
|
+
}
|
|
67
|
+
try { return await response.json() } catch { throw new Error('Qoder account response was not JSON') }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 套餐名称查询失败不影响额度;不保存服务端返回的用户标识和链接。 */
|
|
71
|
+
export async function fetchAccountQuota(credential: QoderCredential, {
|
|
72
|
+
signal, fetchImpl = globalThis.fetch,
|
|
73
|
+
}: { signal: AbortSignal; fetchImpl?: typeof fetch }): Promise<AccountQuota> {
|
|
74
|
+
signal.throwIfAborted()
|
|
75
|
+
const [usage, plan] = await Promise.all([
|
|
76
|
+
fetchDocument(credential.access, '/api/v2/quota/usage', signal, fetchImpl),
|
|
77
|
+
fetchDocument(credential.access, '/api/v2/user/plan', signal, fetchImpl).catch(() => undefined),
|
|
78
|
+
])
|
|
79
|
+
signal.throwIfAborted()
|
|
80
|
+
return normalizeQuota(usage, plan)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 余额仅保存在内存,按账号隔离;成功查询后才替换快照。 */
|
|
84
|
+
export class QuotaCache {
|
|
85
|
+
private owner = ''
|
|
86
|
+
private value?: AccountQuota
|
|
87
|
+
private lastFailureAt = 0
|
|
88
|
+
error?: string
|
|
89
|
+
|
|
90
|
+
clear(): void {
|
|
91
|
+
this.owner = ''
|
|
92
|
+
this.value = undefined
|
|
93
|
+
this.error = undefined
|
|
94
|
+
this.lastFailureAt = 0
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
peek(credential: QoderCredential): AccountQuota | undefined {
|
|
98
|
+
return this.owner === accountKey(credential) ? this.value : undefined
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async load(credential: QoderCredential, options: {
|
|
102
|
+
signal: AbortSignal; force?: boolean; fetchImpl?: typeof fetch
|
|
103
|
+
}): Promise<AccountQuota | undefined> {
|
|
104
|
+
const owner = accountKey(credential)
|
|
105
|
+
if (owner !== this.owner) {
|
|
106
|
+
this.clear()
|
|
107
|
+
this.owner = owner
|
|
108
|
+
}
|
|
109
|
+
if (!options.force && ((this.value && Date.now() - this.value.fetchedAt < QUOTA_TTL_MS)
|
|
110
|
+
|| (this.lastFailureAt > 0 && Date.now() - this.lastFailureAt < 15_000))) return this.value
|
|
111
|
+
try {
|
|
112
|
+
const value = await fetchAccountQuota(credential, options)
|
|
113
|
+
options.signal.throwIfAborted()
|
|
114
|
+
if (owner === this.owner) {
|
|
115
|
+
this.value = value
|
|
116
|
+
this.error = undefined
|
|
117
|
+
this.lastFailureAt = 0
|
|
118
|
+
}
|
|
119
|
+
return value
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (options.signal.aborted) throw error
|
|
122
|
+
if (owner === this.owner) {
|
|
123
|
+
this.error = error instanceof Error ? error.message : 'Qoder quota lookup failed'
|
|
124
|
+
this.lastFailureAt = Date.now()
|
|
125
|
+
}
|
|
126
|
+
return this.owner === owner ? this.value : undefined
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
package/lib/catalog.ts
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/** 实时读取 Qoder 模型目录,并通过 Pi 的目录存储保留安全的能力快照。 */
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
3
|
+
import type { ProviderModelConfig } from '@earendil-works/pi-coding-agent'
|
|
4
|
+
import type { Model, RefreshModelsContext, ThinkingLevelMap } from '@earendil-works/pi-ai'
|
|
5
|
+
import { CONFIG, ensureAuthWasm, withTimeout } from './qoder-core.mjs'
|
|
6
|
+
import type { QoderCatalogModel, QoderCredential, QoderModelDefinition } from './types.ts'
|
|
7
|
+
|
|
8
|
+
export const PROVIDER_ID = 'qoder'
|
|
9
|
+
export const API_ID = 'qoder-native'
|
|
10
|
+
export const CATALOG_TTL_MS = 300_000
|
|
11
|
+
export type ChatConfig = Extract<ProviderModelConfig, { reasoning: boolean }>
|
|
12
|
+
|
|
13
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
14
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** 不将 null、空字符串或布尔值误记为零。 */
|
|
18
|
+
export function finiteNumber(value: unknown): number | undefined {
|
|
19
|
+
if (typeof value !== 'number' && (typeof value !== 'string' || value.trim() === '')) return undefined
|
|
20
|
+
const number = Number(value)
|
|
21
|
+
return Number.isFinite(number) && number >= 0 ? number : undefined
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function positiveInt(value: unknown): number | undefined {
|
|
25
|
+
const number = finiteNumber(value)
|
|
26
|
+
return number !== undefined && Number.isSafeInteger(number) && number > 0 ? number : undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 目录与余额缓存按账号隔离,不保存真实账号 ID 或 Token。 */
|
|
30
|
+
export function accountKey(credential: QoderCredential): string {
|
|
31
|
+
return createHash('sha256').update(credential.uid || credential.access).digest('hex').slice(0, 24)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function cleanText(value: unknown): string {
|
|
35
|
+
return typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim().slice(0, 160) : ''
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 思考档位以服务端 thinking_config 为准,未知档位暂不暴露。 */
|
|
39
|
+
function thinkingLevels(config: unknown): ThinkingLevelMap {
|
|
40
|
+
const levels: ThinkingLevelMap = { minimal: null, off: null, low: null, medium: null, high: null, xhigh: null, max: null }
|
|
41
|
+
if (!isRecord(config)) return levels
|
|
42
|
+
if (isRecord(config.disabled)) levels.off = 'none'
|
|
43
|
+
const enabled = isRecord(config.enabled) ? config.enabled : undefined
|
|
44
|
+
const efforts = enabled && isRecord(enabled.efforts) ? enabled.efforts : {}
|
|
45
|
+
for (const level of ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const) {
|
|
46
|
+
if (Object.hasOwn(efforts, level)) levels[level] = level
|
|
47
|
+
}
|
|
48
|
+
return levels
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 选用服务端提供的最大窗口;输入预算和输出上限分别保存。 */
|
|
52
|
+
export function parseCatalog(payload: unknown): QoderCatalogModel[] {
|
|
53
|
+
if (!isRecord(payload) || !Array.isArray(payload.chat)) throw new Error('Qoder model directory has no chat catalog')
|
|
54
|
+
const result: QoderCatalogModel[] = []
|
|
55
|
+
const ids = new Set<string>()
|
|
56
|
+
const keys = new Set<string>()
|
|
57
|
+
for (const item of payload.chat) {
|
|
58
|
+
if (!isRecord(item) || item.enable === false || (item.source !== undefined && item.source !== 'system')
|
|
59
|
+
|| (item.format !== undefined && item.format !== 'openai')) continue
|
|
60
|
+
const key = cleanText(item.key)
|
|
61
|
+
const id = cleanText(item.display_name)
|
|
62
|
+
if (!/^[A-Za-z0-9_.-]+$/.test(key) || !id || ids.has(id) || keys.has(key)) continue
|
|
63
|
+
const configs = isRecord(item.context_config) ? Object.values(item.context_config) : []
|
|
64
|
+
const windows = [...new Set(configs.flatMap(option => {
|
|
65
|
+
const tokens = isRecord(option) ? positiveInt(option.token_count) : undefined
|
|
66
|
+
return tokens === undefined ? [] : [tokens]
|
|
67
|
+
}))].sort((a, b) => a - b)
|
|
68
|
+
const maxInput = positiveInt(item.max_input_tokens)
|
|
69
|
+
const window = windows.at(-1) ?? maxInput
|
|
70
|
+
if (!window) continue
|
|
71
|
+
const levels = thinkingLevels(item.thinking_config)
|
|
72
|
+
const piReasoning = Object.values(levels).some(value => typeof value === 'string')
|
|
73
|
+
const enabledThinking = isRecord(item.thinking_config) && isRecord(item.thinking_config.enabled)
|
|
74
|
+
const priceFactor = finiteNumber(item.price_factor)
|
|
75
|
+
result.push({
|
|
76
|
+
key, display: id, source: 'system',
|
|
77
|
+
catalogVl: item.is_vl === true,
|
|
78
|
+
catalogReasoning: item.is_reasoning === true || enabledThinking,
|
|
79
|
+
piReasoning, levels, window,
|
|
80
|
+
maxInput: maxInput ?? window,
|
|
81
|
+
maxOutput: positiveInt(item.max_output_tokens) ?? 32768,
|
|
82
|
+
contextWindows: windows.length ? windows : [window],
|
|
83
|
+
...(priceFactor === undefined ? {} : { priceFactor }),
|
|
84
|
+
})
|
|
85
|
+
ids.add(id)
|
|
86
|
+
keys.add(key)
|
|
87
|
+
}
|
|
88
|
+
if (result.length === 0) throw new Error('Qoder model directory contains no supported enabled chat models')
|
|
89
|
+
return result
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function priceLabel(definition: QoderCatalogModel | undefined): string {
|
|
93
|
+
return definition?.priceFactor === undefined ? 'rate unknown' : `${definition.priceFactor.toFixed(2)}x`
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 首次登录前不猜测国际版模型;成功获取的目录由 Pi 缓存并用于离线恢复。 */
|
|
97
|
+
export function snapshotModels(): ChatConfig[] {
|
|
98
|
+
return []
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 能力信息放进模型采样元数据,使缓存恢复、新模型与多账号请求采用同一份路由信息。 */
|
|
102
|
+
function modelConfig(definition: QoderCatalogModel, owner: string): ChatConfig {
|
|
103
|
+
return {
|
|
104
|
+
id: definition.display,
|
|
105
|
+
name: definition.priceFactor === undefined ? definition.display : `${definition.display} (${priceLabel(definition)})`,
|
|
106
|
+
reasoning: definition.piReasoning,
|
|
107
|
+
input: definition.catalogVl ? ['text', 'image'] : ['text'],
|
|
108
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
109
|
+
contextWindow: definition.window,
|
|
110
|
+
maxTokens: definition.maxOutput,
|
|
111
|
+
...(definition.piReasoning ? { thinkingLevelMap: definition.levels } : {}),
|
|
112
|
+
samplingParams: { qoderGlobal: { version: 1, account: owner, definition } },
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 验证从 Pi 缓存或 models.json 恢复的元数据,避免未知结构直接进入请求。 */
|
|
117
|
+
export function catalogDefinition(model: Pick<Model<string>, 'samplingParams'>): QoderCatalogModel | undefined {
|
|
118
|
+
const meta = model.samplingParams?.qoderGlobal
|
|
119
|
+
if (!isRecord(meta) || meta.version !== 1 || !isRecord(meta.definition)) return undefined
|
|
120
|
+
const def = meta.definition
|
|
121
|
+
if (typeof def.key !== 'string' || !/^[A-Za-z0-9_.-]+$/.test(def.key)
|
|
122
|
+
|| typeof def.display !== 'string' || !cleanText(def.display)
|
|
123
|
+
|| typeof def.catalogVl !== 'boolean' || typeof def.catalogReasoning !== 'boolean'
|
|
124
|
+
|| typeof def.piReasoning !== 'boolean' || !isRecord(def.levels)
|
|
125
|
+
|| !positiveInt(def.window) || !positiveInt(def.maxInput) || !positiveInt(def.maxOutput)
|
|
126
|
+
|| !Array.isArray(def.contextWindows) || !def.contextWindows.every(value => positiveInt(value) !== undefined)
|
|
127
|
+
|| Object.values(def.levels).some(value => value !== null && typeof value !== 'string')
|
|
128
|
+
|| (def.priceFactor !== undefined && finiteNumber(def.priceFactor) === undefined)) return undefined
|
|
129
|
+
return def as unknown as QoderCatalogModel
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function definitionForRequest(model: Model<string>): QoderModelDefinition | undefined {
|
|
133
|
+
return catalogDefinition(model)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 签名元数据;就地读取 CONFIG,兼容 /reload 后仍是旧版 core 的情况。 */
|
|
137
|
+
function clientMeta(): string {
|
|
138
|
+
const config = CONFIG as unknown as Record<string, unknown>
|
|
139
|
+
const text = (value: unknown, fallback: string) => (typeof value === 'string' && value !== '' ? value : fallback)
|
|
140
|
+
return JSON.stringify({
|
|
141
|
+
client_type: text(config.clientType, '5'),
|
|
142
|
+
business_product: text(config.businessProduct, 'app'),
|
|
143
|
+
business_type: text(config.businessType, 'agent'),
|
|
144
|
+
scene: text(config.scene, 'assistant'),
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function fetchCatalog(credential: QoderCredential, {
|
|
149
|
+
signal, endpoint = CONFIG.endpoint, fetchImpl = globalThis.fetch,
|
|
150
|
+
}: { signal: AbortSignal; endpoint?: string; fetchImpl?: typeof fetch }): Promise<QoderCatalogModel[]> {
|
|
151
|
+
signal.throwIfAborted()
|
|
152
|
+
const wasm = await ensureAuthWasm()
|
|
153
|
+
const context = new wasm.QoderContext(credential.machineId, CONFIG.cliVersion, JSON.stringify({
|
|
154
|
+
uid: credential.uid, encrypt_user_info: credential.encryptUserInfo, key: credential.signingKey,
|
|
155
|
+
}), clientMeta())
|
|
156
|
+
let url: string
|
|
157
|
+
let headers: Record<string, string>
|
|
158
|
+
try {
|
|
159
|
+
const request = context.prepareRequest(endpoint, '/api/v2/model/list', 'GET', 'auth', undefined, undefined)
|
|
160
|
+
url = request.url
|
|
161
|
+
headers = Object.fromEntries(request.headers.entries())
|
|
162
|
+
request.free()
|
|
163
|
+
} finally {
|
|
164
|
+
context.free()
|
|
165
|
+
}
|
|
166
|
+
const response = await fetchImpl(url, { headers, signal: withTimeout(signal, CONFIG.authRequestTimeoutMs) })
|
|
167
|
+
if (!response.ok) {
|
|
168
|
+
await response.body?.cancel()
|
|
169
|
+
throw new Error(`Qoder model directory returned HTTP ${response.status}`)
|
|
170
|
+
}
|
|
171
|
+
const raw = await response.text()
|
|
172
|
+
signal.throwIfAborted()
|
|
173
|
+
let payload: unknown
|
|
174
|
+
try { payload = JSON.parse(raw) } catch {
|
|
175
|
+
try { payload = JSON.parse(wasm.decrypt_server_response(raw)) } catch {
|
|
176
|
+
throw new Error('Qoder model directory could not be decoded')
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return parseCatalog(payload)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Pi 负责凭据刷新和缓存落盘;所有发布均通过宿主的代次检查。 */
|
|
183
|
+
export function createCatalogRefresh() {
|
|
184
|
+
let current = snapshotModels()
|
|
185
|
+
let currentOwner = ''
|
|
186
|
+
let checkedAt = 0
|
|
187
|
+
let lastEndpoint = ''
|
|
188
|
+
return async (context: RefreshModelsContext): Promise<ProviderModelConfig[]> => {
|
|
189
|
+
const credential = context.credential?.type === 'oauth' ? context.credential as QoderCredential : undefined
|
|
190
|
+
const owner = credential ? accountKey(credential) : ''
|
|
191
|
+
const endpoint = (context.baseUrl || CONFIG.endpoint).replace(/\/+$/, '')
|
|
192
|
+
if (owner !== currentOwner || endpoint !== lastEndpoint) {
|
|
193
|
+
current = snapshotModels()
|
|
194
|
+
currentOwner = owner
|
|
195
|
+
checkedAt = 0
|
|
196
|
+
lastEndpoint = endpoint
|
|
197
|
+
}
|
|
198
|
+
if (context.stored && (context.stored.checkedAt ?? 0) > checkedAt) {
|
|
199
|
+
// 缓存可以来自其他网关;模型定义与网关无关,恢复时按当前 baseUrl 重写,避免换默认网关后整份目录失效。
|
|
200
|
+
const cached: ChatConfig[] = []
|
|
201
|
+
for (const model of context.stored.models) {
|
|
202
|
+
if (model.type !== 'chat' || model.provider !== PROVIDER_ID || model.api !== API_ID) continue
|
|
203
|
+
const meta = model.samplingParams?.qoderGlobal
|
|
204
|
+
const definition = catalogDefinition(model)
|
|
205
|
+
if (definition && isRecord(meta) && meta.account === owner) cached.push(modelConfig(definition, owner))
|
|
206
|
+
}
|
|
207
|
+
if (cached.length) {
|
|
208
|
+
const accepted = await context.publish({ update: () => {
|
|
209
|
+
current = cached
|
|
210
|
+
checkedAt = context.stored?.checkedAt ?? 0
|
|
211
|
+
} })
|
|
212
|
+
if (!accepted) return current
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (!credential || !context.allowNetwork || (!context.force && checkedAt > 0 && Date.now() - checkedAt < CATALOG_TTL_MS)) return current
|
|
216
|
+
const definitions = await fetchCatalog(credential, { signal: context.signal, endpoint })
|
|
217
|
+
const models = definitions.map(def => modelConfig(def, owner))
|
|
218
|
+
const now = Date.now()
|
|
219
|
+
const accepted = await context.publish({
|
|
220
|
+
persist: {
|
|
221
|
+
models: models.map(model => ({ ...model, type: 'chat' as const, provider: PROVIDER_ID, api: API_ID, baseUrl: endpoint })),
|
|
222
|
+
checkedAt: now,
|
|
223
|
+
},
|
|
224
|
+
update: () => { current = models; checkedAt = now },
|
|
225
|
+
})
|
|
226
|
+
return accepted ? models : current
|
|
227
|
+
}
|
|
228
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** 账号积分报告:纯文本快照与随终端宽度、主题变化的展示。 */
|
|
2
|
+
import type { Theme, ThemeColor } from '@earendil-works/pi-coding-agent'
|
|
3
|
+
import { Text, visibleWidth } from '@earendil-works/pi-tui'
|
|
4
|
+
import type { AccountQuota } from './account.ts'
|
|
5
|
+
|
|
6
|
+
const numberFormat = new Intl.NumberFormat('en-US', { maximumFractionDigits: 8 })
|
|
7
|
+
export const formatCredits = (value: number): string => numberFormat.format(value)
|
|
8
|
+
|
|
9
|
+
/** 余额耗尽用错误色,低于或等于一成时用警告色,其余使用成功色。 */
|
|
10
|
+
export function balanceColor(remaining: number, total: number): ThemeColor {
|
|
11
|
+
if (remaining === 0) return 'error'
|
|
12
|
+
return total > 0 && remaining / total <= 0.1 ? 'warning' : 'success'
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function localTime(timestamp: number): string {
|
|
16
|
+
const date = new Date(timestamp)
|
|
17
|
+
if (!Number.isFinite(date.getTime())) return 'unavailable'
|
|
18
|
+
const pad = (value: number) => String(value).padStart(2, '0')
|
|
19
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function localOffset(timestamp: number): string {
|
|
23
|
+
const minutes = -new Date(timestamp).getTimezoneOffset()
|
|
24
|
+
const absolute = Math.abs(minutes)
|
|
25
|
+
return `UTC${minutes < 0 ? '-' : '+'}${String(Math.floor(absolute / 60)).padStart(2, '0')}:${String(absolute % 60).padStart(2, '0')}`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 保存未着色的报告;积分池列宽跟随实际数值,保留小数与千位分隔。 */
|
|
29
|
+
export function accountReportLines(account: AccountQuota, cached = false): string[] {
|
|
30
|
+
const ratio = account.total > 0 ? Math.max(0, Math.min(1, account.remaining / account.total)) : undefined
|
|
31
|
+
const filled = ratio === undefined ? 0 : Math.round(ratio * 20)
|
|
32
|
+
const progress = `${'█'.repeat(filled)}${'░'.repeat(20 - filled)}`
|
|
33
|
+
const percent = ratio === undefined ? 'availability unavailable' : `${(ratio * 100).toFixed(1)}% available`
|
|
34
|
+
const rows = account.pools.map(pool => [pool.name, formatCredits(pool.remaining), formatCredits(pool.used), formatCredits(pool.total)])
|
|
35
|
+
const headings = ['Credit pool', 'Remaining', 'Used', 'Total']
|
|
36
|
+
const widths = headings.map((heading, index) => Math.max(visibleWidth(heading), ...rows.map(row => visibleWidth(row[index]))))
|
|
37
|
+
const table = (row: string[]) => row.map((cell, index) => {
|
|
38
|
+
const spaces = ' '.repeat(Math.max(0, widths[index] - visibleWidth(cell)))
|
|
39
|
+
return index === 0 ? cell + spaces : spaces + cell
|
|
40
|
+
}).join(' ')
|
|
41
|
+
const timezone = localOffset(account.fetchedAt)
|
|
42
|
+
const lines = [
|
|
43
|
+
`Qoder | ${account.plan}`,
|
|
44
|
+
'',
|
|
45
|
+
`REMAINING ${formatCredits(account.remaining)} credits`,
|
|
46
|
+
`${progress} ${percent}`,
|
|
47
|
+
`Total ${formatCredits(account.total)} | Used ${formatCredits(account.used)}`,
|
|
48
|
+
'',
|
|
49
|
+
table(headings),
|
|
50
|
+
...rows.map(table),
|
|
51
|
+
'',
|
|
52
|
+
`Updated ${localTime(account.fetchedAt)}${cached ? ' (cached)' : ''}`,
|
|
53
|
+
]
|
|
54
|
+
if (account.resetAt) {
|
|
55
|
+
// 到期日可能跨越夏令时切换;偏移不同时在该行单独标注。
|
|
56
|
+
const expiryOffset = localOffset(account.resetAt)
|
|
57
|
+
lines.push(`Quota expiry ${localTime(account.resetAt)}${expiryOffset === timezone ? '' : ` ${expiryOffset}`}`)
|
|
58
|
+
}
|
|
59
|
+
lines.push(`Timezone ${timezone}`)
|
|
60
|
+
return lines
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const tableHeading = /^Credit pool\s+Remaining\s+Used\s+Total$/
|
|
64
|
+
const tableRow = /^(.+?) {2,}([\d,.]+) {2,}([\d,.]+) {2,}([\d,.]+)$/
|
|
65
|
+
const number = (text: string) => Number(text.replaceAll(',', ''))
|
|
66
|
+
|
|
67
|
+
/** 在渲染时着色;旧版报告与其他用量行交给原有渲染器。 */
|
|
68
|
+
export function creditReportComponent(lines: string[], theme: Theme, fallback: (line: string) => string) {
|
|
69
|
+
const text = new Text('', 0, 0)
|
|
70
|
+
const total = number(lines.find(line => /^Total [\d,.]+/.test(line))?.match(/^Total ([\d,.]+)/)?.[1] ?? '0')
|
|
71
|
+
const remaining = number(lines.find(line => /^REMAINING /.test(line))?.match(/^REMAINING ([\d,.]+)/)?.[1] ?? '0')
|
|
72
|
+
const balance = balanceColor(remaining, total)
|
|
73
|
+
const style = (line: string): string => {
|
|
74
|
+
if (line.startsWith('Qoder | ')) return theme.bold(theme.fg('accent', 'Qoder')) + line.slice(8)
|
|
75
|
+
const hero = /^REMAINING ([\d,.]+) credits$/.exec(line)
|
|
76
|
+
if (hero) return `${theme.bold('REMAINING')} ${theme.bold(theme.fg(balance, `${hero[1]} credits`))}`
|
|
77
|
+
const progress = /^(█*)(░*)( .+)$/.exec(line)
|
|
78
|
+
if (progress && progress[1].length + progress[2].length > 0) {
|
|
79
|
+
return theme.fg(balance, progress[1]) + theme.fg('dim', progress[2]) + theme.fg('muted', progress[3])
|
|
80
|
+
}
|
|
81
|
+
const totals = /^Total ([\d,.]+) \| Used ([\d,.]+)$/.exec(line)
|
|
82
|
+
if (totals) return `${theme.fg('muted', 'Total')} ${totals[1]}${theme.fg('muted', ' | Used')} ${theme.fg('warning', totals[2])}`
|
|
83
|
+
if (tableHeading.test(line) || /^(Updated|Quota expiry|Timezone) {2,}/.test(line)) return theme.fg('muted', line)
|
|
84
|
+
const row = tableRow.exec(line)
|
|
85
|
+
if (row) {
|
|
86
|
+
return line.replace(/([\d,.]+)( {2,})([\d,.]+)( {2,})([\d,.]+)$/, (_match, left, firstGap, middle, secondGap, right) =>
|
|
87
|
+
theme.bold(theme.fg(balanceColor(number(row[2]), number(row[4])), left))
|
|
88
|
+
+ firstGap + theme.bold(theme.fg('warning', middle)) + secondGap + right)
|
|
89
|
+
}
|
|
90
|
+
return fallback(line)
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
render(width: number): string[] {
|
|
94
|
+
if (width <= 0) return []
|
|
95
|
+
const stacked = lines.some(line => (tableHeading.test(line) || tableRow.test(line)) && visibleWidth(line) > width)
|
|
96
|
+
const output = lines.flatMap(line => {
|
|
97
|
+
if (stacked && tableHeading.test(line)) return [theme.fg('muted', 'Credit pools')]
|
|
98
|
+
const row = stacked && tableRow.exec(line)
|
|
99
|
+
if (!row) return [style(line)]
|
|
100
|
+
return [
|
|
101
|
+
theme.bold(row[1]),
|
|
102
|
+
` Remaining ${theme.bold(theme.fg(balanceColor(number(row[2]), number(row[4])), row[2]))}`,
|
|
103
|
+
` Used ${theme.fg('warning', row[3])}`,
|
|
104
|
+
` Total ${row[4]}`,
|
|
105
|
+
]
|
|
106
|
+
})
|
|
107
|
+
text.setText(output.join('\n'))
|
|
108
|
+
return text.render(width)
|
|
109
|
+
},
|
|
110
|
+
invalidate() { text.invalidate() },
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/** 模型倍率报告:纯文本快照、对齐表格与窄终端逐项布局。 */
|
|
2
|
+
import type { Theme } from '@earendil-works/pi-coding-agent'
|
|
3
|
+
import { Text, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui'
|
|
4
|
+
import { creditReportComponent, formatCredits } from './credit-report.ts'
|
|
5
|
+
|
|
6
|
+
export interface ModelRateRow {
|
|
7
|
+
model: string
|
|
8
|
+
rate: string
|
|
9
|
+
context: number
|
|
10
|
+
current: boolean
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const headings = ['Model', 'Rate', 'Context']
|
|
14
|
+
const tableHeading = /^Model +Rate +Context(?: +Credits +Requests)?$/
|
|
15
|
+
const legacyTitle = /^Model rates \| \d+ models$/
|
|
16
|
+
const notes = ['Rate = credit multiplier. Context in tokens.', 'Session usage: /qoder usage']
|
|
17
|
+
const reportNote = /^(?:Context in tokens\.|Rate is a credit multiplier;|Rate = credit multiplier\.|> Current model at report time\.|Unreported:|Session usage: \/qoder usage$)/
|
|
18
|
+
|
|
19
|
+
/** 仅在能精确表示时缩写窗口,避免把 1,048,576 等窗口写成 1M。 */
|
|
20
|
+
function contextLabel(tokens: number): string {
|
|
21
|
+
if (tokens >= 1_000_000 && tokens % 1_000_000 === 0) return `${tokens / 1_000_000}M`
|
|
22
|
+
if (tokens >= 1_000 && tokens % 1_000 === 0) return `${tokens / 1_000}K`
|
|
23
|
+
return formatCredits(tokens)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function tableWidths(rows: readonly string[][]): number[] {
|
|
27
|
+
return headings.map((heading, index) => Math.max(visibleWidth(heading), ...rows.map(row => visibleWidth(row[index]))))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function paddedCells(cells: readonly string[], widths: readonly number[]): string[] {
|
|
31
|
+
return cells.map((cell, index) => {
|
|
32
|
+
const spaces = ' '.repeat(Math.max(0, widths[index] - visibleWidth(cell)))
|
|
33
|
+
return index === 0 ? cell + spaces : spaces + cell
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 当前模型标记放在名称末尾,使表头和全部模型名使用同一左边界。 */
|
|
38
|
+
export function modelReportLines(models: readonly ModelRateRow[]): string[] {
|
|
39
|
+
if (models.length === 0) return ['No Qoder models available.']
|
|
40
|
+
const rows = models.map(model => [
|
|
41
|
+
`${model.model.replace(/ {2,}/g, ' ')}${model.current ? ' (current)' : ''}`,
|
|
42
|
+
model.rate === 'rate unknown' ? 'unknown' : model.rate,
|
|
43
|
+
contextLabel(model.context),
|
|
44
|
+
])
|
|
45
|
+
const widths = tableWidths(rows)
|
|
46
|
+
return [paddedCells(headings, widths).join(' '), ...rows.map(row => paddedCells(row, widths).join(' ')), '', ...notes]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseRow(line: string): string[] | undefined {
|
|
50
|
+
const cells = line.trim().split(/ {2,}/)
|
|
51
|
+
if ((cells.length !== 3 && cells.length !== 5) || !/^(?:[\d.e+-]+x|unknown)$/.test(cells[1])
|
|
52
|
+
|| !/^[\d,.]+[KM]?$/.test(cells[2])) return undefined
|
|
53
|
+
// 已保存的五列表格也移除空用量列,并把原行首标记转换为名称后的标记。
|
|
54
|
+
const name = cells.length === 5 && cells[0].startsWith('> ') ? `${cells[0].slice(2)} (current)` : cells[0]
|
|
55
|
+
return [name, cells[1], cells[2]]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 账号与更早的逐行报告复用原渲染器;模型表格在每次渲染时按宽度重新布局。 */
|
|
59
|
+
export function usageReportComponent(lines: string[], theme: Theme, fallback: (line: string) => string) {
|
|
60
|
+
// 重载已有报告时也移除旧标题及紧随的空行,保留其他报告段落之间的间距。
|
|
61
|
+
lines = lines.filter((line, index, all) => !legacyTitle.test(line)
|
|
62
|
+
&& !(line === '' && index > 0 && legacyTitle.test(all[index - 1])))
|
|
63
|
+
const style = (line: string): string => {
|
|
64
|
+
if (reportNote.test(line)) return theme.fg('muted', line)
|
|
65
|
+
if (line === 'No Qoder models available.') return theme.fg('warning', line)
|
|
66
|
+
return fallback(line)
|
|
67
|
+
}
|
|
68
|
+
const start = lines.findIndex(line => tableHeading.test(line))
|
|
69
|
+
const rows: string[][] = []
|
|
70
|
+
let end = start + 1
|
|
71
|
+
if (start >= 0) {
|
|
72
|
+
for (; end < lines.length; end += 1) {
|
|
73
|
+
const row = parseRow(lines[end])
|
|
74
|
+
if (!row) break
|
|
75
|
+
rows.push(row)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const remaining = start < 0 ? [] : lines.slice(end).filter(line => !reportNote.test(line))
|
|
79
|
+
while (remaining[0] === '') remaining.shift()
|
|
80
|
+
const before = creditReportComponent(start < 0 ? lines : lines.slice(0, start), theme, style)
|
|
81
|
+
const after = creditReportComponent(remaining.length ? ['', ...remaining] : [], theme, style)
|
|
82
|
+
const text = new Text('', 0, 0)
|
|
83
|
+
const widths = tableWidths(rows)
|
|
84
|
+
const cellStyle = (cell: string, index: number, row: readonly string[]): string => {
|
|
85
|
+
if (index === 0) return row[0].endsWith(' (current)') ? theme.bold(theme.fg('accent', cell)) : theme.bold(cell)
|
|
86
|
+
if (index === 1) return row[1] === 'unknown' ? theme.fg('warning', cell) : theme.bold(theme.fg('accent', cell))
|
|
87
|
+
return theme.fg('muted', cell)
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
render(width: number): string[] {
|
|
91
|
+
if (width <= 0) return []
|
|
92
|
+
if (start < 0) return before.render(width)
|
|
93
|
+
const tableFits = widths.reduce((sum, value) => sum + value, 0) + 2 * (headings.length - 1) <= width
|
|
94
|
+
const output = tableFits
|
|
95
|
+
? [theme.fg('muted', paddedCells(headings, widths).join(' ')), ...rows.map(row =>
|
|
96
|
+
paddedCells(row, widths).map((cell, index) => cellStyle(cell, index, row)).join(' '))]
|
|
97
|
+
: rows.flatMap((row, index) => [
|
|
98
|
+
...(index ? [''] : []), cellStyle(row[0], 0, row),
|
|
99
|
+
...headings.slice(1).map((label, column) => `${theme.fg('muted', ` ${label.padEnd(7)} `)}${cellStyle(row[column + 1], column + 1, row)}`),
|
|
100
|
+
])
|
|
101
|
+
output.push('', ...notes.map(line => theme.fg('muted', line)))
|
|
102
|
+
text.setText(output.join('\n'))
|
|
103
|
+
return [...before.render(width), ...text.render(width), ...(remaining.length ? after.render(width) : [])].map(line => truncateToWidth(line, width))
|
|
104
|
+
},
|
|
105
|
+
invalidate() { before.invalidate(); text.invalidate(); after.invalidate() },
|
|
106
|
+
}
|
|
107
|
+
}
|