@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.
@@ -0,0 +1,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 { 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
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Qoder 网页搜索(`/algo/api/v1/webSearch/oneSearch`)。
3
+ *
4
+ * 该接口由 Qoder 客户端内置的 `WebSearch` 工具使用,与模型能力无关:
5
+ * 客户端自己请求搜索网关,把 `pageItems` 作为工具结果回填给模型。
6
+ *
7
+ * 请求要求登录与 WASM 签名,body 是加密信封:
8
+ * `{ payload: "<json string>", encodeVersion: "1" }`。
9
+ */
10
+ import { CONFIG, ensureAuthWasm, signChatRequest } from './qoder-core.mjs'
11
+ import type { QoderCredential } from './types.ts'
12
+
13
+ /** CN 网关自带的搜索路径;国际版同一路径挂在 `api*.qoder.sh`。 */
14
+ export const SEARCH_PATH = '/api/v1/webSearch/oneSearch?Encode=1'
15
+ const SEARCH_TIMEOUT_MS = 20_000
16
+
17
+ export interface SearchHit {
18
+ title: string
19
+ link: string
20
+ snippet: string
21
+ publishedTime?: string
22
+ hostname?: string
23
+ }
24
+
25
+ export interface SearchResult {
26
+ query: string
27
+ hits: SearchHit[]
28
+ errorCode: number
29
+ errorMessage?: string
30
+ requestId?: string
31
+ }
32
+
33
+ function isRecord(value: unknown): value is Record<string, unknown> {
34
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
35
+ }
36
+
37
+ function text(value: unknown): string {
38
+ return typeof value === 'string' ? value : ''
39
+ }
40
+
41
+ /** 请求体与 Qoder 客户端的 `search()` 保持一致;关闭正文抓取以控制上下文体积。 */
42
+ export function searchBody(query: string, options: {
43
+ allowedDomains?: string[]
44
+ blockedDomains?: string[]
45
+ requestSetId?: string
46
+ } = {}): Record<string, unknown> {
47
+ const payload = {
48
+ query,
49
+ ...(options.allowedDomains?.length ? { allowed_domains: options.allowedDomains } : {}),
50
+ ...(options.blockedDomains?.length ? { blocked_domains: options.blockedDomains } : {}),
51
+ timeRange: 'NoLimit',
52
+ contents: { mainText: false, markdownText: false, summary: false },
53
+ ...(options.requestSetId ? { request_set_id: options.requestSetId } : {}),
54
+ }
55
+ return { payload: JSON.stringify(payload), encodeVersion: '1' }
56
+ }
57
+
58
+ /** 兼容 pageItems/page_items 与 camelCase/snake_case 字段。 */
59
+ export function parseSearchResult(body: unknown, query: string): SearchResult {
60
+ const data = isRecord(body) && isRecord(body.data) ? body.data : body
61
+ if (!isRecord(data)) throw new Error('Qoder web search response is not an object')
62
+ const items = Array.isArray(data.pageItems)
63
+ ? data.pageItems
64
+ : Array.isArray(data.page_items) ? data.page_items : []
65
+ const hits: SearchHit[] = []
66
+ for (const item of items) {
67
+ if (!isRecord(item)) continue
68
+ const link = text(item.link)
69
+ if (link === '') continue
70
+ hits.push({
71
+ title: text(item.title),
72
+ link,
73
+ snippet: text(item.snippet),
74
+ ...(text(item.publishedTime ?? item.published_time) ? { publishedTime: text(item.publishedTime ?? item.published_time) } : {}),
75
+ ...(text(item.hostname) ? { hostname: text(item.hostname) } : {}),
76
+ })
77
+ }
78
+ const errorCode = typeof data.errorCode === 'number' ? data.errorCode
79
+ : typeof data.error_code === 'number' ? data.error_code : 0
80
+ return {
81
+ query,
82
+ hits,
83
+ errorCode,
84
+ ...(text(data.errorMsg ?? data.error_msg) ? { errorMessage: text(data.errorMsg ?? data.error_msg) } : {}),
85
+ ...(text(data.requestId ?? data.request_id) ? { requestId: text(data.requestId ?? data.request_id) } : {}),
86
+ }
87
+ }
88
+
89
+ /** 用与对话相同的 WASM 上下文签名搜索请求,避免另写一套加密逻辑。 */
90
+ export async function signSearchRequest(body: unknown, credential: QoderCredential, {
91
+ endpoint = CONFIG.endpoint,
92
+ cliVersion = CONFIG.cliVersion,
93
+ }: { endpoint?: string; cliVersion?: string } = {}) {
94
+ const signed = await signChatRequest(body as Record<string, unknown>, {
95
+ machineId: credential.machineId ?? '',
96
+ ...(credential.uid === undefined ? {} : { uid: credential.uid }),
97
+ ...(credential.encryptUserInfo === undefined ? {} : { encryptUserInfo: credential.encryptUserInfo }),
98
+ ...(credential.signingKey === undefined ? {} : { signingKey: credential.signingKey }),
99
+ ...(credential.dataPolicy === undefined ? {} : { dataPolicy: credential.dataPolicy }),
100
+ }, {
101
+ endpoint,
102
+ apiPath: SEARCH_PATH,
103
+ cliVersion,
104
+ })
105
+ // 搜索返回 JSON,不是 SSE;去掉对话专用的流式头。
106
+ for (const name of ['accept', 'cache-control', 'x-model-key', 'x-model-source']) {
107
+ for (const key of Object.keys(signed.headers)) {
108
+ if (key.toLowerCase() === name) delete signed.headers[key]
109
+ }
110
+ }
111
+ signed.headers.accept = 'application/json'
112
+ return signed
113
+ }
114
+
115
+ export async function searchWeb(
116
+ query: string,
117
+ credential: QoderCredential,
118
+ options: {
119
+ signal?: AbortSignal
120
+ fetchImpl?: typeof fetch
121
+ endpoint?: string
122
+ allowedDomains?: string[]
123
+ blockedDomains?: string[]
124
+ requestSetId?: string
125
+ } = {},
126
+ ): Promise<SearchResult> {
127
+ const trimmed = query.trim()
128
+ if (trimmed === '') throw new Error('Qoder web search needs a non-empty query')
129
+ options.signal?.throwIfAborted()
130
+ const signed = await signSearchRequest(searchBody(trimmed, options), credential, {
131
+ ...(options.endpoint === undefined ? {} : { endpoint: options.endpoint }),
132
+ })
133
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS)
134
+ const signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
135
+ const response = await (options.fetchImpl ?? globalThis.fetch)(signed.url, {
136
+ method: 'POST',
137
+ headers: signed.headers,
138
+ body: signed.body,
139
+ signal,
140
+ })
141
+ if (!response.ok) {
142
+ await response.body?.cancel()
143
+ throw new Error(`Qoder web search returned HTTP ${response.status}`)
144
+ }
145
+ const raw = await response.text()
146
+ let parsed: unknown
147
+ try {
148
+ parsed = JSON.parse(raw)
149
+ } catch {
150
+ // 部分区域返回 WASM 加密响应,复用同一套解密逻辑。
151
+ const wasm = await ensureAuthWasm()
152
+ parsed = JSON.parse(wasm.decrypt_server_response(raw))
153
+ }
154
+ const result = parseSearchResult(parsed, trimmed)
155
+ if (result.errorCode !== 0) {
156
+ throw new Error(`Qoder web search failed (code ${result.errorCode})${result.errorMessage ? `: ${result.errorMessage}` : ''}`)
157
+ }
158
+ return result
159
+ }
160
+
161
+ /** 工具结果文本:标题、链接、摘要,控制长度避免撑爆上下文。 */
162
+ export function formatSearchResult(result: SearchResult, limit = 8): string {
163
+ if (result.hits.length === 0) return `No web results for "${result.query}".`
164
+ const lines = [`Web results for "${result.query}" (${Math.min(limit, result.hits.length)} shown):`]
165
+ for (const hit of result.hits.slice(0, limit)) {
166
+ lines.push('', `${hit.title || hit.hostname || hit.link}`, hit.link)
167
+ if (hit.snippet) lines.push(hit.snippet.replace(/\s+/g, ' ').slice(0, 400))
168
+ if (hit.publishedTime) lines.push(`Published: ${hit.publishedTime}`)
169
+ }
170
+ return lines.join('\n')
171
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@hex4c59/pi-ext-qoder",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Qoder international provider for pi: device login, signed streaming, live models and credits",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/Hex4C59/my-pi-extensions",
9
+ "directory": "qoder"
10
+ },
11
+ "type": "module",
12
+ "publishConfig": { "registry": "https://registry.npmjs.org/", "access": "public" },
13
+ "engines": {
14
+ "node": ">=22.19.0"
15
+ },
16
+ "peerDependencies": {
17
+ "@earendil-works/pi-coding-agent": "*",
18
+ "@earendil-works/pi-ai": "*",
19
+ "@earendil-works/pi-tui": "*"
20
+ },
21
+ "pi": {
22
+ "extensions": [
23
+ "./extensions/qoder.ts"
24
+ ]
25
+ },
26
+ "devDependencies": {
27
+ "@earendil-works/pi-coding-agent": "1.5.0",
28
+ "@earendil-works/pi-ai": "1.5.0",
29
+ "@earendil-works/pi-tui": "1.5.0",
30
+ "@types/node": "^22.19.0",
31
+ "typescript": "^6.0.3"
32
+ },
33
+ "scripts": {
34
+ "typecheck": "tsc --noEmit",
35
+ "test": "node ../test-utils/report-overlay.mjs ./lib/report-overlay.ts && node tests/offline.mjs",
36
+ "test:process": "node tests/process.mjs",
37
+ "test:tui": "node tests/tui.mjs",
38
+ "prepare:signing": "node scripts/prepare-signing.mjs"
39
+ },
40
+ "files": [
41
+ "extensions",
42
+ "lib",
43
+ "scripts",
44
+ "vendor/PROVENANCE.md",
45
+ "vendor/LICENSE.qoder",
46
+ "vendor/auth_glue.mjs",
47
+ "vendor/auth_wasm.wasm",
48
+ "THIRD_PARTY.md",
49
+ "LICENSE",
50
+ "NOTICE",
51
+ "README.md"
52
+ ]
53
+ }
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ /** 从固定版本官方 CLI 静态提取本机签名资源;不执行 CLI,也不读取登录态。 */
3
+ import { createHash } from 'node:crypto'
4
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
5
+ import { dirname, join, resolve } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+
8
+ const ROOT = dirname(dirname(fileURLToPath(import.meta.url)))
9
+ const BUNDLE_SHA256 = 'ca132c21eb2eec93d41138a6911009ef1f8a1e92b3cb372793e36c98fa1ea688'
10
+ const WASM_SHA256 = 'c7a14b11d6c23b94ac39f6868ebd3dd6a70492efe87c864c33857adadb9f0951'
11
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex')
12
+
13
+ const args = process.argv.slice(2)
14
+ if (args.length !== 2 || args[0] !== '--bundle') {
15
+ console.error('Usage: node scripts/prepare-signing.mjs --bundle <qodercli-1.1.85/package/bundle/qoder-worker-runtime.mjs>')
16
+ process.exitCode = 1
17
+ } else {
18
+ const bytes = await readFile(resolve(args[1]))
19
+ if (digest(bytes) !== BUNDLE_SHA256) throw new Error('Expected the unmodified @qoder-ai/qodercli@1.1.85 worker bundle; SHA-256 mismatch')
20
+ const source = bytes.toString('utf8')
21
+ let wasm
22
+ for (const match of source.matchAll(/['"](AGFzbQ[A-Za-z0-9+/=]{200,})['"]/g)) {
23
+ const candidate = Buffer.from(match[1], 'base64')
24
+ if (digest(candidate) === WASM_SHA256) { wasm = candidate; break }
25
+ }
26
+ if (!wasm) throw new Error('Pinned Qoder signing WASM not found')
27
+ // 此版本的 glue 是连续的顶层声明,边界由整个 bundle 的哈希固定。
28
+ const start = source.indexOf('var Api={};HA(Api,')
29
+ const end = source.indexOf('import*as WVA from"node:fs/promises";', start)
30
+ if (start < 0 || end <= start) throw new Error('Pinned Qoder signing glue boundaries not found')
31
+ const glue = `/** 从 Qoder CLI 1.1.85 提取;仅增加 ESM 导出、打包器辅助函数与 Node require 兼容。 */
32
+ import { createRequire } from 'node:module'
33
+ const module = { require: createRequire(import.meta.url) }
34
+ const HA = (target, getters) => {
35
+ for (const [key, get] of Object.entries(getters)) Object.defineProperty(target, key, { get, enumerable: true })
36
+ }
37
+ const C = initialize => {
38
+ let ready = false
39
+ return () => { if (!ready) { ready = true; initialize() } }
40
+ }
41
+ ${source.slice(start, end)}
42
+ tpi()
43
+ export { Api as sUi }
44
+ export const initAuthWasm = Api.default
45
+ `
46
+ const vendor = join(ROOT, 'vendor')
47
+ await mkdir(vendor, { recursive: true })
48
+ await writeFile(join(vendor, 'auth_wasm.wasm'), wasm)
49
+ await writeFile(join(vendor, 'auth_glue.mjs'), glue)
50
+ console.log(`Prepared local Qoder 1.1.85 signing resources: WASM ${wasm.length} bytes, SHA-256 ${digest(wasm)}; glue SHA-256 ${digest(glue)}`)
51
+ }