@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.
@@ -0,0 +1,243 @@
1
+ /**
2
+ * GitHub Copilot Auto 路由协议的常量与类型。
3
+ *
4
+ * 协议未文档化,以下内容以**实测**为准(2026-11-11,账号 free_educational_quota)。
5
+ * 两个独立 Auto 通道并存,本扩展同时支持:
6
+ *
7
+ * 1. `/auto`(新,OpenCode v2 / Copilot 客户端使用)
8
+ * POST → { session_token, selected_model: <完整模型对象>, expires_at, ... }
9
+ * 优点:直接返回选中模型的完整 capabilities,无需再查目录。
10
+ *
11
+ * 2. `/models/session`(旧,VS Code copilot-chat 使用)
12
+ * POST → { selected_model: "<id>", available_models: [...], ... }
13
+ * 只给出 id 字符串与授权清单,元数据需回目录查。
14
+ *
15
+ * 两者下发同一种 session_token,均可作为 `Copilot-Session-Token` 使用。
16
+ */
17
+
18
+ /** 扩展注册的 provider id,与内置 `github-copilot` 明确区分。 */
19
+ export const PROVIDER_ID = 'copilot-auto'
20
+
21
+ /** provider 在 `/model` 与 `/login` 中的显示名。 */
22
+ export const PROVIDER_NAME = 'GitHub Copilot (Auto)'
23
+
24
+ /**
25
+ * Auto 通道使用的 API 实现 id。
26
+ *
27
+ * 注册为自定义 id 而非直接复用 `openai-responses`,是为了让扩展在
28
+ * provider.api 层明确接管请求,避免与内置 copilot provider 混淆。
29
+ */
30
+ export const API_ID = 'copilot-auto-responses'
31
+
32
+ /** Copilot 默认 API 根地址;实际值优先由 `/copilot_internal/user` 的 endpoints.api 决定。 */
33
+ export const DEFAULT_CAPI_BASE = 'https://api.individual.githubcopilot.com'
34
+
35
+ /**
36
+ * 请求 Copilot API 使用的版本头。
37
+ *
38
+ * 实测(2026-11-11):
39
+ * - `/models`、`/models/session`:`2025-07-16` 与 `2026-08-01` 均可用;
40
+ * - `/auto`:**只接受 `2026-08-01`**。用 `2025-07-16` 返回
41
+ * `404 bad request: error: invalid apiVersion`。
42
+ *
43
+ * 旧版本文档曾把 `/auto` 的 404 误判为「端点不存在」,实际是版本头不匹配。
44
+ */
45
+ export const AUTO_API_VERSION = '2026-08-01'
46
+
47
+ /**
48
+ * `/models` 与 `/models/session` 使用的版本头。
49
+ *
50
+ * 保持 `2025-07-16`:这是 VS Code copilot-chat 0.72.0 的量级,兼容性已验证。
51
+ * 该请求另需满足 ≥ 2025-07-16,否则 `/models/session/intent` 报
52
+ * "auto-intent proxy requires API version 2025-07-16 or later"。
53
+ */
54
+ export const API_VERSION = '2025-07-16'
55
+
56
+ /** 凭据可用长于此值的时长仍视为有效,避免临界过期。 */
57
+ export const SESSION_EXPIRY_SKEW_MS = 30_000
58
+
59
+ /**
60
+ * 服务端自身的令牌提前量。
61
+ *
62
+ * `/auto` 与 VS Code 一致:令牌在服务端过期前 5 分钟即视为失效并重新协商,
63
+ * 避免请求发出时刚好过期。
64
+ */
65
+ export const SERVER_EXPIRY_SKEW_MS = 300_000
66
+
67
+ /** 单次 session 协商的超时。对应 VS Code 的 AutoV2Fetcher.TIMEOUT_MS = 5_000。 */
68
+ export const SESSION_TIMEOUT_MS = 5_000
69
+
70
+ /** `/auto` 协商失败后,降级条目的有效期(与 OpenCode 一致的 5 分钟)。 */
71
+ export const FALLBACK_VALIDITY_MS = 300_000
72
+
73
+ /**
74
+ * 模拟 VS Code 客户端的请求头。
75
+ *
76
+ * Copilot 会按这些头校验调用方身份;缺失 `Editor-Version` 时直接返回
77
+ * "bad request: missing Editor-Version header for IDE auth"。
78
+ * 版本号取自本机已安装并验证可用的 copilot-chat 0.72.0。
79
+ */
80
+ export const CLIENT_HEADERS: Readonly<Record<string, string>> = {
81
+ 'User-Agent': 'GitHubCopilotChat/0.72.0',
82
+ 'Editor-Version': 'vscode/1.144.1',
83
+ 'Editor-Plugin-Version': 'copilot-chat/0.72.0',
84
+ 'Copilot-Integration-Id': 'vscode-chat',
85
+ }
86
+
87
+ /**
88
+ * `/auto` 的响应体(字段名来自实测)。
89
+ *
90
+ * `selected_model` 是**完整对象**而非字符串——这与 `/models/session` 不同。
91
+ * 该对象携带 `capabilities`、`billing`、`supported_endpoints`,可直接构造 pi 模型。
92
+ */
93
+ export interface AutoRouteResponse {
94
+ session_token: string
95
+ selected_model: CatalogEntry
96
+ /** Unix 秒。 */
97
+ expires_at: number
98
+ discounted_costs?: Record<string, number>
99
+ multi_turn?: boolean
100
+ multi_turn_mode?: string
101
+ hydra_scores?: unknown
102
+ selection_reason?: string
103
+ }
104
+
105
+ /** `/models/session` 的响应体(旧通道,字段名来自实测)。 */
106
+ export interface AutoSessionResponse {
107
+ available_models: string[]
108
+ selected_model: string
109
+ session_token: string
110
+ expires_at: number
111
+ discounted_costs?: Record<string, number>
112
+ }
113
+
114
+ /** session token 的 JWT 载荷。仅用于本地读取过期时间,不校验签名。 */
115
+ export interface AutoSessionTokenPayload {
116
+ available_models?: string[]
117
+ selected_model?: string
118
+ auto_tier?: string
119
+ reasoning_bucket?: string
120
+ sub?: string
121
+ iat?: number
122
+ exp?: number
123
+ discounted_costs?: Record<string, number>
124
+ auto_session_id?: string
125
+ }
126
+
127
+ /** 一次已协商的 Auto 会话。 */
128
+ export interface AutoSession {
129
+ /** 注入 `Copilot-Session-Token` 的 JWT。 */
130
+ token: string
131
+ /** 服务端为本次请求选中的真实模型 id。 */
132
+ selectedModel: string
133
+ /**
134
+ * 本次会话允许使用的全部模型 id。
135
+ *
136
+ * `/auto` 不返回授权清单,此时为 `[]`(表示「不做额外限制」)。
137
+ * `/models/session` 会返回确切清单,用于裁剪模型选择器。
138
+ */
139
+ availableModels: string[]
140
+ /** 毫秒时间戳,已内含服务端的提前量。 */
141
+ expiresAt: number
142
+ /** 每个模型的折扣系数,用于展示与成本核算。 */
143
+ discountedCosts: Record<string, number>
144
+ /** 服务端会话标识,便于排查。 */
145
+ sessionId?: string
146
+ /** `/auto` 直接下发的选中模型完整元数据;旧通道无此字段。 */
147
+ selectedModelSpec?: CatalogEntry
148
+ /** 本次协商走的通道。 */
149
+ channel?: 'auto' | 'models-session'
150
+ /** 是否由降级路径产生(无 session_token,不能用于 Auto 专属模型)。 */
151
+ degraded?: boolean
152
+ }
153
+
154
+ /** `/models` 中的单个模型条目(仅取本扩展使用的字段)。 */
155
+ export interface CatalogEntry {
156
+ id: string
157
+ name?: string
158
+ version?: string
159
+ object?: string
160
+ vendor?: string
161
+ preview?: boolean
162
+ model_picker_category?: string
163
+ model_picker_price_category?: string
164
+ /**
165
+ * 客户端是否在模型选择器中展示该条目。
166
+ *
167
+ * `/models` 提供该字段;`/auto` 下发选中模型时**不含**此字段,
168
+ * 因此判断可用性不能只依赖它。
169
+ */
170
+ model_picker_enabled?: boolean
171
+ /**
172
+ * 是否为聊天降级目标。
173
+ *
174
+ * 实测:本账号只有 `gpt-5.3-codex` 为 true。`/auto` 协商失败时,
175
+ * OpenCode 优先降级到该模型(其次选带 `auto_discount` 的条目)。
176
+ */
177
+ is_chat_fallback?: boolean
178
+ supported_endpoints?: string[]
179
+ capabilities?: {
180
+ limits?: {
181
+ max_context_window_tokens?: number
182
+ max_output_tokens?: number
183
+ max_prompt_tokens?: number
184
+ vision?: {
185
+ max_prompt_images?: number
186
+ supported_media_types?: string[]
187
+ }
188
+ }
189
+ supports?: {
190
+ tool_calls?: boolean
191
+ parallel_tool_calls?: boolean
192
+ streaming?: boolean
193
+ vision?: boolean
194
+ structured_outputs?: boolean
195
+ /** 实测含 `none`/`low`/`medium`/`high`/`xhigh`/`max` 等值。 */
196
+ reasoning_effort?: string[]
197
+ adaptive_thinking?: boolean
198
+ max_thinking_budget?: number
199
+ }
200
+ tokenizer?: string
201
+ family?: string
202
+ }
203
+ policy?: { state?: string }
204
+ billing?: {
205
+ restricted_to?: string[]
206
+ /**
207
+ * Auto 通道的折扣倍率。**存在该字段即表示该模型参与 Auto 路由**,
208
+ * 也是 OpenCode 判断「是否应展示 Auto 条目」的唯一依据。
209
+ */
210
+ auto_discount?: number
211
+ token_prices?: {
212
+ batch_size?: number
213
+ cache_price?: number
214
+ input_price?: number
215
+ output_price?: number
216
+ default?: {
217
+ cache_price?: number
218
+ cache_read_price?: number
219
+ cache_write_price?: number
220
+ input_price?: number
221
+ output_price?: number
222
+ max_prompt_tokens?: number
223
+ }
224
+ long_context?: {
225
+ input_price?: number
226
+ output_price?: number
227
+ }
228
+ }
229
+ }
230
+ }
231
+
232
+ /** `/models` 的响应体。 */
233
+ export interface CatalogResponse {
234
+ data: CatalogEntry[]
235
+ }
236
+
237
+ /** `/copilot_internal/user` 的响应体(仅取本扩展使用的字段)。 */
238
+ export interface CopilotUserResponse {
239
+ endpoints?: {
240
+ api?: string
241
+ proxy?: string
242
+ }
243
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Auto 会话缓存。
3
+ *
4
+ * 缓存策略对齐 VS Code `copilot-chat` 的 AutomodeService 与 OpenCode v2:
5
+ * - 缓存键是**会话**(conversation id),不是提示词;
6
+ * - 条目有效性由未过期、请求模型一致、vision 需求被满足三项决定;
7
+ * - 最多保留 50 条,超出时淘汰最早插入的条目;
8
+ * - 同键并发只协商一次(routingSingler);
9
+ * - **上下文压缩后立即失效**(OpenCode 的 `compaction` hook),
10
+ * 因为压缩会改写对话形态,旧令牌对应的路由决策不再适用。
11
+ *
12
+ * 之所以按会话而非提示词缓存:Auto 的模型选择由服务端决定,同一次对话
13
+ * 多轮之间需要保持同一模型,否则上下文会在不同模型间跳转。而提示词每次
14
+ * 都不同,按提示词缓存会让几乎每个请求都重新协商,既慢又破坏一致性。
15
+ *
16
+ * 缓存只存在内存中。session_token 生命周期很短(实测约 1 小时),
17
+ * 持久化没有价值且会扩大凭据暴露面。
18
+ */
19
+
20
+ import {
21
+ negotiateForModel,
22
+ sessionUsable,
23
+ type NegotiateInput,
24
+ type NegotiateResult,
25
+ type RequestTarget,
26
+ } from './client.ts'
27
+ import { AUTO_MODEL_ID } from './catalog.ts'
28
+ import type { AutoSession } from './protocol.ts'
29
+
30
+ /** 与 VS Code 的 CACHE_MAX_ENTRIES 保持一致。 */
31
+ const MAX_ENTRIES = 50
32
+
33
+ interface Entry {
34
+ session: AutoSession
35
+ /** 实际应发给 `/responses` 的模型 id。 */
36
+ effectiveModel: string
37
+ /** 本次请求是否需要图片能力,用于判断可复用性。 */
38
+ needsVision: boolean
39
+ /** 用户请求的模型,用于检测「会话缓存与当前模型不匹配」。 */
40
+ requestedModel: string
41
+ /** 该会话能否覆盖用户请求的模型。 */
42
+ unsupported: boolean
43
+ }
44
+
45
+ /** 缓存键由会话标识与 API 根地址组成,避免多账号或代理间串用。 */
46
+ function cacheKey(conversationId: string, baseUrl: string): string {
47
+ return `${conversationId}\u0000${baseUrl}`
48
+ }
49
+
50
+ export interface AcquireOptions {
51
+ /** 会话标识;ephemeral 会话使用固定字符串。 */
52
+ conversationId: string
53
+ /** 本次请求是否包含图片。 */
54
+ needsVision: boolean
55
+ /**
56
+ * 本次请求指定的模型。
57
+ *
58
+ * 决定协商哪个通道:`auto` 走 `/auto` 由服务端决定;具体模型优先走
59
+ * `/models/session`,因为该通道会公布确切的覆盖清单。
60
+ */
61
+ model?: string
62
+ /** 协商超时(毫秒)。 */
63
+ timeoutMs?: number
64
+ /** 协商失败时的降级候选。 */
65
+ catalog?: NegotiateInput['catalog']
66
+ }
67
+
68
+ export class AutoSessionCache {
69
+ private readonly entries = new Map<string, Entry>()
70
+ private readonly pending = new Map<string, Promise<NegotiateResult>>()
71
+
72
+ /**
73
+ * 取得该会话可用、且能覆盖请求模型的 Auto 会话。
74
+ *
75
+ * 命中条件:未过期、请求模型一致、vision 需求被满足。
76
+ */
77
+ async acquire(target: RequestTarget, prompt: string, options: AcquireOptions): Promise<NegotiateResult> {
78
+ const key = cacheKey(options.conversationId, target.baseUrl)
79
+ const cached = this.entries.get(key)
80
+
81
+ if (cached !== undefined && this.compatible(cached, options)) {
82
+ // 重新插入以反映最近使用顺序。
83
+ this.entries.delete(key)
84
+ this.entries.set(key, cached)
85
+ return {
86
+ session: cached.session,
87
+ effectiveModel: cached.effectiveModel,
88
+ unsupported: cached.unsupported,
89
+ }
90
+ }
91
+
92
+ const inFlight = this.pending.get(key)
93
+ if (inFlight !== undefined) return inFlight
94
+
95
+ const requestedModel = options.model ?? AUTO_MODEL_ID
96
+ const task = negotiateForModel(target, requestedModel, {
97
+ prompt,
98
+ needsVision: options.needsVision,
99
+ ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
100
+ ...(options.catalog === undefined ? {} : { catalog: options.catalog }),
101
+ })
102
+ .then((result) => {
103
+ this.store(key, {
104
+ session: result.session,
105
+ effectiveModel: result.effectiveModel,
106
+ needsVision: options.needsVision,
107
+ requestedModel,
108
+ unsupported: result.unsupported,
109
+ })
110
+ return result
111
+ })
112
+ .finally(() => {
113
+ this.pending.delete(key)
114
+ })
115
+
116
+ this.pending.set(key, task)
117
+ return task
118
+ }
119
+
120
+ /** 条目是否仍可复用。 */
121
+ private compatible(entry: Entry, options: AcquireOptions): boolean {
122
+ if (!sessionUsable(entry.session)) return false
123
+ // 图片请求必须复用已经验证过 vision 的会话;文本请求可复用任意会话。
124
+ if (options.needsVision && !entry.needsVision) return false
125
+ // 切换模型后不得沿用旧路由结果。
126
+ if (options.model !== undefined && options.model !== entry.requestedModel) return false
127
+ return true
128
+ }
129
+
130
+ /** 写入条目并执行有界淘汰(最早插入者先出)。 */
131
+ private store(key: string, entry: Entry): void {
132
+ this.entries.delete(key)
133
+ this.entries.set(key, entry)
134
+ while (this.entries.size > MAX_ENTRIES) {
135
+ const oldest = this.entries.keys().next().value
136
+ if (oldest === undefined) break
137
+ this.entries.delete(oldest)
138
+ }
139
+ }
140
+
141
+ /**
142
+ * 让某会话的缓存失效,下一次 acquire 重新协商。
143
+ *
144
+ * 服务端可能因配额或策略变更提前作废令牌;此时请求会拿到 401/403,
145
+ * 调用方应失效缓存并重试一次。
146
+ */
147
+ invalidate(conversationId: string, baseUrl: string): void {
148
+ this.entries.delete(cacheKey(conversationId, baseUrl))
149
+ }
150
+
151
+ /**
152
+ * 让某会话的令牌立即作废,但保留模型信息。
153
+ *
154
+ * 对应 OpenCode 的 `compaction` hook:把 `until` 置 0,下次 acquire
155
+ * 必定重新协商。这里直接删除条目,语义等价且更简单。
156
+ */
157
+ expire(conversationId: string, baseUrl: string): void {
158
+ this.entries.delete(cacheKey(conversationId, baseUrl))
159
+ }
160
+
161
+ /** 清空缓存,用于登出或凭据切换。 */
162
+ clear(): void {
163
+ this.entries.clear()
164
+ }
165
+
166
+ /** 当前缓存条目数,供状态展示与排查。 */
167
+ get size(): number {
168
+ return this.entries.size
169
+ }
170
+
171
+ /** 当前缓存中各会话选中的模型,供状态展示。 */
172
+ snapshot(): { requested: string; effective: string; degraded: boolean }[] {
173
+ return [...this.entries.values()].map((entry) => ({
174
+ requested: entry.requestedModel,
175
+ effective: entry.effectiveModel,
176
+ degraded: entry.session.degraded === true,
177
+ }))
178
+ }
179
+ }
180
+
181
+ /** 进程内共享实例。 */
182
+ export const autoSessions = new AutoSessionCache()