@hex4c59/pi-ext-qoder 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE +9 -0
- package/README.md +151 -2
- package/THIRD_PARTY.md +13 -0
- package/extensions/qoder.ts +960 -0
- package/lib/account.ts +129 -0
- package/lib/catalog.ts +228 -0
- package/lib/credit-report.ts +112 -0
- package/lib/model-report.ts +107 -0
- package/lib/qoder-core.mjs +864 -0
- package/lib/relay-registry.ts +34 -0
- package/lib/report-overlay.ts +175 -0
- package/lib/request-body.ts +48 -0
- package/lib/sse.ts +63 -0
- package/lib/types.ts +100 -0
- package/lib/usage-ui.ts +354 -0
- package/lib/web-search.ts +171 -0
- package/package.json +51 -4
- package/scripts/prepare-signing.mjs +51 -0
- package/vendor/LICENSE.qoder +202 -0
- package/vendor/PROVENANCE.md +42 -0
- package/vendor/auth_glue.mjs +14 -0
- package/vendor/auth_wasm.wasm +0 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ExtensionContext } from '@earendil-works/pi-coding-agent'
|
|
2
|
+
|
|
3
|
+
export interface RelayAction {
|
|
4
|
+
value: string
|
|
5
|
+
label: string
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface RelayService {
|
|
9
|
+
label: string
|
|
10
|
+
actions: readonly RelayAction[]
|
|
11
|
+
run: (ctx: ExtensionContext, section: string) => Promise<void>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const REGISTRY_KEY = Symbol.for('hex4c59.pi-ext.relay.registry')
|
|
15
|
+
type RegistryHolder = Record<symbol, Map<string, RelayService> | undefined>
|
|
16
|
+
|
|
17
|
+
/** 同一 Pi 进程内的轻量注册表;只在已加载的扩展之间使用。 */
|
|
18
|
+
export function relayServices(): Map<string, RelayService> {
|
|
19
|
+
const holder = globalThis as unknown as RegistryHolder
|
|
20
|
+
return (holder[REGISTRY_KEY] ??= new Map())
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function registerRelayService(
|
|
24
|
+
id: string,
|
|
25
|
+
label: string,
|
|
26
|
+
actions: readonly RelayAction[],
|
|
27
|
+
run: RelayService['run'],
|
|
28
|
+
): void {
|
|
29
|
+
relayServices().set(id, { label, actions, run })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function unregisterRelayService(id: string): void {
|
|
33
|
+
relayServices().delete(id)
|
|
34
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { DynamicBorder, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Container, matchesKey, SelectList, Spacer, Text, truncateToWidth, type Component, type OverlayHandle, type TUI } from "@earendil-works/pi-tui";
|
|
3
|
+
|
|
4
|
+
type LineStyler = (lines: readonly string[], theme: Theme) => string[];
|
|
5
|
+
|
|
6
|
+
class ReportOverlay implements Component {
|
|
7
|
+
private offset = 0;
|
|
8
|
+
private readonly tui: TUI;
|
|
9
|
+
private readonly theme: Theme;
|
|
10
|
+
private readonly lines: readonly string[];
|
|
11
|
+
private readonly done: (result: void) => void;
|
|
12
|
+
private readonly style: LineStyler | undefined;
|
|
13
|
+
private removeInputListener: (() => void) | undefined;
|
|
14
|
+
|
|
15
|
+
constructor(
|
|
16
|
+
tui: TUI,
|
|
17
|
+
theme: Theme,
|
|
18
|
+
lines: readonly string[],
|
|
19
|
+
done: (result: void) => void,
|
|
20
|
+
style?: LineStyler,
|
|
21
|
+
) {
|
|
22
|
+
this.tui = tui;
|
|
23
|
+
this.theme = theme;
|
|
24
|
+
this.lines = lines;
|
|
25
|
+
this.done = done;
|
|
26
|
+
this.style = style;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
private get maxVisible(): number {
|
|
30
|
+
const rows = Math.max(12, this.tui.terminal.rows);
|
|
31
|
+
return Math.max(3, Math.floor(rows * 0.8) - 4);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
render(width: number): string[] {
|
|
35
|
+
if (width < 3) return [];
|
|
36
|
+
const innerWidth = width - 2;
|
|
37
|
+
const border = (text: string) => this.theme.fg("border", text);
|
|
38
|
+
const fit = (text: string) => truncateToWidth(text, innerWidth, "…", true);
|
|
39
|
+
const styled = this.style ? this.style(this.lines, this.theme) : [...this.lines];
|
|
40
|
+
const limit = Math.max(0, styled.length - this.maxVisible);
|
|
41
|
+
this.offset = Math.min(this.offset, limit);
|
|
42
|
+
const visible = styled.slice(this.offset, this.offset + this.maxVisible);
|
|
43
|
+
const hint = styled.length > visible.length
|
|
44
|
+
? `${this.offset + 1}-${this.offset + visible.length}/${styled.length} · PgUp/PgDn scroll · Esc close`
|
|
45
|
+
: "Esc close";
|
|
46
|
+
|
|
47
|
+
return [
|
|
48
|
+
border(`╭${"─".repeat(innerWidth)}╮`),
|
|
49
|
+
...visible.map((line) => border("│") + fit(` ${line}`) + border("│")),
|
|
50
|
+
border("│") + fit(this.theme.fg("dim", ` ${hint}`)) + border("│"),
|
|
51
|
+
border(`╰${"─".repeat(innerWidth)}╯`),
|
|
52
|
+
];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
handleInput(data: string): void {
|
|
56
|
+
this.handleReportInput(data);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private handleReportInput(data: string): boolean {
|
|
60
|
+
if (matchesKey(data, "escape")) {
|
|
61
|
+
this.done(undefined);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
const limit = Math.max(0, this.lines.length - this.maxVisible);
|
|
65
|
+
const nextOffset = matchesKey(data, "pageUp")
|
|
66
|
+
? Math.max(0, this.offset - this.maxVisible)
|
|
67
|
+
: matchesKey(data, "pageDown")
|
|
68
|
+
? Math.min(limit, this.offset + this.maxVisible)
|
|
69
|
+
: this.offset;
|
|
70
|
+
if (nextOffset === this.offset) return false;
|
|
71
|
+
this.offset = nextOffset;
|
|
72
|
+
this.tui.requestRender();
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
setOverlayHandle(handle: OverlayHandle): void {
|
|
77
|
+
this.removeInputListener = this.tui.addInputListener((data) => {
|
|
78
|
+
if (handle.isFocused()) handle.unfocus();
|
|
79
|
+
return this.handleReportInput(data) ? { consume: true } : undefined;
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
dispose(): void {
|
|
84
|
+
this.removeInputListener?.();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
invalidate(): void {}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 一次性报告只做临时 overlay,不追加会话条目。非 TUI 模式退化为通知。 */
|
|
91
|
+
export async function showReport(
|
|
92
|
+
ctx: ExtensionContext,
|
|
93
|
+
title: string,
|
|
94
|
+
lines: readonly string[],
|
|
95
|
+
style?: LineStyler,
|
|
96
|
+
): Promise<void> {
|
|
97
|
+
if (!ctx.hasUI) return;
|
|
98
|
+
if (ctx.mode !== "tui") {
|
|
99
|
+
ctx.ui.notify(`${title}\n${lines.join("\n")}`, "info");
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
let report: ReportOverlay | undefined;
|
|
103
|
+
await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
|
|
104
|
+
report = new ReportOverlay(tui, theme, lines, done, style);
|
|
105
|
+
return report;
|
|
106
|
+
}, {
|
|
107
|
+
overlay: true,
|
|
108
|
+
overlayOptions: {
|
|
109
|
+
anchor: "bottom-center",
|
|
110
|
+
width: "100%",
|
|
111
|
+
minWidth: 40,
|
|
112
|
+
maxHeight: "80%",
|
|
113
|
+
// 与输入区同宽,只留出编辑器上沿和底栏的高度。
|
|
114
|
+
margin: { bottom: 6 },
|
|
115
|
+
nonCapturing: true,
|
|
116
|
+
},
|
|
117
|
+
onHandle: (handle) => report?.setOverlayHandle(handle),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 无标题菜单;只保留边框、选项和底部按键提示,不占标题行。 */
|
|
122
|
+
export async function showMenu(
|
|
123
|
+
ctx: ExtensionContext,
|
|
124
|
+
actions: readonly { value: string; label: string }[],
|
|
125
|
+
signal?: AbortSignal,
|
|
126
|
+
): Promise<string | undefined> {
|
|
127
|
+
if (!ctx.hasUI || ctx.mode !== "tui" || signal?.aborted) return undefined;
|
|
128
|
+
return await ctx.ui.custom<string | undefined>((tui, theme, _keybindings, done) => {
|
|
129
|
+
const items = actions.map((action) => ({ value: action.value, label: action.label, description: undefined }));
|
|
130
|
+
const list = new SelectList(items, Math.min(items.length, 10), {
|
|
131
|
+
selectedPrefix: (text) => theme.fg("accent", text),
|
|
132
|
+
selectedText: (text) => theme.fg("accent", text),
|
|
133
|
+
description: (text) => theme.fg("muted", text),
|
|
134
|
+
scrollInfo: (text) => theme.fg("dim", text),
|
|
135
|
+
noMatch: (text) => theme.fg("warning", text),
|
|
136
|
+
});
|
|
137
|
+
const container = new Container();
|
|
138
|
+
container.addChild(new DynamicBorder((text) => theme.fg("border", text)));
|
|
139
|
+
container.addChild(new Spacer(1));
|
|
140
|
+
container.addChild(list);
|
|
141
|
+
container.addChild(new Spacer(1));
|
|
142
|
+
container.addChild(new Text(theme.fg("dim", "↑↓ navigate enter select escape/ctrl+c cancel"), 1, 0));
|
|
143
|
+
container.addChild(new DynamicBorder((text) => theme.fg("border", text)));
|
|
144
|
+
|
|
145
|
+
const finish = (value: string | undefined) => {
|
|
146
|
+
signal?.removeEventListener("abort", onAbort);
|
|
147
|
+
done(value);
|
|
148
|
+
};
|
|
149
|
+
const onAbort = () => finish(undefined);
|
|
150
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
151
|
+
list.onSelect = (item) => finish(item.value);
|
|
152
|
+
list.onCancel = () => finish(undefined);
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
capturesViewportInput: list.capturesViewportInput,
|
|
156
|
+
render(width: number) {
|
|
157
|
+
return container.render(width).map((line) => truncateToWidth(line, width, "…"));
|
|
158
|
+
},
|
|
159
|
+
invalidate() {
|
|
160
|
+
container.invalidate();
|
|
161
|
+
},
|
|
162
|
+
handleInput(data: string) {
|
|
163
|
+
if (signal?.aborted) {
|
|
164
|
+
finish(undefined);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
list.handleInput(data);
|
|
168
|
+
tui.requestRender();
|
|
169
|
+
},
|
|
170
|
+
dispose() {
|
|
171
|
+
signal?.removeEventListener("abort", onAbort);
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
});
|
|
175
|
+
}
|
|
@@ -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
|
+
}
|