@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/CHANGELOG.md +6 -0
- package/LICENSE +21 -21
- package/README.md +152 -152
- package/lib/usage-ui.ts +353 -354
- package/package.json +57 -53
- package/vendor/PROVENANCE.md +42 -42
- package/vendor/auth_glue.mjs +0 -0
- package/vendor/auth_wasm.wasm +0 -0
- package/lib/relay-registry.ts +0 -34
- package/lib/report-overlay.ts +0 -175
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 {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
{ value: '
|
|
15
|
-
{ value: '
|
|
16
|
-
{ value: '
|
|
17
|
-
{ value: '
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
||
|
|
37
|
-
|| finiteNumber(value.
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
let
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
let
|
|
88
|
-
let
|
|
89
|
-
let
|
|
90
|
-
let
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
if (record
|
|
98
|
-
else
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
if (/^(
|
|
125
|
-
if (/^(
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
if (value
|
|
145
|
-
if (value === '
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
)
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
if (
|
|
153
|
-
if (
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
let
|
|
164
|
-
let
|
|
165
|
-
let
|
|
166
|
-
let
|
|
167
|
-
let
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
const
|
|
229
|
-
const
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
`
|
|
236
|
-
`
|
|
237
|
-
`
|
|
238
|
-
`
|
|
239
|
-
`
|
|
240
|
-
`
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
'
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
if (section
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
if (summary.
|
|
252
|
-
if (summary.
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
})
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
const
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
}
|
|
270
|
-
lines.push(
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
if (!
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
timer
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
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
|
+
}
|