@hex4c59/pi-ext-qoder 0.1.0 → 0.1.1

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/lib/usage-ui.ts CHANGED
@@ -1,354 +1,353 @@
1
- /** Qoder 积分状态、逐次请求记录和会话内按模型汇总。界面文案使用英文。 */
2
- import type { ExtensionAPI, ExtensionContext, SessionEntry, Theme } from '@earendil-works/pi-coding-agent'
3
- import type { AssistantMessage } from '@earendil-works/pi-ai'
4
- import { QuotaCache, QUOTA_TTL_MS } from './account.ts'
5
- import { accountReportLines, balanceColor, formatCredits } from './credit-report.ts'
6
- import { modelReportLines } from './model-report.ts'
7
- import { showMenu, showReport } from './report-overlay.ts'
8
- import { registerRelayService, unregisterRelayService } from './relay-registry.ts'
9
- import { PROVIDER_ID, catalogDefinition, cleanText, finiteNumber, isRecord, priceLabel } from './catalog.ts'
10
- import type { QoderCredential, QoderRequestRecord, QoderUsage } from './types.ts'
11
-
12
- export const REQUEST_ENTRY = 'qoder-request'
13
- const MENU_ACTIONS = [
14
- { value: 'status', label: 'Status' },
15
- { value: 'account', label: 'Quota' },
16
- { value: 'models', label: 'Model rates' },
17
- { value: 'usage', label: 'Request history' },
18
- { value: 'refresh', label: 'Refresh' },
19
- ] as const
20
- export { formatCredits } from './credit-report.ts'
21
-
22
- export function requestRecord(message: AssistantMessage, fallbackId: string): QoderRequestRecord {
23
- const usage = message.usage as QoderUsage
24
- return {
25
- id: usage.qoderRequestId || fallbackId,
26
- model: cleanText(message.model),
27
- credits: finiteNumber(usage.credits) ?? null,
28
- tokens: finiteNumber(usage.totalTokens) ?? 0,
29
- timestamp: message.timestamp,
30
- stopReason: message.stopReason,
31
- }
32
- }
33
-
34
- function storedRecord(value: unknown): QoderRequestRecord | undefined {
35
- if (!isRecord(value) || typeof value.id !== 'string' || typeof value.model !== 'string'
36
- || typeof value.timestamp !== 'number' || typeof value.stopReason !== 'string'
37
- || finiteNumber(value.tokens) === undefined
38
- || (value.credits !== null && finiteNumber(value.credits) === undefined)) return undefined
39
- return {
40
- id: value.id, model: cleanText(value.model), timestamp: value.timestamp,
41
- stopReason: cleanText(value.stopReason), tokens: Number(value.tokens),
42
- credits: value.credits === null ? null : Number(value.credits),
43
- }
44
- }
45
-
46
- /** 记录和 assistant 用量都能恢复;两者通过请求 ID 去重,旧会话也可读取已有 credits。 */
47
- export function requestsFromBranch(entries: readonly SessionEntry[]): QoderRequestRecord[] {
48
- const records = new Map<string, QoderRequestRecord>()
49
- for (const entry of entries) {
50
- if (entry.type === 'custom' && entry.customType === REQUEST_ENTRY) {
51
- const record = storedRecord(entry.data)
52
- if (record) records.set(record.id, record)
53
- } else if (entry.type === 'message' && entry.message.role === 'assistant' && entry.message.provider === PROVIDER_ID) {
54
- const record = requestRecord(entry.message, `message:${entry.id}`)
55
- if (!records.has(record.id)) records.set(record.id, record)
56
- }
57
- }
58
- return [...records.values()]
59
- }
60
-
61
- /**
62
- * 只保留最近一次连续使用本 provider 的记录。
63
- *
64
- * 不同 provider 的积分体系彼此独立:切到别家再切回来,应当重新计数;
65
- * 同一 provider 内换模型则继续累加。`model_change` 是会话里的切换点,
66
- * 因此以“最后一次仍属于本 provider 的切换点”为起点。
67
- */
68
- export function currentProviderRun(entries: readonly SessionEntry[]): SessionEntry[] {
69
- let start = 0
70
- for (let index = 0; index < entries.length; index += 1) {
71
- const entry = entries[index]
72
- if (entry.type !== 'model_change') continue
73
- // 本次切换的目标仍在本 provider 时不算断点,继续沿用之前的累计。
74
- if (entry.provider === PROVIDER_ID) continue
75
- start = index + 1
76
- }
77
- return [...entries.slice(start)]
78
- }
79
-
80
- /** 请求在首字节前失败(无 token)时实际未产生消耗,不应计为用量缺失。 */
81
- export function failedBeforeUsage(record: QoderRequestRecord): boolean {
82
- return record.credits === null && record.stopReason === 'error' && record.tokens === 0
83
- }
84
-
85
- export function summarizeRequests(records: readonly QoderRequestRecord[]) {
86
- const byModel = new Map<string, { credits: number; requests: number; unreported: number; cancelledWithoutUsage: number }>()
87
- let credits = 0
88
- let unreported = 0
89
- let cancelledWithoutUsage = 0
90
- let failedWithoutUsage = 0
91
- let last: QoderRequestRecord | undefined
92
- for (const record of records) {
93
- const model = byModel.get(record.model) ?? { credits: 0, requests: 0, unreported: 0, cancelledWithoutUsage: 0 }
94
- model.requests += 1
95
- if (record.credits === null) {
96
- // 取消、以及首字节前失败(429 排队、504 超时等)都没有产生消耗,不算积分缺失。
97
- if (record.stopReason === 'aborted') { model.cancelledWithoutUsage += 1; cancelledWithoutUsage += 1 }
98
- else if (failedBeforeUsage(record)) { failedWithoutUsage += 1 }
99
- else { model.unreported += 1; unreported += 1 }
100
- } else {
101
- model.credits += record.credits
102
- credits += record.credits
103
- last = record
104
- }
105
- byModel.set(record.model, model)
106
- }
107
- return { credits, unreported, cancelledWithoutUsage, failedWithoutUsage, requests: records.length, byModel, last }
108
- }
109
-
110
- export function requestLine(record: QoderRequestRecord): string {
111
- const credits = record.credits === null
112
- ? record.stopReason === 'aborted' ? 'credits unknown'
113
- : failedBeforeUsage(record) ? 'no credits used' : 'credits unreported'
114
- : `${formatCredits(record.credits)} credits`
115
- const status = record.stopReason === 'aborted' ? 'cancelled' : record.stopReason
116
- return `Qoder ${record.model} · ${credits} · ${formatCredits(record.tokens)} tokens · ${status}`
117
- }
118
-
119
- /** 在渲染时着色,保留会话中的纯文本,并兼容已经保存的报告。 */
120
- function highlightUsageLine(line: string, theme: Theme): string {
121
- if (line === 'Qoder credits' || line === 'Session usage by model' || /^(Models:|Latest \d+ requests)/.test(line)) {
122
- return theme.bold(theme.fg('accent', line))
123
- }
124
- if (/^(Account checked:|Quota period ends:)/.test(line)) return theme.fg('muted', line)
125
- if (/^(Catalog refresh failed:|Qoder refresh:)/.test(line)) return theme.fg('error', line)
126
- if (/^(Account quota unavailable|Run \/login|Qoder .*unavailable)/.test(line)) return theme.fg('warning', line)
127
- const label = /^([A-Za-z][A-Za-z ]*?):(.*)$/.exec(line)
128
- if (label) return theme.bold(theme.fg('accent', label[1])) + ':' + label[2]
129
- const pool = /^(.+?): ([\d,.]+) \/ ([\d,.]+) credits remaining$/.exec(line)
130
- const number = (value: string) => Number(value.replaceAll(',', ''))
131
- if (pool) {
132
- const color = balanceColor(number(pool[2]), number(pool[3]))
133
- return `${theme.bold(pool[1])}: ${theme.bold(theme.fg(color, pool[2]))} / ${theme.fg('accent', pool[3])} credits remaining`
134
- }
135
- const total = /\btotal ([\d,.]+)/.exec(line)?.[1]
136
- const highlightValues = (text: string) => text.replace(
137
- /\b(?:total|used|remaining) [\d,.]+|\b[\d,.]+ (?:reported )?credits\b|\bcredits unknown\b|\b[\d,.]+ tokens\b|\b[\d.]+x\b|\b(?:\d+ )?unreported\b|\b(?:stop|error|aborted|cancelled|length|toolUse)\b/g,
138
- value => {
139
- const [label, amount] = value.split(' ')
140
- if (label === 'total' || label === 'used' || label === 'remaining') {
141
- const color = label === 'total' ? 'accent' : label === 'used' ? 'warning' : balanceColor(number(amount), total ? number(total) : 0)
142
- return `${label} ${theme.bold(theme.fg(color, amount))}`
143
- }
144
- if (value.endsWith('credits') || value.endsWith('unreported') || value === 'credits unknown') return theme.bold(theme.fg('warning', value))
145
- if (value === 'error') return theme.fg('error', value)
146
- if (value === 'aborted' || value === 'cancelled' || value === 'length') return theme.fg('warning', value)
147
- return theme.fg(value === 'stop' ? 'success' : 'accent', value)
148
- },
149
- )
150
- const parts = line.split(' · ')
151
- return parts.map((part, index) => {
152
- if (/^\d{4}-\d{2}-\d{2}T/.test(part)) return theme.fg('muted', part)
153
- if (part.startsWith('Qoder ') || (index === 0 && parts[1]?.endsWith(' tokens'))) return theme.bold(theme.fg('accent', part))
154
- if (index === 0 && parts[1]?.startsWith('total ')) return theme.bold(part)
155
- const modelTotal = /^(.+?): ([\d,.]+ credits)$/.exec(part)
156
- return modelTotal ? `${theme.fg('accent', modelTotal[1])}: ${highlightValues(modelTotal[2])}` : highlightValues(part)
157
- }).join(theme.fg('muted', ' · '))
158
- }
159
-
160
- /** 所有后台资源随 session_start 建立,在 shutdown/reload 时清理并取消未完成的请求。 */
161
- export function installUsageUi(pi: ExtensionAPI, resolveCredential: (hint?: string) => QoderCredential) {
162
- const quota = new QuotaCache()
163
- let context: ExtensionContext | undefined
164
- let controller = new AbortController()
165
- let timer: ReturnType<typeof setInterval> | undefined
166
- let pending: Promise<void> | undefined
167
- let records: QoderRequestRecord[] = []
168
- let catalogError: string | undefined
169
-
170
- const credential = () => {
171
- try { return resolveCredential() } catch { return undefined }
172
- }
173
- const offline = () => process.env.PI_OFFLINE !== undefined && !['', '0', 'false', 'no'].includes(process.env.PI_OFFLINE.toLowerCase())
174
-
175
- const render = () => {
176
- const ctx = context
177
- if (!ctx?.hasUI || ctx.mode !== 'tui' || controller.signal.aborted) return
178
- // 积分与用量只在 /qoder 报告中查看,不在编辑区上方保留常驻摘要。
179
- if (ctx.model?.provider !== PROVIDER_ID) ctx.ui.setStatus(PROVIDER_ID, undefined)
180
- ctx.ui.setWidget(PROVIDER_ID, undefined)
181
- }
182
-
183
- /** 只替换当前同名模型的最新描述,不自动切换到另一个模型。 */
184
- const updateSelectedModel = async (ctx: ExtensionContext) => {
185
- if (ctx.model?.provider !== PROVIDER_ID || !ctx.isIdle() || controller.signal.aborted) return
186
- const latest = ctx.modelRegistry.find(PROVIDER_ID, ctx.model.id)
187
- if (latest && JSON.stringify(latest) !== JSON.stringify(ctx.model)) await pi.setModel(latest)
188
- }
189
-
190
- const refresh = async (force = false, forceQuota = false, allowInactive = false): Promise<void> => {
191
- if (pending) {
192
- await pending
193
- if (force && !controller.signal.aborted) return refresh(true, forceQuota, allowInactive)
194
- return
195
- }
196
- const ctx = context
197
- if (!ctx || controller.signal.aborted || (offline() && !force) || (ctx.model?.provider !== PROVIDER_ID && !force && !allowInactive)) {
198
- render()
199
- return
200
- }
201
- pending = (async () => {
202
- try {
203
- if (!credential()) { quota.clear(); render(); return }
204
- const refreshed = await ctx.modelRegistry.refresh({
205
- providers: [PROVIDER_ID], allowNetwork: true, force, signal: controller.signal,
206
- })
207
- controller.signal.throwIfAborted()
208
- catalogError = refreshed.errors.get(PROVIDER_ID)?.message
209
- const auth = await ctx.modelRegistry.getProviderAuth(PROVIDER_ID)
210
- controller.signal.throwIfAborted()
211
- if (!auth?.auth.apiKey) { quota.clear(); render(); return }
212
- const current = resolveCredential(auth.auth.apiKey)
213
- await quota.load(current, { signal: controller.signal, force: force || forceQuota })
214
- controller.signal.throwIfAborted()
215
- await updateSelectedModel(ctx)
216
- render()
217
- } catch (error) {
218
- if (!controller.signal.aborted) {
219
- catalogError = error instanceof Error ? error.message : 'Qoder refresh failed'
220
- render()
221
- }
222
- }
223
- })()
224
- try { await pending } finally { pending = undefined }
225
- }
226
-
227
- const reportLines = (section: string): string[] => {
228
- const ctx = context
229
- const current = credential()
230
- const account = current && quota.peek(current)
231
- const summary = summarizeRequests(records)
232
- if (section === 'status') {
233
- const modelCount = ctx?.modelRegistry.getAll().filter(item => item.provider === PROVIDER_ID).length ?? 0
234
- return [
235
- `Qoder | ${account?.plan ?? 'account'}`,
236
- `Signed in: ${current ? 'yes' : 'no — run /login and choose Qoder'}`,
237
- `Models: ${modelCount} visible`,
238
- `Catalog: ${catalogError ? `error: ${catalogError}` : 'using snapshot'}`,
239
- `Session credits: ${formatCredits(summary.credits)} · ${summary.requests} request(s)`,
240
- `Account credits: ${account ? `${formatCredits(account.remaining)} / ${formatCredits(account.total)} remaining` : 'not loaded — open Quota'}`,
241
- ...(account ? [`Quota updated: ${new Date(account.fetchedAt).toISOString()}`] : []),
242
- ]
243
- }
244
- const lines = account ? accountReportLines(account, Boolean(quota.error)) : [
245
- 'Qoder credits',
246
- current ? `Account quota unavailable${quota.error ? `: ${quota.error}` : ''}` : 'Run /login and choose Qoder',
247
- ]
248
- if (section === 'account') return lines
249
- if (section !== 'models') {
250
- lines.push('', `Session: ${formatCredits(summary.credits)} reported credits · ${summary.requests} requests${summary.unreported ? ` · ${summary.unreported} unreported` : ''}`)
251
- if (summary.cancelledWithoutUsage) lines.push(`Cancelled requests without usage: ${summary.cancelledWithoutUsage}`)
252
- if (summary.failedWithoutUsage) lines.push(`Failed before any usage: ${summary.failedWithoutUsage}`)
253
- if (summary.unreported || summary.cancelledWithoutUsage) lines.push('Session credits include reported usage only; requests without usage remain unknown.')
254
- }
255
- if (section !== 'usage') {
256
- const models = ctx?.modelRegistry.getAll().filter(item => item.provider === PROVIDER_ID) ?? []
257
- lines.push('', ...modelReportLines(models.map(model => ({
258
- model: model.id, rate: priceLabel(catalogDefinition(model)), context: model.contextWindow,
259
- current: ctx?.model?.provider === PROVIDER_ID && ctx.model.id === model.id,
260
- }))))
261
- if (catalogError) lines.push(`Catalog refresh failed: ${catalogError}`)
262
- }
263
- if (section !== 'models') {
264
- lines.push('', 'Session usage by model')
265
- for (const [model, usage] of summary.byModel) {
266
- const found = ctx?.modelRegistry.find(PROVIDER_ID, model)
267
- const rate = found ? priceLabel(catalogDefinition(found)) : 'rate unknown'
268
- lines.push(`${model} · ${rate === 'rate unknown' ? 'unknown' : rate} · ${formatCredits(usage.credits)} credits · ${usage.requests} requests${usage.unreported ? ` · ${usage.unreported} unreported` : ''}${usage.cancelledWithoutUsage ? ` · ${usage.cancelledWithoutUsage} cancelled without usage` : ''}`)
269
- }
270
- lines.push('', `Latest ${Math.min(records.length, 50)} requests`)
271
- for (const record of records.slice(-50)) lines.push(`${new Date(record.timestamp).toISOString()} · ${requestLine(record)}`)
272
- }
273
- return lines
274
- }
275
-
276
- // 逐次请求只作为会话数据保存;聊天区仅渲染用户主动查询的报告。
277
- const openService = async (ctx: ExtensionContext, initialSection = ''): Promise<void> => {
278
- context = ctx
279
- let section = initialSection.trim()
280
- const interactiveMenu = section === '' && ctx.hasUI && ctx.mode === 'tui'
281
- while (true) {
282
- if (section === '' && interactiveMenu) {
283
- const choice = await showMenu(ctx, MENU_ACTIONS, controller.signal)
284
- if (choice === undefined || controller.signal.aborted) return
285
- section = choice
286
- }
287
- if (section && !MENU_ACTIONS.some(action => action.value === section)) {
288
- if (ctx.hasUI) ctx.ui.notify('Usage: /qoder [account|models|usage|refresh|status]', 'warning')
289
- return
290
- }
291
- // Status/Usage 只读当前缓存;只有明确需要余额或目录时才等网络。
292
- if (section === 'refresh' || section === 'account' || section === 'models') {
293
- await refresh(section === 'refresh', false, true)
294
- }
295
- if (!controller.signal.aborted) await showReport(ctx, 'Qoder', reportLines(section), (lines, theme) => lines.map(line => highlightUsageLine(line, theme)))
296
- if (!interactiveMenu) return
297
- section = ''
298
- }
299
- }
300
-
301
- pi.registerCommand('qoder', {
302
- description: 'Open the Qoder menu for credits, model rates, request history and refresh',
303
- getArgumentCompletions: prefix => MENU_ACTIONS.filter(action => action.value.startsWith(prefix)).map(action => ({ value: action.value, label: action.value, description: action.label })),
304
- handler: async (args, ctx) => {
305
- await openService(ctx, args.trim())
306
- },
307
- })
308
- registerRelayService('qoder', 'Qoder', MENU_ACTIONS, (ctx, section) => openService(ctx, section))
309
-
310
- pi.on('session_start', async (_event, ctx) => {
311
- context = ctx
312
- controller = new AbortController()
313
- records = requestsFromBranch(currentProviderRun(ctx.sessionManager.getBranch()))
314
- render()
315
- timer = setInterval(() => { void refresh() }, QUOTA_TTL_MS)
316
- timer.unref()
317
- await refresh()
318
- })
319
- pi.on('session_tree', async (_event, ctx) => {
320
- context = ctx
321
- records = requestsFromBranch(currentProviderRun(ctx.sessionManager.getBranch()))
322
- render()
323
- })
324
- pi.on('model_select', async (_event, ctx) => {
325
- context = ctx
326
- render()
327
- // setModel 也触发此事件;当前刷新负责收尾,避免递归等待同一个 Promise。
328
- if (!pending) await refresh()
329
- })
330
- pi.on('agent_settled', async (_event, ctx) => {
331
- context = ctx
332
- await refresh(false, true)
333
- })
334
- pi.on('session_shutdown', () => {
335
- unregisterRelayService('qoder')
336
- controller.abort()
337
- if (timer) clearInterval(timer)
338
- timer = undefined
339
- context = undefined
340
- quota.clear()
341
- })
342
-
343
- return {
344
- /** 在传输层记录所有完成或失败的尝试,包括工具循环和内部摘要请求。 */
345
- record(message: AssistantMessage): void {
346
- if (!context || controller.signal.aborted) return
347
- const record = requestRecord(message, crypto.randomUUID())
348
- if (records.some(previous => previous.id === record.id)) return
349
- records.push(record)
350
- pi.appendEntry(REQUEST_ENTRY, record)
351
- render()
352
- },
353
- }
354
- }
1
+ /** Qoder 积分状态、逐次请求记录和会话内按模型汇总。界面文案使用英文。 */
2
+ import type { ExtensionAPI, ExtensionContext, SessionEntry, Theme } from '@earendil-works/pi-coding-agent'
3
+ import type { AssistantMessage } from '@earendil-works/pi-ai'
4
+ import { registerRelayService, showMenu, showReport, unregisterRelayService } from '@hex4c59/pi-ext-ui-kit'
5
+ import { QuotaCache, QUOTA_TTL_MS } from './account.ts'
6
+ import { accountReportLines, balanceColor, formatCredits } from './credit-report.ts'
7
+ import { modelReportLines } from './model-report.ts'
8
+ import { PROVIDER_ID, catalogDefinition, cleanText, finiteNumber, isRecord, priceLabel } from './catalog.ts'
9
+ import type { QoderCredential, QoderRequestRecord, QoderUsage } from './types.ts'
10
+
11
+ export const REQUEST_ENTRY = 'qoder-request'
12
+ const MENU_ACTIONS = [
13
+ { value: 'status', label: 'Status' },
14
+ { value: 'account', label: 'Quota' },
15
+ { value: 'models', label: 'Model rates' },
16
+ { value: 'usage', label: 'Request history' },
17
+ { value: 'refresh', label: 'Refresh' },
18
+ ] as const
19
+ export { formatCredits } from './credit-report.ts'
20
+
21
+ export function requestRecord(message: AssistantMessage, fallbackId: string): QoderRequestRecord {
22
+ const usage = message.usage as QoderUsage
23
+ return {
24
+ id: usage.qoderRequestId || fallbackId,
25
+ model: cleanText(message.model),
26
+ credits: finiteNumber(usage.credits) ?? null,
27
+ tokens: finiteNumber(usage.totalTokens) ?? 0,
28
+ timestamp: message.timestamp,
29
+ stopReason: message.stopReason,
30
+ }
31
+ }
32
+
33
+ function storedRecord(value: unknown): QoderRequestRecord | undefined {
34
+ if (!isRecord(value) || typeof value.id !== 'string' || typeof value.model !== 'string'
35
+ || typeof value.timestamp !== 'number' || typeof value.stopReason !== 'string'
36
+ || finiteNumber(value.tokens) === undefined
37
+ || (value.credits !== null && finiteNumber(value.credits) === undefined)) return undefined
38
+ return {
39
+ id: value.id, model: cleanText(value.model), timestamp: value.timestamp,
40
+ stopReason: cleanText(value.stopReason), tokens: Number(value.tokens),
41
+ credits: value.credits === null ? null : Number(value.credits),
42
+ }
43
+ }
44
+
45
+ /** 记录和 assistant 用量都能恢复;两者通过请求 ID 去重,旧会话也可读取已有 credits。 */
46
+ export function requestsFromBranch(entries: readonly SessionEntry[]): QoderRequestRecord[] {
47
+ const records = new Map<string, QoderRequestRecord>()
48
+ for (const entry of entries) {
49
+ if (entry.type === 'custom' && entry.customType === REQUEST_ENTRY) {
50
+ const record = storedRecord(entry.data)
51
+ if (record) records.set(record.id, record)
52
+ } else if (entry.type === 'message' && entry.message.role === 'assistant' && entry.message.provider === PROVIDER_ID) {
53
+ const record = requestRecord(entry.message, `message:${entry.id}`)
54
+ if (!records.has(record.id)) records.set(record.id, record)
55
+ }
56
+ }
57
+ return [...records.values()]
58
+ }
59
+
60
+ /**
61
+ * 只保留最近一次连续使用本 provider 的记录。
62
+ *
63
+ * 不同 provider 的积分体系彼此独立:切到别家再切回来,应当重新计数;
64
+ * 同一 provider 内换模型则继续累加。`model_change` 是会话里的切换点,
65
+ * 因此以“最后一次仍属于本 provider 的切换点”为起点。
66
+ */
67
+ export function currentProviderRun(entries: readonly SessionEntry[]): SessionEntry[] {
68
+ let start = 0
69
+ for (let index = 0; index < entries.length; index += 1) {
70
+ const entry = entries[index]
71
+ if (entry.type !== 'model_change') continue
72
+ // 本次切换的目标仍在本 provider 时不算断点,继续沿用之前的累计。
73
+ if (entry.provider === PROVIDER_ID) continue
74
+ start = index + 1
75
+ }
76
+ return [...entries.slice(start)]
77
+ }
78
+
79
+ /** 请求在首字节前失败(无 token)时实际未产生消耗,不应计为用量缺失。 */
80
+ export function failedBeforeUsage(record: QoderRequestRecord): boolean {
81
+ return record.credits === null && record.stopReason === 'error' && record.tokens === 0
82
+ }
83
+
84
+ export function summarizeRequests(records: readonly QoderRequestRecord[]) {
85
+ const byModel = new Map<string, { credits: number; requests: number; unreported: number; cancelledWithoutUsage: number }>()
86
+ let credits = 0
87
+ let unreported = 0
88
+ let cancelledWithoutUsage = 0
89
+ let failedWithoutUsage = 0
90
+ let last: QoderRequestRecord | undefined
91
+ for (const record of records) {
92
+ const model = byModel.get(record.model) ?? { credits: 0, requests: 0, unreported: 0, cancelledWithoutUsage: 0 }
93
+ model.requests += 1
94
+ if (record.credits === null) {
95
+ // 取消、以及首字节前失败(429 排队、504 超时等)都没有产生消耗,不算积分缺失。
96
+ if (record.stopReason === 'aborted') { model.cancelledWithoutUsage += 1; cancelledWithoutUsage += 1 }
97
+ else if (failedBeforeUsage(record)) { failedWithoutUsage += 1 }
98
+ else { model.unreported += 1; unreported += 1 }
99
+ } else {
100
+ model.credits += record.credits
101
+ credits += record.credits
102
+ last = record
103
+ }
104
+ byModel.set(record.model, model)
105
+ }
106
+ return { credits, unreported, cancelledWithoutUsage, failedWithoutUsage, requests: records.length, byModel, last }
107
+ }
108
+
109
+ export function requestLine(record: QoderRequestRecord): string {
110
+ const credits = record.credits === null
111
+ ? record.stopReason === 'aborted' ? 'credits unknown'
112
+ : failedBeforeUsage(record) ? 'no credits used' : 'credits unreported'
113
+ : `${formatCredits(record.credits)} credits`
114
+ const status = record.stopReason === 'aborted' ? 'cancelled' : record.stopReason
115
+ return `Qoder ${record.model} · ${credits} · ${formatCredits(record.tokens)} tokens · ${status}`
116
+ }
117
+
118
+ /** 在渲染时着色,保留会话中的纯文本,并兼容已经保存的报告。 */
119
+ function highlightUsageLine(line: string, theme: Theme): string {
120
+ if (line === 'Qoder credits' || line === 'Session usage by model' || /^(Models:|Latest \d+ requests)/.test(line)) {
121
+ return theme.bold(theme.fg('accent', line))
122
+ }
123
+ if (/^(Account checked:|Quota period ends:)/.test(line)) return theme.fg('muted', line)
124
+ if (/^(Catalog refresh failed:|Qoder refresh:)/.test(line)) return theme.fg('error', line)
125
+ if (/^(Account quota unavailable|Run \/login|Qoder .*unavailable)/.test(line)) return theme.fg('warning', line)
126
+ const label = /^([A-Za-z][A-Za-z ]*?):(.*)$/.exec(line)
127
+ if (label) return theme.bold(theme.fg('accent', label[1])) + ':' + label[2]
128
+ const pool = /^(.+?): ([\d,.]+) \/ ([\d,.]+) credits remaining$/.exec(line)
129
+ const number = (value: string) => Number(value.replaceAll(',', ''))
130
+ if (pool) {
131
+ const color = balanceColor(number(pool[2]), number(pool[3]))
132
+ return `${theme.bold(pool[1])}: ${theme.bold(theme.fg(color, pool[2]))} / ${theme.fg('accent', pool[3])} credits remaining`
133
+ }
134
+ const total = /\btotal ([\d,.]+)/.exec(line)?.[1]
135
+ const highlightValues = (text: string) => text.replace(
136
+ /\b(?:total|used|remaining) [\d,.]+|\b[\d,.]+ (?:reported )?credits\b|\bcredits unknown\b|\b[\d,.]+ tokens\b|\b[\d.]+x\b|\b(?:\d+ )?unreported\b|\b(?:stop|error|aborted|cancelled|length|toolUse)\b/g,
137
+ value => {
138
+ const [label, amount] = value.split(' ')
139
+ if (label === 'total' || label === 'used' || label === 'remaining') {
140
+ const color = label === 'total' ? 'accent' : label === 'used' ? 'warning' : balanceColor(number(amount), total ? number(total) : 0)
141
+ return `${label} ${theme.bold(theme.fg(color, amount))}`
142
+ }
143
+ if (value.endsWith('credits') || value.endsWith('unreported') || value === 'credits unknown') return theme.bold(theme.fg('warning', value))
144
+ if (value === 'error') return theme.fg('error', value)
145
+ if (value === 'aborted' || value === 'cancelled' || value === 'length') return theme.fg('warning', value)
146
+ return theme.fg(value === 'stop' ? 'success' : 'accent', value)
147
+ },
148
+ )
149
+ const parts = line.split(' · ')
150
+ return parts.map((part, index) => {
151
+ if (/^\d{4}-\d{2}-\d{2}T/.test(part)) return theme.fg('muted', part)
152
+ if (part.startsWith('Qoder ') || (index === 0 && parts[1]?.endsWith(' tokens'))) return theme.bold(theme.fg('accent', part))
153
+ if (index === 0 && parts[1]?.startsWith('total ')) return theme.bold(part)
154
+ const modelTotal = /^(.+?): ([\d,.]+ credits)$/.exec(part)
155
+ return modelTotal ? `${theme.fg('accent', modelTotal[1])}: ${highlightValues(modelTotal[2])}` : highlightValues(part)
156
+ }).join(theme.fg('muted', ' · '))
157
+ }
158
+
159
+ /** 所有后台资源随 session_start 建立,在 shutdown/reload 时清理并取消未完成的请求。 */
160
+ export function installUsageUi(pi: ExtensionAPI, resolveCredential: (hint?: string) => QoderCredential) {
161
+ const quota = new QuotaCache()
162
+ let context: ExtensionContext | undefined
163
+ let controller = new AbortController()
164
+ let timer: ReturnType<typeof setInterval> | undefined
165
+ let pending: Promise<void> | undefined
166
+ let records: QoderRequestRecord[] = []
167
+ let catalogError: string | undefined
168
+
169
+ const credential = () => {
170
+ try { return resolveCredential() } catch { return undefined }
171
+ }
172
+ const offline = () => process.env.PI_OFFLINE !== undefined && !['', '0', 'false', 'no'].includes(process.env.PI_OFFLINE.toLowerCase())
173
+
174
+ const render = () => {
175
+ const ctx = context
176
+ if (!ctx?.hasUI || ctx.mode !== 'tui' || controller.signal.aborted) return
177
+ // 积分与用量只在 /qoder 报告中查看,不在编辑区上方保留常驻摘要。
178
+ if (ctx.model?.provider !== PROVIDER_ID) ctx.ui.setStatus(PROVIDER_ID, undefined)
179
+ ctx.ui.setWidget(PROVIDER_ID, undefined)
180
+ }
181
+
182
+ /** 只替换当前同名模型的最新描述,不自动切换到另一个模型。 */
183
+ const updateSelectedModel = async (ctx: ExtensionContext) => {
184
+ if (ctx.model?.provider !== PROVIDER_ID || !ctx.isIdle() || controller.signal.aborted) return
185
+ const latest = ctx.modelRegistry.find(PROVIDER_ID, ctx.model.id)
186
+ if (latest && JSON.stringify(latest) !== JSON.stringify(ctx.model)) await pi.setModel(latest)
187
+ }
188
+
189
+ const refresh = async (force = false, forceQuota = false, allowInactive = false): Promise<void> => {
190
+ if (pending) {
191
+ await pending
192
+ if (force && !controller.signal.aborted) return refresh(true, forceQuota, allowInactive)
193
+ return
194
+ }
195
+ const ctx = context
196
+ if (!ctx || controller.signal.aborted || (offline() && !force) || (ctx.model?.provider !== PROVIDER_ID && !force && !allowInactive)) {
197
+ render()
198
+ return
199
+ }
200
+ pending = (async () => {
201
+ try {
202
+ if (!credential()) { quota.clear(); render(); return }
203
+ const refreshed = await ctx.modelRegistry.refresh({
204
+ providers: [PROVIDER_ID], allowNetwork: true, force, signal: controller.signal,
205
+ })
206
+ controller.signal.throwIfAborted()
207
+ catalogError = refreshed.errors.get(PROVIDER_ID)?.message
208
+ const auth = await ctx.modelRegistry.getProviderAuth(PROVIDER_ID)
209
+ controller.signal.throwIfAborted()
210
+ if (!auth?.auth.apiKey) { quota.clear(); render(); return }
211
+ const current = resolveCredential(auth.auth.apiKey)
212
+ await quota.load(current, { signal: controller.signal, force: force || forceQuota })
213
+ controller.signal.throwIfAborted()
214
+ await updateSelectedModel(ctx)
215
+ render()
216
+ } catch (error) {
217
+ if (!controller.signal.aborted) {
218
+ catalogError = error instanceof Error ? error.message : 'Qoder refresh failed'
219
+ render()
220
+ }
221
+ }
222
+ })()
223
+ try { await pending } finally { pending = undefined }
224
+ }
225
+
226
+ const reportLines = (section: string): string[] => {
227
+ const ctx = context
228
+ const current = credential()
229
+ const account = current && quota.peek(current)
230
+ const summary = summarizeRequests(records)
231
+ if (section === 'status') {
232
+ const modelCount = ctx?.modelRegistry.getAll().filter(item => item.provider === PROVIDER_ID).length ?? 0
233
+ return [
234
+ `Qoder | ${account?.plan ?? 'account'}`,
235
+ `Signed in: ${current ? 'yes' : 'no — run /login and choose Qoder'}`,
236
+ `Models: ${modelCount} visible`,
237
+ `Catalog: ${catalogError ? `error: ${catalogError}` : 'using snapshot'}`,
238
+ `Session credits: ${formatCredits(summary.credits)} · ${summary.requests} request(s)`,
239
+ `Account credits: ${account ? `${formatCredits(account.remaining)} / ${formatCredits(account.total)} remaining` : 'not loaded — open Quota'}`,
240
+ ...(account ? [`Quota updated: ${new Date(account.fetchedAt).toISOString()}`] : []),
241
+ ]
242
+ }
243
+ const lines = account ? accountReportLines(account, Boolean(quota.error)) : [
244
+ 'Qoder credits',
245
+ current ? `Account quota unavailable${quota.error ? `: ${quota.error}` : ''}` : 'Run /login and choose Qoder',
246
+ ]
247
+ if (section === 'account') return lines
248
+ if (section !== 'models') {
249
+ lines.push('', `Session: ${formatCredits(summary.credits)} reported credits · ${summary.requests} requests${summary.unreported ? ` · ${summary.unreported} unreported` : ''}`)
250
+ if (summary.cancelledWithoutUsage) lines.push(`Cancelled requests without usage: ${summary.cancelledWithoutUsage}`)
251
+ if (summary.failedWithoutUsage) lines.push(`Failed before any usage: ${summary.failedWithoutUsage}`)
252
+ if (summary.unreported || summary.cancelledWithoutUsage) lines.push('Session credits include reported usage only; requests without usage remain unknown.')
253
+ }
254
+ if (section !== 'usage') {
255
+ const models = ctx?.modelRegistry.getAll().filter(item => item.provider === PROVIDER_ID) ?? []
256
+ lines.push('', ...modelReportLines(models.map(model => ({
257
+ model: model.id, rate: priceLabel(catalogDefinition(model)), context: model.contextWindow,
258
+ current: ctx?.model?.provider === PROVIDER_ID && ctx.model.id === model.id,
259
+ }))))
260
+ if (catalogError) lines.push(`Catalog refresh failed: ${catalogError}`)
261
+ }
262
+ if (section !== 'models') {
263
+ lines.push('', 'Session usage by model')
264
+ for (const [model, usage] of summary.byModel) {
265
+ const found = ctx?.modelRegistry.find(PROVIDER_ID, model)
266
+ const rate = found ? priceLabel(catalogDefinition(found)) : 'rate unknown'
267
+ lines.push(`${model} · ${rate === 'rate unknown' ? 'unknown' : rate} · ${formatCredits(usage.credits)} credits · ${usage.requests} requests${usage.unreported ? ` · ${usage.unreported} unreported` : ''}${usage.cancelledWithoutUsage ? ` · ${usage.cancelledWithoutUsage} cancelled without usage` : ''}`)
268
+ }
269
+ lines.push('', `Latest ${Math.min(records.length, 50)} requests`)
270
+ for (const record of records.slice(-50)) lines.push(`${new Date(record.timestamp).toISOString()} · ${requestLine(record)}`)
271
+ }
272
+ return lines
273
+ }
274
+
275
+ // 逐次请求只作为会话数据保存;聊天区仅渲染用户主动查询的报告。
276
+ const openService = async (ctx: ExtensionContext, initialSection = ''): Promise<void> => {
277
+ context = ctx
278
+ let section = initialSection.trim()
279
+ const interactiveMenu = section === '' && ctx.hasUI && ctx.mode === 'tui'
280
+ while (true) {
281
+ if (section === '' && interactiveMenu) {
282
+ const choice = await showMenu(ctx, MENU_ACTIONS, controller.signal)
283
+ if (choice === undefined || controller.signal.aborted) return
284
+ section = choice
285
+ }
286
+ if (section && !MENU_ACTIONS.some(action => action.value === section)) {
287
+ if (ctx.hasUI) ctx.ui.notify('Usage: /qoder [account|models|usage|refresh|status]', 'warning')
288
+ return
289
+ }
290
+ // Status/Usage 只读当前缓存;只有明确需要余额或目录时才等网络。
291
+ if (section === 'refresh' || section === 'account' || section === 'models') {
292
+ await refresh(section === 'refresh', false, true)
293
+ }
294
+ if (!controller.signal.aborted) await showReport(ctx, 'Qoder', reportLines(section), (lines, theme) => lines.map(line => highlightUsageLine(line, theme)))
295
+ if (!interactiveMenu) return
296
+ section = ''
297
+ }
298
+ }
299
+
300
+ pi.registerCommand('qoder', {
301
+ description: 'Open the Qoder menu for credits, model rates, request history and refresh',
302
+ getArgumentCompletions: prefix => MENU_ACTIONS.filter(action => action.value.startsWith(prefix)).map(action => ({ value: action.value, label: action.value, description: action.label })),
303
+ handler: async (args, ctx) => {
304
+ await openService(ctx, args.trim())
305
+ },
306
+ })
307
+ registerRelayService('qoder', 'Qoder', MENU_ACTIONS, (ctx, section) => openService(ctx, section))
308
+
309
+ pi.on('session_start', async (_event, ctx) => {
310
+ context = ctx
311
+ controller = new AbortController()
312
+ records = requestsFromBranch(currentProviderRun(ctx.sessionManager.getBranch()))
313
+ render()
314
+ timer = setInterval(() => { void refresh() }, QUOTA_TTL_MS)
315
+ timer.unref()
316
+ await refresh()
317
+ })
318
+ pi.on('session_tree', async (_event, ctx) => {
319
+ context = ctx
320
+ records = requestsFromBranch(currentProviderRun(ctx.sessionManager.getBranch()))
321
+ render()
322
+ })
323
+ pi.on('model_select', async (_event, ctx) => {
324
+ context = ctx
325
+ render()
326
+ // setModel 也触发此事件;当前刷新负责收尾,避免递归等待同一个 Promise。
327
+ if (!pending) await refresh()
328
+ })
329
+ pi.on('agent_settled', async (_event, ctx) => {
330
+ context = ctx
331
+ await refresh(false, true)
332
+ })
333
+ pi.on('session_shutdown', () => {
334
+ unregisterRelayService('qoder')
335
+ controller.abort()
336
+ if (timer) clearInterval(timer)
337
+ timer = undefined
338
+ context = undefined
339
+ quota.clear()
340
+ })
341
+
342
+ return {
343
+ /** 在传输层记录所有完成或失败的尝试,包括工具循环和内部摘要请求。 */
344
+ record(message: AssistantMessage): void {
345
+ if (!context || controller.signal.aborted) return
346
+ const record = requestRecord(message, crypto.randomUUID())
347
+ if (records.some(previous => previous.id === record.id)) return
348
+ records.push(record)
349
+ pi.appendEntry(REQUEST_ENTRY, record)
350
+ render()
351
+ },
352
+ }
353
+ }