@hex4c59/pi-ext-copilot-auto 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/README.md +315 -2
- package/docs/PROTOCOL.md +860 -0
- package/extensions/copilot-auto.ts +341 -0
- package/lib/account.ts +157 -0
- package/lib/auth.ts +156 -0
- package/lib/catalog.ts +299 -0
- package/lib/client.ts +508 -0
- package/lib/debug.ts +39 -0
- package/lib/protocol.ts +243 -0
- package/lib/sessions.ts +182 -0
- package/lib/stream.ts +306 -0
- package/lib/token.ts +83 -0
- package/package.json +40 -4
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub Copilot Auto provider 扩展。
|
|
3
|
+
*
|
|
4
|
+
* 复现 VS Code / OpenCode 的 Auto 模式:请求先经 `/auto` 由服务端决定使用
|
|
5
|
+
* 哪个模型,再用返回的 session_token 调用 `/responses`。这是使用
|
|
6
|
+
* `gpt-5.3-codex`、`mai-code-1.1-flash` 等 Auto 专属模型的唯一途径——
|
|
7
|
+
* 不带 session_token 时这些模型一律返回 400 model_not_supported。
|
|
8
|
+
*
|
|
9
|
+
* 设计取舍:
|
|
10
|
+
* - 复用 pi 已保存的 `github-copilot` OAuth 凭据,无需二次登录;
|
|
11
|
+
* - 目录用 GitHub OAuth refresh token 拉取(access 过期也能工作);
|
|
12
|
+
* - 模型清单在启动时从 `/models` 实时获取,不硬编码;
|
|
13
|
+
* - **同时提供 `auto` 虚拟模型与真实模型**:前者交给服务端路由,
|
|
14
|
+
* 后者用于固定模型;
|
|
15
|
+
* - 请求体、流式解析、工具调用、用量与取消全部交给 pi-ai 的
|
|
16
|
+
* `openai-responses` 实现,本扩展只做路由与请求头注入。
|
|
17
|
+
*
|
|
18
|
+
* 本模块不记录访问令牌、session token 或完整响应体。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
|
|
22
|
+
import {
|
|
23
|
+
type Api,
|
|
24
|
+
type Model,
|
|
25
|
+
createProvider,
|
|
26
|
+
} from '@earendil-works/pi-ai/compat'
|
|
27
|
+
import {
|
|
28
|
+
baseUrlForToken,
|
|
29
|
+
clearRuntimeAccessToken,
|
|
30
|
+
copilotAutoAuth,
|
|
31
|
+
resolveCopilotToken,
|
|
32
|
+
setRuntimeAccessToken,
|
|
33
|
+
storedGithubToken,
|
|
34
|
+
tokenExpired,
|
|
35
|
+
} from '../lib/auth.ts'
|
|
36
|
+
import {
|
|
37
|
+
fetchAccount,
|
|
38
|
+
fetchAuthorizedModels,
|
|
39
|
+
fetchCatalog,
|
|
40
|
+
refreshAccessToken,
|
|
41
|
+
resolveApiBase,
|
|
42
|
+
type RequestTarget,
|
|
43
|
+
} from '../lib/client.ts'
|
|
44
|
+
import { formatAccount, type CopilotAccount } from '../lib/account.ts'
|
|
45
|
+
import {
|
|
46
|
+
AUTO_MODEL_ID,
|
|
47
|
+
type ModelSpec,
|
|
48
|
+
buildModelList,
|
|
49
|
+
specFromCatalog,
|
|
50
|
+
} from '../lib/catalog.ts'
|
|
51
|
+
import type { CatalogEntry } from '../lib/protocol.ts'
|
|
52
|
+
import { API_ID, CLIENT_HEADERS, DEFAULT_CAPI_BASE, PROVIDER_ID, PROVIDER_NAME } from '../lib/protocol.ts'
|
|
53
|
+
import { autoSessions } from '../lib/sessions.ts'
|
|
54
|
+
import { setCatalogProvider, streamAuto } from '../lib/stream.ts'
|
|
55
|
+
|
|
56
|
+
/** 最近一次成功加载的模型清单,供同步 getModels() 返回。 */
|
|
57
|
+
let catalogModels: ModelSpec[] = []
|
|
58
|
+
/** 最近一次成功加载的原始目录,供协商降级使用。 */
|
|
59
|
+
let catalogEntries: CatalogEntry[] = []
|
|
60
|
+
/** 目录加载状态,供 `/copilot-auto` 展示。 */
|
|
61
|
+
let catalogLoaded = false
|
|
62
|
+
/** 最近一次加载失败的原因(不含凭据)。 */
|
|
63
|
+
let lastError: string | undefined
|
|
64
|
+
/** 由账号端点解析出的 API 根地址。 */
|
|
65
|
+
let resolvedBase: string | undefined
|
|
66
|
+
/** 最近一次从 `/models/session` 得到的授权模型清单。 */
|
|
67
|
+
let authorizedModels: string[] = []
|
|
68
|
+
|
|
69
|
+
/** 额度缓存:避免反复请求,但保留足够短的有效期以反映真实消耗。 */
|
|
70
|
+
const ACCOUNT_TTL_MS = 60_000
|
|
71
|
+
let accountCache: { account: CopilotAccount; fetchedAt: number } | undefined
|
|
72
|
+
|
|
73
|
+
/** 把 ModelSpec 转成 pi 的模型定义。 */
|
|
74
|
+
function toModel(spec: ModelSpec, baseUrl: string): Model<Api> {
|
|
75
|
+
const model: Model<Api> = {
|
|
76
|
+
id: spec.id,
|
|
77
|
+
name: spec.name,
|
|
78
|
+
api: API_ID as Api,
|
|
79
|
+
provider: PROVIDER_ID,
|
|
80
|
+
baseUrl,
|
|
81
|
+
reasoning: spec.reasoning,
|
|
82
|
+
input: spec.input,
|
|
83
|
+
cost: spec.cost,
|
|
84
|
+
contextWindow: spec.contextWindow,
|
|
85
|
+
maxTokens: spec.maxTokens,
|
|
86
|
+
headers: { ...CLIENT_HEADERS },
|
|
87
|
+
}
|
|
88
|
+
if (spec.thinkingLevelMap !== undefined) model.thinkingLevelMap = spec.thinkingLevelMap
|
|
89
|
+
return model
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 确保存在可用的 Copilot access 令牌。
|
|
94
|
+
*
|
|
95
|
+
* 存储的 access 通常已过期(实测直接用它请求 `/models` 得到 401)。
|
|
96
|
+
* 这里用 GitHub OAuth refresh token 换一个新的,只保存在内存中。
|
|
97
|
+
*
|
|
98
|
+
* 失败不抛物:保持原有凭据,让 pi 自己报缺 key,避免扩展把启动弄断。
|
|
99
|
+
*/
|
|
100
|
+
async function ensureAccessToken(signal?: AbortSignal): Promise<void> {
|
|
101
|
+
const current = resolveCopilotToken()
|
|
102
|
+
if (current !== undefined && !tokenExpired(current)) return
|
|
103
|
+
|
|
104
|
+
const github = storedGithubToken()
|
|
105
|
+
if (github === undefined) return
|
|
106
|
+
const refreshed = await refreshAccessToken(github, signal)
|
|
107
|
+
if (refreshed === undefined) {
|
|
108
|
+
clearRuntimeAccessToken()
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
setRuntimeAccessToken(refreshed.token, refreshed.expiresAt)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 拉取目录并解析 API 根地址。
|
|
116
|
+
*
|
|
117
|
+
* 关键:**用 GitHub OAuth refresh token 拉目录**,不是 Copilot access token。
|
|
118
|
+
* 实测 access 过期时 `/models` 返回 401,而 refresh 仍然 200。
|
|
119
|
+
* OpenCode v2 采用同样的做法。
|
|
120
|
+
*/
|
|
121
|
+
async function loadModels(signal?: AbortSignal): Promise<{ entries: CatalogEntry[]; baseUrl: string }> {
|
|
122
|
+
const access = resolveCopilotToken()
|
|
123
|
+
const github = storedGithubToken()
|
|
124
|
+
const token = github ?? access
|
|
125
|
+
if (token === undefined) {
|
|
126
|
+
throw new Error('未登录:请运行 /login 选择 "GitHub Copilot"')
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// baseURL 优先取账号端点的 endpoints.api(OpenCode 的做法),
|
|
130
|
+
// 其次用 access token 的 proxy-ep 推导,最后回退默认地址。
|
|
131
|
+
let baseUrl = resolvedBase
|
|
132
|
+
if (baseUrl === undefined && github !== undefined) {
|
|
133
|
+
baseUrl = await resolveApiBase(github, signal)
|
|
134
|
+
if (baseUrl !== undefined) resolvedBase = baseUrl
|
|
135
|
+
}
|
|
136
|
+
if (baseUrl === undefined) {
|
|
137
|
+
baseUrl = access !== undefined ? baseUrlForToken(access) : DEFAULT_CAPI_BASE
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const target: RequestTarget = {
|
|
141
|
+
token,
|
|
142
|
+
baseUrl,
|
|
143
|
+
...(signal === undefined ? {} : { signal }),
|
|
144
|
+
}
|
|
145
|
+
const entries = await fetchCatalog(target)
|
|
146
|
+
return { entries, baseUrl }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 查询 `/models/session` 公布的授权模型清单。
|
|
151
|
+
*
|
|
152
|
+
* 这一步是必要的:实测只有该清单里的模型能拿到可用的 session token,
|
|
153
|
+
* 其余模型无论 `/models` 怎么写都会返回 `model_not_supported` 或
|
|
154
|
+
* `Requested model not available for session`。
|
|
155
|
+
*
|
|
156
|
+
* 用 access 令牌(该端点不认 refresh 令牌);用 refresh 会双双失败。
|
|
157
|
+
* 失败时返回空数组(表示不过滤),避免一次网络抖动清空选择器。
|
|
158
|
+
*/
|
|
159
|
+
async function loadAuthorizedModels(): Promise<string[]> {
|
|
160
|
+
const access = resolveCopilotToken()
|
|
161
|
+
if (access === undefined) return []
|
|
162
|
+
|
|
163
|
+
const baseUrl = resolvedBase ?? baseUrlForToken(access)
|
|
164
|
+
return fetchAuthorizedModels({ token: access, baseUrl }).catch(() => [])
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 解析凭据并拉取目录。
|
|
169
|
+
*
|
|
170
|
+
* 未登录或网络失败时返回空列表,让 pi 以「无可用模型」继续启动,而不是
|
|
171
|
+
* 让扩展工厂抛错影响整个进程。失败原因记录在 lastError 中。
|
|
172
|
+
*/
|
|
173
|
+
async function safeLoadModels(signal?: AbortSignal): Promise<{ specs: ModelSpec[]; baseUrl: string }> {
|
|
174
|
+
try {
|
|
175
|
+
const result = await loadModels(signal)
|
|
176
|
+
catalogEntries = result.entries
|
|
177
|
+
catalogLoaded = true
|
|
178
|
+
lastError = undefined
|
|
179
|
+
|
|
180
|
+
const authorized = await loadAuthorizedModels().catch(() => [])
|
|
181
|
+
authorizedModels = authorized
|
|
182
|
+
|
|
183
|
+
// Auto 虚拟条目与真实模型并列:前者交给服务端路由(实测能选中目录之外的
|
|
184
|
+
// 模型),后者仅包含 `/models/session` 确认授权的条目。
|
|
185
|
+
const built = buildModelList(result.entries, authorized)
|
|
186
|
+
const specs = built.auto === undefined ? built.specs : [built.auto, ...built.specs]
|
|
187
|
+
return { specs, baseUrl: result.baseUrl }
|
|
188
|
+
} catch (error) {
|
|
189
|
+
lastError = error instanceof Error ? error.message : String(error)
|
|
190
|
+
return { specs: [], baseUrl: DEFAULT_CAPI_BASE }
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export default async function (pi: ExtensionAPI) {
|
|
195
|
+
// 先把 access 令牌刷新好:auth.resolve 依赖它,且目录拉取也要用到。
|
|
196
|
+
await ensureAccessToken()
|
|
197
|
+
|
|
198
|
+
// 在工厂内拉取目录:pi 会等待异步工厂完成,因此启动时的模型选择与
|
|
199
|
+
// `pi --list-models` 都能看到这些模型。
|
|
200
|
+
const loaded = await safeLoadModels()
|
|
201
|
+
catalogModels = loaded.specs
|
|
202
|
+
const baseUrl = loaded.baseUrl
|
|
203
|
+
|
|
204
|
+
// 让流式实现能读到当前目录(协商失败时用于挑选降级模型)。
|
|
205
|
+
setCatalogProvider(() => catalogEntries)
|
|
206
|
+
|
|
207
|
+
const provider = createProvider({
|
|
208
|
+
id: PROVIDER_ID,
|
|
209
|
+
name: PROVIDER_NAME,
|
|
210
|
+
baseUrl,
|
|
211
|
+
auth: { apiKey: copilotAutoAuth() },
|
|
212
|
+
models: catalogModels.map((spec) => toModel(spec, baseUrl)),
|
|
213
|
+
// 自定义 streamSimple:先协商 Auto 会话,再委托 openai-responses。
|
|
214
|
+
api: {
|
|
215
|
+
[API_ID as Api]: {
|
|
216
|
+
stream: streamAuto,
|
|
217
|
+
streamSimple: streamAuto,
|
|
218
|
+
},
|
|
219
|
+
},
|
|
220
|
+
// 运行期刷新:账号套餐或 Copilot 目录变化后,/model 会重新拉取。
|
|
221
|
+
async fetchModels({ signal }) {
|
|
222
|
+
const refreshed = await safeLoadModels(signal)
|
|
223
|
+
if (refreshed.specs.length > 0) {
|
|
224
|
+
catalogModels = refreshed.specs
|
|
225
|
+
const refreshedBase = refreshed.baseUrl
|
|
226
|
+
return refreshed.specs.map((spec) => toModel(spec, refreshedBase))
|
|
227
|
+
}
|
|
228
|
+
return catalogModels.map((spec) => toModel(spec, baseUrl))
|
|
229
|
+
},
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
pi.registerProvider(provider)
|
|
233
|
+
|
|
234
|
+
pi.registerCommand('copilot-auto', {
|
|
235
|
+
description: '显示 Copilot Auto provider 状态与账号额度',
|
|
236
|
+
async handler(_args, ctx) {
|
|
237
|
+
const token = resolveCopilotToken()
|
|
238
|
+
const lines: string[] = []
|
|
239
|
+
lines.push(`provider: ${PROVIDER_ID}`)
|
|
240
|
+
if (token === undefined) {
|
|
241
|
+
lines.push('凭据: 未登录(运行 /login 选择 "GitHub Copilot")')
|
|
242
|
+
} else {
|
|
243
|
+
lines.push('凭据: github-copilot OAuth')
|
|
244
|
+
}
|
|
245
|
+
lines.push(`API: ${resolvedBase ?? baseUrl}`)
|
|
246
|
+
|
|
247
|
+
// 额度查询独立于对话通道,失败不应影响其它信息的展示。
|
|
248
|
+
// 结果缓存 60 秒:频繁执行命令时不会反复打 API,又能反映真实消耗。
|
|
249
|
+
const githubToken = storedGithubToken()
|
|
250
|
+
if (githubToken !== undefined) {
|
|
251
|
+
try {
|
|
252
|
+
const cached = accountCache
|
|
253
|
+
const fresh = cached !== undefined && Date.now() - cached.fetchedAt < ACCOUNT_TTL_MS
|
|
254
|
+
const account = fresh && cached !== undefined
|
|
255
|
+
? cached.account
|
|
256
|
+
: await fetchAccount(githubToken)
|
|
257
|
+
if (!fresh) accountCache = { account, fetchedAt: Date.now() }
|
|
258
|
+
lines.push(...formatAccount(account))
|
|
259
|
+
} catch (error) {
|
|
260
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
261
|
+
lines.push(`额度: 查询失败(${reason})`)
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
lines.push(catalogLoaded
|
|
266
|
+
? `目录: ${catalogEntries.length} 个条目`
|
|
267
|
+
: `目录: 加载失败(${lastError ?? '未知原因'})`)
|
|
268
|
+
|
|
269
|
+
const routable = catalogEntries.filter((entry) => entry.billing?.auto_discount !== undefined)
|
|
270
|
+
lines.push(`Auto 可路由: ${routable.length} 个`)
|
|
271
|
+
lines.push(authorizedModels.length === 0
|
|
272
|
+
? '已授权模型: 未获取(协商失败时不过滤)'
|
|
273
|
+
: `已授权模型: ${authorizedModels.join(', ')}`)
|
|
274
|
+
|
|
275
|
+
// 缓存中各会话的服务端选择,用于确认实际发出的模型。
|
|
276
|
+
const sessions = autoSessions.snapshot()
|
|
277
|
+
if (sessions.length > 0) {
|
|
278
|
+
const pairs = sessions.map((entry) =>
|
|
279
|
+
entry.degraded
|
|
280
|
+
? `${entry.requested} → 降级`
|
|
281
|
+
: `${entry.requested} → ${entry.effective}`)
|
|
282
|
+
lines.push(`会话路由: ${pairs.join(' | ')}`)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (catalogModels.length > 0) {
|
|
286
|
+
lines.push(`可选: ${catalogModels.map((model) => model.id).join(', ')}`)
|
|
287
|
+
}
|
|
288
|
+
lines.push(`会话缓存: ${autoSessions.size} 条`)
|
|
289
|
+
ctx.ui.notify(lines.join('\n'), token === undefined ? 'warning' : 'info')
|
|
290
|
+
},
|
|
291
|
+
})
|
|
292
|
+
|
|
293
|
+
// 会话切换时清空会话缓存,避免沿用其他账号或旧对话的 session token。
|
|
294
|
+
pi.on('session_start', () => {
|
|
295
|
+
autoSessions.clear()
|
|
296
|
+
})
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* 上下文压缩后立即作废会话令牌。
|
|
300
|
+
*
|
|
301
|
+
* 对齐 OpenCode 的 `compaction` hook(它把该会话的 `until` 置 0)。
|
|
302
|
+
* 压缩改写了对话形态,旧令牌对应的路由决策不再适用;继续复用会让后续
|
|
303
|
+
* 请求沿用压缩前的模型选择。这里清空整个缓存,效果等价且不依赖
|
|
304
|
+
* 事件里是否带有会话标识。
|
|
305
|
+
*/
|
|
306
|
+
pi.on('session_compact', () => {
|
|
307
|
+
autoSessions.clear()
|
|
308
|
+
})
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* 切换到另一条分支后同样作废。
|
|
312
|
+
*
|
|
313
|
+
* `/tree` 跳转后对话上下文发生了变化,代理键(首个用户消息摘要)也可能
|
|
314
|
+
* 变化;主动清空可避免把旧分支的路由结果带给新分支。
|
|
315
|
+
*/
|
|
316
|
+
pi.on('session_tree', () => {
|
|
317
|
+
autoSessions.clear()
|
|
318
|
+
})
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** 供测试使用:最近一次加载的模型清单。 */
|
|
322
|
+
export function loadedModels(): ModelSpec[] {
|
|
323
|
+
return catalogModels.map((spec) => ({ ...spec }))
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** 供测试使用:最近一次加载的原始目录。 */
|
|
327
|
+
export function loadedCatalog(): CatalogEntry[] {
|
|
328
|
+
return [...catalogEntries]
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** 供测试使用:目录加载状态。 */
|
|
332
|
+
export function catalogState(): { loaded: boolean; count: number; error?: string } {
|
|
333
|
+
return {
|
|
334
|
+
loaded: catalogLoaded,
|
|
335
|
+
count: catalogEntries.length,
|
|
336
|
+
...(lastError === undefined ? {} : { error: lastError }),
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** 供测试使用:Auto 模型 id。 */
|
|
341
|
+
export { AUTO_MODEL_ID, specFromCatalog }
|
package/lib/account.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 账号额度查询与格式化。
|
|
3
|
+
*
|
|
4
|
+
* 数据来源是 `https://api.github.com/copilot_internal/user`,它同时返回套餐标识
|
|
5
|
+
* (`access_type_sku`)与额度快照(`quota_snapshots`)。这个端点接受 **GitHub
|
|
6
|
+
* OAuth 令牌**(auth.json 中 `github-copilot.refresh`),而不是 Copilot 访问令牌。
|
|
7
|
+
*
|
|
8
|
+
* ## 该看哪个额度维度
|
|
9
|
+
*
|
|
10
|
+
* VS Code `copilot-chat` 0.72.0 的判定(源码 `extension.js`):
|
|
11
|
+
*
|
|
12
|
+
* ```js
|
|
13
|
+
* get isFreeUser() { return this.sku === "free_limited_copilot" }
|
|
14
|
+
* // 读额度时:
|
|
15
|
+
* isFreeUser ? header("x-quota-snapshot-chat")
|
|
16
|
+
* : header("x-quota-snapshot-premium_models")
|
|
17
|
+
* ?? header("x-quota-snapshot-premium_interactions")
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* 即:只有 `free_limited_copilot` 用 `chat` 维度,**其它所有套餐**(含
|
|
21
|
+
* `free_educational_quota`)统一用 `premium_interactions`。因此对多数账号
|
|
22
|
+
* 展示 `chat`/`completions` 会误导——它们不反映真实余额。
|
|
23
|
+
*
|
|
24
|
+
* ## 计费按 token 折算
|
|
25
|
+
*
|
|
26
|
+
* 实测 `mai-code-1.1-flash`(最便宜的 Auto 模型)约 3 万 token 消耗
|
|
27
|
+
* 1 次 premium。所有 Auto 模型都从同一个 `premium_interactions` 池扣减,
|
|
28
|
+
* 没有「免费的对话通道」。
|
|
29
|
+
*
|
|
30
|
+
* 扣减有 40-50 秒延迟,且 `remaining` 是取整值;需要精确值时读
|
|
31
|
+
* `quota_remaining`(浮点)。
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/** 单个额度快照。字段按可选处理,以适配不同套餐。 */
|
|
35
|
+
export interface QuotaSnapshot {
|
|
36
|
+
/** `chat`、`completions`、`premium_interactions` 等。 */
|
|
37
|
+
quota_id: string
|
|
38
|
+
/** 是否无限量。服务端用 `entitlement: -1` 表达该语义。 */
|
|
39
|
+
unlimited?: boolean
|
|
40
|
+
/** 是否具备该额度。 */
|
|
41
|
+
has_quota?: boolean
|
|
42
|
+
/** 已用额度(credits,取整)。 */
|
|
43
|
+
credits_used?: number
|
|
44
|
+
/** 剩余额度(取整值)。 */
|
|
45
|
+
remaining?: number
|
|
46
|
+
/** 精确剩余额度(浮点)。小额消耗只体现在这里。 */
|
|
47
|
+
quota_remaining?: number
|
|
48
|
+
/** 总配额。 */
|
|
49
|
+
entitlement?: number
|
|
50
|
+
/** 剩余百分比,0-100。 */
|
|
51
|
+
percent_remaining?: number
|
|
52
|
+
/** 是否基于 token 计费。 */
|
|
53
|
+
token_based_billing?: boolean
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** `/copilot_internal/user` 的响应(只取本扩展使用的字段)。 */
|
|
57
|
+
export interface CopilotAccount {
|
|
58
|
+
id?: number
|
|
59
|
+
login?: string
|
|
60
|
+
/** 套餐标识,例如 `free_educational_quota`。 */
|
|
61
|
+
access_type_sku?: string
|
|
62
|
+
/** 计划类型,例如 `individual`。 */
|
|
63
|
+
copilot_plan?: string
|
|
64
|
+
/** 开通时间,ISO 8601。 */
|
|
65
|
+
assigned_date?: string
|
|
66
|
+
/** 额度重置日期,`YYYY-MM-DD`。 */
|
|
67
|
+
quota_reset_date?: string
|
|
68
|
+
/** 各维度额度快照。 */
|
|
69
|
+
quota_snapshots?: Record<string, QuotaSnapshot>
|
|
70
|
+
/** 是否可升级套餐。 */
|
|
71
|
+
can_upgrade_plan?: boolean
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 判定该套餐应当读取哪个额度维度。
|
|
76
|
+
*
|
|
77
|
+
* 与 VS Code 的 `isFreeUser` 保持一致:只有 `free_limited_copilot` 用 `chat`,
|
|
78
|
+
* 其余全部用 `premium_interactions`(源站可能改名 `premium_models`)。
|
|
79
|
+
*/
|
|
80
|
+
export function primaryQuotaId(sku: string | undefined): string {
|
|
81
|
+
return sku === 'free_limited_copilot' ? 'chat' : 'premium_interactions'
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 格式化额度快照为一行人类可读文本。
|
|
86
|
+
*
|
|
87
|
+
* 规则:
|
|
88
|
+
* - 优先用精确值 `quota_remaining`,避免取整掩盖小额消耗;
|
|
89
|
+
* - `unlimited` 次之(服务端以 `entitlement: -1` 表达);
|
|
90
|
+
* - 信息不足时明确显示「未知」,不猜测数值。
|
|
91
|
+
*/
|
|
92
|
+
export function formatQuota(quota: QuotaSnapshot, label: string): string {
|
|
93
|
+
if (quota.unlimited === true) return `${label}: 无上限`
|
|
94
|
+
if (quota.has_quota === false) return `${label}: 未开通`
|
|
95
|
+
|
|
96
|
+
const total = typeof quota.entitlement === 'number' ? quota.entitlement : undefined
|
|
97
|
+
const percent = typeof quota.percent_remaining === 'number' ? quota.percent_remaining : undefined
|
|
98
|
+
// 优先精确值:取整字段会隐藏 0.4 这类消耗。
|
|
99
|
+
const remaining = typeof quota.quota_remaining === 'number'
|
|
100
|
+
? quota.quota_remaining
|
|
101
|
+
: quota.remaining
|
|
102
|
+
const used = typeof quota.credits_used === 'number' ? quota.credits_used : undefined
|
|
103
|
+
|
|
104
|
+
if (remaining !== undefined && total !== undefined && total > 0) {
|
|
105
|
+
const pct = percent !== undefined ? ` (${percent.toFixed(1)}%)` : ''
|
|
106
|
+
const shown = Number.isInteger(remaining) ? String(remaining) : remaining.toFixed(1)
|
|
107
|
+
const usedPart = used !== undefined ? `,已用 ${used}` : ''
|
|
108
|
+
return `${label}: ${shown}/${total}${pct}${usedPart}`
|
|
109
|
+
}
|
|
110
|
+
if (remaining !== undefined) return `${label}: 剩余 ${remaining}`
|
|
111
|
+
if (used !== undefined) return `${label}: 已用 ${used}`
|
|
112
|
+
return `${label}: 未知`
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 额度维度的展示名。未列出的维度直接使用原始 id。 */
|
|
116
|
+
const QUOTA_LABELS: Record<string, string> = {
|
|
117
|
+
premium_interactions: '高级请求',
|
|
118
|
+
premium_models: '高级请求',
|
|
119
|
+
chat: '对话',
|
|
120
|
+
completions: '代码补全',
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 把账号信息格式化为多行文本,供 `/copilot-auto` 输出。
|
|
125
|
+
*
|
|
126
|
+
* 只展示该套餐真正计费的维度,其余维度不显示——它们要么对该 SKU 无效,
|
|
127
|
+
* 要么是无上限的声明,罗列出来只会让人误以为存在额外免费额度。
|
|
128
|
+
*/
|
|
129
|
+
export function formatAccount(account: CopilotAccount): string[] {
|
|
130
|
+
const lines: string[] = []
|
|
131
|
+
|
|
132
|
+
if (account.login !== undefined) {
|
|
133
|
+
const sku = account.access_type_sku ?? '未知套餐'
|
|
134
|
+
lines.push(`账号: ${account.login} (${sku})`)
|
|
135
|
+
} else if (account.access_type_sku !== undefined) {
|
|
136
|
+
lines.push(`套餐: ${account.access_type_sku}`)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const snapshots = account.quota_snapshots
|
|
140
|
+
if (snapshots !== undefined) {
|
|
141
|
+
const wanted = primaryQuotaId(account.access_type_sku)
|
|
142
|
+
const quota = snapshots[wanted] ?? snapshots['premium_interactions'] ?? snapshots['premium_models']
|
|
143
|
+
if (quota !== undefined) {
|
|
144
|
+
const label = QUOTA_LABELS[quota.quota_id] ?? quota.quota_id
|
|
145
|
+
lines.push(formatQuota(quota, label))
|
|
146
|
+
// 按 token 计费时说明折算关系,否则「还剩 186 次」会被误解成 186 个请求。
|
|
147
|
+
if (quota.token_based_billing === true) {
|
|
148
|
+
lines.push('计费方式: 按 token 折算(约 3 万 token ≈ 1 次)')
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (account.quota_reset_date !== undefined) {
|
|
154
|
+
lines.push(`额度重置: ${account.quota_reset_date}`)
|
|
155
|
+
}
|
|
156
|
+
return lines
|
|
157
|
+
}
|
package/lib/auth.ts
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 认证:复用 pi 已保存的 GitHub Copilot 凭据。
|
|
3
|
+
*
|
|
4
|
+
* 用户已经为内置的 `github-copilot` provider 完成过 `/login`,其凭据保存在
|
|
5
|
+
* `~/.pi/agent/auth.json`。本扩展不再要求二次登录,而是直接读取那份 OAuth
|
|
6
|
+
* 记录。
|
|
7
|
+
*
|
|
8
|
+
* 两种令牌的用途不同,**不能混用**:
|
|
9
|
+
*
|
|
10
|
+
* | 令牌 | 字段 | 用于 |
|
|
11
|
+
* | --- | --- | --- |
|
|
12
|
+
* | Copilot access | `access`(`tid=...;exp=...`) | `/responses` 对话 |
|
|
13
|
+
* | GitHub OAuth | `refresh` | `/models`、`/auto`、`/copilot_internal/user` |
|
|
14
|
+
*
|
|
15
|
+
* 实测(2026-11-11):access 过期时 `/models` 返回 401,而用 `refresh`
|
|
16
|
+
* 请求同一端点仍是 200。OpenCode v2 正是用 `refresh` 拉目录,本扩展照此实现。
|
|
17
|
+
*
|
|
18
|
+
* OAuth 的刷新仍由内置 provider 负责,本扩展只读不写,避免两处同时
|
|
19
|
+
* 刷新同一个 refresh token。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { ApiKeyAuth, AuthResult, Credential } from '@earendil-works/pi-ai/compat'
|
|
23
|
+
import { readStoredCredential } from '@earendil-works/pi-coding-agent'
|
|
24
|
+
import { DEFAULT_CAPI_BASE } from './protocol.ts'
|
|
25
|
+
import { proxyEndpointFromToken, tokenFromEnv, tokenExpiry } from './token.ts'
|
|
26
|
+
|
|
27
|
+
/** 读取 pi 保存的 Copilot OAuth 凭据原始记录。不记录其内容。 */
|
|
28
|
+
function storedRecord(): Record<string, unknown> | undefined {
|
|
29
|
+
const raw = readStoredCredential('github-copilot')
|
|
30
|
+
if (raw === null || typeof raw !== 'object') return undefined
|
|
31
|
+
const record = raw as Record<string, unknown>
|
|
32
|
+
if (record['type'] !== 'oauth') return undefined
|
|
33
|
+
return record
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 读取 Copilot 访问令牌(凭据的 `access` 字段),用于 `/responses`。 */
|
|
37
|
+
export function storedCopilotToken(): string | undefined {
|
|
38
|
+
const record = storedRecord()
|
|
39
|
+
if (record === undefined) return undefined
|
|
40
|
+
const access = record['access']
|
|
41
|
+
if (typeof access !== 'string' || access === '') return undefined
|
|
42
|
+
return access
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 读取 GitHub OAuth 令牌(凭据的 `refresh` 字段)。
|
|
47
|
+
*
|
|
48
|
+
* `/models`、`/auto` 与 `api.github.com` 的账号端点都认这个令牌,
|
|
49
|
+
* 不认 Copilot 访问令牌(用错会得到 401)。
|
|
50
|
+
*/
|
|
51
|
+
export function storedGithubToken(): string | undefined {
|
|
52
|
+
const record = storedRecord()
|
|
53
|
+
if (record === undefined) return undefined
|
|
54
|
+
const refresh = record['refresh']
|
|
55
|
+
if (typeof refresh !== 'string' || refresh === '') return undefined
|
|
56
|
+
return refresh
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 解析本次请求的访问令牌。
|
|
61
|
+
*
|
|
62
|
+
* 优先级与 pi 的内置 provider 一致:环境变量 COPILOT_GITHUB_TOKEN 允许在 CI
|
|
63
|
+
* 等场景下不写凭据文件;否则读取已存储的 OAuth access token。
|
|
64
|
+
*/
|
|
65
|
+
export function resolveCopilotToken(credential?: Credential): string | undefined {
|
|
66
|
+
// 运行期刷新过的新令牌优先:存储里的 access 很可能已过期。
|
|
67
|
+
const runtime = runtimeAccessToken()
|
|
68
|
+
if (runtime !== undefined) return runtime
|
|
69
|
+
if (credential !== undefined && credential.type === 'api_key') {
|
|
70
|
+
const key = credential.key
|
|
71
|
+
if (typeof key === 'string' && key !== '') return key
|
|
72
|
+
}
|
|
73
|
+
if (credential !== undefined && credential.type === 'oauth') {
|
|
74
|
+
const access = (credential as Record<string, unknown>)['access']
|
|
75
|
+
if (typeof access === 'string' && access !== '') return access
|
|
76
|
+
}
|
|
77
|
+
return tokenFromEnv() ?? storedCopilotToken()
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 由访问令牌推导 API 根地址。
|
|
82
|
+
*
|
|
83
|
+
* 令牌的 `proxy-ep` 字段决定实际主机(企业版与区域化部署会不同);
|
|
84
|
+
* 无法推导时回退到 Copilot 公共地址。
|
|
85
|
+
*
|
|
86
|
+
* 注意:更权威的来源是 `/copilot_internal/user` 的 `endpoints.api`
|
|
87
|
+
* (见 `resolveApiBase`)。这里作为同步回退使用,因为没有该网络结果时
|
|
88
|
+
* `ApiKeyAuth.resolve` 仍需立即返回。
|
|
89
|
+
*/
|
|
90
|
+
export function baseUrlForToken(token: string): string {
|
|
91
|
+
return proxyEndpointFromToken(token) ?? DEFAULT_CAPI_BASE
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 令牌是否已过期(缺失过期时间时视为未知,按可用处理)。 */
|
|
95
|
+
export function tokenExpired(token: string, now = Date.now()): boolean {
|
|
96
|
+
const expires = tokenExpiry(token)
|
|
97
|
+
return expires !== undefined && expires <= now
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 运行期刷新的 Copilot 访问令牌。
|
|
102
|
+
*
|
|
103
|
+
* 为什么需要它:`auth.resolve` 在 access 过期时无法返回可用 key,pi 会直接
|
|
104
|
+
* 报 "No API key found"。而 `/copilot_internal/v2/token` 能用 refresh token
|
|
105
|
+
* 换到新 access(已实测 200)。
|
|
106
|
+
*
|
|
107
|
+
* 令牌只存内存,不写回 auth.json:写入会与内置 provider 的刷新链路产生
|
|
108
|
+
* 竞争,可能两边同时轮换同一个 refresh token。
|
|
109
|
+
*/
|
|
110
|
+
let runtimeAccess: { token: string; expiresAt: number } | undefined
|
|
111
|
+
|
|
112
|
+
/** 记录一次刷新得到的 access 令牌。 */
|
|
113
|
+
export function setRuntimeAccessToken(token: string, expiresAt: number): void {
|
|
114
|
+
runtimeAccess = { token, expiresAt }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 丢弃运行期令牌(登出或刷新失败时)。 */
|
|
118
|
+
export function clearRuntimeAccessToken(): void {
|
|
119
|
+
runtimeAccess = undefined
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 读取仍然有效的运行期令牌。 */
|
|
123
|
+
export function runtimeAccessToken(now = Date.now()): string | undefined {
|
|
124
|
+
if (runtimeAccess === undefined) return undefined
|
|
125
|
+
// 预留 60 秒,避免在传输途中过期。
|
|
126
|
+
if (runtimeAccess.expiresAt > 0 && runtimeAccess.expiresAt - 60_000 <= now) return undefined
|
|
127
|
+
return runtimeAccess.token
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 构造 `ApiKeyAuth`。
|
|
132
|
+
*
|
|
133
|
+
* `resolve` 不发起网络请求,也不执行命令,因此可以安全地用于
|
|
134
|
+
* `checkAuth` 等无副作用的探测路径。
|
|
135
|
+
*/
|
|
136
|
+
export function copilotAutoAuth(): ApiKeyAuth {
|
|
137
|
+
return {
|
|
138
|
+
name: 'GitHub Copilot',
|
|
139
|
+
resolve({ credential }): Promise<AuthResult | undefined> {
|
|
140
|
+
const token = resolveCopilotToken(credential)
|
|
141
|
+
if (token === undefined) return Promise.resolve(undefined)
|
|
142
|
+
if (tokenExpired(token)) {
|
|
143
|
+
// 过期且没有运行期刷新结果时,不静默失败,而是明确让 pi 报缺凭据,
|
|
144
|
+
// 同时扩展会在启动/刷新目录时尝试用 refresh token 换新 access。
|
|
145
|
+
return Promise.resolve(undefined)
|
|
146
|
+
}
|
|
147
|
+
return Promise.resolve({
|
|
148
|
+
auth: {
|
|
149
|
+
apiKey: token,
|
|
150
|
+
baseUrl: baseUrlForToken(token),
|
|
151
|
+
},
|
|
152
|
+
source: 'GitHub Copilot OAuth',
|
|
153
|
+
})
|
|
154
|
+
},
|
|
155
|
+
}
|
|
156
|
+
}
|