@hex4c59/pi-ext-qoder 0.0.0-stage → 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.
@@ -0,0 +1,48 @@
1
+ /** 国际版 agent-chat 的官方 CLI 路由信封。 */
2
+ import { randomUUID } from 'node:crypto'
3
+ import { buildQoderBody } from './qoder-core.mjs'
4
+ import type { QoderBodyOptions } from './types.ts'
5
+
6
+ function isRecord(value: unknown): value is Record<string, unknown> {
7
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
8
+ }
9
+
10
+ /** 图片仍通过 messages 传递,路由上下文只提取文本。 */
11
+ function messageText(message: unknown): string {
12
+ if (!isRecord(message)) return ''
13
+ if (typeof message.content === 'string') return message.content
14
+ if (!Array.isArray(message.content)) return ''
15
+ return message.content.flatMap(part => isRecord(part) && part.type === 'text' && typeof part.text === 'string' ? [part.text] : []).join('')
16
+ }
17
+
18
+ /** 在通用模型参数上补齐官方 CLI 的 Agent 路由字段。 */
19
+ export function buildAgentRequest(options: QoderBodyOptions) {
20
+ const built = buildQoderBody(options)
21
+ const request = options.requestId || randomUUID()
22
+ const text = messageText(options.messages.filter(message => isRecord(message) && message.role === 'user').at(-1))
23
+ const system = options.messages.filter(message => isRecord(message) && message.role === 'system').map(messageText).join('\n\n')
24
+ const body = Object.assign(built.body, {
25
+ request_id: request,
26
+ chat_record_id: request,
27
+ request_set_id: request,
28
+ session_id: options.sessionId || request,
29
+ chat_task: 'FREE_INPUT',
30
+ is_reply: true,
31
+ is_retry: false,
32
+ source: 1,
33
+ version: '3',
34
+ agent_id: 'agent_common',
35
+ aliyun_user_type: '',
36
+ session_type: 'qodercli',
37
+ task_id: 'common',
38
+ chat_context: {
39
+ text, features: [],
40
+ extra: { context: [], modelConfig: { key: built.def.key, is_reasoning: built.body.model_config.is_reasoning }, originalContent: text },
41
+ chatPrompt: '', imageUrls: null,
42
+ },
43
+ })
44
+ Object.assign(body.parameters, { context_length: Number(options.window) > 0 ? Number(options.window) : built.def.window })
45
+ if (options.toolChoice !== undefined) Object.assign(body.parameters, { tool_choice: options.toolChoice })
46
+ if (system !== '') Object.assign(body, { system })
47
+ return { ...built, body }
48
+ }
package/lib/sse.ts ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * 按 SSE 事件边界读取 data,保留跨网络分块的 UTF-8 和 CRLF。
3
+ * 提前结束迭代或取消请求时释放响应体;调用方负责解释 [DONE] 与 JSON。
4
+ */
5
+ export async function* readSseData(
6
+ body: ReadableStream<Uint8Array>,
7
+ signal?: AbortSignal,
8
+ ): AsyncGenerator<string> {
9
+ signal?.throwIfAborted()
10
+ const reader = body.getReader()
11
+ const decoder = new TextDecoder('utf-8', { fatal: true })
12
+ let buffer = ''
13
+ let data: string[] = []
14
+ const onAbort = () => {
15
+ void reader.cancel(signal?.reason).catch(() => {})
16
+ }
17
+ signal?.addEventListener('abort', onAbort, { once: true })
18
+
19
+ const lineData = (line: string): string | undefined => {
20
+ if (line === '') {
21
+ if (data.length === 0) return undefined
22
+ const event = data.join('\n')
23
+ data = []
24
+ return event
25
+ }
26
+ if (line === 'data') data.push('')
27
+ else if (line.startsWith('data:')) {
28
+ const value = line.slice(5)
29
+ data.push(value.startsWith(' ') ? value.slice(1) : value)
30
+ }
31
+ return undefined
32
+ }
33
+
34
+ try {
35
+ for (;;) {
36
+ signal?.throwIfAborted()
37
+ const { value, done } = await reader.read()
38
+ signal?.throwIfAborted()
39
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true })
40
+ let newline: number
41
+ while ((newline = buffer.indexOf('\n')) >= 0) {
42
+ const line = buffer.slice(0, newline).replace(/\r$/, '')
43
+ buffer = buffer.slice(newline + 1)
44
+ const event = lineData(line)
45
+ if (event !== undefined) yield event
46
+ }
47
+ if (!done) continue
48
+ // 兼容上游在最后一个 data 行后直接关闭连接。
49
+ if (buffer !== '') lineData(buffer.replace(/\r$/, ''))
50
+ const final = lineData('')
51
+ if (final !== undefined) yield final
52
+ break
53
+ }
54
+ } finally {
55
+ signal?.removeEventListener('abort', onAbort)
56
+ try {
57
+ await reader.cancel()
58
+ } catch {
59
+ // 响应体可能已经关闭或因取消而失败。
60
+ }
61
+ reader.releaseLock()
62
+ }
63
+ }
package/lib/types.ts ADDED
@@ -0,0 +1,100 @@
1
+ import type { OAuthCredentials, ThinkingLevelMap, Usage } from '@earendil-works/pi-ai'
2
+
3
+ /** Pi 保存的 OAuth 凭据,以及重新生成签名材料所需的账号信息。 */
4
+ export interface QoderCredential extends OAuthCredentials {
5
+ type?: 'oauth'
6
+ uid?: string
7
+ machineId?: string
8
+ encryptUserInfo?: string
9
+ signingKey?: string
10
+ dataPolicy?: string
11
+ tokenExpireAt?: number
12
+ refreshExpireAt?: number
13
+ cliVersion?: string
14
+ organizationId?: string
15
+ organizationTags?: unknown[]
16
+ dataPolicyAgreed?: boolean
17
+ }
18
+
19
+ /** 上游模型快照与 Pi 思考档位的映射。 */
20
+ export interface QoderModelDefinition {
21
+ key: string
22
+ display: string
23
+ catalogReasoning: boolean
24
+ catalogVl: boolean
25
+ piReasoning: boolean
26
+ levels: ThinkingLevelMap
27
+ window: number
28
+ maxInput: number
29
+ source?: string
30
+ }
31
+
32
+ /** 经过筛选的实时目录信息;只保存可公开的模型能力与倍率。 */
33
+ export interface QoderCatalogModel extends QoderModelDefinition {
34
+ contextWindows: number[]
35
+ maxOutput: number
36
+ priceFactor?: number
37
+ }
38
+
39
+ /** credits 独立于 Pi 的美元 cost 字段保存。 */
40
+ export interface QoderUsage extends Usage {
41
+ credits?: number
42
+ qoderRequestId?: string
43
+ }
44
+
45
+ /** 每次请求的会话记录,不含提示词、账号标识或凭据。 */
46
+ export interface QoderRequestRecord {
47
+ id: string
48
+ model: string
49
+ credits: number | null
50
+ tokens: number
51
+ timestamp: number
52
+ stopReason: string
53
+ }
54
+
55
+ /** 登录和刷新使用的可取消 HTTP 请求。 */
56
+ export interface QoderAuthRequestOptions {
57
+ fetchImpl?: typeof globalThis.fetch
58
+ signal?: AbortSignal
59
+ }
60
+
61
+ /** 每次签名可覆盖的网关、路径和客户端版本。 */
62
+ export interface QoderSigningOptions {
63
+ endpoint?: string
64
+ apiPath?: string
65
+ cliVersion?: string
66
+ }
67
+
68
+ /** WASM 签名使用的账号与设备材料。 */
69
+ export interface QoderSigningFacts {
70
+ machineId: string
71
+ uid?: string
72
+ encryptUserInfo?: string
73
+ signingKey?: string
74
+ dataPolicy?: string
75
+ }
76
+
77
+ /** 登录和刷新时交给 WASM 的新 Token 与组织信息。 */
78
+ export interface QoderSigningFieldsInput {
79
+ uid: string
80
+ token: string
81
+ organizationId?: string
82
+ organizationTags?: unknown[]
83
+ dataPolicyAgreed?: boolean
84
+ }
85
+
86
+ /** 对话请求体中可配置的参数,未指定的值使用上游默认值。 */
87
+ export interface QoderBodyOptions {
88
+ requestId?: string
89
+ sessionId?: string
90
+ modelId: string
91
+ definition?: QoderModelDefinition
92
+ messages: unknown[]
93
+ tools?: unknown[]
94
+ toolChoice?: unknown
95
+ effort?: string
96
+ maxTokens?: number
97
+ temperature?: number
98
+ topP?: number
99
+ window?: number
100
+ }
@@ -0,0 +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 { 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
+ }